nornir 0.4.31

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
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
//! Server-backed clickable tabs that turn nornir CLI/gRPC verbs into viz
//! surfaces: πŸ” Search (BM25 + symbol lookup), 🚦 Gates (release gates + trace),
//! πŸ“ˆ Bench (history charts), and the picker's workspace info + ⟳ Sync-now panel.
//!
//! All are **remote-only** (they drive the running `nornir-server` over the
//! existing gRPC RPCs via [`super::remote`]); in local-warehouse mode they show
//! a one-line hint instead. Calls run on the synchronous click (a private
//! current-thread runtime inside each `remote::*` fn) β€” fine for the
//! interaction rates here; results are cached in the state until re-run.

use eframe::egui::{self};

use super::action_log::{ActionLog, Kind};
use super::facett_theme::{Theme, GREEN, RED};
use super::remote;

/// Endpoint+token bundle handed to the ops tabs each frame (None in local mode).
#[derive(Clone)]
pub struct Server {
    pub endpoint: String,
    pub token: String,
}

fn local_hint(ui: &mut egui::Ui, what: &str) {
    ui.add_space(20.0);
    ui.label(format!(
        "{what} is server-backed β€” launch the viz against a running nornir-server \
         (NORNIR_SERVER=…) to use it."
    ));
}

// ── πŸ” Search ────────────────────────────────────────────────────────────────

#[derive(Default)]
pub struct SearchState {
    query: String,
    corpus: String,
    sym_repo: String,
    sym_query: String,
    vec_repo: String,
    vec_query: String,
    call_repo: String,
    call_name: String,
    call_to: String,
    hits: Option<Result<Vec<remote::Hit>, String>>,
    syms: Option<Result<Vec<remote::KnownSym>, String>>,
    vhits: Option<Result<Vec<remote::VecHit>, String>>,
    stats: Option<Result<(u64, Vec<(String, String)>), String>>,
    // (label, rows of "a β†’ b  (file:line)")
    calls: Option<Result<(String, Vec<String>), String>>,
    theme: Theme,
}

impl SearchState {
    /// Re-skin this pane with a facett palette (broadcast from the picker).
    pub fn set_palette(&mut self, t: Theme) {
        self.theme = t;
    }

