nornir 0.4.20

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
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
//! egui app — paints the lanes + edges and the "time machine" panel.

use std::path::PathBuf;
use std::sync::OnceLock;

use anyhow::Result;
use eframe::egui::{
    self, Align2, Color32, ColorImage, FontId, Pos2, Rect, CornerRadius, Sense, Stroke,
    TextureHandle, TextureOptions, Vec2,
};
use uuid::Uuid;

use super::graph::{draw_dep_graph, DepGraphView};
use super::model::{Timeline, load_timeline};
use super::timetravel::{TimeTravelState, draw_timetravel};

const SPLASH_DURATION_SECS: f32 = 2.5;
const SPLASH_FADE_SECS: f32 = 1.0;
const WATERMARK_ALPHA: u8 = 22;

/// Human build identifier for the viz client, e.g.
/// `v0.4.11 (a1b2c3d, built 2026-06-12 22:50 UTC)`. The SHA + build time come
/// from `build.rs` (`NORNIR_BUILD_SHA`/`NORNIR_BUILD_EPOCH`); they change every
/// build, so this is how you tell a fresh client from a stale one. Shown in the
/// window title and the ℹ About popup, and emitted in `state_json["about"]`.
pub fn client_build() -> String {
    let ver = env!("CARGO_PKG_VERSION");
    let sha = option_env!("NORNIR_BUILD_SHA").unwrap_or("unknown");
    let epoch: i64 = option_env!("NORNIR_BUILD_EPOCH")
        .and_then(|s| s.parse().ok())
        .unwrap_or(0);
    let when = chrono::DateTime::<chrono::Utc>::from_timestamp(epoch, 0)
        .map(|t| t.format("%Y-%m-%d %H:%M UTC").to_string())
        .unwrap_or_default();
    if when.is_empty() {
        format!("v{ver} ({sha})")
    } else {
        format!("v{ver} ({sha}, built {when})")
    }
}

// Media moved to `.nornir/assets/` in 1e8d062; the old `assets/` path 404'd and
// broke the `viz` build.
static NORNIR_WEBP_BYTES: &[u8] = include_bytes!("../../.nornir/assets/nornir.webp");

fn decode_nornir() -> Option<ColorImage> {
    static CACHE: OnceLock<Option<ColorImage>> = OnceLock::new();
    CACHE
        .get_or_init(|| {
            let img = image::load_from_memory(NORNIR_WEBP_BYTES).ok()?;
            let rgba = img.to_rgba8();
            let (w, h) = (rgba.width() as usize, rgba.height() as usize);
            Some(ColorImage::from_rgba_unmultiplied([w, h], rgba.as_raw()))
        })
        .clone()
}

#[derive(PartialEq, Eq, Clone, Copy)]
enum Tab {
    Timeline,
    DepGraph,
    CallGraph,
    Funnel,
    TimeTravel,
    LiveRun,
    Release,
    Knowledge,
    Warehouse,
    Mcp,
    Search,
    Gates,
    Bench,
    Test,
    Leaderboard,
    Security,
}

impl Tab {
    /// Every tab, in header order — for the external state dump.
    const ALL: [Tab; 16] = [
        Tab::Timeline,
        Tab::DepGraph,
        Tab::CallGraph,
        Tab::Funnel,
        Tab::TimeTravel,
        Tab::LiveRun,
        Tab::Release,
        Tab::Knowledge,
        Tab::Warehouse,
        Tab::Mcp,
        Tab::Search,
        Tab::Gates,
        Tab::Bench,
        Tab::Test,
        Tab::Leaderboard,
        Tab::Security,
    ];

    /// Resolve a tab from its `state_json()["tab"]` debug name (the names in
    /// [`Tab::ALL`]). `None` for an unknown name. Used by the robot-UI-tester
    /// control channel (`viz.click`) and the headless test injectors.
    fn from_name(name: &str) -> Option<Tab> {
        Tab::ALL.into_iter().find(|t| format!("{t:?}") == name)
    }
}

impl std::fmt::Debug for Tab {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Tab::Timeline => "Timeline",
            Tab::DepGraph => "DepGraph",
            Tab::CallGraph => "CallGraph",
            Tab::Funnel => "Funnel",
            Tab::TimeTravel => "TimeTravel",
            Tab::LiveRun => "LiveRun",
            Tab::Release => "Release",
            Tab::Knowledge => "Knowledge",
            Tab::Warehouse => "Warehouse",
            Tab::Mcp => "Mcp",
            Tab::Search => "Search",
            Tab::Gates => "Gates",
            Tab::Bench => "Bench",
            Tab::Test => "Test",
            Tab::Leaderboard => "Leaderboard",
            Tab::Security => "Security",
        };
        f.write_str(s)
    }
}

/// Where the timeline comes from: a local Iceberg warehouse (embedded, opens
/// it directly) or a running `nornir-server` (thin client over the
/// `Viz.Timeline` gRPC). Both yield the same [`Timeline`], so the rest of the
/// app is source-agnostic.
pub enum Source {
    Local(PathBuf),
    Remote { endpoint: String, token: String },
}

impl Source {
    fn load(&self, workspace: &str) -> Result<Timeline> {
        match self {
            Source::Local(root) => load_timeline(root, workspace),
            Source::Remote { endpoint, token } => {
                super::remote::fetch_timeline(endpoint, token, workspace)
            }
        }
    }
}

pub struct UrdrThreadsApp {
    source: Source,
    source_label: String,
    workspace_name: String,
    /// Local checkout root the Knowledge/Security tabs scan `workspace_root/<repo>`
    /// under. Kept so a workspace switch can re-scope those local-disk scanners.
    workspace_root: PathBuf,
    /// Workspaces offered in the picker (server-registered for remote; just the
    /// current one for local). Switching re-scopes every server-backed tab.
    workspaces: Vec<String>,
    timeline: Result<Timeline>,
    selected: Option<Uuid>,
    /// Repo selected in the Dep Graph tab (for the cargo-deps drill-down panel).
    dep_selected_repo: Option<String>,
    /// Dep Graph tab view state — deep-closure toggle (C5), direct/transitive
    /// edge classification (C7), pan/zoom + click-collapse navigation (I3).
    dep_view: DepGraphView,
    last_reload: std::time::Instant,
    tab: Tab,
    started_at: std::time::Instant,
    nornir_tex: Option<TextureHandle>,
    timetravel: TimeTravelState,
    live: super::live::LiveRunState,
    /// 🚀 Release tab — the `release_events` op DAG (op-log + lit-up dep-graph).
    release: super::release_tab::ReleaseTabState,
    /// 🧪 Test tab (C6) — the `test_results` matrix (per-repo green/red board).
    test: super::test_tab::TestTabState,
    /// 🏆 Leaderboard tab (H5) — the `agent_model_runs` bake-off, models ranked
    /// by score + tokens/s.
    leaderboard: super::leaderboard_tab::LeaderboardTabState,
    knowledge: super::knowledge::KnowledgeState,
    warehouse: super::warehouse_tab::WarehouseBrowser,
    callgraph: super::callgraph::CallGraphState,
    funnel: super::funnel_tab::FunnelTabState,
    mcp: super::mcp_tab::McpTab,
    /// Server-backed clickable tabs (remote mode only).
    search: super::ops_tabs::SearchState,
    gates: super::ops_tabs::GatesState,
    bench: super::ops_tabs::BenchState,
    security: super::security_tab::SecurityTab,
    /// 🚦 Pre-flight capability checks, surfaced as a popup after the splash.
    preflight: super::preflight::Preflight,
    ws_panel: super::ops_tabs::WorkspacePanel,
    /// Configured repo names (for the Gates/Bench repo pickers).
    repos: Vec<String>,
    /// Auto-reload the timeline (and refresh the warehouse table list) on a
    /// timer so a server-monitored workspace animates as it republishes.
    auto_refresh: bool,
    refresh_secs: u64,
    /// Human-readable connection status (set at build: "connected: N
    /// workspace(s)" / "CONNECT FAILED: …" / "local (no server)"). Surfaced in
    /// the UI header AND the external state dump so the test matrix sees it.
    connect_status: String,
    /// Throttle for the external state dump (`NORNIR_VIZ_STATE`).
    last_dump: std::time::Instant,
    /// Last (tab, workspace) we logged a click for — change detection.
    last_click: (Tab, String),
    /// TOTAL user-action debug log (ring buffer + stderr + file sink). Always-on;
    /// every tab switch / button / query / RPC pushes here. See `action_log.rs`.
    action_log: super::action_log::ActionLog,
    /// Whether the bottom action-trail overlay panel is shown (toggle in the bar).
    show_action_log: bool,
    /// Whether the ℹ About popup window is open (toggle in the top bar).
    show_about: bool,
    /// Cached `Health.Ping` server identity (version + repo count), fetched lazily
    /// the first time the About popup opens in remote mode. `None` until queried;
    /// `Some(Err)` if the ping failed.
    server_info: Option<Result<super::remote::ServerInfo, String>>,
    /// The **active facett palette** (C8) — the single app-wide theme every pane
    /// paints with. The top-bar picker mutates it; on change we re-apply egui
    /// `Visuals` and broadcast it to every tab (`broadcast_palette`) so the whole
    /// viz re-skins together. Emitted in `state_json["palette"]` (LAW #6) so a
    /// switch is observable headlessly.
    palette: super::facett_theme::Theme,
    /// Whether `palette`'s visuals have been pushed to the egui `Context` for the
    /// current value (so we only call `set_visuals` on change, not every frame).
    palette_applied: bool,
}

impl UrdrThreadsApp {
    pub fn new(warehouse_root: PathBuf, workspace_name: String) -> Self {
        Self::with_repos(warehouse_root, workspace_name, PathBuf::new(), Vec::new())
    }

    /// Extended constructor: also seed the Knowledge tab with a workspace
    /// root (the parent containing repo dirs) and the configured repo names.
    pub fn with_repos(
        warehouse_root: PathBuf,
        workspace_name: String,
        workspace_root: PathBuf,
        repos: Vec<String>,
    ) -> Self {
        let log_dir = warehouse_root
            .parent()
            .map(|p| p.join("logs"))
            .unwrap_or_else(|| warehouse_root.join("logs"));
        let label = warehouse_root.display().to_string();
        // Local mode has a single workspace — no server set to auto-select from.
        Self::build(Source::Local(warehouse_root), label, workspace_name, None, workspace_root, repos, log_dir)
    }

