scsh 1.17.2

Scoped Skills Helper — preflight a git repo and run its scoped skills in ephemeral containers.
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
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
use super::cast::cast_player_page;
use super::client_js::live_client_js;
use super::escape::esc;
use super::proc::{empty_output_html, empty_output_label};
use super::session::session_page;
use super::session_export::session_export_page;
use crate::daemon::model::{DaemonMode, ProcKind, ProcRecord, ProcStatus, Session, Store};

/// A one-proc store for the cast player page tests: the proc has a registered cast and
/// the given status.
fn store_with_cast_proc(status: ProcStatus) -> Store {
  let mut store = Store::new(DaemonMode::Persistent, 7274, 1);
  store.sessions.insert(
    "castab".into(),
    Session {
      id: "castab".into(),
      started_at: 1,
      ended_at: None,
      profile: Some("default".into()),
      kind: None,
      repo: "/tmp/repo".into(),
      branch: "main".into(),
      last_seen_at: 1,
      client_connected: true,
      run_pid: None,
      skills: vec![],
      procs: vec![ProcRecord {
        index: 0,
        kind: ProcKind::Skill,
        label: "claude: add".into(),
        status,
        note: None,
        detail: None,
        fail_reason: None,
        container_name: None,
        cast_path: Some("/tmp/x.cast".into()),
        diff_path: None,
        skill_source: None,
        route: None,
        result_path: None,
        harness: Some("claude".into()),
        skill_name: Some("add".into()),
        model: None,
        started_at: Some(1),
        elapsed: None,
        lines: vec![],
      }],
      workflow: None,
      parent_session: None,
    },
  );
  store
}

fn session_procs_html(html: &str) -> &str {
  let needle = r#"<div class="procs" id="session-procs">"#;
  let start = html.find(needle).expect("session-procs") + needle.len();
  let tail = &html[start..];
  // The procs div is the body's last element; the page footer is the script block.
  let end = tail.find("<script").expect("script block after procs");
  &tail[..end]
}

#[test]
fn esc_handles_basic_html() {
  assert_eq!(esc("<a>"), "&lt;a&gt;");
}

#[test]
fn browser_player_is_first_party_and_carries_no_third_party_license() {
  // The whole point of the first-party beecast-player: neither the session browser nor
  // the exported pages (same crate family) ship ANY third-party code.
  let js = super::PLAYER_JS;
  let css = super::PLAYER_CSS;
  assert!(js.contains("BeeCastPlayer"), "the first-party player global must be defined");
  assert!(js.contains("BeeCastVT"), "the DOM-free core must be bundled first");
  assert!(js.contains("Clean-room implementation"), "the clean-room statement rides in the asset");
  for banned in ["asciinema-player", "AsciinemaPlayer", "@license", "Apache"] {
    assert!(!js.contains(banned), "browser player JS must not carry '{banned}'");
    assert!(!css.contains(banned), "browser player CSS must not carry '{banned}'");
  }
}

/// Run the DOM-free VT core's behavior tests under Node (parsing all three asciicast
/// versions plus the terminal state machine). Skips silently when `node` is not on PATH —
/// the Rust-side structural tests above still gate the asset itself.
#[test]
fn vt_core_node_selftest() {
  if crate::runtime::which("node").is_none() {
    return;
  }
  let dir = std::env::temp_dir().join(format!("scsh-vt-selftest-{}", std::process::id()));
  std::fs::create_dir_all(&dir).unwrap();
  let bundle = dir.join("player.js");
  std::fs::write(&bundle, super::PLAYER_JS).unwrap();
  let script = format!(
    r#"
const assert = require('assert');
require({bundle:?});
const VT = globalThis.BeeCastVT;

// v3: intervals sum; term size from header; resize + marker events survive; # comments skip.
let c = VT.parseCast('{{"version":3,"term":{{"cols":10,"rows":3}}}}\n# note\n[0.5,"o","hi"]\n[0.5,"m","chapter"]\n[1.0,"r","20x5"]\n');
assert.strictEqual(c.cols, 10); assert.strictEqual(c.rows, 3);
assert.strictEqual(c.events.length, 3);
assert.strictEqual(c.duration, 2);
assert.strictEqual(c.events[2].t, 2);

// v2: absolute times.
c = VT.parseCast('{{"version":2,"width":80,"height":24}}\n[0.5,"o","a"]\n[2.0,"o","b"]\n');
assert.strictEqual(c.duration, 2); assert.strictEqual(c.events[1].t, 2);

// v1: one JSON doc, stdout deltas.
c = VT.parseCast('{{"version":1,"width":5,"height":2,"stdout":[[0.1,"x"],[0.2,"y"]]}}');
assert.strictEqual(c.cols, 5); assert.strictEqual(c.events.length, 2);
assert(Math.abs(c.duration - 0.3) < 1e-9);

// Plain text + CR/LF.
let t = new VT.Term(10, 3);
t.write('hello\r\nworld');
assert.deepStrictEqual(t.textLines(), ['hello', 'world', '']);

// CUP + overwrite mid-screen.
t.write('\x1b[1;3Hga');
assert.strictEqual(t.textLines()[0], 'hegao');

// ED 2 clears everything.
t.write('\x1b[2J');
assert.deepStrictEqual(t.textLines(), ['', '', '']);

// SGR runs merge; colors land on cells.
t = new VT.Term(10, 1);
t.write('\x1b[31mred\x1b[0m ok');
const runs = t.snapshot().rows[0];
assert.strictEqual(runs[0].text, 'red'); assert.strictEqual(runs[0].fg, 1);
assert.strictEqual(runs[1].fg, null);

// 256-color + truecolor.
t = new VT.Term(4, 1);
t.write('\x1b[38;5;196mX\x1b[38;2;1;2;3mY');
const r2 = t.snapshot().rows[0];
assert.strictEqual(r2[0].fg, 196);
assert.strictEqual(r2[1].fg, '#010203');
assert.strictEqual(VT.color256(196), '#ff0000');
assert.strictEqual(VT.color256(232), '#080808');

// Deferred wrap: printing in the last column does not wrap until the next char.
t = new VT.Term(3, 2);
t.write('abc');
assert.strictEqual(t.snapshot().cursor.y, 0);
t.write('d');
assert.deepStrictEqual(t.textLines(), ['abc', 'd']);

// Scroll region: LF at the region bottom scrolls only the region.
t = new VT.Term(5, 4);
t.write('aa\r\nbb\r\ncc\r\ndd');
t.write('\x1b[2;3r\x1b[3;1H\n');
const lines = t.textLines();
assert.strictEqual(lines[0], 'aa');
assert.strictEqual(lines[1], 'cc');
assert.strictEqual(lines[3], 'dd');

// Alternate screen: primary content comes back on exit.
t = new VT.Term(5, 2);
t.write('main');
t.write('\x1b[?1049h\x1b[Halt');
assert.strictEqual(t.textLines()[0], 'alt');
t.write('\x1b[?1049l');
assert.strictEqual(t.textLines()[0], 'main');

// DEC special graphics: tmux border characters.
t = new VT.Term(4, 1);
t.write('\x1b(0qqx\x1b(B');
assert.strictEqual(t.textLines()[0], '──│');

// Cursor hide/show.
t = new VT.Term(2, 1);
t.write('\x1b[?25l');
assert.strictEqual(t.snapshot().cursor.visible, false);
t.write('\x1b[?25h');
assert.strictEqual(t.snapshot().cursor.visible, true);

// OSC titles are consumed, never printed.
t = new VT.Term(8, 1);
t.write('\x1b]0;title\x07ok');
assert.strictEqual(t.textLines()[0], 'ok');

console.log('vt selftest OK');
"#,
    bundle = bundle
  );
  let out = std::process::Command::new("node")
    .arg("-")
    .arg("--input-type=commonjs")
    .stdin(std::process::Stdio::piped())
    .stdout(std::process::Stdio::piped())
    .stderr(std::process::Stdio::piped())
    .spawn()
    .and_then(|mut child| {
      use std::io::Write;
      child.stdin.take().unwrap().write_all(script.as_bytes())?;
      child.wait_with_output()
    })
    .expect("node runs");
  let _ = std::fs::remove_dir_all(&dir);
  assert!(
    out.status.success() && String::from_utf8_lossy(&out.stdout).contains("vt selftest OK"),
    "vt selftest failed:\nstdout: {}\nstderr: {}",
    String::from_utf8_lossy(&out.stdout),
    String::from_utf8_lossy(&out.stderr)
  );
}