    pub fn draw(&mut self, ui: &mut egui::Ui, srv: Option<&Server>, workspace: &str, log: &ActionLog) {
        let theme = self.theme;
        let Some(srv) = srv else { return local_hint(ui, "Search") };
        ui.horizontal(|ui| {
            ui.heading("πŸ” Search");
            if ui.button("index stats").on_hover_text("Index.Stats β€” corpus doc counts").clicked() {
                log.push(Kind::Rpc, "Index.Stats");
                self.stats = Some(remote::index_stats(&srv.endpoint, &srv.token, workspace).map_err(|e| format!("{e:#}")));
            }
            if let Some(Ok((total, by))) = &self.stats {
                ui.label(format!("index: {total} docs [{}]",
                    by.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>().join(", ")));
            } else if let Some(Err(e)) = &self.stats {
                ui.colored_label(RED, e);
            }
        });

        // BM25 full-text over the Tantivy corpora (Search.Query).
        ui.group(|ui| {
            ui.label("Full-text (BM25 over docs/code/bench/changelog/config)");
            ui.horizontal(|ui| {
                let go = ui.text_edit_singleline(&mut self.query).lost_focus()
                    && ui.input(|i| i.key_pressed(egui::Key::Enter));
                ui.label("corpus:");
                egui::ComboBox::from_id_salt("search_corpus")
                    .selected_text(if self.corpus.is_empty() { "all".into() } else { self.corpus.clone() })
                    .show_ui(ui, |ui| {
                        for c in ["", "docs", "code", "bench_history", "changelog", "config"] {
                            ui.selectable_value(&mut self.corpus, c.to_string(), if c.is_empty() { "all" } else { c });
                        }
                    });
                if (ui.button("Search").clicked() || go) && !self.query.trim().is_empty() {
                    log.push(Kind::Query, format!("Search.Query q={:?} corpus={:?}", self.query, self.corpus));
                    self.hits = Some(
                        remote::search(&srv.endpoint, &srv.token, &self.query, &self.corpus, "", 25, workspace)
                            .map_err(|e| format!("{e:#}")),
                    );
                }
            });
        });
        match &self.hits {
            Some(Ok(hits)) => {
                ui.label(format!("{} hit(s)", hits.len()));
                egui::ScrollArea::vertical().max_height(220.0).auto_shrink([false, false]).id_salt("hits").show(ui, |ui| {
                    for h in hits {
                        ui.horizontal(|ui| {
                            ui.colored_label(theme.text_dim, format!("[{}/{}] {:.2}", h.corpus, h.repo, h.score));
                            ui.strong(if h.title.is_empty() { &h.path } else { &h.title });
                        });
                        if !h.snippet.is_empty() {
                            ui.label(egui::RichText::new(&h.snippet).size(11.0).color(theme.text_dim));
                        }
                        ui.separator();
                    }
                });
            }
            Some(Err(e)) => { ui.colored_label(RED, e); }
            None => {}
        }

        ui.add_space(8.0);
        // Symbol lookup (Knowledge.SymbolLookup over symbol_facts).
        ui.group(|ui| {
            ui.label("Symbol lookup (item-name substring over symbol_facts)");
            ui.horizontal(|ui| {
                ui.label("repo:");
                ui.add(egui::TextEdit::singleline(&mut self.sym_repo).desired_width(120.0).hint_text("blank=all"));
                let go = ui.text_edit_singleline(&mut self.sym_query).lost_focus()
                    && ui.input(|i| i.key_pressed(egui::Key::Enter));
                if (ui.button("Lookup").clicked() || go) && !self.sym_query.trim().is_empty() {
                    log.push(Kind::Query, format!("Knowledge.SymbolLookup q={:?} repo={:?}", self.sym_query, self.sym_repo));
                    self.syms = Some(
                        remote::knowledge_lookup(&srv.endpoint, &srv.token, &self.sym_repo, &self.sym_query, 50, workspace)
                            .map_err(|e| format!("{e:#}")),
                    );
                }
            });
        });
        match &self.syms {
            Some(Ok(syms)) => {
                ui.label(format!("{} symbol(s)", syms.len()));
                egui::ScrollArea::vertical().max_height(220.0).auto_shrink([false, false]).id_salt("syms").show(ui, |ui| {
                    for s in syms {
                        ui.horizontal(|ui| {
                            ui.colored_label(theme.text_dim, format!("{} {}", s.visibility, s.item_kind));
                            ui.strong(&s.item_name);
                            ui.label(egui::RichText::new(format!("{}:{}", s.file, s.line)).monospace().size(11.0));
                        });
                        if !s.signature.is_empty() {
                            ui.label(egui::RichText::new(&s.signature).monospace().size(11.0).color(theme.text_dim));
                        }
                        ui.separator();
                    }
                });
            }
            Some(Err(e)) => { ui.colored_label(RED, e); }
            None => {}
        }

        ui.add_space(8.0);
        // Semantic / vector search (Vector.Search β€” GPU on oden, CPU fallback).
        ui.group(|ui| {
            ui.label("Semantic (vector embeddings β€” meaning, not keywords)");
            ui.horizontal(|ui| {
                ui.label("repo:");
                ui.add(egui::TextEdit::singleline(&mut self.vec_repo).desired_width(120.0).hint_text("repo name"));
                let go = ui.text_edit_singleline(&mut self.vec_query).lost_focus()
                    && ui.input(|i| i.key_pressed(egui::Key::Enter));
                if (ui.button("Semantic search").clicked() || go)
                    && !self.vec_query.trim().is_empty()
                    && !self.vec_repo.trim().is_empty()
                {
                    log.push(Kind::Query, format!("Vector.Search q={:?} repo={:?}", self.vec_query, self.vec_repo));
                    self.vhits = Some(
                        remote::vector_search(&srv.endpoint, &srv.token, &self.vec_repo, &self.vec_query, 15, workspace)
                            .map_err(|e| format!("{e:#}")),
                    );
                }
            });
        });
        match &self.vhits {
            Some(Ok(vh)) => {
                ui.label(format!("{} hit(s)", vh.len()));
                egui::ScrollArea::vertical().max_height(220.0).auto_shrink([false, false]).id_salt("vhits").show(ui, |ui| {
                    for h in vh {
                        ui.horizontal(|ui| {
                            ui.colored_label(GREEN, format!("{:.3}", h.score));
                            ui.label(egui::RichText::new(format!("{}:{}-{}", h.file, h.start_line, h.end_line)).monospace().size(11.0));
                        });
                    }
                });
            }
            Some(Err(e)) => { ui.colored_label(RED, e); }
            None => {}
        }

        ui.add_space(8.0);
        // Call relationships (Knowledge.Callers / Callees / CallPath) β€” the
        // authoritative warehouse set, beyond the capped on-screen graph edges.
        ui.group(|ui| {
            ui.label("Call relationships (callers / callees / path between)");
            ui.horizontal(|ui| {
                ui.label("repo:");
                ui.add(egui::TextEdit::singleline(&mut self.call_repo).desired_width(110.0).hint_text("blank=all"));
                ui.label("fn:");
                ui.add(egui::TextEdit::singleline(&mut self.call_name).desired_width(140.0).hint_text("function"));
                if ui.button("callers").clicked() && !self.call_name.trim().is_empty() {
                    log.push(Kind::Query, format!("Knowledge.Callers fn={:?} repo={:?}", self.call_name, self.call_repo));
                    self.calls = Some(self.run_calls(srv, workspace, true));
                }
                if ui.button("callees").clicked() && !self.call_name.trim().is_empty() {
                    log.push(Kind::Query, format!("Knowledge.Callees fn={:?} repo={:?}", self.call_name, self.call_repo));
                    self.calls = Some(self.run_calls(srv, workspace, false));
                }
            });
            ui.horizontal(|ui| {
                ui.label("…→ to:");
                ui.add(egui::TextEdit::singleline(&mut self.call_to).desired_width(140.0).hint_text("target fn"));
                if ui.button("path between").clicked()
                    && !self.call_name.trim().is_empty()
                    && !self.call_to.trim().is_empty()
                {
                    log.push(Kind::Query, format!("Knowledge.CallPath {:?} β†’ {:?}", self.call_name, self.call_to));
                    self.calls = Some(
                        remote::knowledge_call_path(&srv.endpoint, &srv.token, &self.call_repo, &self.call_name, &self.call_to, workspace)
                            .map(|p| (
                                if p.is_empty() { "no path found".into() } else { format!("path ({} hops)", p.len()) },
                                p,
                            ))
                            .map_err(|e| format!("{e:#}")),
                    );
                }
            });
        });
        match &self.calls {
            Some(Ok((label, rows))) => {
                ui.label(format!("{label}: {}", rows.len()));
                egui::ScrollArea::vertical().max_height(220.0).auto_shrink([false, false]).id_salt("calls").show(ui, |ui| {
                    for row in rows {
                        ui.label(egui::RichText::new(row).monospace().size(11.0));
                    }
                });
            }
            Some(Err(e)) => { ui.colored_label(RED, e); }
            None => {}
        }
    }