    /// Thin-client constructor: load the timeline from a running `nornir-server`
    /// over gRPC instead of opening a local warehouse. The live-run tab streams
    /// the active release run from the server over `Release.Progress` (no local
    /// log dir needed) — so a viz pointed at a remote server (e.g. over Tailscale)
    /// animates the run in real time, the same as a local one.
    pub fn with_remote(
        endpoint: String,
        token: String,
        workspace_name: String,
        workspace_root: PathBuf,
        repos: Vec<String>,
    ) -> Self {
        Self::with_remote_preferring(endpoint, token, workspace_name, None, workspace_root, repos)
    }

    /// As [`with_remote`](Self::with_remote), but with a `preferred_workspace`
    /// hint (derived from `--config`'s `workspace_<name>` path): when no explicit
    /// `--workspace`/`NORNIR_WORKSPACE` is given, the picker selects this
    /// workspace **if the server registers it**, instead of the alphabetically
    /// first one. Stops a config-scoped viz (e.g. `workspace_njord`) from
    /// silently opening an unrelated workspace (`holger`) just because it sorts
    /// first. Falls back to first when the hint is absent or unregistered.
    pub fn with_remote_preferring(
        endpoint: String,
        token: String,
        workspace_name: String,
        preferred_workspace: Option<String>,
        workspace_root: PathBuf,
        repos: Vec<String>,
    ) -> Self {
        let label = format!("server {endpoint}");
        Self::build(
            Source::Remote { endpoint, token },
            label,
            workspace_name,
            preferred_workspace,
            workspace_root,
            repos,
            PathBuf::new(),
        )
    }

    fn build(
        source: Source,
        source_label: String,
        mut workspace_name: String,
        preferred_workspace: Option<String>,
        workspace_root: PathBuf,
        repos: Vec<String>,
        log_dir: PathBuf,
    ) -> Self {
        // Picker contents come FIRST so the initial selection is a real
        // workspace: remote mode lists the server's registered set and, when
        // launched without an explicit --workspace/NORNIR_WORKSPACE, selects
        // the first one (never injecting a placeholder into the picker). An
        // explicit name stays selectable even if unregistered (e.g. the
        // server's served default workspace).
        let mut connect_status = String::from("local (no server)");
        let workspaces = match &source {
            Source::Remote { endpoint, token } => {
                let mut ws = match super::remote::list_workspaces(endpoint, token) {
                    Ok(ws) => {
                        eprintln!("nornir-viz: Workspaces.List → {} workspace(s): {ws:?}", ws.len());
                        connect_status = format!("connected {endpoint}: {} workspace(s)", ws.len());
                        ws
                    }
                    Err(e) => {
                        eprintln!("nornir-viz: Workspaces.List FAILED (picker empty): {e:#}");
                        connect_status = format!("CONNECT FAILED {endpoint}: {e:#}");
                        Vec::new()
                    }
                };
                ws.sort();
                ws.dedup();
                if workspace_name.is_empty() {
                    // Prefer the config-derived workspace (e.g. `workspace_njord`
                    // → `njord`) when the server actually registers it, so a
                    // config-scoped viz opens the matching workspace rather than
                    // whichever sorts first. Otherwise fall back to the first.
                    let preferred = preferred_workspace
                        .as_deref()
                        .filter(|p| ws.iter().any(|w| w == p))
                        .map(str::to_string);
                    if let Some(p) = preferred {
                        eprintln!(
                            "nornir-viz: auto-selected workspace `{p}` (matched --config)"
                        );
                        workspace_name = p;
                    } else if let Some(first) = ws.first() {
                        workspace_name = first.clone();
                        eprintln!("nornir-viz: auto-selected workspace `{workspace_name}` (first registered)");
                    }
                } else if !ws.iter().any(|w| w == &workspace_name) {
                    ws.push(workspace_name.clone());
                }
                ws
            }
            Source::Local(_) => vec![workspace_name.clone()],
        };

        // Remote without a local config → get the repo list (for the repo-driven
        // tabs: Security / Knowledge / Gates / Bench) from the server's workspace
        // record, so the buttons populate without passing --config.
        let mut repos = repos;
        if repos.is_empty() {
            if let Source::Remote { endpoint, token } = &source {
                if let Ok(info) = super::remote::get_workspace(endpoint, token, &workspace_name) {
                    repos = info.members.into_iter().map(|(m, _)| m).collect();
                    eprintln!("nornir-viz: repos from server `{workspace_name}` → {repos:?}");
                }
            }
        }

        let timeline = source.load(&workspace_name);
        // Durable source = the warehouse `release_events` table (LAW
        // persist-to-warehouse-stream-not-tmp): local mode hydrates the live pane
        // from the warehouse on load/reload and tails the workspace log dir as a
        // fast live accelerator; remote mode streams the run from the server over
        // Release.Progress (the server's warehouse is the durable source).
        let live = match &source {
            Source::Remote { endpoint, token } => super::live::LiveRunState::new_remote(
                endpoint.clone(),
                token.clone(),
                workspace_name.clone(),
            ),
            Source::Local(p) => super::live::LiveRunState::new(log_dir, p.clone()),
        };
        // The warehouse browser opens the warehouse directly when local, else
        // browses it over the server's Warehouse.Tables/Scan gRPC.
        let warehouse = match &source {
            Source::Local(p) => super::warehouse_tab::WarehouseBrowser::local(p.clone()),
            Source::Remote { endpoint, token } => super::warehouse_tab::WarehouseBrowser::remote(
                endpoint.clone(),
                token.clone(),
                workspace_name.clone(),
            ),
        };
        let callgraph = match &source {
            Source::Local(p) => super::callgraph::CallGraphState::local(p.clone()),
            Source::Remote { endpoint, token } => super::callgraph::CallGraphState::remote(
                endpoint.clone(),
                token.clone(),
                workspace_name.clone(),
            ),
        };
        let funnel = match &source {
            Source::Local(p) => super::funnel_tab::FunnelTabState::local(p.clone()),
            Source::Remote { endpoint, token } => super::funnel_tab::FunnelTabState::remote(
                endpoint.clone(),
                token.clone(),
                workspace_name.clone(),
            ),
        };
        let mcp = match &source {
            Source::Local(p) => super::mcp_tab::McpTab::local(p.clone()),
            Source::Remote { endpoint, token } => {
                super::mcp_tab::McpTab::remote(endpoint.clone(), token.clone(), workspace_name.clone())
            }
        };
        // 🚀 Release tab reads `release_events` from the local warehouse directly;
        // remote mode reads the same rows over Viz.ReleaseEvents.
        let release = match &source {
            Source::Local(p) => super::release_tab::ReleaseTabState::local(p.clone()),
            Source::Remote { endpoint, token } => super::release_tab::ReleaseTabState::remote(
                endpoint.clone(),
                token.clone(),
                workspace_name.clone(),
            ),
        };
        // 🧪 Test tab reads `test_results` from the local warehouse directly;
        // remote mode shows a note (no Test.Results RPC yet) — same split as Release.
        let test = match &source {
            Source::Local(p) => super::test_tab::TestTabState::local(p.clone()),
            Source::Remote { endpoint, .. } => {
                super::test_tab::TestTabState::remote(endpoint.clone())
            }
        };
        // 🏆 Leaderboard reads `agent_model_runs` from the local warehouse;
        // remote mode reads the same rows over Viz.BakeoffResults — same split.
        let leaderboard = match &source {
            Source::Local(p) => super::leaderboard_tab::LeaderboardTabState::local(p.clone()),
            Source::Remote { endpoint, token } => {
                super::leaderboard_tab::LeaderboardTabState::remote(
                    endpoint.clone(),
                    token.clone(),
                    workspace_name.clone(),
                )
            }
        };
        // 🗺 Knowledge map: local mode scans `workspace_root/<repo>` here; remote
        // mode has no checkout, so the server runs the scan over Viz.Knowledge.
        let knowledge = match &source {
            Source::Local(_) => {
                super::knowledge::KnowledgeState::new(workspace_root.clone(), repos.clone())
            }
            Source::Remote { endpoint, token } => super::knowledge::KnowledgeState::new_remote(
                workspace_root.clone(),
                repos.clone(),
                endpoint.clone(),
                token.clone(),
                workspace_name.clone(),
            ),
        };
        // 📈 Bench tab (P1.3): history charts drive the server's Bench.History
        // (remote); the 📡 LIVE telemetry panel reads `bench_telemetry`/`bench_runs`
        // from the local warehouse as a bench runs — same local/remote split.
        let bench = match &source {
            Source::Local(p) => super::ops_tabs::BenchState::local(p.clone()),
            Source::Remote { endpoint, .. } => {
                super::ops_tabs::BenchState::remote(endpoint.clone())
            }
        };
        // TOTAL action log (N5). The durable warehouse `viz_actions` sink is
        // attached in LOCAL mode (the viz owns the warehouse there); remote mode
        // keeps file/stderr only — the server is the durable side. The `/tmp`
        // file stays the fast live-channel regardless (write both, per the law).
        let mut action_log = super::action_log::ActionLog::new();
        if let Source::Local(p) = &source {
            action_log.attach_warehouse(p.clone());
        }
        action_log.set_context(&workspace_name, "Timeline");

        // Thin/remote client? (borrow before `source` is moved into the struct)
        let preflight_thin = matches!(&source, Source::Remote { .. });
        let mut app = Self {
            source,
            source_label,
            workspace_name,
            workspace_root: workspace_root.clone(),
            workspaces,
            timeline,
            selected: None,
            dep_selected_repo: None,
            dep_view: DepGraphView::new(),
            last_reload: std::time::Instant::now(),
            tab: Tab::Timeline,
            started_at: std::time::Instant::now(),
            nornir_tex: None,
            timetravel: TimeTravelState::default(),
            live,
            release,
            test,
            leaderboard,
            knowledge,
            warehouse,
            callgraph,
            funnel,
            mcp,
            search: super::ops_tabs::SearchState::default(),
            gates: super::ops_tabs::GatesState::default(),
            bench,
            security: super::security_tab::SecurityTab::new(workspace_root, repos.clone()),
            preflight: super::preflight::Preflight::run(preflight_thin),
            ws_panel: super::ops_tabs::WorkspacePanel::default(),
            repos,
            auto_refresh: true,
            refresh_secs: 5,
            connect_status,
            last_dump: std::time::Instant::now(),
            last_click: (Tab::Timeline, String::new()),
            action_log,
            show_action_log: false,
            show_about: false,
            server_info: None,
            palette: super::facett_theme::Theme::default(),
            palette_applied: false,
        };
        // Seed every pane with the default palette so they're palette-driven from
        // frame one (later switches go through `set_palette`).
        app.broadcast_palette();
        app
    }

