nornir 0.4.10

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
//! 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, Color32};

use super::action_log::{ActionLog, Kind};
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>>,
}

impl SearchState {
    pub fn draw(&mut self, ui: &mut egui::Ui, srv: Option<&Server>, workspace: &str, log: &ActionLog) {
        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(Color32::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(Color32::from_gray(150), 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(Color32::from_gray(180)));
                        }
                        ui.separator();
                    }
                });
            }
            Some(Err(e)) => { ui.colored_label(Color32::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(Color32::from_gray(150), 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(Color32::from_gray(170)));
                        }
                        ui.separator();
                    }
                });
            }
            Some(Err(e)) => { ui.colored_label(Color32::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(Color32::from_rgb(120, 180, 120), 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(Color32::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(Color32::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:#}"))
    }
}

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

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

impl GatesState {
    pub fn draw(&mut self, ui: &mut egui::Ui, srv: Option<&Server>, workspace: &str, repos: &[String], log: &ActionLog) {
        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(Color32::from_rgb(80, 180, 120), format!("βœ“ passed ({})", r.passed.len()));
                for p in &r.passed {
                    ui.label(format!("   βœ“ {p}"));
                }
                if !r.failed.is_empty() {
                    ui.colored_label(Color32::RED, format!("βœ— failed ({})", r.failed.len()));
                    for (name, err) in &r.failed {
                        ui.colored_label(Color32::from_rgb(220, 120, 100), format!("   βœ— {name}: {err}"));
                    }
                } else {
                    ui.colored_label(Color32::from_rgb(80, 180, 120), "all gates green β€” releasable");
                }
            }
            Some(Err(e)) => { ui.colored_label(Color32::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(Color32::RED, e); }
                }
            });
        }
    }
}

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

#[derive(Default)]
pub struct BenchState {
    repo: String,
    points: Option<Result<Vec<remote::BenchPoint>, String>>,
    metric: String,
}

impl BenchState {
    pub fn draw(&mut self, ui: &mut egui::Ui, srv: Option<&Server>, workspace: &str, repos: &[String], log: &ActionLog) {
        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(Color32::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,
                        Color32::from_rgb(80, 150, 220),
                    );
                    ui.label(egui::RichText::new(format!("{}", p.value)).monospace().size(11.0));
                });
            }
        });
    }
}

// ── 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();
    }

    /// 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(Color32::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(
                        Color32::from_rgb(80, 180, 120),
                        format!("synced: {fetched} fetched, {} changed{snap}", changed.len()),
                    );
                    for e in errors {
                        ui.colored_label(Color32::from_rgb(220, 120, 100), format!("  {e}"));
                    }
                }
                Err(e) => { ui.colored_label(Color32::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
    }
}