    fn run_calls(&self, srv: &Server, workspace: &str, callers: bool) -> Result<(String, Vec<String>), String> {
        remote::knowledge_calls(&srv.endpoint, &srv.token, &self.call_repo, &self.call_name, callers, 100, workspace)
            .map(|rows| {
                let label = if callers { "callers" } else { "callees" };
                let lines = rows
                    .into_iter()
                    .map(|(caller, callee, file, line)| format!("{caller} β†’ {callee}  ({file}:{line})"))
                    .collect();
                (label.to_string(), lines)
            })
            .map_err(|e| format!("{e:#}"))
    }

    /// πŸ” Search tab's slice of `state_json` (LAW #6): every form field the user
    /// can type into / pick (the BM25 query + corpus dropdown, the symbol/vector
    /// repo+query boxes, the call-graph repo/name/direction), PLUS the rendered
    /// results currently on screen (hit/symbol/vector counts, the index-stats
    /// totals, the call-path rows). So an agent reads back exactly what's typed
    /// and what's shown without a screen.
    pub fn state_json(&self) -> serde_json::Value {
        let result_state = |o: &Option<Result<usize, String>>| match o {
            None => serde_json::json!({ "ran": false }),
            Some(Ok(n)) => serde_json::json!({ "ran": true, "ok": true, "count": n }),
            Some(Err(e)) => serde_json::json!({ "ran": true, "ok": false, "error": e }),
        };
        let hits = self.hits.as_ref().map(|r| r.as_ref().map(|v| v.len()).map_err(|e| e.clone()));
        let syms = self.syms.as_ref().map(|r| r.as_ref().map(|v| v.len()).map_err(|e| e.clone()));
        let vhits = self.vhits.as_ref().map(|r| r.as_ref().map(|v| v.len()).map_err(|e| e.clone()));
        serde_json::json!({
            "palette": self.theme.name,
            // The interactive form state β€” what's typed/selected right now.
            "form": {
                "query": self.query,
                "corpus": self.corpus,
                "sym_repo": self.sym_repo,
                "sym_query": self.sym_query,
                "vec_repo": self.vec_repo,
                "vec_query": self.vec_query,
                "call_repo": self.call_repo,
                "call_name": self.call_name,
                "call_to": self.call_to,
            },
            // The rendered results currently shown for each sub-panel.
            "results": {
                "fulltext": result_state(&hits),
                "symbols": result_state(&syms),
                "vectors": result_state(&vhits),
                "index_stats": match &self.stats {
                    None => serde_json::json!({ "ran": false }),
                    Some(Ok((total, by))) => serde_json::json!({
                        "ran": true, "ok": true, "total": total,
                        "by_corpus": by.iter().map(|(k, v)| serde_json::json!([k, v])).collect::<Vec<_>>(),
                    }),
                    Some(Err(e)) => serde_json::json!({ "ran": true, "ok": false, "error": e }),
                },
                "calls": match &self.calls {
                    None => serde_json::json!({ "ran": false }),
                    Some(Ok((label, rows))) => serde_json::json!({
                        "ran": true, "ok": true, "label": label, "count": rows.len(), "rows": rows,
                    }),
                    Some(Err(e)) => serde_json::json!({ "ran": true, "ok": false, "error": e }),
                },
            },
        })
    }
}