    /// Set the app-wide facett palette (C8) and broadcast it to every pane so the
    /// whole viz re-skins together. Marks the egui `Visuals` stale so the next
    /// `draw_ui` re-applies them. Idempotent — a no-op when the palette is
    /// unchanged. `pub` so the headless test matrix can switch the palette and
    /// then assert `state_json["palette"]` + each pane's `palette` changed.
    pub fn set_palette(&mut self, palette: super::facett_theme::Theme) {
        if palette == self.palette {
            return;
        }
        self.palette = palette;
        self.palette_applied = false;
        self.broadcast_palette();
        super::trace::emit_event("ui.palette", &serde_json::json!({ "palette": palette.name }));
    }

    /// Push the active palette into every pane's `theme` field, so each pane's
    /// custom painting (status fills, accents, zebra/hover/selection, gridlines)
    /// uses the same facett palette (C8). Called on construction + every switch.
    fn broadcast_palette(&mut self) {
        let p = self.palette;
        self.test.set_palette(p);
        self.release.set_palette(p);
        self.leaderboard.set_palette(p);
        self.live.set_palette(p);
        self.knowledge.set_palette(p);
        self.warehouse.set_palette(p);
        self.mcp.set_palette(p);
        self.callgraph.set_palette(p);
        self.funnel.set_palette(p);
        self.security.set_palette(p);
        self.preflight.set_palette(p);
        self.search.set_palette(p);
        self.gates.set_palette(p);
        self.bench.set_palette(p);
        self.timetravel.set_palette(p);
        self.dep_view.set_palette(p);
    }

    /// Build the external state snapshot — every picker's options + selection,
    /// the tab set, timeline/warehouse population, connection status, and any
    /// empty-state placeholders. Written to `NORNIR_VIZ_STATE` so the test
    /// matrix (and the operator) can see exactly what the UI is showing without
    /// a screen. See `dump_state`.
    ///
    /// `pub` so the headless test matrix in `tests/viz_matrix.rs` can call
    /// this without starting a GUI — construct the app with `with_repos` /
    /// `with_remote`, then call `state_json()` directly to get the full UI
    /// state as a JSON value (same JSON the operator sees via
    /// `NORNIR_VIZ_STATE`). No display, no `eframe::run` needed.
    pub fn state_json(&self) -> serde_json::Value {
        let (releases, tl_err) = match &self.timeline {
            Ok(tl) => (tl.lanes.iter().map(|l| l.nodes.len()).sum::<usize>(), None),
            Err(e) => (0, Some(format!("{e:#}"))),
        };
        let mut placeholders = Vec::new();
        if releases == 0 {
            placeholders.push("no releases recorded yet".to_string());
        }
        serde_json::json!({
            "source": self.source_label,
            "connect_status": self.connect_status,
            "tab": format!("{:?}", self.tab),
            "all_tabs": Tab::ALL.iter().map(|t| format!("{t:?}")).collect::<Vec<_>>(),
            // 🎨 The app-wide facett palette (C8) — the single active theme every
            // pane paints with. Switching it re-skins the whole viz; the change is
            // observable headlessly here + in each pane's own `palette` key (LAW #6).
            "palette": self.palette.name,
            "palettes": super::facett_theme::Theme::names(),
            "workspace_picker": {
                "options": self.workspaces,
                "selected": self.workspace_name,
                "count": self.workspaces.len(),
            },
            "repos": self.repos,
            "knowledge": self.knowledge.state_json(),
            // 🗂 Funnel tab (LAW 6): selected plan + per-plan node/edge/ready
            // counts + the E1 demo block, so the headless matrix sees the
            // funnel DAG's data (it contributed nothing before E1).
            "funnel": self.funnel.state_json(),
            // 📡 Live Run (C3): the live release-run pane — the durable warehouse
            // `release_events` baseline it hydrated from (survives a reboot, visible
            // to other clients), plus the run header + rendered event lines, so the
            // headless matrix proves the pane reads from the warehouse, not `/tmp`.
            "live": self.live.state_json(),
            // 🚀 Release op DAG (B3/B4): the release-op rows + per-component status
            // the tab renders, so the headless matrix sees the lit-up graph's data.
            "release": self.release.state_json(),
            // 🧪 Test matrix (C6): per-run green/red summaries + the selected
            // run's cases, so the headless matrix sees the rendered board's data.
            "test": self.test.state_json(),
            // 🏆 Leaderboard (H5): the bake-off runs + the selected run's ranked
            // models (by score + tokens/s) + the winner, so the headless matrix
            // sees the rendered leaderboard's data.
            "leaderboard": self.leaderboard.state_json(),
            // ℹ About popup (C1): client version + endpoint + workspace + warehouse
            // + (remote) server version — the real identity fields the popup shows.
            "about": self.about_info(),
            "timeline": { "releases": releases, "error": tl_err },
            // 🔗 Dep Graph (C5/C7/I3): the laid-out graph the tab paints — deep
            // toggle, node positions, edges classified direct vs transitive, and
            // the collapse set (LAW #6). Computed fresh from the current timeline
            // + view settings so the headless matrix sees it even without a draw.
            "dep_graph": self.dep_graph_state(),
            // ⏳ Time Travel (C4): the cursor (release idx + pinned release), the
            // text⇄graph view mode, and — in graph mode — the dependency graph as
            // it was at that release (reusing depgraph_layout's nodes/positions +
            // direct/transitive edge classification). So the headless matrix sees
            // the time-pinned, coloured graph without a draw.
            "timetravel": self.timetravel_state(),
            // 🔍 Search (LAW 6): the BM25 query + corpus + symbol/vector/call-graph
            // form fields AND the rendered result counts/rows, so an agent reads
            // back exactly what's typed and what's shown.
            "search": self.search.state_json(),
            // 🚦 Gates (LAW 6): the selected/typed repo + the rendered gate report
            // (passed/failed gate names) + whether a regression trace is loaded.
            "gates": self.gates.state_json(),
            // 📈 Bench (LAW 6): the selected repo + metric dropdowns + the loaded
            // history series (per-run date/version/value rows) for the chosen metric.
            "bench": self.bench.state_json(),
            // 🗄 Warehouse (LAW 6): the table list + selected table + chart toggle
            // and chosen columns + the loaded preview shape (columns + row count).
            "warehouse": self.warehouse.state_json(),
            // 📞 MCP (LAW 6): the per-tool usage rows (calls/errors/avg-ms) + total.
            "mcp": self.mcp.state_json(),
            // 🛡 Security (LAW 6): the scan-button repos + which is scanning + the
            // rendered SBOM/vuln/license result.
            "security": self.security.state_json(),
            "preflight": self.preflight.state_json(),
            // Kept for back-compat with existing consumers; the full table list +
            // selection now also lives under `warehouse`.
            "warehouse_tables": self.warehouse.table_names(),
            "placeholders": placeholders,
            // The action-log trail: total count + the last few entries, so the
            // headless test matrix + the operator see "what was clicked" in the
            // same dump as the rest of the UI state.
            "action_log": {
                "file": self.action_log.file_path(),
                "count": self.action_log.count(),
                "recent": self.action_log.recent(12).iter()
                    .map(|e| format!("{} [{}] {}", e.stamp, e.kind.tag(), e.detail))
                    .collect::<Vec<_>>(),
                // N5 — the durable side: this session's id + its recent actions
                // read BACK from the warehouse `viz_actions` table (proves the
                // trail is durable + queryable, not just a /tmp file). Empty
                // array in remote mode (no local warehouse attached).
                "session_id": self.action_log.session_id(),
                "warehouse_recent": serde_json::from_str::<serde_json::Value>(
                    &self.action_log.warehouse_recent_json(12),
                ).unwrap_or(serde_json::Value::Array(Vec::new())),
            },
        })
    }

    /// The About-popup identity block (C1): always carries SOMETHING real — the
    /// **client version** (`CARGO_PKG_VERSION`), the **endpoint**, the **selected
    /// workspace**, and the **warehouse path / mode**. In remote mode it also
    /// carries the **server version** from a cached `Health.Ping` (queried the
    /// first time the popup opens); until queried, `server_version` is null and a
    /// note flags it as a pending RPC.
    pub fn about_info(&self) -> serde_json::Value {
        let (endpoint, warehouse, mode) = match &self.source {
            Source::Local(p) => (String::new(), p.display().to_string(), "local"),
            Source::Remote { endpoint, .. } => (endpoint.clone(), String::new(), "remote"),
        };
        let (server_version, server_repo_count, server_note) = match &self.server_info {
            Some(Ok(info)) => (
                Some(info.version.clone()),
                Some(info.repo_count),
                None,
            ),
            Some(Err(e)) => (None, None, Some(format!("Health.Ping failed: {e}"))),
            None if mode == "remote" => {
                (None, None, Some("server version: open About to query Health.Ping".to_string()))
            }
            None => (None, None, None),
        };
        serde_json::json!({
            "client_version": env!("CARGO_PKG_VERSION"),
            "client_build": client_build(),
            "build_sha": option_env!("NORNIR_BUILD_SHA").unwrap_or("unknown"),
            "mode": mode,
            "endpoint": endpoint,
            "workspace": self.workspace_name,
            "warehouse": warehouse,
            "source_label": self.source_label,
            "connect_status": self.connect_status,
            "server_version": server_version,
            "server_repo_count": server_repo_count,
            "server_note": server_note,
        })
    }