#[test]
fn skipped_workflow_step_renders_as_a_dim_slashed_row() {
  let mut store = store_with_cast_proc(ProcStatus::Skipped);
  {
    let p = &mut store.sessions.get_mut("castab").unwrap().procs[0];
    p.cast_path = None; // a skipped step never ran, so it has no recording
    p.detail = Some("skipped — its when: gate is false".into());
    p.note = Some("step 2/2 · needs probe_credentials".into());
  }
  let html = session_page(&store, "castab").expect("session renders");
  let procs = session_procs_html(&html);
  assert!(procs.contains(r#"class="proc skipped""#), "got: {procs}");
  assert!(!procs.contains("class=\"glyph\""), "proc rows no longer carry a status glyph: {procs}");
  assert!(procs.contains(">skipped</span>"), "skipped elapsed phrase: {procs}");
  // A skipped step is FINISHED, so its collapsed row shows the outcome (the skip reason),
  // not the transient step note — same rule that puts a finished skill's answer in the row.
  assert!(
    procs.contains(r#"<span class="note dim">skipped — its when: gate is false</span>"#),
    "skip reason in the collapsed row: {procs}"
  );
  assert!(procs.contains("data-proc-stop"), "kill control stays in place (WEB-UI §2): {procs}");
  assert!(procs.contains("disabled title="), "skipped step's kill is grayed: {procs}");
  // Live updates speak the same phrases; workflow graph keeps its own icon map.
  let js = live_client_js();
  assert!(js.contains("function elapsedPhrase"));
  assert!(js.contains("'skipped'"));
  assert!(js.contains("function wfDisplayState"), "workflow graph live state");
}

#[test]
fn start_panel_offers_project_creation_and_the_client_wires_it() {
  let store = Store::new(DaemonMode::Persistent, 7274, 1);
  let html = super::index_page(&store);
  for id in ["project-name", "project-create"] {
    assert!(html.contains(&format!("id=\"{id}\"")), "index page should contain #{id}");
  }
  assert!(html.contains("~/.scsh/projects/"), "the panel explains where projects live");
  assert!(html.contains("start-controls"), "Run rows use start-controls for full-width layout");
  assert!(html.contains("start-actions"), "Run action buttons are grouped for right alignment");
  assert!(html.contains(".start-controls"), "start-controls CSS ships");
  assert!(html.contains(".start-actions"), "start-actions CSS ships");
  let js = live_client_js();
  assert!(js.contains("/api/v1/projects/create"), "client js posts project creation");
  assert!(js.contains("function createProject"), "client js wires the button");
  assert!(js.contains("function handleRepoOpened"), "open and create share the response path");
  assert!(js.contains("function showToast"), "existing-project feedback is a toast");
  assert!(js.contains("suggestOpenExistingProject"), "existing name is copied into Open");
  assert!(js.contains("This project already exists, just open it."), "toast copy");
  assert!(js.contains("projectNameOk"), "client rejects dots/slashes before POST");
  assert!(html.contains("no dots/slashes"), "placeholder documents the name rules");
  assert!(html.contains(".toast"), "toast styles ship with the page");
}

#[test]
fn running_cast_preview_starts_near_the_end() {
  let js = live_client_js();
  // A still-running proc's player opens in DECLARED-LIVE mode: parked at the growing edge,
  // the seek bar pinned full-width in live green (player.setLive) — not a near-end
  // autoplay whose playhead jitters as the duration grows.
  assert!(js.contains("box._live = true; createCastPlayer(box, 'end')"), "running casts open live at the edge");
  assert!(!js.contains("near-end"), "the jittery near-end preview is gone");
  assert!(js.contains("beecast-livechange"), "scsh tracks the player's live state");
}

#[test]
fn ui_review_fixes_hold() {
  // 1. Agent-route badges: the chamfer overlay must not swallow the text (the
  //    empty-rectangle bug — .agent-badge's inner span needs the z-index lift too).
  let html = super::index_page(&Store::new(DaemonMode::Persistent, 7274, 1));
  assert!(
    html.contains(".badge > span, .session-status > span, .agent-badge > span"),
    "agent-badge text must sit above the chamfer overlay"
  );
  // 2. Clicking something that renders inputs further down scrolls there.
  let js = live_client_js();
  assert_eq!(js.matches("scrollIntoView").count() >= 2, true, "def form + defs panel scroll into view");
  // 3. A finished proc's collapsed row shows its ANSWER, not the stale run note.
  let mut store = store_with_cast_proc(ProcStatus::Ok);
  {
    let p = &mut store.sessions.get_mut("castab").unwrap().procs[0];
    p.detail = Some("2 + 3 = 5".into());
    p.note = Some("claude run…".into());
  }
  let page = session_page(&store, "castab").expect("session renders");
  assert!(page.contains(r#"<span class="note dim">2 + 3 = 5</span>"#), "the answer rides the collapsed row");
  assert!(!page.contains(r#"<span class="note dim">claude run…</span>"#), "the stale note does not");
  // 4. The meta island is purple and owns the action buttons (top-right corner).
  assert!(page.contains(r#"<div class="card card--accent-left-purple"><div class="session-actions">"#));
  // 5. Proc islands wear status on the left accent bar (and tint the label).
  assert!(html.contains("details.proc.ok { border-left-color: var(--green); }"));
  assert!(html.contains("details.proc.running { border-left-color: var(--orange); }"));
  assert!(html.contains("details.proc.running summary .label { color: var(--orange); }"));
  assert!(
    html.contains(".wf-node.wf-running { border-left-color: var(--orange); }"),
    "graph running matches proc orange"
  );
  assert!(html.contains(".wf-node.wf-stalled { border-left-color: var(--purple); }"), "abandoned/stalled is purple");
  assert!(
    html.contains(".wf-node.wf-force-stopped { border-left-color: var(--red); }"),
    "force-stopped shares fail red"
  );
  assert!(js.contains("stalled:'Abandoned'"), "legend label is Abandoned");
  {
    let p = &mut store.sessions.get_mut("castab").unwrap().procs[0];
    p.elapsed = Some(18.0);
  }
  let page_with_elapsed = session_page(&store, "castab").expect("session renders");
  assert!(
    page_with_elapsed.contains(r#"data-proc-elapsed="0">done in 18s</span>"#),
    "ok rows say done in N: {page_with_elapsed}"
  );
  assert!(!page_with_elapsed.contains(r#"class="glyph""#), "no status glyph on proc rows");
  // 6. The builtin source badge wears purple.
  assert!(html.contains(".badge--purple"), "purple badge class ships");
  assert!(live_client_js().contains(r#"chamfer badge badge--purple"><span>builtin"#), "builtin badge is purple");
}

#[test]
fn session_header_carries_breadcrumbs_and_honest_kind() {
  // The top island: location path on the left (bold, plain text), daemon status right.
  let mut store = store_with_cast_proc(ProcStatus::Running);
  {
    let s = store.sessions.get_mut("castab").unwrap();
    s.kind = Some("workflow".into());
    s.profile = Some("arith".into());
  }
  let html = session_page(&store, "castab").expect("session renders");
  assert!(
    html.contains(r#"<a href="/">scsh</a><span class="crumb-sep">›</span><a href="/">jobs</a><span class="crumb-sep">›</span><a class="job-id" href="/job/castab">castab</a>"#),
    "breadcrumb permalinks in the top island (the id in a fixed font)"
  );
  // The status dot sits at the very RIGHT edge of the island.
  assert!(
    html.contains(r#"{}<span class="dot" aria-hidden="true"></span></span></div>"#.trim_start_matches("{}")),
    "dot last in the island"
  );
  assert!(html.contains(r#"<span class="daemon-right">"#), "daemon status keeps the island's right side");
  assert!(!html.contains("<h1>"), "the body no longer duplicates the path as an h1");
  // Kind/profile/lifecycle live on the page lede — not repeated in the purple island.
  assert!(html.contains(r#"class="page-lede""#), "got lede: {html}");
  assert!(html.contains("workflow <strong>arith</strong>"), "lede names the workflow: {html}");
  assert!(!html.contains(r#"class="session-kind""#), "purple island no longer repeats kind: {html}");
  assert!(!html.contains(r#"<ul class="skills">"#), "purple island drops skills list: {html}");
  // A session with no kind (persisted by an older build) still reads as a profile.
  let mut old = store_with_cast_proc(ProcStatus::Running);
  old.sessions.get_mut("castab").unwrap().profile = Some("default".into());
  let html = session_page(&old, "castab").expect("session renders");
  assert!(html.contains("profile <strong>default</strong>"), "lede defaults kind to profile: {html}");
  assert!(!html.contains(r#"class="session-kind""#), "no session-kind on default profile: {html}");
  // The index island shows just "scsh".
  let html = super::index_page(&store);
  assert!(html.contains(r#"<span class="crumbs"><a href="/">scsh</a></span>"#), "got crumbs on index");
}

#[test]
fn stop_strip_and_kill_buttons_ignore_zombie_sessions() {
  // A dead client's session keeps procs "running" forever. Kill buttons stay visible but
  // DISABLED (WEB-UI §2) — there is nothing left to stop.
  let store = store_with_cast_proc(ProcStatus::Running);
  let html = super::index_page(&store);
  assert!(!html.contains(r#"data-harness-stop=""#), "zombie sessions must not raise stop-all buttons");
  let page = session_page(&store, "castab").expect("session renders");
  assert!(page.contains(r#"data-proc-stop="0""#), "zombie still shows the kill control");
  assert!(page.contains("disabled title=\"Job is no longer running"), "zombie kill is grayed: {page}");

  // The same session, seen moments ago, gets an enabled kill.
  let mut live = store_with_cast_proc(ProcStatus::Running);
  live.sessions.get_mut("castab").unwrap().last_seen_at = crate::daemon::paths::now_unix_secs();
  let html = super::index_page(&live);
  assert!(html.contains(r#"data-harness-stop="claude""#), "live sessions raise the stop-all button");
  let page = session_page(&live, "castab").expect("session renders");
  assert!(page.contains(r#"data-proc-stop="0""#), "live sessions offer per-proc kill");
  assert!(!page.contains(r#"data-proc-stop="0" disabled"#), "live kill is enabled: {page}");
}

#[test]
fn session_meta_agrees_with_lifecycle_badge() {
  // WEB-UI §6 / ENG §13: channels must not disagree. A heartbeat-stale zombie must not
  // say "TERMINATED ABRUPTLY" in the badge and "still running" in Ended.
  let zombie = store_with_cast_proc(ProcStatus::Running);
  let page = session_page(&zombie, "castab").expect("session renders");
  assert!(
    page.contains("terminated abruptly") || page.contains("· terminated"),
    "zombie lifecycle on lede: {page}"
  );
  assert!(!page.contains(r#"class="session-kind""#), "no island status chip: {page}");
  // Ended shows the last-seen timestamp (effective end), not the status phrase.
  assert!(page.contains(r#"data-session-ended>"#), "Ended present: {page}");
  assert!(!page.contains(r#"data-session-ended>still running</dd>"#), "Ended must not contradict: {page}");
  assert!(
    !page.contains(r#"data-session-ended>terminated abruptly</dd>"#),
    "Ended is a time, badge carries the phrase: {page}"
  );
  assert!(page.contains(r#"data-session-ended>19700101-000001 UTC</dd>"#), "Ended uses last_seen: {page}");
  // Repo above Branch.
  let repo = page.find("<dt>Repo</dt>").expect("Repo");
  let branch = page.find("<dt>Branch</dt>").expect("Branch");
  assert!(repo < branch, "Repo should sit above Branch: {page}");
  assert!(page.contains(r#"data-session-started>"#), "meta is server-rendered on first paint");
  assert!(page.contains(r#"data-last-seen="1""#), "last_seen seeds the client lifecycle");

  let mut live = store_with_cast_proc(ProcStatus::Running);
  live.sessions.get_mut("castab").unwrap().last_seen_at = crate::daemon::paths::now_unix_secs();
  let page = session_page(&live, "castab").expect("session renders");
  assert!(page.contains(r#"data-session-ended>still running</dd>"#), "live Ended: {page}");
  assert!(page.contains(r#"id="session-stop""#), "live Force stop stays available");
}

#[test]
fn index_page_shows_colored_harness_chips_per_proc() {
  let mut store = store_with_cast_proc(ProcStatus::Running);
  // A second, finished proc on another harness: its chip renders dimmed.
  {
    let session = store.sessions.get_mut("castab").unwrap();
    let mut done = session.procs[0].clone();
    done.index = 1;
    done.status = ProcStatus::Ok;
    done.harness = Some("grok".into());
    done.label = "grok: add".into();
    session.procs.push(done);
    // Build procs never get a chip — only skill runs count.
    let mut build = session.procs[0].clone();
    build.index = 2;
    build.kind = ProcKind::Build;
    build.harness = Some("codex".into());
    session.procs.push(build);
  }
  let html = super::index_page(&store);
  // A running chip's tip is just `harness · skill`; its start time rides in
  // data-tip-running, from which the tip module ticks a live "running for …" line.
  assert!(
    html.contains(r#"<span class="hchip hchip--claude" data-tip="claude · add" data-tip-running="1">C</span>"#),
    "got: {html}"
  );
  // A finished chip's tip is two lines: `harness · skill`, then the plain status word.
  assert!(
    html.contains("<span class=\"hchip hchip--grok hchip--done\" data-tip=\"grok · add\ndone\">G</span>"),
    "got: {html}"
  );
  assert!(!html.contains(r#"class="hchip hchip--codex"#), "build procs must not render a chip");
  // The stylesheet distinguishes the same letter by harness color, and the client JS
  // mirrors the markup for live re-renders.
  assert!(html.contains(".hchip--claude"));
  assert!(html.contains(".hchip--codex"));
  assert!(html.contains("function harnessChipsHtml"));
}

#[test]
fn index_page_carries_the_setup_panel_and_its_client_wiring() {
  let store = Store::new(DaemonMode::Persistent, 7274, 1);
  let html = super::index_page(&store);
  assert!(html.contains("data-tab=\"setup\""), "nav label tab is Setup");
  assert!(html.contains(">Setup</button>"), "nav shows Setup, not Containers");
  assert!(!html.contains(">Containers</button>"), "Containers nav label is gone");
  assert!(html.contains("id=\"tab-setup\""), "setup panel id");
  assert!(html.contains("Harness setup"), "harness setup heading");
  assert!(html.contains("id=\"setup-cards\""), "harness cards container");
  assert!(html.contains("Images setup"), "images setup island");
  assert!(html.contains("card--accent-left-purple"), "images island uses purple accent");
  assert!(!html.contains("Advanced image management"), "no advanced disclosure");
  // Advanced still has the image table controls.
  for id in ["images-body", "images-build-selected", "images-build-all", "images-rebuild-base", "images-force"] {
    assert!(html.contains(&format!("id=\"{id}\"")), "index page should contain #{id}");
  }
  // First paint already lists every harness + known image (§13: no empty limbo).
  assert!(html.contains("checking…"), "skeleton starts in checking…");
  for name in ["Claude", "Codex", "Grok", "Opencode", "Cursor"] {
    assert!(html.contains(name), "harness card {name} on first paint");
  }
  assert!(html.contains("scsh-base:latest"), "base image row on first paint");
  for tag in
    ["scsh-opencode:latest", "scsh-claude:latest", "scsh-codex:latest", "scsh-grok:latest", "scsh-cursor:latest"]
  {
    assert!(html.contains(tag), "harness image {tag} on first paint");
  }
  let js = live_client_js();
  assert!(js.contains("/api/v1/setup"), "client js should fetch the setup API");
  assert!(js.contains("/api/v1/setup/tests"), "client js posts model probes");
  assert!(js.contains("/api/v1/images/build"), "client js should post builds");
  assert!(js.contains("function refreshSetup"), "setup refresh");
  assert!(js.contains("function startSetupTests"), "setup test starter");
  assert!(js.contains("setup-test-all"), "Test all defaults control");
  assert!(js.contains("data-setup-test"), "per-card Test selected");
  assert!(js.contains("setupCustomModels"), "custom models persist in ui prefs");
  assert!(js.contains("function markImagesChecking"), "refresh keeps rows visible while checking");
  assert!(js.contains("id === 'images'"), "images tab id remains a compatibility alias");
  assert!(!js.contains("loading…"), "must not replace the table with a blank loading row");
  assert!(js.contains("data-image-build"), "per-row build buttons are rendered");
  assert!(js.contains("data-setup-build"), "card Build/Update actions");
  assert!(html.contains("id=\"setup-test-all\""), "Test all defaults on the toolbar");
  assert!(js.contains("setup-models-hint"), "models section explains how to test");
  assert!(js.contains("ready to test"), "summary uses ready-to-test wording");
  assert!(js.contains("setupModelStatusHtml"), "model rows hide raw not_tested");
  assert!(js.contains("setup-ready"), "ready-to-test badge styling");
  assert!(js.contains("function startImageBuildOne"), "per-row build buttons are wired");
  assert!(html.contains("image-action-cell"), "skeleton rows reserve the per-row action cell");
}

#[test]
fn index_page_carries_the_repositories_panel_and_its_client_wiring() {
  let store = Store::new(DaemonMode::Persistent, 7274, 1);
  let html = super::index_page(&store);
  for id in
    ["repo-path", "repo-pick", "repo-open", "repo-blockers", "defs-panel", "defs-list", "def-form", "repos-body"]
  {
    assert!(html.contains(&format!("id=\"{id}\"")), "index page should contain #{id}");
  }
  // The four tabs, and their panels — Run is leftmost and the default landing tab.
  for (tab, panel) in [("run", "tab-run"), ("jobs", "tab-jobs"), ("projects", "tab-projects"), ("setup", "tab-setup")] {
    assert!(html.contains(&format!("data-tab=\"{tab}\"")), "index page should have the {tab} tab");
    assert!(html.contains(&format!("id=\"{panel}\"")), "index page should have panel #{panel}");
  }
  let nav = html.find("<nav class=\"tabs\">").expect("tabs nav");
  let run_btn = html[nav..].find("data-tab=\"run\">Run</button>").expect("Run tab");
  let jobs_btn = html[nav..].find("data-tab=\"jobs\">Jobs</button>").expect("Jobs tab");
  assert!(run_btn < jobs_btn, "Run should be leftmost");
  assert!(html.contains("<section class=\"tab-panel active\" id=\"tab-run\">"), "Run panel active by default");
  assert!(html.contains("class=\"tab active\" data-tab=\"run\">Run</button>"), "Run tab active by default");
  let js = live_client_js();
  assert!(js.contains("saved || 'run'"), "client default tab is Run");
  assert!(js.contains("pathForTab"), "tabs use path URLs, not #tab= hashes");
  assert!(!js.contains("'/#tab='"), "no hash-based tab navigation");
  assert!(js.contains("'/projects'"), "Projects tab path is /projects");
  assert!(super::index::IndexTab::from_path("/projects") == Some(super::index::IndexTab::Projects));
  assert!(super::index::IndexTab::from_path("/setup") == Some(super::index::IndexTab::Setup));
  assert!(super::index::IndexTab::from_path("/images") == Some(super::index::IndexTab::Setup));
  assert!(super::index::IndexTab::from_path("/jobs") == Some(super::index::IndexTab::Jobs));
  assert!(super::index::IndexTab::from_path("/") == Some(super::index::IndexTab::Run));
  assert!(js.contains("/api/v1/repos/open"), "client js opens a repo");
  assert!(js.contains("/api/v1/repos/pick"), "client js pops the folder picker");
  assert!(js.contains("/api/v1/jobs/start"), "client js starts a job");
  assert!(js.contains("function renderRepoJobs"), "client js renders jobs by repository");
  assert!(js.contains("function renderInternalJobs"), "client js renders Internal section");
  assert!(js.contains("chapters pending ⬇"), "export label for pending chapters");
  assert!(js.contains("function syncChaptersPending"), "live chapters-pending sync");
  assert!(js.contains("OPEN_REPO_RUNNABLE"), "client js gates Start on the repo being runnable");
  assert!(js.contains("function initTabs"), "client js wires the tabs");
  assert!(js.contains("history.pushState"), "tab clicks push history (WEB-UI §1)");
  assert!(js.contains("popstate"), "Back/Forward restore the active tab");
  assert!(js.contains("function sessionEndedLabel"), "Ended label shares lifecycle with the badge");
  assert!(js.contains("function activateProcPanel"), "fleet and workflow share arrival cues");
  assert!(js.contains("localStorage"), "UI prefs persist (WEB-UI §7)");
  assert!(!js.contains("fonts.googleapis.com"), "no Google Fonts in the live client");
}

#[test]
fn empty_output_label_depends_on_proc_status() {
  assert_eq!(empty_output_label(ProcStatus::Running), "No output yet.");
  assert_eq!(empty_output_label(ProcStatus::Waiting), "No output yet.");
  assert_eq!(empty_output_label(ProcStatus::Ok), "No output.");
  assert_eq!(empty_output_label(ProcStatus::Fail), "No output.");
}

#[test]
fn session_proc_html_has_no_stray_backslashes() {
  let mut store = Store::new(DaemonMode::Persistent, 7274, 1);
  store.sessions.insert(
    "test".into(),
    Session {
      id: "test".into(),
      started_at: 1,
      ended_at: None,
      profile: Some("default".into()),
      kind: None,
      repo: "/tmp/repo".into(),
      branch: "main".into(),
      last_seen_at: crate::daemon::paths::now_unix_secs(), // live: Force stop only renders for running sessions
      client_connected: false,
      run_pid: None,
      skills: vec![],
      procs: vec![ProcRecord {
        index: 0,
        kind: ProcKind::Skill,
        label: "opencode: add".into(),
        status: ProcStatus::Running,
        note: None,
        detail: None,
        fail_reason: None,
        container_name: None,
        cast_path: None,
        diff_path: None,
        skill_source: None,
        route: None,
        result_path: None,
        harness: Some("opencode".into()),
        skill_name: Some("add".into()),
        model: None,
        started_at: Some(1),
        elapsed: None,
        lines: vec![],
      }],
      workflow: None,
      parent_session: None,
    },
  );
  let html = session_page(&store, "test").expect("session page");
  let procs = session_procs_html(&html);
  assert!(!html.contains("\\\n"), "raw-string line continuations must not leak backslashes");
  assert!(!procs.contains("\\\n"), "autoscroll markup must not leak backslashes");
  assert!(procs.contains(r#"<label class="autoscroll-ctl">"#));
  assert!(procs.contains("Auto-scroll to bottom"));
  assert!(html.contains(r#"<div class="output"><div class="dim">No output yet.</div>"#));
  assert!(html.contains(r#"id="session-stop""#), "running session should offer Force stop");
  assert!(html.contains("Force stop"));
}

#[test]
fn session_page_shows_the_commits_diff_chip_only_when_packed() {
  let mut store = Store::new(DaemonMode::Persistent, 7274, 1);
  store.sessions.insert(
    "difjob".into(),
    Session {
      id: "difjob".into(),
      started_at: 1,
      ended_at: Some(10),
      profile: Some("default".into()),
      kind: None,
      repo: "/tmp/repo".into(),
      branch: "main".into(),
      last_seen_at: 10,
      client_connected: false,
      run_pid: None,
      skills: vec![],
      procs: vec![
        ProcRecord {
          index: 0,
          kind: ProcKind::Skill,
          label: "opencode: add".into(),
          status: ProcStatus::Ok,
          note: None,
          detail: None,
          fail_reason: None,
          container_name: None,
          cast_path: None,
          diff_path: Some("/tmp/scsh-home/sessions/difjob/diffs/add-p0.html".into()),
          skill_source: None,
          route: None,
          result_path: None,
          harness: Some("opencode".into()),
          skill_name: Some("add".into()),
          model: None,
          started_at: Some(1),
          elapsed: Some(2.0),
          lines: vec![],
        },
        ProcRecord {
          index: 1,
          kind: ProcKind::Skill,
          label: "claude: add".into(),
          status: ProcStatus::Ok,
          note: None,
          detail: None,
          fail_reason: None,
          container_name: None,
          cast_path: None,
          diff_path: None,
          skill_source: None,
          route: None,
          result_path: None,
          harness: Some("claude".into()),
          skill_name: Some("add".into()),
          model: None,
          started_at: Some(1),
          elapsed: Some(2.0),
          lines: vec![],
        },
      ],
      workflow: None,
      parent_session: None,
    },
  );
  let html = session_page(&store, "difjob").expect("session page");
  let procs = session_procs_html(&html);
  // The step whose commits were packed links its review page; the other has no chip.
  assert!(procs.contains(r#"href="/diff/difjob/0""#), "packed step links its diff: {procs}");
  assert!(procs.contains("⇄ commits diff"), "the chip is labeled: {procs}");
  assert!(!procs.contains(r#"href="/diff/difjob/1""#), "unpacked step has no diff link: {procs}");
  assert_eq!(procs.matches("data-proc-diff").count(), 1, "exactly one chip: {procs}");
  // Plain click navigates in THIS tab; cmd/ctrl+click keeps its native new-tab meaning.
  assert!(!procs.contains("target="), "no target override on the diff chip: {procs}");
}

#[test]
fn ended_session_grays_force_stop_button_in_place() {
  let mut store = Store::new(DaemonMode::Persistent, 7274, 1);
  store.sessions.insert(
    "done01".into(),
    Session {
      id: "done01".into(),
      started_at: 1,
      ended_at: Some(10),
      profile: Some("default".into()),
      kind: None,
      repo: "/tmp/repo".into(),
      branch: "main".into(),
      last_seen_at: 10,
      client_connected: false,
      run_pid: None,
      skills: vec![],
      procs: vec![],
      workflow: None,
      parent_session: None,
    },
  );
  let html = session_page(&store, "done01").expect("session page");
  // WEB-UI §2: the control stays, grayed, with an explanation — it does not vanish.
  assert!(html.contains(r#"id="session-stop""#), "ended session still shows Force stop");
  assert!(html.contains(r#"id="session-stop" data-session="done01" disabled"#), "Force stop is disabled: {html}");
  assert!(html.contains(r#"class="page-lede""#), "session page has a plain-language lede");
  assert!(
    html.contains("· completed ·") || html.contains("completed"),
    "lede carries the completed lifecycle: {html}"
  );
  assert!(
    !html.contains(r#"class="session-kind""#),
    "ended session has no session-kind heading in the island: {html}"
  );
  assert!(
    !html.contains(r#"session-actions"><span class="chamfer session-status"#),
    "no badge in the top-right actions slot"
  );
  assert!(!html.contains(r#"<ul class="skills">"#), "no skills list in purple island");
}

#[test]
fn offline_export_keeps_meta_without_kind_heading() {
  let session = Session {
    id: "exp01".into(),
    started_at: 1,
    ended_at: Some(10),
    profile: Some("code-review".into()),
    kind: Some("profile".into()),
    repo: "/tmp/repo".into(),
    branch: "main".into(),
    last_seen_at: 10,
    client_connected: false,
    run_pid: None,
    skills: vec![],
    procs: vec![],
    workflow: None,
    parent_session: None,
  };
  let html = session_export_page(&session, &[]);
  assert!(!html.contains(r#"class="session-kind""#), "export drops session-kind: {html}");
  assert!(html.contains(r#"<dl class="session-meta">"#), "export keeps session-meta: {html}");
  assert!(html.contains("<code>exp01</code>"), "job id in meta: {html}");
  assert!(html.contains("accessibility: 'snapshot'"), "export player opts enable a11y snapshot");
}

#[test]
fn offline_export_embeds_commits_diff_when_present() {
  use super::session_export::CastExport;
  let session = Session {
    id: "expdf".into(),
    started_at: 1,
    ended_at: Some(10),
    profile: Some("default".into()),
    kind: Some("profile".into()),
    repo: "/tmp/repo".into(),
    branch: "main".into(),
    last_seen_at: 10,
    client_connected: false,
    run_pid: None,
    skills: vec![],
    procs: vec![ProcRecord {
      index: 0,
      kind: ProcKind::Skill,
      label: "opencode: add".into(),
      status: ProcStatus::Ok,
      note: None,
      detail: Some("ok".into()),
      fail_reason: None,
      container_name: None,
      cast_path: None,
      diff_path: Some("/tmp/diff.html".into()),
      skill_source: None,
      route: None,
      result_path: None,
      harness: Some("opencode".into()),
      skill_name: Some("add".into()),
      model: None,
      started_at: Some(1),
      elapsed: Some(1.0),
      lines: vec![],
    }],
    workflow: None,
    parent_session: None,
  };
  let hostile = r#"<html><body></script><p>diff</p></body></html>"#;
  let exports = [CastExport::Note { text: "no recording".into(), diff_html: Some(hostile.into()) }];
  let html = session_export_page(&session, &exports);
  assert!(html.contains(r#"<span class="proc-diff""#), "summary carries static commits-diff chip");
  assert!(html.contains(r#"<details class="proc-diff">"#), "body embeds the packed diff");
  assert!(html.contains("srcdoc="), "diff rides in an iframe srcdoc");
  assert!(
    html.contains(r#"sandbox="allow-scripts allow-same-origin""#),
    "packdiff ≥ 0.3 needs scripts + same-origin for WASM/localStorage: {html}"
  );
  assert!(html.contains("<\\/"), "hostile </ is broken for srcdoc like CASTS");
  assert!(!html.contains("</script><p>diff"), "raw </script> must not appear unescaped");
}

#[test]
fn session_page_renders_fleet_comparison_for_shared_skill_source() {
  let mut store = Store::new(DaemonMode::Persistent, 7274, 1);
  store.sessions.insert(
    "fleet1".into(),
    Session {
      id: "fleet1".into(),
      started_at: 1,
      ended_at: Some(10),
      profile: Some("default".into()),
      kind: Some("profile".into()),
      repo: "/tmp/repo".into(),
      branch: "main".into(),
      last_seen_at: 10,
      client_connected: false,
      run_pid: None,
      skills: vec![],
      procs: vec![
        ProcRecord {
          index: 0,
          kind: ProcKind::Skill,
          label: "opencode: add-opencode".into(),
          status: ProcStatus::Ok,
          note: None,
          detail: Some("2 + 3 = 5".into()),
          fail_reason: None,
          container_name: None,
          cast_path: None,
          diff_path: None,
          skill_source: Some("add".into()),
          route: Some("opencode".into()),
          result_path: None,
          harness: Some("opencode".into()),
          skill_name: Some("add-opencode".into()),
          model: None,
          started_at: Some(1),
          elapsed: Some(1.0),
          lines: vec![],
        },
        ProcRecord {
          index: 1,
          kind: ProcKind::Skill,
          label: "claude: add-claude".into(),
          status: ProcStatus::Ok,
          note: None,
          detail: Some("2 + 3 = 5".into()),
          fail_reason: None,
          container_name: None,
          cast_path: None,
          diff_path: None,
          skill_source: Some("add".into()),
          route: Some("claude".into()),
          result_path: None,
          harness: Some("claude".into()),
          skill_name: Some("add-claude".into()),
          model: None,
          started_at: Some(1),
          elapsed: Some(1.2),
          lines: vec![],
        },
      ],
      workflow: None,
      parent_session: None,
    },
  );
  let html = session_page(&store, "fleet1").expect("session page");
  assert!(html.contains(r#"class="fleets""#), "fleet section present: {html}");
  assert!(html.contains(r#"class="fleet-compare""#), "comparison table present");
  assert!(html.contains(r#"data-skill-source="add""#), "grouped by skill_source");
  assert!(html.contains(r#"class="fleet-jump" data-proc="0""#), "jump to first route");
  assert!(html.contains(r#"class="fleet-jump" data-proc="1""#), "jump to second route");
  let fleets_at = html.find(r#"class="fleets""#).expect("fleets");
  let procs_at = html.find(r#"id="session-procs""#).expect("procs");
  assert!(fleets_at < procs_at, "fleet HTML sits before #session-procs");
}

#[test]
fn fleet_routes_stack_completed_before_running_before_waiting() {
  let mut store = Store::new(DaemonMode::Persistent, 7274, 1);
  store.sessions.insert(
    "fleet2".into(),
    Session {
      id: "fleet2".into(),
      started_at: 1,
      ended_at: None,
      profile: Some("default".into()),
      kind: Some("profile".into()),
      repo: "/tmp/repo".into(),
      branch: "main".into(),
      last_seen_at: crate::daemon::paths::now_unix_secs(),
      client_connected: true,
      run_pid: Some(1),
      skills: vec![],
      procs: vec![
        ProcRecord {
          index: 0,
          kind: ProcKind::Skill,
          label: "claude: add-waiting".into(),
          status: ProcStatus::Waiting,
          note: None,
          detail: None,
          fail_reason: None,
          container_name: None,
          cast_path: None,
          diff_path: None,
          skill_source: Some("add".into()),
          route: Some("waiting-route".into()),
          result_path: None,
          harness: Some("claude".into()),
          skill_name: Some("add-waiting-route".into()),
          model: None,
          started_at: None,
          elapsed: None,
          lines: vec![],
        },
        ProcRecord {
          index: 1,
          kind: ProcKind::Skill,
          label: "claude: add-done".into(),
          status: ProcStatus::Ok,
          note: None,
          detail: Some("ok".into()),
          fail_reason: None,
          container_name: None,
          cast_path: None,
          diff_path: None,
          skill_source: Some("add".into()),
          route: Some("done-route".into()),
          result_path: None,
          harness: Some("claude".into()),
          skill_name: Some("add-done-route".into()),
          model: None,
          started_at: Some(1),
          elapsed: Some(1.0),
          lines: vec![],
        },
        ProcRecord {
          index: 2,
          kind: ProcKind::Skill,
          label: "claude: add-running".into(),
          status: ProcStatus::Running,
          note: None,
          detail: None,
          fail_reason: None,
          container_name: None,
          cast_path: None,
          diff_path: None,
          skill_source: Some("add".into()),
          route: Some("running-route".into()),
          result_path: None,
          harness: Some("claude".into()),
          skill_name: Some("add-running-route".into()),
          model: None,
          started_at: Some(1),
          elapsed: None,
          lines: vec![],
        },
      ],
      workflow: None,
      parent_session: None,
    },
  );
  let html = session_page(&store, "fleet2").expect("fleet page");
  let done_at = html.find("done-route").expect("done route");
  let running_at = html.find("running-route").expect("running route");
  let waiting_at = html.find("waiting-route").expect("waiting route");
  assert!(done_at < running_at && running_at < waiting_at, "Completed → Running → Waiting: {html}");
}

#[test]
fn client_js_wires_fleet_jumps_and_accessibility_snapshot() {
  let js = live_client_js();
  assert!(js.contains("function parseIndexFilter"), "client parses /project and /repo");
  assert!(js.contains("function repoFilterHref"), "client builds filter hrefs");
  assert!(js.contains("repo-filter-link"), "live Projects rows stay clickable");
}

#[test]
fn client_js_wires_force_stop() {
  let js = live_client_js();
  assert!(js.contains("/api/v1/session/stop"), "client js posts session stop");
  assert!(js.contains("function forceStopSession"), "client js defines forceStopSession");
  assert!(js.contains("function scshConfirm"), "Force stop uses an in-app confirm dialog");
  assert!(js.contains("scsh-dialog"), "dialog markup class ships");
  assert!(!js.contains("confirm("), "no browser confirm() for Force stop");
  assert!(!js.contains("alert("), "Force stop errors use toast, not alert()");
}

#[test]
fn client_js_mirrors_the_commits_diff_chip() {
  // Integration (and the packdiff pack) happens after a step finished, so the chip usually
  // arrives on a live tick: the client must render the same markup session.rs serves.
  let js = live_client_js();
  assert!(js.contains("function procDiffBtnHtml"), "client js builds the diff chip");
  assert!(js.contains("p.diff_path"), "client js keys the chip on the proc's diff_path");
  assert!(js.contains("⇄ commits diff"), "the live chip carries the same label");
  assert!(js.contains("initProcDiffs"), "chips present at page render are wired too");
}

#[test]
fn recorded_proc_embeds_cast_player_instead_of_text_output() {
  let mut store = Store::new(DaemonMode::Persistent, 7274, 1);
  store.sessions.insert(
    "castab".into(),
    Session {
      id: "castab".into(),
      started_at: 1,
      ended_at: None,
      profile: Some("default".into()),
      kind: None,
      repo: "/tmp/repo".into(),
      branch: "main".into(),
      last_seen_at: 1,
      client_connected: true,
      run_pid: None,
      skills: vec![],
      procs: vec![ProcRecord {
        index: 2,
        kind: ProcKind::Skill,
        label: "claude: add".into(),
        status: ProcStatus::Ok,
        note: None,
        detail: None,
        fail_reason: None,
        container_name: None,
        cast_path: Some("/tmp/x.cast".into()),
        diff_path: None,
        skill_source: None,
        route: None,
        result_path: None,
        harness: Some("claude".into()),
        skill_name: Some("add".into()),
        model: None,
        started_at: Some(1),
        elapsed: Some(3.0),
        lines: vec![],
      }],
      workflow: None,
      parent_session: None,
    },
  );
  let html = session_page(&store, "castab").expect("session page");
  // The page loads the player assets and embeds a player box wired to the cast endpoint.
  assert!(html.contains(r#"<link rel="stylesheet" href="/assets/scsh-cast-player.css">"#), "player css");
  assert!(html.contains(r#"<script src="/assets/scsh-cast-player.js"></script>"#), "player js");
  let procs = session_procs_html(&html);
  assert!(procs.contains(r#"<div class="cast" data-cast-url="/cast/castab/2""#), "cast embed");
  // Fullscreen lives in the player's own control bar now (⛶ + the f key, via
  // fullscreenEl) — the page toolbar carries no fullscreen button of its own. Opening a
  // section focuses its player, so space and f work with no click first.
  assert!(!procs.contains("data-cast-fs"), "no page-side fullscreen button");
  assert!(procs.contains("f fullscreen"), "the keys hint teaches f");
  // Streaming drives itself (WS growth appends + the finish reload), so there is no manual
  // Reload button; chapters are the player's own chrome (☰ panel + c key + seek ticks) —
  // no scsh-side chip row or fullscreen sidebar.
  assert!(!procs.contains("data-cast-reload"), "no manual reload in a streaming toolbar");
  assert!(procs.contains("c chapters"), "the keys hint teaches the chapters panel");
  let js = live_client_js();
  assert!(!js.contains("data-cast-reload"), "client js builds no reload button");
  assert!(!js.contains("cast-chapters"), "no scsh-side chapter chips");
  assert!(!js.contains("cast-fs-chapters"), "no scsh-side fullscreen chapters sidebar");
  assert!(js.contains("markers"), "chapters reach the player as markers");
  assert!(js.contains("function focusCastPlayer"), "open sections hand the player the keyboard");
  assert!(js.contains("if (det.open) focusCastPlayer(box)"), "focus follows the section toggle");
  // Run snapshot sits in the proc island's top-right (above Force stop), cyan chamfer —
  // not inside the cast toolbar (toolbar keeps only `.cast` download + keys hint).
  assert!(!procs.contains("data-cast-link"), "no link-at-time in the inline toolbar");
  assert!(procs.contains(r#"class="chamfer btn btn--cyan btn--sm proc-snapshot""#), "run snapshot link");
  assert!(procs.contains(r#"href="/cast/castab/2/export.html" data-cast-export"#), "run snapshot href");
  assert!(
    !procs.contains(r#"cast-toolbar"><a href="/cast/castab/2/export.html"#),
    "snapshot is outside the cast toolbar"
  );
  assert!(procs.contains(r#"<a href="/cast/castab/2?dl=1" download>"#), "download link");
  // A recorded proc shows the player, NOT the text output / autoscroll control.
  assert!(!procs.contains(r#"<div class="output">"#), "no text output for recorded proc");
  assert!(!procs.contains("autoscroll-ctl"), "no autoscroll control for recorded proc");
}

#[test]
fn empty_output_html_has_no_backslash_artifacts() {
  let html = empty_output_html(ProcStatus::Ok);
  assert_eq!(html, "<div class=\"dim\">No output.</div>\n");
  assert!(!html.contains("\\"));
  let running = empty_output_html(ProcStatus::Running);
  assert_eq!(running, "<div class=\"dim\">No output yet.</div>\n");
  assert!(!running.contains("\\"));
}

#[test]
fn session_proc_html_shows_autoscroll_while_running() {
  let mut store = Store::new(DaemonMode::Persistent, 7274, 1);
  store.sessions.insert(
    "test".into(),
    Session {
      id: "test".into(),
      started_at: 1,
      ended_at: None,
      profile: Some("default".into()),
      kind: None,
      repo: "/tmp/repo".into(),
      branch: "main".into(),
      last_seen_at: 1,
      client_connected: true,
      run_pid: None,
      skills: vec![],
      procs: vec![ProcRecord {
        index: 0,
        kind: ProcKind::Skill,
        label: "opencode: add".into(),
        status: ProcStatus::Running,
        note: None,
        detail: None,
        fail_reason: None,
        container_name: None,
        cast_path: None,
        diff_path: None,
        skill_source: None,
        route: None,
        result_path: None,
        harness: Some("opencode".into()),
        skill_name: Some("add".into()),
        model: None,
        started_at: Some(1),
        elapsed: None,
        lines: vec![],
      }],
      workflow: None,
      parent_session: None,
    },
  );
  let html = session_page(&store, "test").expect("session page");
  let procs = session_procs_html(&html);
  assert!(procs.contains(r#"<label class="autoscroll-ctl">"#));
}

#[test]
fn empty_cast_shows_placeholder_instead_of_player_error() {
  // Both the session-page embed and the standalone player page fetch the cast text first
  // and render a calm placeholder when it has no complete event lines yet, instead of
  // handing the player an empty/404 cast (which errors).
  let js = live_client_js();
  assert!(js.contains("Recording in progress — no frames yet."));
  assert!(js.contains("No recorded frames."));
  assert!(js.contains("cast-placeholder"));
  assert!(js.contains("{ data: text }"), "player mounts over the already-fetched text");
  let page = cast_player_page(&store_with_cast_proc(ProcStatus::Running), "castab", 0).expect("player page");
  assert!(page.contains("Recording in progress — no frames yet."));
  assert!(page.contains("cast-placeholder"));
  assert!(page.contains("const LIVE = true;"));
  let done = cast_player_page(&store_with_cast_proc(ProcStatus::Ok), "castab", 0).expect("player page");
  assert!(done.contains("const LIVE = false;"));
}

#[test]
fn cast_growth_notifications_append_in_place() {
  // The session page routes WS messages by type: cast_growth appends the newly recorded
  // suffix to the mounted player IN PLACE (no re-creation, no seek, no reload banner) —
  // smooth live following. Everything else stays on the tick path.
  let js = live_client_js();
  assert!(js.contains("if (msg.type === 'cast_growth') { onCastGrowth(msg); return; }"));
  assert!(js.contains("onWsMessage(JSON.parse(ev.data))"));
  assert!(js.contains("function followCastGrowth"));
  assert!(js.contains("box._player.append(text.slice(prev))"));
  assert!(!js.contains("Recording grew: +"), "the reload banner is gone — growth is invisible and smooth");
  // The standalone player page listens on its own WS connection — but only while the proc
  // runs — and follows growth the same way.
  let page = cast_player_page(&store_with_cast_proc(ProcStatus::Running), "castab", 0).expect("player page");
  assert!(page.contains("'cast_growth'"));
  assert!(page.contains("const SESSION = 'castab';"));
  assert!(page.contains("const PROC = 0;"));
  assert!(page.contains("player.append(text.slice(loadedChars))"));
  assert!(!page.contains("Recording grew: +"));
  assert!(page.contains("if (!castRunning) return;"), "no WS connect once the proc finished");
  // The player bundle itself carries the live-follow API the pages rely on.
  assert!(super::PLAYER_JS.contains("Player.prototype.append"), "the vendored player must have append");
  assert!(super::PLAYER_JS.contains("appendCast"), "the DOM-free core must parse appends");
}

#[test]
fn live_follows_from_player_toolbar_not_scsh_chrome() {
  // Session-page embed: no external Live button — the player owns ● Live when running.
  let running =
    super::proc::cast_embed_html("castab", &store_with_cast_proc(ProcStatus::Running).sessions["castab"].procs[0]);
  assert!(!running.contains("data-cast-live"), "session embed has no scsh Live button");
  let done = super::proc::cast_embed_html("castab", &store_with_cast_proc(ProcStatus::Ok).sessions["castab"].procs[0]);
  assert!(!done.contains("data-cast-live"));
  let js = live_client_js();
  assert!(js.contains("function setCastLive(box, on)"));
  assert!(js.contains("box._player.setLive(true)"));
  assert!(js.contains("controls: running ? { live: true } : true"), "running casts enable player Live control");
  assert!(js.contains("live: !!(box._live || running)"), "running casts start declared-live");
  // Standalone page: likewise no page-chrome Live toggle.
  let page = cast_player_page(&store_with_cast_proc(ProcStatus::Running), "castab", 0).expect("player page");
  assert!(!page.contains("live-toggle"), "standalone page has no external Live button");
  assert!(page.contains("controls: wantLive ? { live: true } : true"));
  let finished = cast_player_page(&store_with_cast_proc(ProcStatus::Ok), "castab", 0).expect("player page");
  assert!(!finished.contains("live-toggle"));
}

#[test]
fn export_html_download_renders_on_both_pages_and_hides_without_frames() {
  // Standalone player page: the download link points at the export endpoint, starts
  // hidden, and rides the same no-frames state as the placeholder.
  let page = cast_player_page(&store_with_cast_proc(ProcStatus::Ok), "castab", 0).expect("player page");
  assert!(page.contains(r#"<a id="dl-html" href="/cast/castab/0/export.html" download hidden>⬇ download .html</a>"#));
  assert!(page.contains("document.getElementById('dl-html').hidden = !stats.events;"));
  // Session-page embed: run snapshot lives in `.proc-actions` (hidden until frames);
  // client JS unhides it when the cast has events.
  let session = session_page(&store_with_cast_proc(ProcStatus::Ok), "castab").expect("session page");
  let procs = session_procs_html(&session);
  assert!(
    procs.contains(r#"class="chamfer btn btn--cyan btn--sm proc-snapshot""#)
      && procs.contains(r#"href="/cast/castab/0/export.html" data-cast-export download hidden"#)
      && procs.contains("<span>run snapshot ⬇</span>"),
    "run snapshot button: {procs}"
  );
  let js = live_client_js();
  assert!(js.contains("ensureProcSnapshot"));
  assert!(js.contains("exportLink.hidden = !stats.events;"));
  assert!(js.contains("incomplete ⬇"), "live cast export says incomplete while running");
  assert!(js.contains("run snapshot ⬇"), "finished cast export says run snapshot");
}

#[test]
fn session_page_header_offers_the_session_export_download() {
  // A session with a recorded proc gets the whole-session download button in the header
  // (decided server-side: any proc with a registered cast; the endpoint 404s edge cases).
  let html = session_page(&store_with_cast_proc(ProcStatus::Ok), "castab").expect("session page");
  assert!(
    html.contains(r#"href="/job/castab/export.html" download"#) && html.contains("session-export"),
    "session export button"
  );
  // No recorded proc anywhere → no button (nothing to export; the 404 would only confuse).
  let mut store = store_with_cast_proc(ProcStatus::Ok);
  store.sessions.get_mut("castab").unwrap().procs[0].cast_path = None;
  let bare = session_page(&store, "castab").expect("session page");
  // (The `.session-export` CSS rule is in the shared shell, so match the anchor itself.)
  assert!(!bare.contains("<a class=\"session-export\""), "no export button without any registered cast");
}

#[test]
fn live_client_js_counts_alive_clients_and_shutdown() {
  let js = live_client_js();
  assert!(js.contains("alive_clients"));
  assert!(js.contains("shutting down in"));
}

#[test]
fn live_client_js_skips_index_render_without_sessions() {
  let js = live_client_js();
  assert!(js.contains("if (!body || sessions == null) return"));
  // renderIndex (and the jobs-per-repo view) run only when a snapshot is present.
  assert!(js.contains("if (snapshot) {"));
  assert!(js.contains("renderIndex(snapshot, nowUnix)"));
}

#[test]
fn live_client_js_shows_connecting_on_ws_close() {
  let js = live_client_js();
  assert!(js.contains("setDaemonStatus('connecting', 'connecting…', null)"));
  assert!(!js.contains("daemon unreachable"));
}

#[test]
fn wrap_page_connecting_status_uses_blue() {
  use super::layout::wrap_page;
  let html = wrap_page("scsh sessions", 7274, None, "", "<p>body</p>");
  assert!(html.contains("class=\"daemon-status connecting\""));
  assert!(html.contains(".daemon-status.connecting .dot { background: var(--cyan);"));
  assert!(!html.contains("fonts.googleapis.com"), "offline-first: no CDN fonts (WEB-UI §5)");
  assert!(html.contains("position: sticky"), "status chrome is pinned");
  assert!(html.contains("--daemon-status-height"), "tabs stick flush under a shared status height");
  assert!(!html.contains("top: 3.1rem"), "no hard-coded sticky gap above the tabs");
  assert!(html.contains("width: 100%"), "status chrome spans the viewport");
  assert!(html.contains(r#"class="page-shell""#), "content sits in a centered column under the bar");
}

#[test]
fn every_daemon_page_carries_the_inline_favicon() {
  use super::layout::wrap_page;
  // A data: URI, so the dashboard and the standalone player page stay request-free.
  let html = wrap_page("scsh sessions", 7274, None, "", "<p>body</p>");
  assert!(html.contains("<link rel=\"icon\" href=\"data:image/svg+xml,"), "dashboard favicon");
  let player = cast_player_page(&store_with_cast_proc(ProcStatus::Ok), "castab", 0).expect("player page");
  assert!(player.contains("<link rel=\"icon\" href=\"data:image/svg+xml,"), "player-page favicon");
  assert!(!player.contains("fonts.googleapis.com"), "cast player page is offline-first too");
}

#[test]
fn wrap_page_serves_valid_css_braces() {
  use super::layout::wrap_page;
  let html = wrap_page("scsh sessions", 7274, None, "Hello lede", "<p>body</p>");
  assert!(html.contains(":root {"));
  assert!(!html.contains(":root {{"));
  assert!(html.contains(".daemon-status {"));
  assert!(html.contains(r#"class="page-lede""#), "lede renders in the content column");
  assert!(html.contains("Hello lede"));
  // Status bar is the first body child so it pins full-width at the top; lede follows under it.
  let status_at = html.find(r#"id="daemon-status""#).expect("status bar");
  let shell_at = html.find(r#"class="page-shell""#).expect("page shell");
  let lede_at = html.find(r#"class="page-lede""#).expect("lede");
  assert!(status_at < shell_at && shell_at < lede_at, "chrome, then shell, then lede");
}

#[test]
fn review_round_four_fixes_hold() {
  use crate::daemon::model::OpenRepo;
  // (1) The Projects tab is populated server-side — jobs grouped by repository, plus a
  // "no jobs yet" row for repos opened with none — so it shows on first paint instead of
  // waiting for a full WebSocket snapshot a quiet daemon never sends.
  let mut store = store_with_cast_proc(ProcStatus::Ok);
  store.sessions.get_mut("castab").unwrap().ended_at = Some(5);
  store.open_repo(OpenRepo { path: "/work/empty".into(), opened_at: 9, clean: true });
  let html = super::index_page(&store);
  assert!(html.contains(r#"class="repo-filter-link""#), "project/repo names are filter links");
  assert!(html.contains(r#"title="/tmp/repo""#) || html.contains(r#"title="/tmp/repo">"#), "got: {html}");
  // Prefer a stable substring: the filter href for a non-project path.
  assert!(html.contains("/repo/tmp/repo") || html.contains("href=\"/repo/tmp/repo\""), "repo filter href: {html}");
  // Jobs are grouped by the task they ran, with a compact age stamp per job (the exact
  // age depends on the wall clock, so pin up to the stamp). The link — color and
  // underline — covers EXACTLY the six-letter id, in a fixed font (.job-id): never the
  // badge or the age stamp.
  assert!(
    html.contains(
      r#"<div class="repo-jobgroup"><span class="repo-jobgroup-name">default</span><div class="repo-job"><span class="chamfer session-status completed"><span>completed</span></span> <a class="job-id" href="/job/castab">castab</a> <span class="dim">"#
    ),
    "got: {html}"
  );
  assert!(
    html.contains(r#"title="/work/empty""#)
      && html.contains(r#"href="/repo/work/empty""#)
      && html.contains(r#"no jobs yet"#),
    "got: {html}"
  );
  // (2) Chips and counts carry instant data-tip tooltips, served by the shared floating tip
  // (native title tooltips were reset by every live table re-render).
  assert!(html.contains(r#"<span class="chip-count" data-tip="1 run in this job">1</span>"#), "got: {html}");
  assert!(html.contains(".ui-tip"), "tooltip CSS ships");
  assert!(html.contains("initTips"), "tooltip delegation ships");
  assert!(!super::index_page(&store).contains(r#"hchip--claude hchip--done" title="#), "chips use data-tip, not title");
  // (3) The UI speaks "jobs": table header, breadcrumb, empty states.
  assert!(html.contains("<th>Job</th>"), "got: {html}");
  assert!(!html.contains("<th>Session</th>"));
  // (4) A finished recording advertises WHEN it ended, and the chapters poll is bounded by
  // it — no more eternal "summarizing…" on casts that will never gain chapters.
  let mut ended = store_with_cast_proc(ProcStatus::Ok);
  ended.sessions.get_mut("castab").unwrap().procs[0].elapsed = Some(30.0);
  let shtml = session_page(&ended, "castab").expect("session renders");
  assert!(shtml.contains(r#" data-status="ok" data-ended="31">"#), "got: {shtml}");
  assert!(shtml.contains("CHAPTERS_WAIT_SECS"), "bounded summarizing window ships");
  // A still-running recording has no end yet (the session-meta dl has its own unrelated
  // data-ended, so pin the cast box's tag specifically).
  let running = session_page(&store_with_cast_proc(ProcStatus::Running), "castab").expect("session renders");
  assert!(running.contains(r#" data-status="running">"#), "got: {running}");
  assert!(!running.contains(r#" data-status="running" data-ended"#), "got: {running}");
  // (5) The per-container button reads "Force stop", not "kill" and without a leading ✕.
  let mut live = store_with_cast_proc(ProcStatus::Running);
  live.sessions.get_mut("castab").unwrap().last_seen_at = crate::daemon::paths::now_unix_secs();
  let shtml = session_page(&live, "castab").expect("session renders");
  assert!(shtml.contains(">Force stop</button>") || shtml.contains("<span>Force stop</span>"), "got: {shtml}");
  assert!(!shtml.contains("✕ Force stop"), "no leading ✕ on Force stop");
  assert!(!shtml.contains("✕ kill"));
  assert!(shtml.contains("<span>incomplete ⬇</span>"), "running job export says incomplete: {shtml}");
  assert!(shtml.contains(r#"class="chamfer btn btn--cyan btn--sm session-export""#), "export matches Force stop size");
  assert!(
    shtml.find("session-export").unwrap() < shtml.find("id=\"session-stop\"").unwrap(),
    "job snapshot sits above Force stop in the actions stack"
  );
  assert!(shtml.contains("job snapshot ⬇") || shtml.contains("incomplete ⬇"), "snapshot wording is explicit");
  // Finished job with a cast but no chapters sidecar → chapters pending (not incomplete).
  let done = session_page(&store_with_cast_proc(ProcStatus::Ok), "castab").expect("done session");
  assert!(
    done.contains("<span>chapters pending ⬇</span>"),
    "finished job missing sidecar uses chapters pending: {done}"
  );
  assert!(done.contains("1 cast finalizing chapters"), "pending counter on job page: {done}");
  assert!(!done.contains("<span>incomplete ⬇</span>"), "finished job meta export is not incomplete");
  assert!(!done.contains(r#"<ul class="skills">"#), "no skills list on job page island");
  // Settled: cast + sidecar on disk → job snapshot.
  let dir = std::env::temp_dir().join(format!("scsh-chap-ready-{}", crate::runtime::random_nonce_6()));
  std::fs::create_dir_all(&dir).unwrap();
  let cast = dir.join("ready.cast");
  std::fs::write(&cast, "{\"version\":3}\n").unwrap();
  std::fs::write(dir.join("ready.chapters.json"), r#"{"summary":"ok","chapters":[]}"#).unwrap();
  let mut settled = store_with_cast_proc(ProcStatus::Ok);
  {
    let s = settled.sessions.get_mut("castab").unwrap();
    s.ended_at = Some(10);
    s.procs[0].cast_path = Some(cast.to_string_lossy().into_owned());
  }
  let settled_html = session_page(&settled, "castab").expect("settled session");
  assert!(
    settled_html.contains("<span>job snapshot ⬇</span>"),
    "settled job export label: {settled_html}"
  );
  assert!(
    !settled_html.contains(r#"id="chapters-pending""#),
    "no pending line when sidecar exists: {settled_html}"
  );
  let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn review_round_five_fixes_hold() {
  // Projects: running jobs sort above completed ones, grouped by the task that ran, each
  // line stamped with a compact age; the launch tab reads "Run".
  let now = crate::daemon::paths::now_unix_secs();
  let mut store = store_with_cast_proc(ProcStatus::Ok);
  store.sessions.get_mut("castab").unwrap().ended_at = Some(5);
  {
    let done = store.sessions.get("castab").unwrap().clone();
    let mut live = done.clone();
    live.id = "livejb".into();
    live.ended_at = None;
    live.last_seen_at = now;
    live.profile = Some("arith".into());
    live.procs[0].status = ProcStatus::Running;
    store.sessions.insert("livejb".into(), live);
  }
  let html = super::index_page(&store);
  let arith = html.find(r#"<span class="repo-jobgroup-name">arith</span>"#).expect("arith group");
  let default = html.find(r#"<span class="repo-jobgroup-name">default</span>"#).expect("default group");
  assert!(arith < default, "the group with a running job sorts above the finished one: {html}");
  assert!(html.contains(r#"<span class="chamfer session-status running"><span>running</span></span> <a class="job-id" href="/job/livejb">livejb</a> <span class="dim">"#), "got: {html}");
  assert!(html.contains(r#"data-tab="run">Run</button>"#), "got: {html}");
  assert!(!html.contains("New job"));
  assert!(!html.contains("Start a job"));
  // Image-build sessions land under Projects → Internal, not the main Projects table.
  {
    let mut img = store_with_cast_proc(ProcStatus::Ok);
    img.sessions.get_mut("castab").unwrap().repo = crate::daemon::server::IMAGE_BUILDS_REPO.into();
    img.sessions.get_mut("castab").unwrap().profile = Some("build-images".into());
    img.sessions.get_mut("castab").unwrap().ended_at = Some(5);
    let html = super::index_page(&img);
    assert!(html.contains(r#"id="internal-jobs-card""#), "Internal section present: {html}");
    assert!(html.contains(r#"<p class="section-label">Internal</p>"#), "Internal label: {html}");
    assert!(html.contains(r#"<span class="repo-jobgroup-name">build-images</span>"#), "grouped by profile: {html}");
    assert!(html.contains(r#"href="/job/castab""#), "job link in Internal: {html}");
    assert!(
      !html.contains(r#"data-repo="(image builds)""#),
      "image builds excluded from Projects table: {html}"
    );
  }
  // Short ages are single-unit; both renderers ship the same helper and group markup.
  assert_eq!(super::format::format_short_age(45), "45s");
  assert_eq!(super::format::format_short_age(200), "3m");
  assert_eq!(super::format::format_short_age(7300), "2h");
  assert_eq!(super::format::format_short_age(200_000), "2d");
  assert!(html.contains("function formatShortAge"), "JS mirror ships");
  assert!(html.contains(".repo-jobgroup"), "group CSS ships");
  // The inline player pane has NO forced height — the player sizes its own box to the
  // recording's aspect at full width, so the pane is exactly as tall as the terminal wants
  // (the page-side sizeCastPane workaround is gone).
  let shtml = session_page(&store, "castab").expect("session renders");
  assert!(!shtml.contains("sizeCastPane"), "the pane-sizing workaround must stay gone");
  assert!(!shtml.contains(".cast-player { width: 100%; height:"), "no forced pane height");
  assert!(shtml.contains("height: 100% !important"), "fullscreen fills the grid cell for a stable mount measure");
  assert!(shtml.contains(".cast:fullscreen .beecast-player"), "fullscreen styles the player root");
}

#[test]
fn project_and_repo_filter_urls_normalize_extra_slashes() {
  use super::index::{parse_index_filter, IndexFilter};
  assert_eq!(parse_index_filter("/project//demo-1/"), Some(IndexFilter::Project("demo-1".into())));
  assert_eq!(parse_index_filter("/project/demo-1"), Some(IndexFilter::Project("demo-1".into())));
  assert_eq!(parse_index_filter("/project/"), None);
  assert_eq!(parse_index_filter("/project"), None);
  assert_eq!(parse_index_filter("/repo///Users/dima/foo/"), Some(IndexFilter::Repo("/Users/dima/foo".into())));
  assert_eq!(parse_index_filter("/repo/Users/dima/foo"), Some(IndexFilter::Repo("/Users/dima/foo".into())));
  assert_eq!(parse_index_filter("/repo/tmp/my%20repo"), Some(IndexFilter::Repo("/tmp/my repo".into())));
  assert_eq!(parse_index_filter("/repo/"), None);
}

#[test]
fn filtered_index_page_shows_only_matching_repo_and_opens_projects_tab() {
  use super::index::{index_page_with_filter, IndexFilter};
  let mut store = store_with_cast_proc(ProcStatus::Ok);
  store.sessions.get_mut("castab").unwrap().repo = "/tmp/repo".into();
  store.sessions.get_mut("castab").unwrap().ended_at = Some(5);
  {
    let mut other = store.sessions.get("castab").unwrap().clone();
    other.id = "other1".into();
    other.repo = "/tmp/other".into();
    store.sessions.insert("other1".into(), other);
  }
  let html = index_page_with_filter(&store, Some(IndexFilter::Repo("/tmp/repo".into())));
  assert!(html.contains(r#"class="tab active" data-tab="projects""#), "Projects tab active when filtered: {html}");
  assert!(html.contains("filter-banner"), "filter banner present");
  assert!(html.contains("Show all"), "clear-filter link");
  assert!(html.contains("href=\"/projects\""), "Show all clears to /projects");
  assert!(html.contains("castab"), "matching job shown");
  assert!(!html.contains(">other1<") && !html.contains("/job/other1"), "other repo's job hidden");
  assert!(html.contains(r#"class="repo-filter-link""#));
}

#[test]
fn review_round_six_fixes_hold() {
  let store = store_with_cast_proc(ProcStatus::Ok);
  let html = super::index_page(&store);
  // Durations can never render backwards: stale tick frames are dropped, and a superseded
  // WebSocket is fully retired before a reconnect (the "oscillating Duration" bug).
  assert!(html.contains("lastTickSecs"), "monotonic tick guard ships");
  assert!(html.contains("Retire any superseded socket"), "socket retirement ships");
  // The runtime switcher is a segmented control above the images table, not loose buttons
  // in the action strip; tips are multi-line and can tick a live running-for line.
  assert!(html.contains(r#"<div id="images-runtimes" class="images-runtimes"></div>"#), "got: {html}");
  assert!(html.contains(".seg-opt"), "segmented-control CSS ships");
  assert!(html.contains("data-tip-running"), "live-ticking tip support ships");
  assert!(html.contains("white-space: pre-line"), "multi-line tip CSS ships");
  // Both JS chip-count writers share one renderer, so live re-syncs keep the tooltip.
  assert!(html.contains("function chipCountHtml"), "shared chip-count renderer ships");
}

#[test]
fn workflow_graph_renders_builtin_shapes() {
  use crate::daemon::workflow::{WorkflowMeta, WorkflowNodeMeta};
  fn skill_proc(index: usize, id: &str, harness: &str, status: ProcStatus) -> ProcRecord {
    ProcRecord {
      index,
      kind: ProcKind::Skill,
      label: format!("{harness}: {id}"),
      status,
      note: None,
      detail: None,
      fail_reason: None,
      container_name: None,
      cast_path: None,
      diff_path: None,
      skill_source: Some(id.into()),
      route: None,
      result_path: None,
      harness: Some(harness.into()),
      skill_name: Some(id.into()),
      model: None,
      started_at: Some(1),
      elapsed: Some(1.0),
      lines: vec![],
    }
  }
  // arith: add + multiply → summarize
  let mut store = Store::new(DaemonMode::Persistent, 7274, 1);
  store.sessions.insert(
    "arith1".into(),
    Session {
      id: "arith1".into(),
      started_at: 1,
      ended_at: Some(10),
      profile: Some("arith".into()),
      kind: Some("workflow".into()),
      repo: "/tmp/r".into(),
      branch: "main".into(),
      skills: vec![],
      procs: vec![
        skill_proc(0, "add", "claude", ProcStatus::Ok),
        skill_proc(1, "multiply", "codex", ProcStatus::Ok),
        skill_proc(2, "summarize", "grok", ProcStatus::Ok),
      ],
      last_seen_at: 10,
      client_connected: false,
      run_pid: None,
      workflow: Some(WorkflowMeta {
        nodes: vec![
          WorkflowNodeMeta {
            id: "add".into(),
            proc_index: Some(0),
            order: 0,
            needs: vec![],
            conditional: false,
            when_summary: None,
          },
          WorkflowNodeMeta {
            id: "multiply".into(),
            proc_index: Some(1),
            order: 1,
            needs: vec![],
            conditional: false,
            when_summary: None,
          },
          WorkflowNodeMeta {
            id: "summarize".into(),
            proc_index: Some(2),
            order: 2,
            needs: vec!["add".into(), "multiply".into()],
            conditional: false,
            when_summary: None,
          },
        ],
      }),
      parent_session: None,
    },
  );
  let html = session_page(&store, "arith1").expect("page");
  assert!(html.contains(r#"id="workflow-graph""#), "workflow card present");
  assert!(html.contains("3 tasks · "), "summary starts with task count");
  assert!(html.contains(r#">3 done</a>"#), "summary counts by status, not edge count");
  assert!(html.contains(r#"class="wf-jump""#), "status counters are jump links");
  assert!(html.contains("Jump to first done task"), "done counter links to a done node");
  assert!(
    html.contains("href=\"#task-add\"") || html.contains("href=\"#task-multiply\""),
    "done jump targets a real node"
  );
  assert!(!html.contains("dependencies</p>"), "summary must not say N dependencies");
  assert!(!html.contains(r#"class="workflow-summary dim">3 tasks · 2 dependencies"#));
  assert!(html.contains(r#"data-workflow-step="add""#));
  assert!(html.contains(r#"data-workflow-step="multiply""#));
  assert!(html.contains(r#"data-workflow-step="summarize""#));
  assert!(html.contains(r#"id="task-add""#));
  assert!(html.contains("href=\"#task-summarize\""));
  // Exactly two fan-in edges into summarize (paths in the graph SVG — not the embedded client JS).
  let graph = html.split(r#"id="workflow-graph""#).nth(1).expect("graph card");
  let graph = graph.split("</svg>").next().expect("svg");
  assert_eq!(graph.matches("marker-end=\"url(#wf-arrow)\"").count(), 2);
  assert!(html.contains(r#"class="wf-arrowhead""#), "open chevron arrowheads, not filled triangles");
  // Fan-in ports land at distinct y on summarize (not a single shared tip).
  let mut end_ys = Vec::new();
  for part in graph.split(r#"class="wf-edge" d=""#) {
    if !part.contains(r#"marker-end="url(#wf-arrow)""#) {
      continue;
    }
    let Some(d) = part.split('"').next() else {
      continue;
    };
    if let Some(y) = d.rsplit(',').next() {
      end_ys.push(y.to_string());
    }
  }
  assert_eq!(end_ys.len(), 2, "expected two edge end ys, got {end_ys:?}");
  assert_ne!(end_ys[0], end_ys[1], "fan-in edges must enter at different heights: {end_ys:?}");

  // All-done graph: legend only lists Done, not unused statuses.
  assert!(html.contains(r#"<li class="wf-leg wf-leg-done""#));
  assert!(!html.contains(r#"<li class="wf-leg wf-leg-running""#));
  assert!(!html.contains(r#"<li class="wf-leg wf-leg-waiting""#));
  assert!(!html.contains(r#"<li class="wf-leg wf-leg-failed""#));
  assert!(!html.contains(r#"<li class="wf-leg wf-leg-stalled""#));
  assert!(!html.contains(r#"<li class="wf-leg wf-leg-skipped""#));

  // fruits fan-out — live session so Waiting→Ready (deps met) is not collapsed to Stalled
  let now = crate::daemon::paths::now_unix_secs();
  store.sessions.insert(
    "fruit1".into(),
    Session {
      id: "fruit1".into(),
      started_at: now.saturating_sub(5),
      ended_at: None,
      profile: Some("fruits".into()),
      kind: Some("workflow".into()),
      repo: "/tmp/r".into(),
      branch: "main".into(),
      skills: vec![],
      procs: vec![
        skill_proc(0, "categorize", "claude", ProcStatus::Ok),
        skill_proc(1, "sort_fruits", "claude", ProcStatus::Waiting),
        skill_proc(2, "sort_vegetables", "claude", ProcStatus::Waiting),
      ],
      last_seen_at: now,
      client_connected: true,
      run_pid: Some(1),
      workflow: Some(WorkflowMeta {
        nodes: vec![
          WorkflowNodeMeta {
            id: "categorize".into(),
            proc_index: Some(0),
            order: 0,
            needs: vec![],
            conditional: false,
            when_summary: None,
          },
          WorkflowNodeMeta {
            id: "sort_fruits".into(),
            proc_index: Some(1),
            order: 1,
            needs: vec!["categorize".into()],
            conditional: false,
            when_summary: None,
          },
          WorkflowNodeMeta {
            id: "sort_vegetables".into(),
            proc_index: Some(2),
            order: 2,
            needs: vec!["categorize".into()],
            conditional: false,
            when_summary: None,
          },
        ],
      }),
      parent_session: None,
    },
  );
  let fruits = session_page(&store, "fruit1").expect("fruits");
  assert!(
    fruits.contains(r#">1 done</a>"#) && fruits.contains(r#">2 ready</a>"#),
    "ready stays separate from waiting in the headline"
  );
  assert!(fruits.contains("data-tip="), "nodes carry instant tooltips");
  assert!(fruits.contains("Ready — dependencies finished; not started yet"), "ready tip explains why the node is idle");
  assert_eq!(
    fruits
      .split(r#"id="workflow-graph""#)
      .nth(1)
      .unwrap()
      .split("</svg>")
      .next()
      .unwrap()
      .matches("marker-end=\"url(#wf-arrow)\"")
      .count(),
    2
  );
  assert!(fruits.contains(r#"data-workflow-step="categorize""#));

  // code-review conditional gate
  store.sessions.insert(
    "rev001".into(),
    Session {
      id: "rev001".into(),
      started_at: 1,
      ended_at: None,
      profile: Some("code-review".into()),
      kind: Some("workflow".into()),
      repo: "/tmp/r".into(),
      branch: "main".into(),
      skills: vec![],
      procs: vec![
        skill_proc(0, "probe_credentials", "claude", ProcStatus::Ok),
        skill_proc(1, "review", "claude", ProcStatus::Skipped),
      ],
      last_seen_at: 1,
      client_connected: true,
      run_pid: Some(1),
      workflow: Some(WorkflowMeta {
        nodes: vec![
          WorkflowNodeMeta {
            id: "probe_credentials".into(),
            proc_index: Some(0),
            order: 0,
            needs: vec![],
            conditional: false,
            when_summary: None,
          },
          WorkflowNodeMeta {
            id: "review".into(),
            proc_index: Some(1),
            order: 1,
            needs: vec!["probe_credentials".into()],
            conditional: true,
            when_summary: Some("Runs only if probe_credentials.ok = true".into()),
          },
        ],
      }),
      parent_session: None,
    },
  );
  let review = session_page(&store, "rev001").expect("review");
  assert!(review.contains(r#"class="wf-gate""#), "gate marker");
  assert!(review.contains(">when</span>"), "gate label is the word when, not a diamond");
  assert!(
    review.contains("Runs only when its gate passes"),
    "gate tooltip is generic — no raw gate literals in the browser"
  );
  // Node ids may appear; gate *expressions* must not.
  assert!(!review.contains("probe_credentials.ok"), "no gate operand leakage");
  assert!(!review.contains("Runs only if"), "no authored when_summary in the page");
  assert!(!review.contains("Conditional task"), "no cryptic Conditional task label");
  assert!(!review.contains(''), "no diamond glyph");
  assert!(review.contains(r#"wf-skipped"#));
  assert_eq!(
    review
      .split(r#"id="workflow-graph""#)
      .nth(1)
      .unwrap()
      .split("</svg>")
      .next()
      .unwrap()
      .matches("marker-end=\"url(#wf-arrow)\"")
      .count(),
    1
  );

  // Waiting tip names the blocker (WEB-UI §4 disclosure; not a bare "1 waiting on").
  let now = crate::daemon::paths::now_unix_secs();
  store.sessions.insert(
    "wait1".into(),
    Session {
      id: "wait1".into(),
      started_at: now.saturating_sub(5),
      ended_at: None,
      profile: Some("arith".into()),
      kind: Some("workflow".into()),
      repo: "/tmp/r".into(),
      branch: "main".into(),
      skills: vec![],
      procs: vec![
        skill_proc(0, "add", "claude", ProcStatus::Running),
        skill_proc(1, "summarize", "grok", ProcStatus::Waiting),
      ],
      last_seen_at: now,
      client_connected: true,
      run_pid: Some(1),
      workflow: Some(WorkflowMeta {
        nodes: vec![
          WorkflowNodeMeta {
            id: "add".into(),
            proc_index: Some(0),
            order: 0,
            needs: vec![],
            conditional: false,
            when_summary: None,
          },
          WorkflowNodeMeta {
            id: "summarize".into(),
            proc_index: Some(1),
            order: 1,
            needs: vec!["add".into()],
            conditional: false,
            when_summary: None,
          },
        ],
      }),
      parent_session: None,
    },
  );
  let waiting = session_page(&store, "wait1").expect("waiting");
  assert!(waiting.contains("Waiting on:"), "waiting tip explains blockers");
  assert!(waiting.contains("waiting on add"), "meta line names the blocker");
  assert!(waiting.contains("margin-inline: auto"), "graph stage centers when it fits");

  // Force-stopped is distinct from a natural failure (✕ vs ✗) but shares the fail/red accent.
  store.sessions.insert(
    "stop1".into(),
    Session {
      id: "stop1".into(),
      started_at: now.saturating_sub(30),
      ended_at: Some(now),
      profile: Some("demo-pr".into()),
      kind: Some("definition".into()),
      repo: "/tmp/r".into(),
      branch: "main".into(),
      skills: vec![],
      procs: vec![
        {
          let mut p = skill_proc(0, "cursor-build", "cursor", ProcStatus::Fail);
          p.fail_reason = Some(crate::failure::reason::FORCE_STOPPED.into());
          p.detail = Some("force-stopped from the session browser".into());
          p
        },
        {
          let mut p = skill_proc(1, "claude-run", "claude", ProcStatus::Fail);
          p.fail_reason = Some(crate::failure::reason::HARNESS_NONZERO.into());
          p
        },
      ],
      last_seen_at: now,
      client_connected: false,
      run_pid: None,
      workflow: Some(WorkflowMeta {
        nodes: vec![
          WorkflowNodeMeta {
            id: "cursor-build".into(),
            proc_index: Some(0),
            order: 0,
            needs: vec![],
            conditional: false,
            when_summary: None,
          },
          WorkflowNodeMeta {
            id: "claude-run".into(),
            proc_index: Some(1),
            order: 1,
            needs: vec![],
            conditional: false,
            when_summary: None,
          },
        ],
      }),
      parent_session: None,
    },
  );
  let stopped = session_page(&store, "stop1").expect("force-stopped page");
  let summary =
    stopped.split(r#"class="workflow-summary dim">"#).nth(1).and_then(|s| s.split("</p>").next()).unwrap_or("?");
  assert!(stopped.contains(r#"wf-force-stopped"#), "force-stopped node class; summary={summary}");
  assert!(stopped.contains("Force-stopped"), "force-stopped label; summary={summary}");
  assert!(summary.contains("force-stopped"), "summary counts force-stopped separately: {summary}");
  assert!(summary.contains("failed"), "natural failure stays failed: {summary}");
  assert!(stopped.contains("wf-leg-force-stopped"), "legend lists force-stopped");

  // Flat skill session (no authored DAG): still gets a job graph from its skill proc.
  let flat = store_with_cast_proc(ProcStatus::Ok);
  let flat_html = session_page(&flat, "castab").expect("flat");
  assert!(flat_html.contains(r#"id="workflow-graph""#), "every job with skills gets a graph");
  assert!(flat_html.contains("Job graph"), "card title is Job graph");
  assert!(flat_html.contains(r#"data-workflow-step="add""#) || flat_html.contains("wf-node"), "skill node present");

  // Client wiring
  let js = live_client_js();
  assert!(js.contains("function updateWorkflowGraph"));
  assert!(js.contains("function activateWorkflowTask"));
  assert!(js.contains("function initWorkflowGraph"));
  assert!(js.contains("function wfLegendHtml"));
  assert!(js.contains("function wfBuildGraphHtml"), "late graph creation without reload");
  assert!(js.contains("function wfNodeTip"), "useful node tooltips");
  assert!(js.contains("function wfSummaryHtml"), "status counters are jump links");
  assert!(js.contains("a.wf-jump"), "summary jump click wiring");
  assert!(js.contains("history.pushState"), "task clicks push history");
  assert!(js.contains("pendingWorkflowStep"), "pre-registration pending selection");
  assert!(js.contains("Task details are not available yet"), "pending status copy");
}