// ── 🚦 Gates ─────────────────────────────────────────────────────────────────

#[derive(Default)]
pub struct GatesState {
    repo: String,
    report: Option<Result<remote::GateReport, String>>,
    trace: Option<Result<String, String>>,
    theme: Theme,
}

impl GatesState {
    /// Re-skin this pane with a facett palette (broadcast from the picker).
    pub fn set_palette(&mut self, t: Theme) {
        self.theme = t;
    }

    pub fn draw(&mut self, ui: &mut egui::Ui, srv: Option<&Server>, workspace: &str, repos: &[String], log: &ActionLog) {
        let theme = self.theme;
        let Some(srv) = srv else { return local_hint(ui, "Gates") };
        ui.heading("🚦 Release gates");
        if self.repo.is_empty() {
            self.repo = repos.first().cloned().unwrap_or_default();
        }
        ui.horizontal(|ui| {
            ui.label("repo:");
            egui::ComboBox::from_id_salt("gate_repo")
                .selected_text(if self.repo.is_empty() { "β€”".into() } else { self.repo.clone() })
                .show_ui(ui, |ui| {
                    for r in repos {
                        ui.selectable_value(&mut self.repo, r.clone(), r);
                    }
                });
            // Allow a free-typed repo when the config has none listed.
            ui.add(egui::TextEdit::singleline(&mut self.repo).desired_width(160.0).hint_text("repo name"));
            if ui.button("Run all gates").clicked() && !self.repo.trim().is_empty() {
                log.push(Kind::Rpc, format!("Release.GateAll repo={}", self.repo));
                self.report = Some(
                    remote::gate_all(&srv.endpoint, &srv.token, &self.repo, workspace).map_err(|e| format!("{e:#}")),
                );
            }
            if ui.button("Trace regression").clicked() && !self.repo.trim().is_empty() {
                log.push(Kind::Rpc, format!("Release.Trace repo={}", self.repo));
                self.trace = Some(
                    remote::trace(&srv.endpoint, &srv.token, &self.repo, workspace).map_err(|e| format!("{e:#}")),
                );
            }
        });
        ui.separator();
        match &self.report {
            Some(Ok(r)) => {
                ui.colored_label(GREEN, format!("βœ“ passed ({})", r.passed.len()));
                for p in &r.passed {
                    ui.colored_label(theme.text_dim, format!("   βœ“ {p}"));
                }
                if !r.failed.is_empty() {
                    ui.colored_label(RED, format!("βœ— failed ({})", r.failed.len()));
                    for (name, err) in &r.failed {
                        ui.colored_label(RED, format!("   βœ— {name}: {err}"));
                    }
                } else {
                    ui.colored_label(GREEN, "all gates green β€” releasable");
                }
            }
            Some(Err(e)) => { ui.colored_label(RED, e); }
            None => {}
        }
        if let Some(tr) = &self.trace {
            ui.separator();
            ui.label("regression trace:");
            egui::ScrollArea::vertical().max_height(240.0).auto_shrink([false, false]).id_salt("trace").show(ui, |ui| {
                match tr {
                    Ok(json) => {
                        let pretty = serde_json::from_str::<serde_json::Value>(json)
                            .ok()
                            .and_then(|v| serde_json::to_string_pretty(&v).ok())
                            .unwrap_or_else(|| json.clone());
                        ui.add(egui::Label::new(egui::RichText::new(pretty).monospace().size(11.0)));
                    }
                    Err(e) => { ui.colored_label(RED, e); }
                }
            });
        }
    }