    /// The 🔗 Dep Graph tab's laid-out structure for `state_json` (LAW #6):
    /// deep toggle, classified edges, node positions, collapse set. Computed
    /// from the current timeline + view settings; `Null` when no timeline /
    /// snapshot is loaded.
    fn dep_graph_state(&self) -> serde_json::Value {
        match &self.timeline {
            Ok(tl) => self.dep_view.state_json_for(tl, self.selected),
            Err(_) => serde_json::Value::Null,
        }
    }

    /// The ⏳ Time Travel tab's cursor + (graph-mode) time-pinned dependency
    /// graph for `state_json` (LAW #6). `Null` when no timeline is loaded.
    fn timetravel_state(&self) -> serde_json::Value {
        match &self.timeline {
            Ok(tl) => self.timetravel.state_json(tl),
            Err(_) => serde_json::Value::Null,
        }
    }

    /// Lazily fetch the server's `Health.Ping` identity (remote mode only),
    /// caching the result so the About popup doesn't ping every frame.
    fn ensure_server_info(&mut self) {
        if self.server_info.is_some() {
            return;
        }
        if let Source::Remote { endpoint, token } = &self.source {
            self.server_info =
                Some(super::remote::ping(endpoint, token).map_err(|e| format!("{e:#}")));
        }
    }

    /// Headless test driver — render **every tab** once through a bare egui
    /// context, exercising each tab's data-load + draw so a per-tab panic
    /// (index-out-of-bounds, bad data) is caught by a test instead of crashing
    /// the live GUI. No window/GPU needed (egui produces shapes, not pixels).
    pub fn render_all_tabs_headless(&mut self) {
        for t in Tab::ALL {
            self.tab = t;
            let ctx = egui::Context::default();
            let _ = ctx.run(egui::RawInput::default(), |ctx| self.draw_ui(ctx));
        }
    }

    /// Write [`state_json`](Self::state_json) to `$NORNIR_VIZ_STATE` (default
    /// `/tmp/nornir_viz_state.json`). Throttled; called every frame.
    fn dump_state(&mut self) {
        if self.last_dump.elapsed().as_millis() < 300 {
            return;
        }
        self.last_dump = std::time::Instant::now();
        let path = std::env::var("NORNIR_VIZ_STATE")
            .unwrap_or_else(|_| "/tmp/nornir_viz_state.json".to_string());
        if let Ok(s) = serde_json::to_string_pretty(&self.state_json()) {
            let _ = std::fs::write(&path, s);
        }
    }

    /// Robot-UI-tester drive-half: poll the control channel (`$NORNIR_VIZ_CMD`)
    /// once per frame and apply any pending command — switch the active tab
    /// (by `state_json()["tab"]` debug name) and/or the workspace. The command
    /// file is consumed (removed) by [`control::take_pending`], so each command
    /// fires exactly once; the result shows up in the next `$NORNIR_VIZ_STATE`
    /// dump that `viz.state` reads back. See `control.rs`.
    fn poll_control_channel(&mut self) {
        let Some(pending) = super::control::take_pending() else { return };
        match pending {
            Ok(cmd) => self.apply_command(&cmd),
            Err(e) => {
                self.action_log.push(super::action_log::Kind::Error, format!("viz.click: {e}"));
            }
        }
    }

    /// Apply one robot-drive [`VizCommand`](super::control::VizCommand): set the
    /// tab (validated by name) and/or switch the workspace, logging each as a
    /// CLICK in the action trail so the drive is auditable in the same log as a
    /// human click. Exposed `pub` so the inject-assert test can drive the exact
    /// same code path the live control channel runs without touching files.
    pub fn apply_command(&mut self, cmd: &super::control::VizCommand) {
        if let Some(name) = &cmd.tab {
            if let Some(t) = Tab::from_name(name) {
                if self.tab != t {
                    self.action_log.push(
                        super::action_log::Kind::Click,
                        format!("viz.click tab → {name}"),
                    );
                }
                self.tab = t;
            } else {
                self.action_log.push(
                    super::action_log::Kind::Error,
                    format!("viz.click: unknown tab {name:?}"),
                );
            }
        }
        if let Some(ws) = &cmd.workspace {
            if *ws != self.workspace_name {
                self.action_log.push(
                    super::action_log::Kind::Click,
                    format!("viz.click workspace → {ws}"),
                );
                self.switch_workspace(ws.clone());
            }
        }
        if let Some(pal) = &cmd.palette {
            match super::facett_theme::Theme::by_name(pal) {
                Some(t) if t != self.palette => {
                    self.action_log.push(
                        super::action_log::Kind::Click,
                        format!("viz.click palette → {}", t.name),
                    );
                    self.set_palette(t);
                }
                Some(_) => {} // already active — no-op
                None => self.action_log.push(
                    super::action_log::Kind::Error,
                    format!("viz.click: unknown palette {pal:?}"),
                ),
            }
        }
    }

    /// Log a click trail to stderr whenever the tab or workspace changes, so the
    /// operator watching the server log sees "what I clicked".
    fn log_click(&mut self) {
        let now = (self.tab, self.workspace_name.clone());
        if now != self.last_click {
            eprintln!(
                "nornir-viz CLICK: tab={:?} workspace={} | {}",
                self.tab, self.workspace_name, self.connect_status
            );
            self.last_click = now;
        }
    }

    fn reload(&mut self) {
        // The INPUT of a reload: which source + workspace we're asking for.
        super::trace::emit_in(
            "server.reload",
            &serde_json::json!({ "source": self.source_label, "workspace": self.workspace_name }),
        );
        self.timeline = self.source.load(&self.workspace_name);
        // Re-read the release-op DAG on the next Release-tab draw too, so a fresh
        // `nornir release run` shows without restarting the viz.
        self.release.reload();
        // Same for the 🧪 Test matrix — a fresh `nornir test` shows without restart.
        self.test.reload();
        // 📡 Live Run re-hydrates from the durable warehouse `release_events`
        // table (LAW persist-to-warehouse-stream-not-tmp): on reload/reboot the run
        // is re-read from the warehouse, not just whatever `/tmp` log survived.
        self.live.reload();
        // Same for the 🏆 Leaderboard — a fresh `nornir bakeoff` shows on reload.
        self.leaderboard.reload();
        // 📡 P1.3: re-read the live bench telemetry so a fresh `nornir bench` run
        // re-hydrates the Bench pane's live panel from the warehouse on reload.
        self.bench.reload();
        self.last_reload = std::time::Instant::now();
        match &self.timeline {
            Ok(tl) => {
                let releases: usize = tl.lanes.iter().map(|l| l.nodes.len()).sum();
                self.action_log.push(
                    super::action_log::Kind::Rpc,
                    format!(
                        "reload timeline workspace={}{releases} release(s)",
                        self.workspace_name,
                    ),
                );
                // The OUTPUT data: the per-lane (per-repo) release counts the
                // timeline actually carries — what the user sees painted.
                super::trace::emit_out(
                    "server.reload",
                    &serde_json::json!({
                        "workspace": self.workspace_name,
                        "releases": releases,
                        "lanes": tl.lanes.iter()
                            .map(|l| serde_json::json!({ "repo": l.repo, "releases": l.nodes.len() }))
                            .collect::<Vec<_>>(),
                    }),
                );
            }
            Err(e) => {
                self.action_log
                    .push(super::action_log::Kind::Error, format!("reload failed: {e:#}"));
                super::trace::emit("server.reload", super::trace::Phase::Out,
                    &serde_json::json!({ "workspace": self.workspace_name, "error": format!("{e:#}") }));
            }
        }
    }

    /// The server bundle for the ops tabs (None in local-warehouse mode).
    fn server(&self) -> Option<super::ops_tabs::Server> {
        match &self.source {
            Source::Remote { endpoint, token } => {
                Some(super::ops_tabs::Server { endpoint: endpoint.clone(), token: token.clone() })
            }
            Source::Local(_) => None,
        }
    }

    /// Switch the active workspace (the picker): re-scope every server-backed tab
    /// (timeline, warehouse, call graph) and reload immediately.
    fn switch_workspace(&mut self, ws: String) {
        if ws == self.workspace_name {
            return;
        }
        self.action_log.push(
            super::action_log::Kind::Life,
            format!("switch workspace {}{}", self.workspace_name, ws),
        );
        self.workspace_name = ws.clone();
        self.selected = None;
        self.warehouse.set_workspace(ws.clone());
        self.funnel.set_workspace(ws.clone());
        self.mcp.set_workspace(ws.clone());
        self.callgraph.set_workspace(ws.clone());
        // Re-point the thin-mode RPC-backed tabs at the new workspace so their
        // Viz.ReleaseEvents / Viz.BakeoffResults / Viz.ReleaseEvents-hydrate
        // refetch for the right server workspace (no-ops in local mode).
        self.release.set_workspace(ws.clone());
        self.leaderboard.set_workspace(ws.clone());
        self.live.set_workspace(ws.clone());
        // Re-scope the Knowledge tab: the workspace's repo set changes per
        // workspace, so fetch the new members (server mode) and hand the tab the
        // fresh root + repos. It drops the stale scans and arms a background
        // rescan, so the map re-scopes for the new workspace without blocking.
        if let Source::Remote { endpoint, token } = &self.source {
            match super::remote::get_workspace(endpoint, token, &ws) {
                Ok(info) => {
                    self.repos = info.members.into_iter().map(|(m, _)| m).collect();
                    eprintln!("nornir-viz: repos from server `{ws}` → {:?}", self.repos);
                }
                Err(e) => eprintln!("nornir-viz: Workspaces.Get(`{ws}`) failed on switch: {e:#}"),
            }
        }
        self.knowledge.set_workspace(self.workspace_root.clone(), self.repos.clone());
        self.knowledge.set_workspace_name(ws.clone());
        // 🛡 Security scans the workspace's configured repos too — re-scope it
        // with the same fresh root + members, else its repo buttons keep
        // listing the previously selected workspace.
        self.security.set_workspace(self.workspace_root.clone(), self.repos.clone());
        self.reload();
        self.warehouse.refresh_tables();
    }

    /// Test-only data injector for the headless snapshot harness
    /// (`tests/viz_snapshots.rs`).
    ///
    /// Local `workspace_*` warehouses are empty in this checkout (the live
    /// release / dep-graph / bench data lives on the `nornir-server` and is
    /// reached over gRPC via [`with_remote`](Self::with_remote)). To render a
    /// viz tab **with real, non-zero data** as a committed PNG proof — without
    /// standing up a server — the snapshot test builds a concrete [`Timeline`]
    /// from the public [`crate::viz::model`] types and injects it here.
    ///
    /// Besides swapping in the timeline + repo list, this:
    ///   * selects `tab` by its `state_json()["tab"]` debug name (so the test
    ///     drives a specific view without depending on the private `Tab` enum),
    ///   * ages `started_at` past the splash so the opaque intro overlay does
    ///     not cover the captured frame, and
    ///   * disables `auto_refresh` so the next `draw_ui` frame does not reload
    ///     the (empty) source warehouse over the injected timeline.
    ///
    /// Returns `true` if `tab` matched a known tab name.
    #[doc(hidden)]
    pub fn inject_timeline_for_test(
        &mut self,
        tab: &str,
        timeline: Timeline,
        repos: Vec<String>,
    ) -> bool {
        let matched = match tab {
            "Timeline" => { self.tab = Tab::Timeline; true }
            "DepGraph" => { self.tab = Tab::DepGraph; true }
            "CallGraph" => { self.tab = Tab::CallGraph; true }
            "Funnel" => { self.tab = Tab::Funnel; true }
            "TimeTravel" => { self.tab = Tab::TimeTravel; true }
            "LiveRun" => { self.tab = Tab::LiveRun; true }
            "Release" => { self.tab = Tab::Release; true }
            "Knowledge" => { self.tab = Tab::Knowledge; true }
            "Warehouse" => { self.tab = Tab::Warehouse; true }
            "Mcp" => { self.tab = Tab::Mcp; true }
            "Search" => { self.tab = Tab::Search; true }
            "Gates" => { self.tab = Tab::Gates; true }
            "Bench" => { self.tab = Tab::Bench; true }
            "Test" => { self.tab = Tab::Test; true }
            "Leaderboard" => { self.tab = Tab::Leaderboard; true }
            "Security" => { self.tab = Tab::Security; true }
            _ => false,
        };
        if !repos.is_empty() {
            self.repos = repos;
        }
        self.timeline = Ok(timeline);
        self.auto_refresh = false;
        // Push `started_at` back so the splash overlay has fully faded out.
        self.started_at = std::time::Instant::now()
            - std::time::Duration::from_secs_f32(SPLASH_DURATION_SECS + 1.0);
        matched
    }

    /// Test-only: run the Knowledge scan **synchronously** (no GUI loop to drain
    /// the background slot) against the current `workspace_root`/`repos`, so the
    /// inject-and-assert harness can read the real symbol/call counts back out of
    /// `state_json()["knowledge"]`. Returns immediately after the scan completes.
    #[doc(hidden)]
    pub fn knowledge_scan_blocking_for_test(&mut self) {
        self.knowledge.scan_blocking_for_test();
    }

    /// Test-only: inject release-op rows into the 🚀 Release tab directly (no
    /// warehouse on disk), then select the tab — so the inject-and-assert harness
    /// can read the op-log rows + per-component status back out of
    /// `state_json()["release"]`. Mirrors `inject_timeline_for_test` for the
    /// release-events surface.
    #[doc(hidden)]
    pub fn inject_release_events_for_test(
        &mut self,
        rows: Vec<crate::warehouse::release_events::ReleaseEventRow>,
    ) {
        self.tab = Tab::Release;
        self.release.inject_for_test(rows);
        self.auto_refresh = false;
        self.started_at = std::time::Instant::now()
            - std::time::Duration::from_secs_f32(SPLASH_DURATION_SECS + 1.0);
    }

    /// Test-only: hydrate the 📡 Live Run pane from injected `release_events`
    /// rows (no warehouse on disk), exactly as the durable warehouse read would,
    /// then select the tab — so the inject-and-assert harness can read the
    /// hydrated run + rendered event lines back out of `state_json()["live"]`.
    /// Mirrors `inject_release_events_for_test` for the live surface (C3).
    #[doc(hidden)]
    pub fn inject_live_release_events_for_test(
        &mut self,
        rows: Vec<crate::warehouse::release_events::ReleaseEventRow>,
    ) {
        self.tab = Tab::LiveRun;
        self.live.inject_for_test(rows);
        self.auto_refresh = false;
        self.started_at = std::time::Instant::now()
            - std::time::Duration::from_secs_f32(SPLASH_DURATION_SECS + 1.0);
    }

    /// Test-only: hydrate the 📡 Live Run pane from the **real on-disk warehouse**
    /// `release_events` table synchronously (the durable read path the pane runs on
    /// load/reload), then select the tab — so an inject-and-assert test can seed
    /// `release_events` rows to a warehouse, point the app at it, and read the
    /// hydrated run back out of `state_json()["live"]` (C3, proves warehouse-sourced).
    #[doc(hidden)]
    pub fn live_hydrate_from_warehouse_for_test(&mut self) {
        self.tab = Tab::LiveRun;
        self.live.reload();
        self.auto_refresh = false;
        self.started_at = std::time::Instant::now()
            - std::time::Duration::from_secs_f32(SPLASH_DURATION_SECS + 1.0);
    }

    /// Test-only: drive the 🔗 Dep Graph view's deep toggle (C5) and collapse
    /// set (I3) directly, so the inject-and-assert harness can flip to the
    /// transitive-closure explode / collapse a node and read the resulting
    /// laid-out graph back out of `state_json()["dep_graph"]`.
    #[doc(hidden)]
    pub fn set_dep_view_for_test(&mut self, deep: bool, collapsed: &[&str]) {
        self.dep_view.deep = deep;
        self.dep_view.collapsed = collapsed.iter().map(|s| s.to_string()).collect();
    }

    /// Test-only: drive the ⏳ Time Travel tab's cursor (`idx`), the C4 text⇄graph
    /// toggle, and the reused dep-view deep flag directly, so the inject-and-assert
    /// harness can pin to a point in time, switch to graph view, and read the
    /// time-pinned graph (nodes/edges + direct/transitive classes) back out of
    /// `state_json()["timetravel"]`. Mirrors `set_dep_view_for_test`.
    #[doc(hidden)]
    pub fn set_timetravel_for_test(&mut self, idx: usize, graph: bool, deep: bool) {
        self.tab = Tab::TimeTravel;
        self.timetravel.idx = idx;
        self.timetravel.graph = graph;
        self.timetravel.dep_view.deep = deep;
    }

    /// Test-only: inject `test_results` rows into the 🧪 Test tab directly (no
    /// warehouse on disk), then select the tab — so the inject-and-assert harness
    /// can read the matrix (per-run green/red counts + cases) back out of
    /// `state_json()["test"]`. Mirrors `inject_release_events_for_test`.
    #[doc(hidden)]
    pub fn inject_test_results_for_test(
        &mut self,
        rows: Vec<crate::warehouse::test_results::TestResultRow>,
    ) {
        self.tab = Tab::Test;
        self.test.inject_for_test(rows);
        self.auto_refresh = false;
        self.started_at = std::time::Instant::now()
            - std::time::Duration::from_secs_f32(SPLASH_DURATION_SECS + 1.0);
    }

    /// Test-only: inject `agent_model_runs` rows into the 🏆 Leaderboard tab
    /// directly (no warehouse on disk), then select the tab — so the
    /// inject-and-assert harness can read the ranked leaderboard (winner +
    /// per-model score/tokens-per-s) back out of `state_json()["leaderboard"]`.
    /// Mirrors `inject_test_results_for_test`.
    #[doc(hidden)]
    pub fn inject_bakeoff_for_test(
        &mut self,
        rows: Vec<crate::warehouse::agent_model_runs::AgentModelRunRow>,
    ) {
        self.tab = Tab::Leaderboard;
        self.leaderboard.inject_for_test(rows);
        self.auto_refresh = false;
        self.started_at = std::time::Instant::now()
            - std::time::Duration::from_secs_f32(SPLASH_DURATION_SECS + 1.0);
    }

    /// Test-only (P1.3): inject `bench_telemetry` rows + `bench_runs` (for
    /// per-bench pass/fail) into the 📈 Bench tab's LIVE telemetry panel directly
    /// (no warehouse on disk), then select the tab — so the inject-and-assert
    /// harness reads the live benches (name + green/red status + cores-busy/N +
    /// CPU sparkline) back out of `state_json()["bench"]["live"]`. Mirrors
    /// `inject_test_results_for_test`.
    #[doc(hidden)]
    pub fn inject_bench_telemetry_for_test(
        &mut self,
        telemetry: Vec<crate::warehouse::iceberg::BenchTelemetryRow>,
        runs: Vec<(String, crate::bench::BenchRun)>,
    ) {
        self.tab = Tab::Bench;
        self.bench.inject_live_for_test(telemetry, runs);
        self.auto_refresh = false;
        self.started_at = std::time::Instant::now()
            - std::time::Duration::from_secs_f32(SPLASH_DURATION_SECS + 1.0);
    }

    /// Test-only: re-scope the Knowledge tab to a fresh `workspace_root`/`repos`
    /// (what a workspace switch does), so a test can assert the scans reset.
    #[doc(hidden)]
    pub fn knowledge_set_workspace_for_test(&mut self, workspace_root: PathBuf, repos: Vec<String>) {
        self.workspace_root = workspace_root.clone();
        self.repos = repos.clone();
        self.knowledge.set_workspace(workspace_root, repos);
    }

    /// Test-only: mutable handle to the Funnel tab, so the E1 viz test can drive
    /// the demo / nuke / confirm-guard through the same code paths the buttons
    /// invoke and then assert `state_json()["funnel"]`.
    #[doc(hidden)]
    pub fn funnel_tab_for_test(&mut self) -> &mut super::funnel_tab::FunnelTabState {
        &mut self.funnel
    }