    /// 🚦 Gates tab's slice of `state_json` (LAW #6): the selected/typed repo
    /// (the picker+free-text field) and the rendered gate report (passed/failed
    /// gate names) + whether a regression trace is loaded.
    pub fn state_json(&self) -> serde_json::Value {
        serde_json::json!({
            "palette": self.theme.name,
            "form": { "repo": self.repo },
            "report": match &self.report {
                None => serde_json::json!({ "ran": false }),
                Some(Ok(r)) => serde_json::json!({
                    "ran": true, "ok": true,
                    "passed": r.passed,
                    "failed": r.failed.iter().map(|(n, e)| serde_json::json!([n, e])).collect::<Vec<_>>(),
                    "releasable": r.failed.is_empty(),
                }),
                Some(Err(e)) => serde_json::json!({ "ran": true, "ok": false, "error": e }),
            },
            "trace": match &self.trace {
                None => serde_json::json!({ "ran": false }),
                Some(Ok(_)) => serde_json::json!({ "ran": true, "ok": true }),
                Some(Err(e)) => serde_json::json!({ "ran": true, "ok": false, "error": e }),
            },
        })
    }
}

// ── πŸ“ˆ Bench ─────────────────────────────────────────────────────────────────

pub struct BenchState {
    repo: String,
    points: Option<Result<Vec<remote::BenchPoint>, String>>,
    metric: String,
    /// πŸ“‘ P1.3: live bench telemetry (cores-busy/N + status) read from the
    /// warehouse `bench_telemetry`/`bench_runs` tables as a bench runs. Always
    /// present β€” local mode reads the tables, remote shows a "no RPC yet" note.
    live: super::bench_live::BenchLive,
    theme: Theme,
}

impl Default for BenchState {
    fn default() -> Self {
        Self {
            repo: String::new(),
            points: None,
            metric: String::new(),
            live: super::bench_live::BenchLive::local(std::path::PathBuf::new()),
            theme: Theme::default(),
        }
    }
}

impl BenchState {
    /// Local mode: the live telemetry panel reads the warehouse at `root`.
    pub fn local(root: std::path::PathBuf) -> Self {
        Self {
            repo: String::new(),
            points: None,
            metric: String::new(),
            live: super::bench_live::BenchLive::local(root),
            theme: Theme::default(),
        }
    }

    /// Remote mode: the history charts drive the server's `Bench.History`; the
    /// live telemetry panel reads `bench_telemetry`/`bench_runs` over the
    /// `Viz.BenchTelemetry` RPC.
    pub fn remote(endpoint: String, token: String, workspace: String) -> Self {
        Self {
            repo: String::new(),
            points: None,
            metric: String::new(),
            live: super::bench_live::BenchLive::remote(endpoint, token, workspace),
            theme: Theme::default(),
        }
    }