    /// Test-only: drive the workspace picker exactly as a click does — re-scope
    /// every tab (timeline, warehouse, release, leaderboard, knowledge, security,
    /// …) to `ws` and reload. The workspace×function matrix uses this to prove
    /// each function follows a switch with no stale leak from the previous one.
    #[doc(hidden)]
    pub fn switch_workspace_for_test(&mut self, ws: String) {
        self.switch_workspace(ws);
    }
}

const LANE_HEIGHT: f32 = 80.0;
const LANE_PAD: f32 = 24.0;
const NODE_RADIUS: f32 = 14.0;
const LEFT_GUTTER: f32 = 140.0;

/// A gate/release status → colour on the active facett palette (C8). Delegates
/// to the palette's shared semantic ramp so the timeline + side panel re-skin
/// with the theme.
fn status_color(theme: &super::facett_theme::Theme, status: &str) -> Color32 {
    theme.status_color(status)
}

impl eframe::App for UrdrThreadsApp {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        self.draw_ui(ctx);
    }
}

impl UrdrThreadsApp {
    /// Full per-frame UI build, independent of `eframe::Frame` (it's unused) so
    /// headless tests can render every tab through a bare `egui::Context`.
    pub fn draw_ui(&mut self, ctx: &egui::Context) {
        // Apply the active facett palette's egui Visuals (C8) — themes the
        // standard widgets (panels, buttons, selection, hyperlinks) to match the
        // custom-painted panes. Only on change, so we don't fight egui every frame.
        if !self.palette_applied {
            ctx.set_visuals(self.palette.visuals());
            self.palette_applied = true;
        }
        // Auto-refresh: reload the timeline + warehouse table list on a timer so a
        // server-monitored workspace animates live as the poll loop republishes.
        if self.auto_refresh && self.last_reload.elapsed().as_secs() >= self.refresh_secs {
            self.reload();
            self.warehouse.refresh_tables();
            ctx.request_repaint();
        }
        if self.auto_refresh {
            // Keep the frame loop ticking even when idle so the timer fires.
            ctx.request_repaint_after(std::time::Duration::from_secs(1));
        }

        // Robot-UI-tester drive-half: apply any pending `viz.click` command from
        // the control channel BEFORE we paint, so this frame reflects it (and the
        // post-frame `dump_state` shows the result to the next `viz.state`). Keep
        // the loop ticking briefly so a command lands within a frame or two even
        // when the window is otherwise idle.
        self.poll_control_channel();
        ctx.request_repaint_after(std::time::Duration::from_millis(250));

        // Tab change detection for the action log (the selectable_values below
        // mutate `self.tab` in place; we compare against this pre-row snapshot).
        let tab_before = self.tab;

        egui::TopBottomPanel::top("top").show(ctx, |ui| {
            // ── Row 1: workspace / source / reload / live / sync controls ──────
            // The button bar overflowed on one line; split into two rows as a
            // stopgap until a better tab-strip strategy lands.
            ui.horizontal(|ui| {
                ui.heading("🧵 Urðr Threads");
                ui.separator();
                // Workspace picker — switching re-scopes timeline/warehouse/callgraph.
                let mut chosen = self.workspace_name.clone();
                let label = if chosen.is_empty() { "(default)".to_string() } else { chosen.clone() };
                egui::ComboBox::from_id_salt("ws_picker")
                    .selected_text(format!("workspace: {label}"))
                    .show_ui(ui, |ui| {
                        for ws in &self.workspaces {
                            ui.selectable_value(&mut chosen, ws.clone(), ws);
                        }
                    });
                if chosen != self.workspace_name {
                    self.switch_workspace(chosen);
                }
                ui.separator();
                ui.label(format!("source: {}", self.source_label));
                if ui.button("↻ reload").clicked() {
                    self.action_log.push(super::action_log::Kind::Click, "↻ reload");
                    self.reload();
                    self.warehouse.refresh_tables();
                }
                ui.checkbox(&mut self.auto_refresh, "live")
                    .on_hover_text(format!("auto-refresh every {}s", self.refresh_secs));
                ui.separator();
                // Workspace info toggle + ⟳ Sync now (remote mode). A sync polls
                // the remote (server-side republish) — reload the view at once so
                // a cleared/changed warehouse shows now, not on the next tick.
                let srv = self.server();
                if self.ws_panel.draw_controls(ui, srv.as_ref(), &self.workspace_name) {
                    self.action_log.push(super::action_log::Kind::Click, "⟳ sync now");
                    self.reload();
                    self.warehouse.refresh_tables();
                    self.callgraph.invalidate();
                }
                ui.label(format!(
                    "(last reload {}s ago)",
                    self.last_reload.elapsed().as_secs()
                ));
                ui.separator();
                // 🐞 action-log overlay toggle + the live entry counter, so the
                // operator can pop the trail open without a terminal.
                let lbl = format!("🐞 log ({})", self.action_log.count());
                if ui.selectable_label(self.show_action_log, lbl)
                    .on_hover_text("toggle the user-action debug trail (also at $NORNIR_VIZ_ACTIONLOG)")
                    .clicked()
                {
                    self.show_action_log = !self.show_action_log;
                }
                ui.separator();
                // ℹ About — client/server version + endpoint + workspace + warehouse.
                if ui.selectable_label(self.show_about, "ℹ About")
                    .on_hover_text("client + server version, endpoint, workspace, warehouse")
                    .clicked()
                {
                    self.show_about = !self.show_about;
                    if self.show_about {
                        self.action_log.push(super::action_log::Kind::Click, "ℹ About");
                        // Query the server version once, on open (remote mode).
                        self.ensure_server_info();
                    }
                }
                ui.separator();
                // 🎨 App-wide facett palette picker (C8) — switching re-skins
                // EVERY pane (status colours, accents, zebra/hover/selection,
                // gridlines, typography) + the egui widgets, all at once.
                ui.label("🎨");
                let mut chosen_pal = self.palette.name.to_string();
                egui::ComboBox::from_id_salt("app_palette")
                    .selected_text(self.palette.name)
                    .show_ui(ui, |ui| {
                        for name in super::facett_theme::Theme::names() {
                            ui.selectable_value(&mut chosen_pal, name.to_string(), name);
                        }
                    });
                if chosen_pal != self.palette.name {
                    if let Some(t) = super::facett_theme::Theme::by_name(&chosen_pal) {
                        self.action_log.push(
                            super::action_log::Kind::Click,
                            format!("🎨 palette → {}", t.name),
                        );
                        self.set_palette(t);
                    }
                }
            });
            // ── Tabs on TWO explicit rows (7 + 6) so the window needn't be wide ──
            ui.horizontal(|ui| {
                ui.selectable_value(&mut self.tab, Tab::Timeline, "🧵 Timeline");
                ui.selectable_value(&mut self.tab, Tab::DepGraph, "🔗 Dep Graph");
                ui.selectable_value(&mut self.tab, Tab::CallGraph, "🕸 Call Graph");
                ui.selectable_value(&mut self.tab, Tab::Funnel, "🗂 Funnel");
                ui.selectable_value(&mut self.tab, Tab::TimeTravel, "⏳ Time Travel");
                ui.selectable_value(&mut self.tab, Tab::LiveRun, "📡 Live Run");
                ui.selectable_value(&mut self.tab, Tab::Release, "🚀 Release");
                ui.selectable_value(&mut self.tab, Tab::Knowledge, "🗺 Knowledge");
            });
            ui.horizontal(|ui| {
                ui.selectable_value(&mut self.tab, Tab::Warehouse, "🗄 Warehouse");
                ui.selectable_value(&mut self.tab, Tab::Mcp, "📞 MCP");
                ui.selectable_value(&mut self.tab, Tab::Search, "🔍 Search");
                ui.selectable_value(&mut self.tab, Tab::Gates, "🚦 Gates");
                ui.selectable_value(&mut self.tab, Tab::Bench, "📈 Bench");
                ui.selectable_value(&mut self.tab, Tab::Test, "🧪 Test");
                ui.selectable_value(&mut self.tab, Tab::Leaderboard, "🏆 Leaderboard");
                ui.selectable_value(&mut self.tab, Tab::Security, "🛡 Security");
            });
        });

        // Keep the action log's durable-row context (workspace + active tab)
        // current, so every `viz_actions` row is stamped with where the user was
        // when they took the action (N5). Cheap: a single mutex update.
        self.action_log.set_context(&self.workspace_name, &format!("{:?}", self.tab));

        // Log the tab switch (edge-triggered) the moment the row mutates it.
        if self.tab != tab_before {
            self.action_log.push(
                super::action_log::Kind::Tab,
                format!("{tab_before:?}{:?}", self.tab),
            );
            // Structured twin: the tab switch as a typed event so an agent
            // following $NORNIR_VIZ_TRACE knows which view's data comes next.
            super::trace::emit_event(
                "ui.tab",
                &serde_json::json!({
                    "from": format!("{tab_before:?}"),
                    "to": format!("{:?}", self.tab),
                }),
            );
        }

        // Side panel: details for the selected release
        egui::SidePanel::right("detail").default_width(360.0).show(ctx, |ui| {
            ui.heading("Time machine");
            ui.separator();
            // Workspace info + sync result (when the ℹ toggle is on).
            self.ws_panel.draw_panel(ui, self.server().as_ref(), &self.workspace_name);
            match (self.selected, &self.timeline) {
                (Some(rid), Ok(tl)) => {
                    ui.label(format!("release_id\n  {rid}"));
                    ui.separator();
                    ui.label("git checkout commands:");
                    for lane in &tl.lanes {
                        if let Some(node) = lane.nodes.iter().find(|n| n.release_id == rid) {
                            let cmd = format!("cd {} && git checkout {}", lane.repo, node.sha);
                            ui.horizontal(|ui| {
                                ui.monospace(&cmd);
                                if ui.button("📋").on_hover_text("copy").clicked() {
                                    ui.ctx().copy_text(cmd.clone());
                                }
                            });
                            let color = status_color(&self.palette, &node.gate_status);
                            ui.colored_label(
                                color,
                                format!(
                                    "  {} • status={} • tests {}/{} • branch={} • dirty={}",
                                    lane.repo,
                                    node.gate_status,
                                    node.tests_passed,
                                    node.tests_failed,
                                    node.branch,
                                    node.dirty,
                                ),
                            );
                            if !node.published_versions.is_empty() {
                                ui.label(format!(
                                    "  published: {}",
                                    node.published_versions
                                        .iter()
                                        .map(|(c, v)| format!("{c}@{v}"))
                                        .collect::<Vec<_>>()
                                        .join(", ")
                                ));
                            }
                            ui.add_space(4.0);
                        }
                    }
                }
                (None, _) => {
                    ui.label("click a node in the timeline →");
                }
                (_, Err(e)) => {
                    ui.colored_label(super::facett_theme::RED, format!("load error:\n{e:#}"));
                }
            }
        });

        // Bottom overlay: the recent action trail (toggle in the top bar). The
        // same entries also stream to stderr + `$NORNIR_VIZ_ACTIONLOG`.
        if self.show_action_log {
            egui::TopBottomPanel::bottom("action_log")
                .resizable(true)
                .default_height(160.0)
                .show(ctx, |ui| {
                    ui.horizontal(|ui| {
                        ui.strong("🐞 Action trail");
                        ui.label(format!("({} total)", self.action_log.count()));
                        ui.separator();
                        ui.monospace(self.action_log.file_path());
                    });
                    ui.separator();
                    egui::ScrollArea::vertical()
                        .stick_to_bottom(true)
                        .auto_shrink([false, false])
                        .show(ui, |ui| {
                            // Render the TAIL of the shared action-log FILE, not just
                            // this viz's own in-memory ring — so a running `nornir
                            // bench`'s `[BENCH]` progress (appended by a SEPARATE
                            // process to the same $NORNIR_VIZ_ACTIONLOG) streams live
                            // here too. The file is the single source of truth.
                            for line in self.action_log.tail_lines(64 * 1024, 256) {
                                // Action-trail lines colour-coded on the active palette
                                // (C8): error→red, bench→amber, rpc/query→accent/amber,
                                // tab→green, life/default→dim text.
                                let color = if line.contains("[ERROR]") {
                                    super::facett_theme::RED
                                } else if line.contains("[BENCH]") {
                                    super::facett_theme::AMBER
                                } else if line.contains("[RPC]") {
                                    self.palette.accent
                                } else if line.contains("[TAB]") {
                                    super::facett_theme::GREEN
                                } else if line.contains("[QUERY]") {
                                    super::facett_theme::AMBER
                                } else if line.contains("[LIFE]") {
                                    self.palette.text_dim
                                } else {
                                    self.palette.text
                                };
                                ui.monospace(egui::RichText::new(line).size(11.0).color(color));
                            }
                        });
                    // Keep the tail live while the panel is open (bench progress).
                    ctx.request_repaint_after(std::time::Duration::from_millis(300));
                });
        }

        // ℹ About window (C1): always shows SOMETHING real — client version,
        // endpoint, workspace, warehouse — plus the server version (remote mode).
        if self.show_about {
            let about = self.about_info();
            let theme = self.palette;
            let mut open = self.show_about;
            egui::Window::new("ℹ About — Urðr Threads")
                .open(&mut open)
                .resizable(false)
                .collapsible(false)
                .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
                .show(ctx, |ui| {
                    let row = |ui: &mut egui::Ui, k: &str, v: &str| {
                        ui.horizontal(|ui| {
                            ui.label(egui::RichText::new(k).strong());
                            ui.monospace(v);
                        });
                    };
                    ui.heading("🧵 Urðr Threads");
                    ui.label("the nornir warehouse visualizer");
                    ui.separator();
                    // The build identity — prominent, so it's obvious this is a
                    // fresh client (version + git SHA + build time).
                    ui.label(
                        egui::RichText::new(client_build())
                            .strong()
                            .monospace()
                            .color(super::facett_theme::GREEN),
                    );
                    let mode = about["mode"].as_str().unwrap_or("?");
                    row(ui, "mode", mode);
                    if mode == "remote" {
                        row(ui, "endpoint", about["endpoint"].as_str().unwrap_or(""));
                        match about["server_version"].as_str() {
                            Some(v) => {
                                let rc = about["server_repo_count"].as_u64().unwrap_or(0);
                                row(ui, "server version", &format!("{v}  ({rc} repos)"));
                            }
                            None => {
                                let note = about["server_note"].as_str().unwrap_or("server version: unknown");
                                ui.colored_label(super::facett_theme::AMBER, note);
                            }
                        }
                    } else {
                        row(ui, "warehouse", about["warehouse"].as_str().unwrap_or(""));
                    }
                    row(ui, "workspace", about["workspace"].as_str().unwrap_or(""));
                    ui.separator();
                    ui.label(
                        egui::RichText::new(about["connect_status"].as_str().unwrap_or(""))
                            .size(11.0)
                            .color(theme.text_dim),
                    );
                });
            self.show_about = open;
        }

        egui::CentralPanel::default().show(ctx, |ui| {
            // Live Run and Knowledge tabs render even when there's no
            // timeline yet — they work without warehouse data.
            if self.tab == Tab::LiveRun {
                self.live.draw(ui);
                return;
            }
            if self.tab == Tab::Release {
                self.release.draw(ui);
                return;
            }
            if self.tab == Tab::Test {
                self.test.draw(ui);
                return;
            }
            if self.tab == Tab::Leaderboard {
                self.leaderboard.draw(ui);
                return;
            }
            if self.tab == Tab::Knowledge {
                self.knowledge.draw(ui);
                return;
            }
            if self.tab == Tab::Warehouse {
                self.warehouse.draw(ui);
                return;
            }
            if self.tab == Tab::Mcp {
                self.mcp.draw(ui);
                return;
            }
            if self.tab == Tab::CallGraph {
                self.callgraph.draw(ui);
                return;
            }
            if self.tab == Tab::Funnel {
                self.funnel.draw(ui, &self.action_log);
                return;
            }
            let srv = self.server();
            if self.tab == Tab::Search {
                self.search.draw(ui, srv.as_ref(), &self.workspace_name, &self.action_log);
                return;
            }
            if self.tab == Tab::Gates {
                self.gates.draw(ui, srv.as_ref(), &self.workspace_name, &self.repos, &self.action_log);
                return;
            }
            if self.tab == Tab::Bench {
                self.bench.draw(ui, srv.as_ref(), &self.workspace_name, &self.repos, &self.action_log);
                return;
            }
            if self.tab == Tab::Security {
                self.security.draw(ui, srv.as_ref(), &self.workspace_name);
                return;
            }
            match &self.timeline {
            Err(e) => {
                ui.colored_label(super::facett_theme::RED, format!("Failed to load warehouse:\n{e:#}"));
            }
            Ok(tl) if tl.is_empty() => {
                ui.label(format!(
                    "No releases recorded for workspace `{}` yet.",
                    self.workspace_name
                ));
                ui.label(&self.connect_status);
            }
            Ok(tl) => match self.tab {
                Tab::Timeline => {
                    self.selected = draw_timeline(ui, tl, self.selected, &self.palette);
                }
                Tab::DepGraph => {
                    if self.selected.is_none() {
                        ui.label("Showing latest snapshot — click a release in 🧵 Timeline to time-travel here.");
                    } else if let Some(rid) = self.selected {
                        if let Some(snap) = tl.snapshot_for(&rid) {
                            ui.label(format!(
                                "Pinned to release {} (snapshot {})",
                                rid, snap.snapshot_id
                            ));
                        }
                    }
                    draw_dep_graph(ui, tl, self.selected, &mut self.dep_selected_repo, &mut self.dep_view);
                }
                Tab::TimeTravel => {
                    // Keyboard shortcuts while on this tab.
                    ctx.input(|i| {
                        if i.key_pressed(egui::Key::ArrowRight) {
                            if let Ok(tl) = &self.timeline {
                                if self.timetravel.idx + 1 < tl.release_order.len() {
                                    self.timetravel.idx += 1;
                                }
                            }
                        }
                        if i.key_pressed(egui::Key::ArrowLeft) {
                            self.timetravel.idx = self.timetravel.idx.saturating_sub(1);
                        }
                        if i.key_pressed(egui::Key::Space) {
                            self.timetravel.playing = !self.timetravel.playing;
                            self.timetravel.last_tick = std::time::Instant::now();
                        }
                    });
                    if let Some(rid) = draw_timetravel(ui, tl, &mut self.timetravel) {
                        self.selected = Some(rid);
                    }
                }
                Tab::Search | Tab::Gates | Tab::Bench | Tab::Security => unreachable!("handled above"),
                Tab::LiveRun => unreachable!("handled above"),
                Tab::Release => unreachable!("handled above"),
                Tab::Test => unreachable!("handled above"),
                Tab::Leaderboard => unreachable!("handled above"),
                Tab::Knowledge => unreachable!("handled above"),
                Tab::Warehouse => unreachable!("handled above"),
                Tab::Mcp => unreachable!("handled above"),
                Tab::CallGraph => unreachable!("handled above"),
                Tab::Funnel => unreachable!("handled above"),
            },
            }
        });

        // Splash + watermark overlay (drawn last so it sits on top
        // of everything but doesn't block clicks).
        self.draw_nornir_overlay(ctx);

        // 🚦 Pre-flight popup — only AFTER the splash has played, so it appears
        // "after the logo popup" as intended. Feed it the warehouse MCP call
        // count (scanning the telemetry once) so a 0-call host gets the
        // "wire up your Claude agent" warning, then draw it over everything.
        if self.started_at.elapsed().as_secs_f32() >= SPLASH_DURATION_SECS {
            self.mcp.ensure_loaded();
            // Build the `claude mcp add` command from THIS client's live
            // connection (no hardcoded token in the binary). We do NOT pin
            // NORNIR_WORKSPACE — the MCP should expose every workspace + its
            // repos, not lock to one (see .nornir: multi-workspace-mcp).
            let add_cmd = match &self.source {
                Source::Remote { endpoint, token } => format!(
                    "# wire nornir's 56 MCP tools to Claude Code, pointed at this server:\n\
                     claude mcp add nornir \\\n  \
                     --env NORNIR_SERVER={endpoint} \\\n  \
                     --env NORNIR_SERVER_TOKEN={token} \\\n  \
                     -- nornir-mcp\n\
                     # then in a session:  /mcp   → `nornir` connected (all workspaces)"
                ),
                Source::Local(_) => "# wire nornir's 56 MCP tools to Claude Code:\n\
                     claude mcp add nornir -- nornir-mcp\n\
                     # then in a session:  /mcp   → `nornir` connected"
                    .to_string(),
            };
            self.preflight
                .set_mcp_calls(self.mcp.total_calls(), self.mcp.is_loaded(), add_cmd);
            self.preflight.draw(ctx);
        } else {
            // keep repainting so the popup appears promptly when the splash ends
            ctx.request_repaint_after(std::time::Duration::from_millis(100));
        }

        // External observability: log click trail (stderr) + dump the full UI
        // state (pickers, tabs, populations, placeholders) so the test matrix
        // and the operator can see what's on screen without a display.
        self.log_click();
        self.dump_state();
    }
}