    /// Re-scope (workspace switch / reload): force the live panel to re-read.
    pub fn reload(&mut self) {
        self.live.reload();
    }

    /// Re-scope to a new workspace (workspace switch): hand the new workspace to
    /// the live panel so its `Viz.BenchTelemetry` reads the right warehouse.
    pub fn set_workspace(&mut self, ws: String) {
        self.live.set_workspace(ws);
    }

    /// Re-skin this pane with a facett palette (broadcast from the picker) β€” the
    /// history charts AND the embedded πŸ“‘ live-telemetry panel both re-skin.
    pub fn set_palette(&mut self, t: Theme) {
        self.theme = t;
        self.live.set_palette(t);
    }

    /// Test-only re-export so the inject-and-assert harness can seed the live
    /// telemetry panel directly.
    #[doc(hidden)]
    pub fn inject_live_for_test(
        &mut self,
        telemetry: Vec<crate::warehouse::iceberg::BenchTelemetryRow>,
        runs: Vec<(String, crate::bench::BenchRun)>,
    ) {
        self.live.inject_for_test(telemetry, runs);
    }

    pub fn draw(&mut self, ui: &mut egui::Ui, srv: Option<&Server>, workspace: &str, repos: &[String], log: &ActionLog) {
        // πŸ“‘ P1.3 LIVE telemetry first β€” visible in BOTH local and remote mode.
        self.live.draw(ui);
        let theme = self.theme;
        let Some(srv) = srv else { return local_hint(ui, "Bench") };
        ui.heading("πŸ“ˆ Bench history");
        if self.repo.is_empty() {
            self.repo = repos.first().cloned().unwrap_or_default();
        }
        ui.horizontal(|ui| {
            ui.label("repo:");
            egui::ComboBox::from_id_salt("bench_repo")
                .selected_text(if self.repo.is_empty() { "β€”".into() } else { self.repo.clone() })
                .show_ui(ui, |ui| {
                    for r in repos {
                        ui.selectable_value(&mut self.repo, r.clone(), r);
                    }
                });
            ui.add(egui::TextEdit::singleline(&mut self.repo).desired_width(160.0).hint_text("repo name"));
            if ui.button("Load history").clicked() && !self.repo.trim().is_empty() {
                log.push(Kind::Rpc, format!("Bench.History repo={}", self.repo));
                self.points = Some(
                    remote::bench_history(&srv.endpoint, &srv.token, &self.repo, workspace).map_err(|e| format!("{e:#}")),
                );
                self.metric.clear();
            }
        });
        ui.separator();
        let points = match &self.points {
            Some(Ok(p)) => p,
            Some(Err(e)) => { ui.colored_label(RED, e); return; }
            None => { ui.label("pick a repo and load its bench history"); return; }
        };
        if points.is_empty() {
            ui.label("no bench history recorded for this repo");
            return;
        }
        let metrics: Vec<String> = {
            let mut m: Vec<String> = points.iter().map(|p| p.metric.clone()).collect();
            m.sort();
            m.dedup();
            m
        };
        if self.metric.is_empty() {
            self.metric = metrics.first().cloned().unwrap_or_default();
        }
        ui.horizontal(|ui| {
            ui.label("metric:");
            egui::ComboBox::from_id_salt("bench_metric")
                .selected_text(&self.metric)
                .show_ui(ui, |ui| {
                    for m in &metrics {
                        ui.selectable_value(&mut self.metric, m.clone(), m);
                    }
                });
        });
        // One bar per run for the chosen metric (chronological as returned).
        let series: Vec<&remote::BenchPoint> = points.iter().filter(|p| p.metric == self.metric).collect();
        if series.is_empty() {
            ui.label("no points for this metric");
            return;
        }
        let max = series.iter().map(|p| p.value.abs()).fold(f64::EPSILON, f64::max);
        egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
            for p in &series {
                ui.horizontal(|ui| {
                    ui.add_sized([150.0, 16.0], egui::Label::new(
                        egui::RichText::new(format!("{} {}", p.date, p.version)).monospace().size(11.0),
                    ));
                    let frac = (p.value.abs() / max) as f32;
                    let (rect, _) = ui.allocate_exact_size(egui::Vec2::new(ui.available_width() - 90.0, 14.0), egui::Sense::hover());
                    ui.painter().rect_filled(
                        egui::Rect::from_min_size(rect.min, egui::Vec2::new((rect.width() * frac).max(1.0), 12.0)),
                        2.0,
                        theme.accent,
                    );
                    ui.label(egui::RichText::new(format!("{}", p.value)).monospace().size(11.0));
                });
            }
        });
    }

    /// πŸ“ˆ Bench tab's slice of `state_json` (LAW #6): the selected repo + metric
    /// (the two dropdowns / free-text repo field) and the loaded history (the
    /// per-run points for the chosen metric β€” date/version/value rows shown).
    pub fn state_json(&self) -> serde_json::Value {
        let live = self.live.state_json();
        match &self.points {
            None => serde_json::json!({
                "palette": self.theme.name,
                "form": { "repo": self.repo, "metric": self.metric },
                "loaded": false,
                "live": live,
            }),
            Some(Err(e)) => serde_json::json!({
                "palette": self.theme.name,
                "form": { "repo": self.repo, "metric": self.metric },
                "loaded": true, "ok": false, "error": e,
                "live": live,
            }),
            Some(Ok(points)) => {
                let mut metrics: Vec<String> = points.iter().map(|p| p.metric.clone()).collect();
                metrics.sort();
                metrics.dedup();
                let series: Vec<serde_json::Value> = points
                    .iter()
                    .filter(|p| p.metric == self.metric)
                    .map(|p| serde_json::json!({
                        "date": p.date, "version": p.version, "value": p.value,
                    }))
                    .collect();
                serde_json::json!({
                    "palette": self.theme.name,
                    "form": { "repo": self.repo, "metric": self.metric },
                    "loaded": true, "ok": true,
                    "metrics": metrics,
                    "point_count": points.len(),
                    "series": series,
                    "live": live,
                })
            }
        }
    }
}