impl UrdrThreadsApp {
    fn ensure_texture(&mut self, ctx: &egui::Context) -> Option<&TextureHandle> {
        if self.nornir_tex.is_none() {
            if let Some(img) = decode_nornir() {
                self.nornir_tex = Some(ctx.load_texture(
                    "nornir-splash",
                    img,
                    TextureOptions::LINEAR,
                ));
            }
        }
        self.nornir_tex.as_ref()
    }

    fn draw_nornir_overlay(&mut self, ctx: &egui::Context) {
        let elapsed = self.started_at.elapsed().as_secs_f32();
        let splash_alpha = if elapsed < SPLASH_DURATION_SECS - SPLASH_FADE_SECS {
            1.0
        } else if elapsed < SPLASH_DURATION_SECS {
            1.0 - (elapsed - (SPLASH_DURATION_SECS - SPLASH_FADE_SECS)) / SPLASH_FADE_SECS
        } else {
            0.0
        };
        // Request continuous repaints during the fade.
        if splash_alpha > 0.0 {
            ctx.request_repaint_after(std::time::Duration::from_millis(16));
        }

        let Some(tex) = self.ensure_texture(ctx) else { return };
        let tex_size = tex.size_vec2();
        let tex_id = tex.id();
        let screen = ctx.content_rect();

        let painter = ctx.layer_painter(egui::LayerId::new(
            egui::Order::Foreground,
            egui::Id::new("nornir-overlay"),
        ));

        // Persistent watermark — small, bottom-right, very faint.
        let wm_w = 220.0;
        let wm_h = wm_w * (tex_size.y / tex_size.x);
        let wm_rect = Rect::from_min_size(
            Pos2::new(screen.right() - wm_w - 18.0, screen.bottom() - wm_h - 18.0),
            Vec2::new(wm_w, wm_h),
        );
        painter.image(
            tex_id,
            wm_rect,
            Rect::from_min_max(Pos2::ZERO, Pos2::new(1.0, 1.0)),
            Color32::from_white_alpha(WATERMARK_ALPHA),
        );

        // Splash overlay during the first few seconds.
        if splash_alpha > 0.0 {
            // Dim everything behind a translucent veil.
            painter.rect_filled(
                screen,
                CornerRadius::ZERO,
                Color32::from_rgba_unmultiplied(8, 8, 12, (splash_alpha * 220.0) as u8),
            );
            // Center the artwork at ~60% of the smaller screen dim.
            let max_w = screen.width().min(screen.height()) * 0.6;
            let img_w = max_w.min(tex_size.x);
            let img_h = img_w * (tex_size.y / tex_size.x);
            let center = screen.center();
            let img_rect = Rect::from_center_size(center, Vec2::new(img_w, img_h));
            let a = (splash_alpha * 255.0) as u8;
            painter.image(
                tex_id,
                img_rect,
                Rect::from_min_max(Pos2::ZERO, Pos2::new(1.0, 1.0)),
                Color32::from_white_alpha(a),
            );
            painter.text(
                Pos2::new(center.x, img_rect.bottom() + 24.0),
                Align2::CENTER_TOP,
                "Urðr Threads",
                FontId::proportional(32.0),
                Color32::from_white_alpha(a),
            );
            painter.text(
                Pos2::new(center.x, img_rect.bottom() + 64.0),
                Align2::CENTER_TOP,
                "weaving releases into provenance",
                FontId::proportional(16.0),
                Color32::from_white_alpha((a as u32 * 200 / 255) as u8),
            );
            // The build identifier — version + SHA + build time. It belongs on
            // the splash the user actually sees at launch (not just the ℹ About
            // popup), so a stale client is obvious the moment it opens.
            painter.text(
                Pos2::new(center.x, img_rect.bottom() + 92.0),
                Align2::CENTER_TOP,
                client_build(),
                FontId::monospace(13.0),
                Color32::from_white_alpha((a as u32 * 170 / 255) as u8),
            );
        }
    }
}