// ── workspace info + ⟳ Sync-now (rendered inline near the picker) ────────────

#[derive(Default)]
pub struct WorkspacePanel {
    open: bool,
    info: Option<Result<remote::WorkspaceInfo, String>>,
    info_for: String,
    sync_result: Option<Result<(u32, Vec<String>, Vec<String>, String), String>>,
}

impl WorkspacePanel {
    /// Compact controls for the top bar: β„Ή toggle + ⟳ Sync now.
    ///
    /// Returns `true` when a sync was just triggered, so the caller can **reload
    /// the displayed timeline/warehouse immediately** β€” otherwise a server-side
    /// republish wouldn't show until the next 5 s auto-reload tick.
    #[must_use]
    pub fn draw_controls(&mut self, ui: &mut egui::Ui, srv: Option<&Server>, workspace: &str) -> bool {
        let Some(srv) = srv else { return false };
        if ui.selectable_label(self.open, "β„Ή info").clicked() {
            self.open = !self.open;
            if self.open {
                self.refresh(srv, workspace);
            }
        }
        let mut synced = false;
        if ui
            .button("⟳ Sync now")
            .on_hover_text(
                "Workspaces.Fetch (force) β€” poll the remote(s) and rebuild this \
                 workspace's warehouse now, then reload the view",
            )
            .clicked()
        {
            // force=true: republish even if no git member changed (e.g. the
            // warehouse was cleared) so it regenerates on demand, not on the poll.
            self.sync_result = Some(
                remote::fetch_workspace(&srv.endpoint, &srv.token, workspace, true)
                    .map_err(|e| format!("{e:#}")),
            );
            self.refresh(srv, workspace); // refresh shown SHAs after a sync
            synced = true;
        }
        synced
    }

    fn refresh(&mut self, srv: &Server, workspace: &str) {
        self.info = Some(remote::get_workspace(&srv.endpoint, &srv.token, workspace).map_err(|e| format!("{e:#}")));
        self.info_for = workspace.to_string();
    }

    /// Readable state for the headless matrix (the "components expose what they
    /// render" law). Includes the AUT6 per-member working-tree freshness:
    /// `{ member: { dirty, digest } }` plus a workspace-level `any_dirty` flag,
    /// so a test can assert the staleness signal without scraping pixels.
    pub fn state_json(&self) -> serde_json::Value {
        match &self.info {
            Some(Ok(i)) => {
                let freshness: serde_json::Map<String, serde_json::Value> = i
                    .freshness
                    .iter()
                    .map(|(name, dirty, digest)| {
                        (name.clone(), serde_json::json!({ "dirty": dirty, "digest": digest }))
                    })
                    .collect();
                let any_dirty = i.freshness.iter().any(|(_, d, _)| *d);
                serde_json::json!({
                    "open": self.open,
                    "workspace": i.name,
                    "snapshot": i.current_snapshot,
                    "freshness": freshness,
                    "any_dirty": any_dirty,
                })
            }
            Some(Err(e)) => serde_json::json!({ "open": self.open, "error": e }),
            None => serde_json::json!({ "open": self.open }),
        }
    }

    /// The expandable detail panel (rendered in the side panel when `open`).
    pub fn draw_panel(&mut self, ui: &mut egui::Ui, srv: Option<&Server>, workspace: &str) {
        if !self.open || srv.is_none() {
            return;
        }
        if self.info_for != workspace {
            self.refresh(srv.unwrap(), workspace);
        }
        ui.separator();
        ui.strong("workspace");
        match &self.info {
            Some(Ok(i)) => {
                ui.label(format!("{} Β· {}", i.name, i.mode));
                ui.label(format!("poll: {}", i.poll));
                ui.label(format!("snapshot: {}", short(&i.current_snapshot)));
                ui.label(format!("updated: {}", i.updated_at));
                ui.label(format!("members ({}):", i.members.len()));
                for (name, summary) in &i.members {
                    ui.label(egui::RichText::new(format!("  {name}: {summary}")).size(11.0));
                }
            }
            Some(Err(e)) => { ui.colored_label(RED, e); }
            None => {}
        }
        if let Some(sync) = &self.sync_result {
            ui.separator();
            match sync {
                Ok((fetched, changed, errors, snapshot)) => {
                    let snap = if snapshot.is_empty() {
                        String::new()
                    } else {
                        format!(" β†’ snapshot {}", short(snapshot))
                    };
                    ui.colored_label(
                        GREEN,
                        format!("synced: {fetched} fetched, {} changed{snap}", changed.len()),
                    );
                    for e in errors {
                        ui.colored_label(RED, format!("  {e}"));
                    }
                }
                Err(e) => { ui.colored_label(RED, e); }
            }
        }
    }
}

fn short(s: &str) -> String {
    // Truncate on a char boundary, not a raw byte index: snapshot ids / tags can
    // contain multibyte UTF-8, and `&s[..12]` would panic mid-codepoint.
    if s.chars().count() > 12 {
        let head: String = s.chars().take(12).collect();
        format!("{head}…")
    } else {
        s.to_string()
    }
}

#[cfg(test)]
mod short_tests {
    use super::short;

    #[test]
    fn short_passes_through_when_within_limit() {
        assert_eq!(short("abc123"), "abc123");
        assert_eq!(short("0123456789ab"), "0123456789ab"); // exactly 12 chars
    }

    #[test]
    fn short_truncates_ascii() {
        assert_eq!(short("0123456789abcdef"), "0123456789ab…");
    }

    #[test]
    fn short_never_panics_on_multibyte_boundary() {
        // Multibyte chars straddling byte index 12: a raw `&s[..12]` would panic
        // ("byte index 12 is not a char boundary"). This must truncate cleanly.
        let s = "ÀâüÀâüÀâüÀâüÀâü"; // each char is 2 bytes
        let out = short(s);
        assert_eq!(out.chars().take(12).collect::<String>(), "ÀâüÀâüÀâüÀâü…".chars().take(12).collect::<String>());
        // 12 chars kept + ellipsis.
        assert_eq!(out.chars().count(), 13);

        // Emoji (4-byte) snapshot label.
        let s = "πŸ¦€πŸ¦€πŸ¦€πŸ¦€πŸ¦€πŸ¦€πŸ¦€πŸ¦€πŸ¦€πŸ¦€πŸ¦€πŸ¦€πŸ¦€πŸ¦€";
        let out = short(s);
        assert_eq!(out.chars().count(), 13); // 12 crabs + ellipsis
    }
}