fn draw_timeline(
    ui: &mut egui::Ui,
    tl: &Timeline,
    mut selected: Option<Uuid>,
    theme: &super::facett_theme::Theme,
) -> Option<Uuid> {
    let available = ui.available_size();
    let needed_h = LANE_PAD + tl.lanes.len() as f32 * (LANE_HEIGHT + LANE_PAD);
    let canvas_size = Vec2::new(available.x.max(800.0), needed_h.max(300.0));
    let (rect, response) = ui.allocate_exact_size(canvas_size, Sense::click());
    let painter = ui.painter_at(rect);

    // background
    painter.rect_filled(rect, CornerRadius::ZERO, theme.bg);

    if tl.release_order.is_empty() {
        return selected;
    }

    let n = tl.release_order.len().max(1);
    let x_step = (rect.width() - LEFT_GUTTER - 40.0) / (n as f32).max(1.0);
    let x_of = |idx: usize| rect.left() + LEFT_GUTTER + 20.0 + idx as f32 * x_step;

    let y_of = |lane_idx: usize| {
        rect.top() + LANE_PAD + lane_idx as f32 * (LANE_HEIGHT + LANE_PAD) + LANE_HEIGHT / 2.0
    };

    // lanes: label + horizontal line + zebra background
    for (li, lane) in tl.lanes.iter().enumerate() {
        let y = y_of(li);
        let lane_rect = Rect::from_min_max(
            Pos2::new(rect.left() + LEFT_GUTTER, y - LANE_HEIGHT / 2.0),
            Pos2::new(rect.right(), y + LANE_HEIGHT / 2.0),
        );
        let zebra = theme.zebra(li % 2 == 1);
        painter.rect_filled(lane_rect, CornerRadius::same(4), zebra);
        painter.line_segment(
            [
                Pos2::new(rect.left() + LEFT_GUTTER, y),
                Pos2::new(rect.right() - 20.0, y),
            ],
            Stroke::new(1.0, theme.gridline()),
        );
        painter.text(
            Pos2::new(rect.left() + 10.0, y),
            Align2::LEFT_CENTER,
            &lane.repo,
            FontId::proportional(18.0),
            theme.text,
        );
    }

    // weave: for each release column draw cross-repo dep edges between
    // the matching lane nodes (from -> to). Uses the latest snapshot
    // for now (per-release snapshot lookup is a follow-up).
    if let Some(snap) = &tl.latest_snapshot {
        for (col_idx, release_id) in tl.release_order.iter().enumerate() {
            let x = x_of(col_idx);
            for edge in &snap.edges {
                let from_lane = tl.lanes.iter().position(|l| l.repo == edge.from);
                let to_lane = tl.lanes.iter().position(|l| l.repo == edge.to);
                if let (Some(fi), Some(ti)) = (from_lane, to_lane) {
                    let has_from = tl.lanes[fi].nodes.iter().any(|n| n.release_id == *release_id);
                    let has_to = tl.lanes[ti].nodes.iter().any(|n| n.release_id == *release_id);
                    if has_from && has_to {
                        painter.line_segment(
                            [Pos2::new(x, y_of(fi)), Pos2::new(x, y_of(ti))],
                            // weave threads in the palette accent (the Norns motif),
                            // softened so the status nodes stay dominant.
                            Stroke::new(2.0, theme.accent.linear_multiply(0.62)),
                        );
                    }
                }
            }
        }
    }

    // nodes (drawn on top of weave)
    for (li, lane) in tl.lanes.iter().enumerate() {
        for node in &lane.nodes {
            let col = tl
                .release_order
                .iter()
                .position(|r| *r == node.release_id)
                .unwrap_or(0);
            let center = Pos2::new(x_of(col), y_of(li));
            let color = status_color(theme, &node.gate_status);
            let is_selected = Some(node.release_id) == selected;
            let r = if is_selected { NODE_RADIUS + 3.0 } else { NODE_RADIUS };
            painter.circle_filled(center, r, color);
            painter.circle_stroke(
                center,
                r,
                // selected node rings in the palette accent; others a faint outline.
                Stroke::new(
                    if is_selected { 3.0 } else { 1.0 },
                    if is_selected { theme.accent } else { theme.node_stroke },
                ),
            );
            if node.dirty {
                painter.text(
                    center + Vec2::new(0.0, NODE_RADIUS + 12.0),
                    Align2::CENTER_TOP,
                    "",
                    FontId::proportional(14.0),
                    super::facett_theme::AMBER,
                );
            }
            painter.text(
                center + Vec2::new(0.0, -NODE_RADIUS - 4.0),
                Align2::CENTER_BOTTOM,
                &node.sha[..node.sha.len().min(7)],
                FontId::monospace(11.0),
                theme.text,
            );

            // hit-test
            if response.clicked() {
                if let Some(pos) = response.interact_pointer_pos() {
                    if pos.distance(center) <= r + 2.0 {
                        selected = Some(node.release_id);
                    }
                }
            }
        }
    }

    selected
}