Skip to main content

mira/
tui.rs

1//! The terminal UI.
2//!
3//! Same four questions the browser UI asks, over the same three routes, in the
4//! place the person asking them already is. The browser UI wins on waterfalls
5//! and charts; this wins on being one `kubectl exec` away and on working with
6//! no server running at all — [`Source::Local`] reads a block directory
7//! in-process, so a detached volume is still readable after the pod that wrote
8//! it is gone.
9//!
10//! Everything here is synchronous. There is no runtime, no task and no channel:
11//! the loop draws, blocks on a key, and runs one query. A query that takes two
12//! seconds freezes the UI for two seconds — which is why the frame is painted
13//! *before* the query runs, so the freeze always has a "running" on it rather
14//! than a stale screen.
15
16mod rata;
17mod source;
18
19use std::time::Instant;
20
21use ratatui::style::{Modifier, Style, Stylize};
22use ratatui::text::Span;
23use yaml_rust2::Yaml;
24
25use crate::term::{self, Key, Term};
26use mira_core::json::Json;
27
28pub use source::{Source, parse_addr};
29
30/// Selectable query windows, coarse on purpose: the point of `[` and `]` is to
31/// change the answer in one keystroke, and a continuous control would need two.
32const WINDOWS: [&str; 7] = ["5m", "15m", "1h", "6h", "24h", "7d", "30d"];
33
34pub fn run(src: Source) -> Result<(), String> {
35    let mut app = App::new(src);
36    let mut term = Term::enter().map_err(|e| e.to_string())?;
37    loop {
38        let (w, h) = term.size();
39        term.draw(&app.frame(w, h)).map_err(|e| e.to_string())?;
40
41        // Deferred so the frame above — the one that says what is running — is
42        // on screen before the query blocks the thread that would have drawn it.
43        if let Some(job) = app.job.take() {
44            app.run(job, h);
45            continue;
46        }
47        // Follow mode is the read timing out rather than a thread or a channel:
48        // the whole UI is one loop, and a key that does not arrive within the
49        // interval is exactly the signal to re-run the query.
50        match term
51            .key(if app.tail { TAIL_MS } else { -1 })
52            .map_err(|e| e.to_string())?
53        {
54            Some(k) if !app.key(k, h) => return Ok(()),
55            // A tick, not a reload: `reload` writes "running" over the status
56            // bar, and a bar that strobes every three seconds is worse than no
57            // bar at all.
58            None if app.tail => app.job = Some(Job::Rows),
59            _ => {}
60        }
61    }
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65enum Tab {
66    Logs,
67    Traces,
68    Metrics,
69}
70
71impl Tab {
72    fn signal(self) -> &'static str {
73        match self {
74            Tab::Traces => "traces",
75            _ => "logs",
76        }
77    }
78
79    /// Where a filter word with no operator goes.
80    ///
81    /// Someone who types `refused` means "show me the ones that say refused",
82    /// which is what every log viewer in the market does with a bare word and
83    /// what this one used to do with it: nothing at all, silently, while the
84    /// filter bar showed the word and the rows looked filtered.
85    ///
86    /// `None` for metrics, whose `where` terms are attribute predicates on data
87    /// points — there is no text column to search, so a bare word there is
88    /// reported rather than invented a meaning for.
89    fn free_text(self) -> Option<&'static str> {
90        match self {
91            Tab::Logs => Some("body"),
92            Tab::Traces => Some("name"),
93            Tab::Metrics => None,
94        }
95    }
96
97    /// Columns of the signal's root table.
98    ///
99    /// This is what decides whether `name=checkout` filters a column or an
100    /// attribute, and getting it wrong is silent both ways: an unknown `field`
101    /// matches nothing rather than erroring, and a column missing from this
102    /// list is sent as `attr`, which the Bloom filter prunes to zero rows. That
103    /// is what happened to `event_name`, added to the schema after this list
104    /// was written — so `tests::the_field_list_is_the_schema` now pins the two
105    /// together. Not an intra-doc link: the target is behind `cfg(test)`, so it
106    /// does not exist in the configuration rustdoc builds.
107    fn fields(self) -> &'static [&'static str] {
108        match self {
109            Tab::Traces => &[
110                "trace_id",
111                "span_id",
112                "parent_span_id",
113                "trace_state",
114                "flags",
115                "name",
116                "kind",
117                "start_time_unix_nano",
118                "duration_nano",
119                "status_code",
120                "status_message",
121                "dropped_attributes_count",
122                "dropped_events_count",
123                "dropped_links_count",
124            ],
125            _ => &[
126                "time_unix_nano",
127                "observed_time_unix_nano",
128                "severity_number",
129                "severity_text",
130                "event_name",
131                "body",
132                "trace_id",
133                "span_id",
134                "flags",
135                "dropped_attributes_count",
136            ],
137        }
138    }
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142enum Mode {
143    List,
144    Filter,
145    Detail,
146    Trace,
147    /// One span of the waterfall, in the same renderer [`Mode::Detail`] uses.
148    ///
149    /// A separate mode rather than a flag on `Detail` because the two differ in
150    /// where they came from and where Esc goes back to, and because the span is
151    /// not in `self.rows` — see [`App::selected`].
152    Span,
153    /// The frame around whatever the filter matched (section 7.3), from `/correlate`.
154    Frame,
155    /// The service map, from `/map`.
156    Map,
157    /// The rules this node evaluates and what they are doing, from `/alerts`.
158    Alerts,
159    /// What the node counts about itself, from `/stats`.
160    Diag,
161    Help,
162}
163
164impl Mode {
165    /// Whether this pane scrolls a rendered body rather than selecting a row.
166    fn scrolls(self) -> bool {
167        matches!(self, Mode::Detail | Mode::Span | Mode::Help | Mode::Diag)
168    }
169}
170
171enum Job {
172    Rows,
173    Names,
174    Series,
175    Trace(String),
176    Frame,
177    Map,
178    Alerts,
179    Diag,
180}
181
182/// What Enter does to the selected line of the frame or map pane.
183enum Pick {
184    Service(String),
185    Trace(String),
186}
187
188/// How the map names the synthetic caller of every root span
189/// (`mira_core::frame::ENTRY`). A string where every other node key is a decimal
190/// entity key, so it cannot collide with one.
191const ENTRY_KEY: &str = "entry";
192
193struct App {
194    src: Source,
195    tab: Tab,
196    win: usize,
197    limit: usize,
198    filter: String,
199    /// The filter as it was before `/` was pressed, so Esc can put it back.
200    filter_undo: String,
201    mode: Mode,
202
203    rows: Vec<Yaml>,
204    sel: usize,
205
206    names: Vec<Yaml>,
207    nsel: usize,
208    series: Vec<Yaml>,
209    ssel: usize,
210    /// Which metrics pane the arrow keys drive.
211    on_series: bool,
212
213    trace: Option<Trace>,
214    /// The frame and map panes, and the one cursor they share — only one of the
215    /// two is ever on screen, and both are lists of things Enter acts on.
216    frame: Option<FrameView>,
217    map: Option<MapView>,
218    /// The alert list shares the same cursor: it is the third pane that is a
219    /// list of things Enter acts on, and only one of the three is ever drawn.
220    alerts: Vec<Yaml>,
221    /// The whole `/api/v1/stats` document, rendered rather than destructured —
222    /// a field added to the endpoint should appear here without a code change.
223    diag: Option<Yaml>,
224    psel: usize,
225    /// Re-run the list query on a timer instead of blocking on a key.
226    tail: bool,
227    scroll: usize,
228    stats: String,
229    /// `blocks_total` from the last answer that scanned any. An empty pane says
230    /// something different when there is nothing to scan: "no rows in the last
231    /// hour" is a window to widen, and "no blocks at all" is the wrong
232    /// directory, which is the mistake a first run actually makes.
233    blocks: i64,
234    status: String,
235    err: bool,
236    job: Option<Job>,
237}
238
239/// How long a follow tick waits for a key before giving up and re-querying.
240///
241/// The same three seconds the browser UI polls on, and for the same reason: a
242/// read here is single-digit milliseconds, so the interval is chosen for how
243/// often a person wants the screen to change, not for what the engine can take.
244const TAIL_MS: i32 = 3000;
245
246/// What `/correlate` came back with, flattened into the two lists it draws.
247///
248/// Services are grouped by name because an entity is an *instance* (section 7.2):
249/// three replicas of one service are three entities, which matters to the
250/// engine and not to someone reading a strip of names.
251struct FrameView {
252    from: i64,
253    to: i64,
254    truncated: bool,
255    services: Vec<(String, usize)>,
256    traces: Vec<String>,
257}
258
259/// The service map as a call tree rather than a graph.
260///
261/// A terminal draws a tree well and a graph badly, and the tree is the reading
262/// that answers the question anyway: what calls what, and where does it start.
263/// One line per node, so every line is something Enter can act on — the same
264/// shape as the waterfall, which is the other tree in this UI.
265struct MapView {
266    rows: Vec<(usize, Yaml)>,
267    unresolved: i64,
268}
269
270struct Trace {
271    id: String,
272    /// Spans in waterfall order — depth-first from each root, children by start
273    /// time — paired with their indent depth.
274    spans: Vec<(Yaml, usize)>,
275    t0: i64,
276    span_ns: i64,
277    sel: usize,
278}
279
280impl App {
281    fn new(src: Source) -> App {
282        App {
283            src,
284            tab: Tab::Logs,
285            win: 2,
286            limit: 200,
287            filter: String::new(),
288            filter_undo: String::new(),
289            mode: Mode::List,
290            rows: Vec::new(),
291            sel: 0,
292            names: Vec::new(),
293            nsel: 0,
294            series: Vec::new(),
295            ssel: 0,
296            on_series: false,
297            trace: None,
298            frame: None,
299            map: None,
300            alerts: Vec::new(),
301            diag: None,
302            psel: 0,
303            tail: false,
304            scroll: 0,
305            stats: String::new(),
306            blocks: 0,
307            status: "loading".into(),
308            err: false,
309            job: Some(Job::Rows),
310        }
311    }
312
313    // ---- queries ----------------------------------------------------------
314
315    fn reload(&mut self) {
316        self.status = "running".into();
317        self.err = false;
318        self.job = Some(match self.tab {
319            Tab::Metrics => Job::Names,
320            _ => Job::Rows,
321        });
322    }
323
324    fn run(&mut self, job: Job, h: usize) {
325        let t = Instant::now();
326        let r = match &job {
327            Job::Rows => self.src.post(source::QUERY, &self.rows_query()),
328            Job::Names => self.src.post(source::NAMES, &self.window_query()),
329            Job::Series => self.src.post(source::SERIES, &self.series_query()),
330            Job::Trace(id) => self.src.post(source::QUERY, &trace_query(id)),
331            Job::Frame => self.src.post(source::CORRELATE, &self.frame_query()),
332            Job::Map => self.src.post(source::MAP, &self.window_query()),
333            Job::Alerts => self.src.get(source::ALERTS),
334            Job::Diag => self.src.get(source::STATS),
335        };
336        let doc = match r {
337            Ok(d) => d,
338            Err(e) => {
339                self.status = e;
340                self.err = true;
341                return;
342            }
343        };
344        self.err = false;
345        self.stats = match job {
346            // Neither answers about blocks, so the scan counters would all read
347            // zero and look like a query that found nothing.
348            Job::Alerts | Job::Diag => ms(t.elapsed()),
349            _ => {
350                self.blocks = doc["stats"]["blocks_total"].as_i64().unwrap_or(0);
351                format!("{} · {}", stats_line(&doc["stats"]), ms(t.elapsed()))
352            }
353        };
354        self.status.clear();
355
356        if let Some(w) = self.ignored_word() {
357            self.status = format!("ignored {w:?}: metrics filters are attr=value terms");
358        }
359
360        match job {
361            Job::Rows => {
362                self.rows = array(&doc["rows"]);
363                // A follow tick must not yank the cursor back to the top:
364                // someone watching a stream is usually reading one row while
365                // the rest of them move under it.
366                match self.tail {
367                    true => self.sel = self.sel.min(self.rows.len().saturating_sub(1)),
368                    false => {
369                        self.sel = 0;
370                        self.scroll = 0;
371                    }
372                }
373                if self.rows.is_empty() {
374                    self.status = match self.blocks {
375                        0 => "nothing has been written here".into(),
376                        _ => "no rows in this window".into(),
377                    };
378                }
379            }
380            Job::Names => {
381                self.names = array(&doc["names"]);
382                self.nsel = 0;
383                self.on_series = false;
384                match self.names.is_empty() {
385                    true => self.status = "no metrics in this window".into(),
386                    // One name selected is one chart the user did not have to
387                    // ask for; the metrics tab is useless until a series loads.
388                    false => self.job = Some(Job::Series),
389                }
390            }
391            Job::Series => {
392                self.series = array(&doc["series"]);
393                self.ssel = 0;
394                self.scroll = 0;
395            }
396            Job::Trace(id) => {
397                let spans = array(&doc["rows"]);
398                if spans.is_empty() {
399                    self.status = format!("no spans found for trace {id}");
400                    self.err = true;
401                    return;
402                }
403                self.trace = Some(Trace::new(id, &spans));
404                self.mode = Mode::Trace;
405                self.scroll = 0;
406                let _ = h;
407            }
408            Job::Frame => {
409                let f = FrameView::new(&doc["frame"]);
410                if f.services.is_empty() && f.traces.is_empty() {
411                    self.status = "nothing matched, so there is no frame to widen".into();
412                    return;
413                }
414                self.frame = Some(f);
415                self.mode = Mode::Frame;
416                self.psel = 0;
417            }
418            Job::Alerts => {
419                self.alerts = array(&doc["alerts"]);
420                self.mode = Mode::Alerts;
421                self.psel = 0;
422                if self.alerts.is_empty() {
423                    // Not "everything is healthy". A node with no rules file
424                    // pages nobody, and that is the one thing this pane must not
425                    // let a reader assume.
426                    self.status =
427                        "this node evaluates no rules — set alerts.rules in mira.yaml".into();
428                }
429            }
430            Job::Diag => {
431                self.diag = Some(doc);
432                self.mode = Mode::Diag;
433                self.scroll = 0;
434            }
435            Job::Map => {
436                let m = MapView::new(&doc["map"]);
437                if m.rows.is_empty() {
438                    // Not an error: a store with logs and no traces is a
439                    // perfectly ordinary store, and the map is built from
440                    // `parent_span_id` at read time.
441                    self.status = "no spans in this window, so there is no map".into();
442                    return;
443                }
444                self.map = Some(m);
445                self.mode = Mode::Map;
446                self.psel = 0;
447            }
448        }
449    }
450
451    fn rows_query(&self) -> String {
452        let mut j = Json::new();
453        j.obj(|j| {
454            j.key("signal");
455            j.str(self.tab.signal());
456            j.key("from");
457            j.str(&format!("-{}", WINDOWS[self.win]));
458            j.key("to");
459            j.str("now");
460            j.key("limit");
461            j.i64(self.limit as i64);
462            j.key("where");
463            self.terms(j);
464        });
465        j.into_string()
466    }
467
468    /// The same filter the list is showing, expanded into a frame.
469    ///
470    /// `traces` then `peers`, in that order and not the other: `traces` measures
471    /// the real extent of what was found, and `peers` then reads the services
472    /// inside it. Reversed, `peers` runs against the window the rows happened to
473    /// land in and finds only what is already on screen.
474    ///
475    /// No `limit`: a frame is bounded by the engine's own entity and trace caps
476    /// and says so in `truncated`, which is a different question from how many
477    /// rows this pane can draw.
478    fn frame_query(&self) -> String {
479        let mut j = Json::new();
480        j.obj(|j| {
481            j.key("signal");
482            j.str(self.tab.signal());
483            j.key("from");
484            j.str(&format!("-{}", WINDOWS[self.win]));
485            j.key("to");
486            j.str("now");
487            j.key("expand");
488            j.arr(|j| {
489                j.str("traces");
490                j.str("peers");
491            });
492            j.key("where");
493            self.terms(j);
494        });
495        j.into_string()
496    }
497
498    fn window_query(&self) -> String {
499        let mut j = Json::new();
500        j.obj(|j| {
501            j.key("from");
502            j.str(&format!("-{}", WINDOWS[self.win]));
503            j.key("to");
504            j.str("now");
505        });
506        j.into_string()
507    }
508
509    fn series_query(&self) -> String {
510        let name = self
511            .names
512            .get(self.nsel)
513            .and_then(|n| n["name"].as_str())
514            .unwrap_or_default()
515            .to_owned();
516        let mut j = Json::new();
517        j.obj(|j| {
518            j.key("name");
519            j.str(&name);
520            j.key("from");
521            j.str(&format!("-{}", WINDOWS[self.win]));
522            j.key("to");
523            j.str("now");
524            // ponytail: 64 series is three screenfuls at three lines each, and
525            // the engine does not report `max_series` truncation the way it
526            // reports `max_points`, so the 65th is invisible here. Give it a
527            // badge when the response grows a count to put in one.
528            j.key("max_series");
529            j.i64(64);
530            // A sparkline is one character per point, so the API's default of
531            // 5 000 would download three orders of magnitude more than the
532            // widest terminal can render. Not scaled to the terminal either:
533            // `spark` buckets by the column's peak, so points past the column
534            // count still decide whether a spike shows, and 400 is enough of
535            // them for any width. What the cap costs — it keeps the newest
536            // 400, not a thinned 400 — is on screen as `+n dropped`.
537            j.key("max_points");
538            j.i64(400);
539            j.key("where");
540            self.terms(j);
541        });
542        j.into_string()
543    }
544
545    /// A word in the filter that this tab has nowhere to put.
546    ///
547    /// Only metrics can produce one — every other tab reads a bare word as free
548    /// text. The one thing that must not happen is silence: the filter bar goes
549    /// on showing the word, so the rows look filtered when they are not.
550    fn ignored_word(&self) -> Option<String> {
551        if self.tab.free_text().is_some() {
552            return None;
553        }
554        parse_filter(&self.filter)
555            .into_iter()
556            .find_map(|p| match p {
557                Part::Word(w) => Some(w),
558                Part::Term(..) => None,
559            })
560    }
561
562    fn terms(&self, j: &mut Json) {
563        j.arr(|j| {
564            for part in parse_filter(&self.filter) {
565                let (key, op, val) = match part {
566                    Part::Term(k, op, v) => (k, op, v),
567                    // A bare word is free text over the tab's message column.
568                    // Quoted, so `scalar` cannot decide that `500` was a number
569                    // and hand `body` an integer to compare against.
570                    Part::Word(w) => match self.tab.free_text() {
571                        Some(f) => {
572                            j.obj(|j| {
573                                j.key("field");
574                                j.str(f);
575                                j.key("contains");
576                                j.str(&w);
577                            });
578                            continue;
579                        }
580                        None => continue,
581                    },
582                };
583                let field = self.tab.fields().contains(&key.as_str());
584                j.obj(|j| {
585                    j.key(if field { "field" } else { "attr" });
586                    j.str(&key);
587                    j.key(op);
588                    scalar(j, &key, &val);
589                });
590            }
591        });
592    }
593
594    // ---- keys -------------------------------------------------------------
595
596    /// Handle one key. `false` means quit.
597    fn key(&mut self, k: Key, h: usize) -> bool {
598        if self.mode == Mode::Filter {
599            return self.filter_key(k);
600        }
601        let page = body_h(h).saturating_sub(1).max(1);
602        match k {
603            Key::Char('q') | Key::Ctrl('c') if self.mode == Mode::List => return false,
604            // Back one step, not back to the list: a span detail was opened
605            // from the waterfall and that is where its reader still is.
606            Key::Char('q') | Key::Esc => {
607                self.mode = match self.mode {
608                    Mode::Span => Mode::Trace,
609                    _ => Mode::List,
610                }
611            }
612            Key::Ctrl('c') => return false,
613            Key::Char('?') => {
614                self.mode = match self.mode {
615                    Mode::Help => Mode::List,
616                    _ => Mode::Help,
617                }
618            }
619            Key::Char('1') => self.go(Tab::Logs),
620            Key::Char('2') => self.go(Tab::Traces),
621            Key::Char('3') => self.go(Tab::Metrics),
622            Key::Char('h') | Key::Left => self.go(match self.tab {
623                Tab::Logs => Tab::Metrics,
624                Tab::Traces => Tab::Logs,
625                Tab::Metrics => Tab::Traces,
626            }),
627            Key::Char('l') | Key::Right => self.go(match self.tab {
628                Tab::Logs => Tab::Traces,
629                Tab::Traces => Tab::Metrics,
630                Tab::Metrics => Tab::Logs,
631            }),
632            Key::Tab if self.tab == Tab::Metrics && self.mode == Mode::List => {
633                self.on_series = !self.on_series;
634            }
635            Key::Char('j') | Key::Down => self.move_by(1),
636            Key::Char('k') | Key::Up => self.move_by(-1),
637            Key::PageDown | Key::Ctrl('f') => self.move_by(page as isize),
638            Key::PageUp | Key::Ctrl('b') => self.move_by(-(page as isize)),
639            Key::Home | Key::Char('g') => self.move_to(0),
640            Key::End | Key::Char('G') => self.move_to(usize::MAX),
641            Key::Char('/') if self.mode == Mode::List => {
642                self.filter_undo = self.filter.clone();
643                self.mode = Mode::Filter;
644            }
645            Key::Char('r') => self.reload(),
646            Key::Char('[') => {
647                self.win = self.win.saturating_sub(1);
648                self.reload();
649            }
650            Key::Char(']') => {
651                self.win = (self.win + 1).min(WINDOWS.len() - 1);
652                self.reload();
653            }
654            Key::Char('+') | Key::Char('=') => {
655                self.limit = (self.limit * 2).min(10_000);
656                self.reload();
657            }
658            Key::Char('-') => {
659                self.limit = (self.limit / 2).max(10);
660                self.reload();
661            }
662            Key::Enter => match self.mode {
663                Mode::List if self.tab == Tab::Metrics && !self.on_series => {
664                    self.job = Some(Job::Series);
665                    self.status = "running".into();
666                }
667                Mode::List => {
668                    self.mode = Mode::Detail;
669                    self.scroll = 0;
670                }
671                // The waterfall renders a span's shape; its attributes and its
672                // status message only exist in the detail view, and without
673                // this the selected span had no way to reach one.
674                Mode::Trace => {
675                    self.mode = Mode::Span;
676                    self.scroll = 0;
677                }
678                Mode::Frame | Mode::Map => self.follow_pick(),
679                Mode::Alerts => self.follow_alert(),
680                _ => {}
681            },
682            Key::Char('t') => self.open_trace(),
683            Key::Char('c') if self.mode == Mode::List => match self.tab {
684                Tab::Metrics => {
685                    self.status = "correlate anchors on logs or traces; switch tab first".into();
686                    self.err = true;
687                }
688                _ => {
689                    self.status = "running".into();
690                    self.job = Some(Job::Frame);
691                }
692            },
693            Key::Char('m') if self.mode == Mode::List => {
694                self.status = "running".into();
695                self.job = Some(Job::Map);
696            }
697            // Both answer for the node rather than for the data, so neither
698            // depends on the tab, the filter or the window — and both are
699            // reachable from wherever the reader already is.
700            Key::Char('a') => {
701                self.status = "running".into();
702                self.job = Some(Job::Alerts);
703            }
704            Key::Char('d') => {
705                self.status = "running".into();
706                self.job = Some(Job::Diag);
707            }
708            // Follow, in the `tail -f` sense. Only the record list: the metrics
709            // tab reloads its name list and reselects, and a pane that
710            // reselects under the reader every three seconds is unusable.
711            Key::Char('f') => match (self.mode, self.tab) {
712                (Mode::List, Tab::Logs | Tab::Traces) => {
713                    self.tail = !self.tail;
714                    if self.tail {
715                        self.reload();
716                    }
717                }
718                _ => {
719                    self.status = "follow needs the logs or traces list".into();
720                    self.err = true;
721                }
722            },
723            _ => {}
724        }
725        true
726    }
727
728    /// Enter, in the frame or map pane.
729    ///
730    /// Everything in either pane is a link back into an ordinary query, which is
731    /// what the algebra's closure buys (section 7.3): there is nothing selectable here
732    /// that lands the reader somewhere they cannot then filter.
733    fn follow_pick(&mut self) {
734        match self.pick() {
735            Some(Pick::Trace(id)) => {
736                self.status = format!("loading trace {id}");
737                self.job = Some(Job::Trace(id));
738            }
739            // Anded onto the filter rather than replacing it: the frame is a
740            // narrowing step, and whatever is already typed is the reason this
741            // frame exists.
742            Some(Pick::Service(name)) => {
743                let t = service_term(&name);
744                // Selecting the same service twice is a double-press, not a
745                // request for the term twice.
746                if !self.filter.contains(&t) {
747                    if !self.filter.is_empty() {
748                        self.filter.push(' ');
749                    }
750                    self.filter.push_str(&t);
751                }
752                self.mode = Mode::List;
753                self.reload();
754            }
755            None => {}
756        }
757    }
758
759    /// Enter, on an alert: show the records the rule counted.
760    ///
761    /// The rule's `where` terms come back from the API already spelled in the
762    /// filter-bar grammar (`alert::filter_of`), so this is an assignment rather
763    /// than a translation — the alert and the query it fired on cannot drift
764    /// into two different filters, because there is only one spelling of them.
765    /// The window is left alone: `over` is how the rule counts, and a reader who
766    /// has just been paged usually wants more history than that, not less.
767    fn follow_alert(&mut self) {
768        let Some(a) = self.alerts.get(self.psel) else {
769            return;
770        };
771        self.tab = match a["signal"].as_str() {
772            Some("traces") => Tab::Traces,
773            _ => Tab::Logs,
774        };
775        self.filter = a["filter"].as_str().unwrap_or_default().to_owned();
776        self.mode = Mode::List;
777        self.reload();
778    }
779
780    /// What the frame or map cursor is pointing at.
781    fn pick(&self) -> Option<Pick> {
782        match self.mode {
783            Mode::Frame => {
784                let f = self.frame.as_ref()?;
785                match f.services.get(self.psel) {
786                    Some((n, _)) => Some(Pick::Service(n.clone())),
787                    None => f
788                        .traces
789                        .get(self.psel - f.services.len())
790                        .map(|t| Pick::Trace(t.clone())),
791                }
792            }
793            Mode::Map => {
794                let (_, n) = self.map.as_ref()?.rows.get(self.psel)?;
795                // `entry` is synthetic — the caller of every root span — so
796                // there is no service behind it to filter on.
797                match n["key"].as_str() {
798                    Some(ENTRY_KEY) => None,
799                    _ => Some(Pick::Service(n["name"].as_str()?.to_owned())),
800                }
801            }
802            _ => None,
803        }
804    }
805
806    fn filter_key(&mut self, k: Key) -> bool {
807        match k {
808            Key::Enter => {
809                self.mode = Mode::List;
810                self.reload();
811            }
812            Key::Esc | Key::Ctrl('c') => {
813                self.filter = std::mem::take(&mut self.filter_undo);
814                self.mode = Mode::List;
815            }
816            Key::Backspace => {
817                self.filter.pop();
818            }
819            Key::Ctrl('u') => self.filter.clear(),
820            Key::Ctrl('w') => {
821                let keep = self.filter.trim_end();
822                let cut = keep.rfind(' ').map_or(0, |i| i + 1);
823                self.filter.truncate(cut);
824            }
825            Key::Char(c) => self.filter.push(c),
826            _ => {}
827        }
828        true
829    }
830
831    fn go(&mut self, tab: Tab) {
832        if self.tab != tab || self.mode != Mode::List {
833            self.tab = tab;
834            self.mode = Mode::List;
835            self.reload();
836        }
837    }
838
839    /// Move whichever cursor the current pane owns.
840    ///
841    /// One function rather than one per view because every view's list is a
842    /// selected index plus a length, and the clamping is the part that is easy
843    /// to get wrong twice.
844    ///
845    /// Clamped in `usize`, not `isize`. The scrolling panes report their length
846    /// as `usize::MAX` — see [`cursor`](App::cursor) — and that is a negative
847    /// `isize`, so an `isize` clamp reads its own upper bound as below its lower
848    /// bound and panics. `j` in the detail pane is the keystroke that did it.
849    fn move_by(&mut self, d: isize) {
850        let (sel, len) = self.cursor();
851        self.set_cursor(sel.saturating_add_signed(d).min(len.saturating_sub(1)));
852    }
853
854    fn move_to(&mut self, n: usize) {
855        let (_, len) = self.cursor();
856        self.set_cursor(n.min(len.saturating_sub(1)));
857    }
858
859    fn cursor(&self) -> (usize, usize) {
860        match (self.mode, self.tab) {
861            // The detail and help panes scroll rather than select, but the
862            // arithmetic is the same and the bound is the line count, which the
863            // renderer knows and this does not — so let it run to the end and
864            // let `frame` clamp.
865            (m, _) if m.scrolls() => (self.scroll, usize::MAX),
866            (Mode::Trace, _) => (
867                self.trace.as_ref().map_or(0, |t| t.sel),
868                self.trace.as_ref().map_or(0, |t| t.spans.len()),
869            ),
870            (Mode::Frame, _) => (self.psel, self.frame.as_ref().map_or(0, FrameView::len)),
871            (Mode::Map, _) => (self.psel, self.map.as_ref().map_or(0, |m| m.rows.len())),
872            (Mode::Alerts, _) => (self.psel, self.alerts.len()),
873            (_, Tab::Metrics) if self.on_series => (self.ssel, self.series.len()),
874            (_, Tab::Metrics) => (self.nsel, self.names.len()),
875            _ => (self.sel, self.rows.len()),
876        }
877    }
878
879    fn set_cursor(&mut self, n: usize) {
880        match (self.mode, self.tab) {
881            (m, _) if m.scrolls() => self.scroll = n,
882            (Mode::Trace, _) => {
883                if let Some(t) = self.trace.as_mut() {
884                    t.sel = n;
885                }
886            }
887            (Mode::Frame | Mode::Map | Mode::Alerts, _) => self.psel = n,
888            (_, Tab::Metrics) if self.on_series => self.ssel = n,
889            (_, Tab::Metrics) => self.nsel = n,
890            _ => self.sel = n,
891        }
892    }
893
894    /// Follow whatever trace the selection points at.
895    ///
896    /// This is the correlation story as one keystroke: a log line carries the
897    /// `trace_id` of the request that emitted it, a span carries its own, and a
898    /// metric exemplar carries the id of the request that produced the
899    /// measurement. Three different tabs, one key, because to the person
900    /// looking it is the same question.
901    fn open_trace(&mut self) {
902        let id = match (self.mode, self.tab) {
903            // Already inside the trace this would open.
904            (Mode::Trace | Mode::Span, _) => return,
905            // These panes have their own selection, and the record list's is
906            // behind them — following that one would open a trace nobody is
907            // pointing at.
908            (Mode::Frame | Mode::Map, _) => match self.pick() {
909                Some(Pick::Trace(id)) => Some(id),
910                _ => None,
911            },
912            (_, Tab::Metrics) => self
913                .series
914                .get(self.ssel)
915                .and_then(|s| s["exemplars"][0]["trace_id"].as_str())
916                .map(str::to_owned),
917            _ => self
918                .rows
919                .get(self.sel)
920                .and_then(|r| r["trace_id"].as_str())
921                .map(str::to_owned),
922        };
923        match id.filter(|s| s.len() == 32 && s.bytes().any(|b| b != b'0')) {
924            Some(id) => {
925                self.status = format!("loading trace {id}");
926                self.job = Some(Job::Trace(id));
927            }
928            None => {
929                self.status = "nothing here carries a trace id".into();
930                self.err = true;
931            }
932        }
933    }
934
935    fn selected(&self) -> Option<&Yaml> {
936        match (self.mode, self.tab) {
937            // The waterfall's own selection, which is not in `self.rows` and
938            // usually cannot be: a followed trace is queried over all of
939            // retention, so its spans are rarely the rows the list tab holds.
940            (Mode::Span, _) => self
941                .trace
942                .as_ref()
943                .and_then(|t| t.spans.get(t.sel))
944                .map(|(s, _)| s),
945            (_, Tab::Metrics) => self.series.get(self.ssel),
946            _ => self.rows.get(self.sel),
947        }
948    }
949
950    // ---- rendering --------------------------------------------------------
951
952    fn frame(&mut self, w: usize, h: usize) -> Vec<String> {
953        // A terminal narrower than this cannot show a timestamp and a body, and
954        // every column computation below starts clamping to zero. Drawing the
955        // frame at 40 anyway is worse than not drawing it: `Term::draw` has no
956        // cursor addressing, so every over-wide row wraps and the top of the
957        // frame scrolls off for good, with nothing on screen saying why.
958        if w < 40 || h < 8 {
959            return vec![rata::row(w, vec!["terminal too small — need 40x8".red()])];
960        }
961        let mut out = Vec::with_capacity(h);
962        out.push(self.tabbar(w));
963        out.push(self.filterbar(w));
964
965        let bh = body_h(h);
966        let mut body = match self.mode {
967            Mode::Help => help(w),
968            Mode::Detail | Mode::Span => self.detail_full(w),
969            Mode::Trace => self.waterfall(w, bh),
970            Mode::Frame => self.frame_pane(w, bh),
971            Mode::Map => self.map_pane(w, bh),
972            Mode::Alerts => self.alerts_pane(w, bh),
973            Mode::Diag => self.diag_pane(w),
974            _ => match self.tab {
975                Tab::Metrics => self.metrics(w, bh),
976                _ => self.records(w, bh),
977            },
978        };
979        // Scrolling panes hand back every line they have and are windowed here,
980        // so each one does not have to reimplement the clamp.
981        if self.mode.scrolls() {
982            self.scroll = self.scroll.min(body.len().saturating_sub(1));
983            body = body.into_iter().skip(self.scroll).take(bh).collect();
984        }
985        body.truncate(bh);
986        while body.len() < bh {
987            body.push(String::new());
988        }
989        out.extend(body);
990        out.push(self.statusbar(w));
991        out.push(self.hints(w));
992        out
993    }
994
995    fn tabbar(&self, w: usize) -> String {
996        let mut left = vec![" mira ".bold()];
997        for (i, (n, t)) in [
998            ("1 logs", Tab::Logs),
999            ("2 traces", Tab::Traces),
1000            ("3 metrics", Tab::Metrics),
1001        ]
1002        .iter()
1003        .enumerate()
1004        {
1005            left.push(Span::raw(if i == 0 { " " } else { "  " }));
1006            left.push(match *t == self.tab {
1007                true => format!(" {n} ").reversed(),
1008                false => format!(" {n} ").dim(),
1009            });
1010        }
1011        rata::bar(w, left, vec![self.src.label().dim(), Span::raw(" ")])
1012    }
1013
1014    fn filterbar(&self, w: usize) -> String {
1015        // The window and limit are reserved before anything else is written, so
1016        // an 80-column terminal clips the filter rather than the two fields that
1017        // say what the filter was applied to.
1018        let right = format!(
1019            "{}last {}  limit {}",
1020            if self.tail { "● follow  " } else { "" },
1021            WINDOWS[self.win],
1022            self.limit
1023        );
1024        let editing = self.mode == Mode::Filter;
1025        let mut left = vec![match editing {
1026            true => " filter> ".bold(),
1027            false => " filter  ".dim(),
1028        }];
1029        match (self.filter.is_empty(), editing) {
1030            (true, false) => {
1031                left.push("(none) — press / to add one, e.g. service.name=checkout".dim());
1032            }
1033            _ => {
1034                left.push(Span::raw(self.filter.clone()));
1035                if editing {
1036                    // A block where the cursor would be. The real cursor is
1037                    // hidden for the whole session, so drawing one is cheaper
1038                    // than showing and positioning it every frame.
1039                    left.push(" ".reversed());
1040                }
1041            }
1042        }
1043        rata::bar(w, left, vec![right.dim(), Span::raw(" ")])
1044    }
1045
1046    fn statusbar(&self, w: usize) -> String {
1047        let mut spans = vec![Span::raw(" ")];
1048        match self.status.is_empty() {
1049            false => spans.push(match self.err {
1050                true => self.status.clone().red(),
1051                false => self.status.clone().yellow(),
1052            }),
1053            true => spans.push(self.stats.clone().dim()),
1054        }
1055        if !self.status.is_empty() && !self.stats.is_empty() {
1056            spans.push(Span::raw("  "));
1057            spans.push(self.stats.clone().dim());
1058        }
1059        rata::row(w, spans)
1060    }
1061
1062    fn hints(&self, w: usize) -> String {
1063        // Where Esc goes, not that it goes somewhere. Every pane here was
1064        // opened from the list under it, and naming that list is the
1065        // difference between one keystroke and pressing `q` until something
1066        // familiar comes back.
1067        let back = match self.tab {
1068            Tab::Logs => "esc → logs",
1069            Tab::Traces => "esc → traces",
1070            Tab::Metrics => "esc → metrics",
1071        };
1072        let keys = match self.mode {
1073            Mode::Filter => "enter apply  esc cancel  ^w word  ^u clear".into(),
1074            Mode::Detail => format!("{back}  ↑↓ scroll  t trace"),
1075            Mode::Trace => format!("{back}  ↑↓ span  enter detail"),
1076            Mode::Span => "esc → waterfall  ↑↓ scroll".into(),
1077            Mode::Frame => format!("{back}  ↑↓ move  enter service→filter, trace→waterfall"),
1078            Mode::Map => format!("{back}  ↑↓ move  enter filter on this service"),
1079            Mode::Alerts => format!("{back}  ↑↓ move  enter show the records that fired  a reload"),
1080            Mode::Diag => format!("{back}  ↑↓ scroll  d reload"),
1081            // The list is longer than a short terminal, and a pane that is
1082            // cut off at the bottom with no hint that it continues is how a
1083            // key ends up looking like it does not exist.
1084            Mode::Help => format!("{back}  ↑↓ scroll"),
1085            Mode::List => {
1086                let full = match self.tab {
1087                    Tab::Metrics => {
1088                        "↑↓ move  tab pane  enter load  ·  m map  a alerts  d node  ·  / filter  [] window  ? help  q quit"
1089                    }
1090                    _ => {
1091                        "↑↓ move  enter detail  t trace  c frame  ·  m map  a alerts  d node  ·  / filter  f follow  ? help  q quit"
1092                    }
1093                };
1094                // The full bar does not fit in 80 columns, and what falls off
1095                // the end is `? help` and `q quit` — the two a reader who is
1096                // stuck needs most. So the narrow terminal drops the panes,
1097                // which are what `?` lists.
1098                match full.chars().count() + 2 <= w {
1099                    true => full.into(),
1100                    false => "↑↓ move  enter open  / filter  ? help  q quit".into(),
1101                }
1102            }
1103        };
1104        rata::row(w, vec![format!(" {keys}").dim()])
1105    }
1106
1107    /// What an empty pane says, instead of nothing at all.
1108    ///
1109    /// What it replaces was a blank body and one yellow phrase in the footer,
1110    /// which reads as a broken pane rather than an empty one — and the footer
1111    /// is the last place anyone looks. The two ways to get here want opposite
1112    /// advice, so they are answered separately: no blocks at all is a
1113    /// `--data-dir` pointed somewhere nothing was ever written, and no rows in
1114    /// a directory that has some is a window or a filter to change.
1115    fn nothing(&self, w: usize, what: &str) -> Vec<String> {
1116        let mut out = vec![String::new()];
1117        let mut say = |s: String, key: bool| {
1118            out.push(rata::row(
1119                w,
1120                vec![match key {
1121                    true => s.bold(),
1122                    false => s.dim(),
1123                }],
1124            ));
1125        };
1126        match self.blocks {
1127            0 => {
1128                say("   nothing has been written here".into(), true);
1129                say(format!("   {} · 0 blocks", self.src.label()), false);
1130                say(String::new(), false);
1131                say(
1132                    "   → --data-dir wants a directory mira has written to, and".into(),
1133                    false,
1134                );
1135                say(
1136                    "     --addr a node that is up. `make demo` fills one.".into(),
1137                    false,
1138                );
1139            }
1140            _ => {
1141                say(format!("   no {what} matched"), true);
1142                say(
1143                    match self.filter.is_empty() {
1144                        true => format!("   last {}, no filter", WINDOWS[self.win]),
1145                        false => format!("   last {} · {}", WINDOWS[self.win], self.filter),
1146                    },
1147                    false,
1148                );
1149                say(String::new(), false);
1150                say(
1151                    "   → ] widens the window · / edits the filter · r re-runs".into(),
1152                    false,
1153                );
1154            }
1155        }
1156        out
1157    }
1158
1159    /// Logs and traces: a list on top, the selection's detail below.
1160    fn records(&self, w: usize, h: usize) -> Vec<String> {
1161        if self.rows.is_empty() {
1162            return self.nothing(
1163                w,
1164                match self.tab {
1165                    Tab::Traces => "spans",
1166                    _ => "records",
1167                },
1168            );
1169        }
1170        // Two thirds to the list. Below about a quarter the detail pane shows
1171        // nothing useful, and above about a half the list stops being a list.
1172        let list_h = (h * 2 / 3).max(1);
1173        let top = window_start(self.sel, list_h, self.rows.len());
1174        let scale = match self.tab {
1175            Tab::Traces => self
1176                .rows
1177                .iter()
1178                .map(|r| i64_of(&r["duration_nano"]))
1179                .max()
1180                .unwrap_or(1)
1181                .max(1),
1182            _ => 1,
1183        };
1184
1185        // Traces are rows, not a `Table`: the duration bar is sized from what
1186        // is left of the line after the fixed columns, which a table's own
1187        // width solver is not told about.
1188        let mut out: Vec<String> = match self.tab {
1189            Tab::Traces => self
1190                .rows
1191                .iter()
1192                .enumerate()
1193                .skip(top)
1194                .take(list_h)
1195                .map(|(i, row)| span_row(row, w, i == self.sel, scale))
1196                .collect(),
1197            _ => rata::log_list(&self.rows, w, list_h, self.sel, top),
1198        };
1199        while out.len() < list_h {
1200            out.push(String::new());
1201        }
1202
1203        // There is always a selection here: the empty case returned above, and
1204        // `sel` is clamped to the rows on every move.
1205        let title = format!(
1206            " {} {} of {} ",
1207            match self.tab {
1208                Tab::Traces => "span",
1209                _ => "record",
1210            },
1211            self.sel + 1,
1212            self.rows.len()
1213        );
1214        out.push(rata::rule(w, &title));
1215        let left = h - out.len();
1216        if let Some(row) = self.selected() {
1217            out.extend(rata::detail(row, w).into_iter().take(left));
1218        }
1219        out
1220    }
1221
1222    fn detail_full(&self, w: usize) -> Vec<String> {
1223        match self.selected() {
1224            Some(row) => rata::detail(row, w),
1225            None => vec![rata::row(w, vec!["  nothing selected".dim()])],
1226        }
1227    }
1228
1229    /// Metric names on the left, the selected name's series on the right.
1230    fn metrics(&self, w: usize, h: usize) -> Vec<String> {
1231        if self.names.is_empty() {
1232            return self.nothing(w, "metrics");
1233        }
1234        let nw = 34.min(w / 3);
1235        let top = window_start(self.nsel, h, self.names.len());
1236        let mut out = Vec::with_capacity(h);
1237
1238        let chart_w = w.saturating_sub(nw + 3);
1239        let right = self.series_lines(chart_w);
1240        let rtop = window_start(self.ssel * 3, h, right.len());
1241
1242        for i in 0..h {
1243            let cells = match self.names.get(top + i) {
1244                Some(n) => {
1245                    let style = match (top + i == self.nsel, self.on_series) {
1246                        (true, false) => Style::default().add_modifier(Modifier::REVERSED),
1247                        (true, true) => Style::default().add_modifier(Modifier::BOLD),
1248                        _ => Style::default(),
1249                    };
1250                    let name = clip(n["name"].as_str().unwrap_or("?"), nw.saturating_sub(9));
1251                    vec![
1252                        (
1253                            nw.saturating_sub(8) as u16,
1254                            vec![Span::styled(format!(" {name}"), style)],
1255                        ),
1256                        (8, vec![clip(n["kind"].as_str().unwrap_or(""), 8).dim()]),
1257                    ]
1258                }
1259                None => vec![(nw as u16, Vec::new())],
1260            };
1261            // The chart half arrives already styled and already `chart_w` wide,
1262            // so it is concatenated rather than re-rendered: pushing ANSI back
1263            // through a `Buffer` would mean parsing the escapes out again.
1264            out.push(format!(
1265                "{}{} │ {}{}",
1266                rata::columns(nw, Style::default(), cells),
1267                term::DIM,
1268                term::RESET,
1269                right.get(rtop + i).map_or("", String::as_str)
1270            ));
1271        }
1272        out
1273    }
1274
1275    /// Three lines per series: its attributes, its sparkline, its exemplars.
1276    ///
1277    /// Pre-rendered as plain strings and then windowed by the caller, because
1278    /// the vertical scroll is over series and each one is a fixed three rows.
1279    fn series_lines(&self, w: usize) -> Vec<String> {
1280        if self.series.is_empty() {
1281            // Rendered even though it is one phrase, so the caller's promise
1282            // that every line here is exactly `w` wide holds for this one too.
1283            // A pane with no names at all never reaches here — `metrics` says
1284            // so itself and returns before splitting the columns.
1285            return vec![rata::row(w, vec![" enter to load this metric".dim()])];
1286        }
1287        let mut out = Vec::with_capacity(self.series.len() * 3);
1288        for (i, s) in self.series.iter().enumerate() {
1289            let sel = self.on_series && i == self.ssel;
1290            let mark = if sel { "▌" } else { " " };
1291            let attrs = pairs(&s["attributes"])
1292                .iter()
1293                .filter(|(k, _)| !k.starts_with("otel.scope."))
1294                .map(|(k, v)| format!("{k}={v}"))
1295                .collect::<Vec<_>>()
1296                .join(" ");
1297            out.push(rata::row(
1298                w,
1299                vec![
1300                    Span::raw(mark),
1301                    Span::styled(
1302                        attrs,
1303                        match sel {
1304                            true => Style::default().add_modifier(Modifier::BOLD),
1305                            false => Style::default(),
1306                        },
1307                    ),
1308                ],
1309            ));
1310
1311            let pts: Vec<f64> = s["points"]
1312                .as_vec()
1313                .map(|v| v.iter().filter_map(|p| num(&p[1])).collect())
1314                .unwrap_or_default();
1315            let mut spans = vec![Span::raw(mark)];
1316            match pts.is_empty() {
1317                true => spans.push("no points".dim()),
1318                false => {
1319                    let (lo, hi) = (
1320                        pts.iter().cloned().fold(f64::INFINITY, f64::min),
1321                        pts.iter().cloned().fold(f64::NEG_INFINITY, f64::max),
1322                    );
1323                    // `max_points` truncation is newest-wins, so a capped
1324                    // sparkline is the tail of the window drawn under a filter
1325                    // bar that still says `last 24h`. Its width is taken out of
1326                    // the bar rather than appended, because the row clips at the
1327                    // edge and the one thing that must not be clipped is the
1328                    // line saying the picture is incomplete. The browser legend
1329                    // carries the same badge, for the same reason.
1330                    let badge = match s["dropped_points"].as_i64().unwrap_or(0) {
1331                        0 => String::new(),
1332                        n => format!("  +{n} dropped"),
1333                    };
1334                    let bars = w.saturating_sub(28 + badge.len()).max(8);
1335                    spans.push(spark(&pts, bars).cyan());
1336                    spans.push(Span::raw("  "));
1337                    spans.push(format!("{} → {}", g(lo), g(hi)).dim());
1338                    if !badge.is_empty() {
1339                        spans.push(badge.yellow());
1340                    }
1341                }
1342            }
1343            let ex = s["exemplars"].as_vec().map_or(0, Vec::len);
1344            if ex > 0 {
1345                spans.push(Span::raw(" "));
1346                spans.push(format!("◆{ex}").magenta());
1347            }
1348            out.push(rata::row(w, spans));
1349
1350            let mut spans = vec![Span::raw(mark)];
1351            if let Some(id) = s["exemplars"][0]["trace_id"].as_str() {
1352                spans.push("◆ ".magenta());
1353                spans.push("trace ".dim());
1354                spans.push(Span::raw(clip(id, 32)));
1355                spans.push("  t to open".dim());
1356            }
1357            out.push(rata::row(w, spans));
1358        }
1359        out
1360    }
1361
1362    /// The frame: the window it measured, the services in it, the traces in it.
1363    fn frame_pane(&self, w: usize, h: usize) -> Vec<String> {
1364        let Some(f) = &self.frame else {
1365            return Vec::new();
1366        };
1367        let mut out = Vec::with_capacity(h);
1368        out.push(rata::row(
1369            w,
1370            vec![
1371                " frame ".bold(),
1372                format!(
1373                    "{} → {}  ·  {}",
1374                    stamp(f.from),
1375                    stamp(f.to),
1376                    dur((f.to - f.from).max(0))
1377                )
1378                .dim(),
1379            ],
1380        ));
1381        if f.truncated {
1382            // A capped frame is a sample, and a sample read as a census is the
1383            // one way this pane can be confidently wrong.
1384            out.push(rata::row(
1385                w,
1386                vec![" sample — narrow the filter before concluding".yellow()],
1387            ));
1388        }
1389
1390        out.push(rata::rule(w, &format!(" {} services ", f.services.len())));
1391        for (i, (name, n)) in f.services.iter().enumerate() {
1392            let hl = rata::hl(i == self.psel);
1393            let mut spans = vec![Span::raw(format!("  {name}"))];
1394            if *n > 1 {
1395                // Three replicas of one service are three entities and one
1396                // name. The count is the only thing on screen that says so.
1397                spans.push(format!("  ×{n}").dim());
1398            }
1399            out.push(rata::row_styled(w, hl, spans));
1400        }
1401
1402        out.push(rata::rule(w, &format!(" {} traces ", f.traces.len())));
1403        let head = h.saturating_sub(out.len());
1404        let top = window_start(
1405            self.psel.saturating_sub(f.services.len()),
1406            head,
1407            f.traces.len(),
1408        );
1409        for (i, id) in f.traces.iter().enumerate().skip(top).take(head) {
1410            let hl = rata::hl(f.services.len() + i == self.psel);
1411            out.push(rata::row_styled(w, hl, vec![Span::raw(format!("  {id}"))]));
1412        }
1413        out
1414    }
1415
1416    /// The service map, as a call tree rooted at `entry`.
1417    fn map_pane(&self, w: usize, h: usize) -> Vec<String> {
1418        let Some(m) = &self.map else {
1419            return Vec::new();
1420        };
1421        let mut out = Vec::with_capacity(h);
1422        let mut head = vec![
1423            " map ".bold(),
1424            format!("{} services", m.rows.len() - 1).dim(),
1425        ];
1426        if m.unresolved > 0 {
1427            // Every edge on screen is a lower bound without this: an unresolved
1428            // span is one whose parent was not in the sample, so its call was
1429            // never counted against anything.
1430            head.push(
1431                format!(
1432                    "  ·  {} spans with a parent outside the sample",
1433                    m.unresolved
1434                )
1435                .yellow(),
1436            );
1437        }
1438        out.push(rata::row(w, head));
1439        out.push(rata::rule(w, ""));
1440
1441        let vis = h.saturating_sub(2);
1442        let top = window_start(self.psel, vis, m.rows.len());
1443        for (i, (depth, n)) in m.rows.iter().enumerate().skip(top).take(vis) {
1444            out.push(map_row(n, *depth, i == self.psel, w));
1445        }
1446        out
1447    }
1448
1449    /// Every rule this node evaluates, firing or not.
1450    ///
1451    /// Quiet rules are listed as prominently as loud ones. An alerting screen
1452    /// that shows only what is on fire cannot answer the question an operator
1453    /// actually has at 3am — "is the rule I wrote for this even running?" — and
1454    /// an empty screen then means both "all clear" and "nothing is watching".
1455    fn alerts_pane(&self, w: usize, h: usize) -> Vec<String> {
1456        let mut out = Vec::with_capacity(h);
1457        let firing = self
1458            .alerts
1459            .iter()
1460            .filter(|a| a["state"].as_str() == Some("firing"))
1461            .count();
1462        out.push(rata::row(
1463            w,
1464            vec![
1465                " alerts ".bold(),
1466                format!("{} rules  ·  ", self.alerts.len()).dim(),
1467                match firing > 0 {
1468                    true => format!("{firing} firing").red(),
1469                    false => format!("{firing} firing").dim(),
1470                },
1471            ],
1472        ));
1473        out.push(rata::rule(w, ""));
1474
1475        // Two lines each, so the selected rule's predicate is on screen without
1476        // a keystroke: the filter *is* the explanation of the number.
1477        let vis = h.saturating_sub(2) / 2;
1478        let top = window_start(self.psel, vis.max(1), self.alerts.len());
1479        for (i, a) in self.alerts.iter().enumerate().skip(top).take(vis) {
1480            let sel = i == self.psel;
1481            let state = a["state"].as_str().unwrap_or("?");
1482            let dot = match state {
1483                "firing" => "●",
1484                "pending" => "◐",
1485                _ => "○",
1486            };
1487            let word = format!("{state:<8}");
1488            out.push(rata::row_styled(
1489                w,
1490                rata::hl(sel),
1491                vec![
1492                    Span::raw(format!("  {dot:<7}")),
1493                    match (sel, state) {
1494                        (true, _) => Span::raw(word),
1495                        (_, "firing") => word.red(),
1496                        (_, "pending") => word.yellow(),
1497                        _ => word.green(),
1498                    },
1499                    Span::raw(format!(
1500                        "{:<28}",
1501                        clip(a["name"].as_str().unwrap_or("?"), 27)
1502                    )),
1503                    Span::raw(alert_value(a)),
1504                ],
1505            ));
1506
1507            out.push(rata::row(
1508                w,
1509                vec![match a["error"].as_str() {
1510                    // An unevaluated rule is not a quiet one, and the pane says
1511                    // which it is: the state above reads "ok" either way.
1512                    Some(e) => format!("          {}", clip(e, w.saturating_sub(11))).red(),
1513                    None => format!(
1514                        "          {}  ·  over {}",
1515                        clip(
1516                            match a["filter"].as_str().unwrap_or_default() {
1517                                "" => "(no filter — every record)",
1518                                f => f,
1519                            },
1520                            w.saturating_sub(30)
1521                        ),
1522                        dur(i64_of(&a["over_nano"]))
1523                    )
1524                    .dim(),
1525                }],
1526            ));
1527        }
1528        out
1529    }
1530
1531    /// What this node counts about itself: `/api/v1/stats`, laid out.
1532    ///
1533    /// Every number here is one the ingest path already keeps or the filesystem
1534    /// already knows, so opening this pane costs a `readdir` and nothing else —
1535    /// a diagnostics screen that perturbs what it measures is worse than none.
1536    /// `mmap` residency is deliberately absent: `mincore` over a week of blocks
1537    /// is thousands of syscalls per refresh, and the page cache is the OS's to
1538    /// report. ponytail: add it per-block behind an explicit key if a hit rate
1539    /// ever turns out to be the question someone is actually asking.
1540    fn diag_pane(&self, w: usize) -> Vec<String> {
1541        let Some(d) = &self.diag else {
1542            return Vec::new();
1543        };
1544        let mut out = Vec::new();
1545        // The one number on this screen that is a reason to wake someone up.
1546        let free = num(&d["free_fraction"]);
1547        let disk = match free {
1548            Some(f) => format!("disk {:.0}% free", f * 100.0),
1549            None => "disk unreadable".to_owned(),
1550        };
1551        let mut head = vec![
1552            " node ".bold(),
1553            format!(
1554                "up {}  ·  peak rss {}  ·  ",
1555                since(i64_of(&d["uptime_s"])),
1556                bytes(i64_of(&d["peak_rss_bytes"]) as f64)
1557            )
1558            .dim(),
1559            match free {
1560                Some(f) if f < 0.1 => disk.red(),
1561                Some(f) if f < 0.2 => disk.yellow(),
1562                _ => disk.dim(),
1563            },
1564        ];
1565        // Only when it has happened. On every volume Mira is meant to run on
1566        // this is zero, and a permanent "degraded syncs 0" would train the eye
1567        // to skip the line on the one node where it is not.
1568        if i64_of(&d["degraded_syncs"]) > 0 {
1569            head.push(
1570                format!(
1571                    "  ·  degraded syncs {}",
1572                    tally(i64_of(&d["degraded_syncs"]) as f64)
1573                )
1574                .yellow(),
1575            );
1576        }
1577        out.push(rata::row(w, head));
1578
1579        let q = &d["queries"];
1580        out.push(rata::rule(w, " queries "));
1581        out.push(kv(w, "served", &tally(num(&q["count"]).unwrap_or(0.0))));
1582        out.push(kv(
1583            w,
1584            "mean",
1585            &format!("{:.2} ms", num(&q["mean_ms"]).unwrap_or(0.0)),
1586        ));
1587        out.push(kv(
1588            w,
1589            "max",
1590            &format!("{:.2} ms", num(&q["max_ms"]).unwrap_or(0.0)),
1591        ));
1592
1593        for signal in ["logs", "traces", "metrics"] {
1594            let s = &d["signals"][signal];
1595            if s.is_badvalue() {
1596                continue;
1597            }
1598            out.push(rata::rule(w, &format!(" {signal} ")));
1599            let (rows, on_disk) = (i64_of(&s["rows"]) as f64, i64_of(&s["bytes"]) as f64);
1600            out.push(kv(w, "rows written", &tally(rows)));
1601            out.push(kv(
1602                w,
1603                "blocks",
1604                &format!(
1605                    "{} on disk  ·  {} published",
1606                    match num(&s["blocks_on_disk"]) {
1607                        Some(b) => tally(b),
1608                        // Absent is "the filesystem would not answer", which is
1609                        // not zero blocks — see the endpoint's own comment.
1610                        None => "?".into(),
1611                    },
1612                    tally(i64_of(&s["blocks_published"]) as f64)
1613                ),
1614            ));
1615            // Bytes per row on disk is the cost-per-GB axis (section 11) measured on
1616            // this node's own data rather than on a benchmark corpus: Arrow
1617            // encoding, dictionary sharing and zstd, all of it, in one number.
1618            out.push(kv(
1619                w,
1620                "bytes on disk",
1621                &match rows > 0.0 {
1622                    true => format!("{}  ·  {:.0} B/row", bytes(on_disk), on_disk / rows),
1623                    false => bytes(on_disk),
1624                },
1625            ));
1626            if let Some(age) = num(&s["open_block_age_s"]) {
1627                out.push(kv(w, "open block", &since(age as i64)));
1628            }
1629            let (shed, failed, refused) = (
1630                i64_of(&s["shed"]),
1631                i64_of(&s["failed"]),
1632                i64_of(&s["refused"]),
1633            );
1634            let counts = format!("{shed} shed  ·  {failed} failed  ·  {refused} refused");
1635            out.push(rata::row(
1636                w,
1637                vec![
1638                    format!("  {:<16}", "rejected").dim(),
1639                    match shed + failed + refused > 0 {
1640                        true => counts.yellow(),
1641                        false => Span::raw(counts),
1642                    },
1643                ],
1644            ));
1645            // Stalled is the readiness condition, so it is the one line here
1646            // that is never printed as a zero and never left off when set.
1647            if let Some(secs) = num(&s["stalled_s"]) {
1648                out.push(rata::row(
1649                    w,
1650                    vec![
1651                        format!("  {:<16}", "stalled").red(),
1652                        format!(
1653                            "{} — this node cannot store this signal",
1654                            since(secs as i64)
1655                        )
1656                        .red(),
1657                    ],
1658                ));
1659            }
1660        }
1661        out
1662    }
1663
1664    fn waterfall(&self, w: usize, h: usize) -> Vec<String> {
1665        let Some(t) = &self.trace else {
1666            return Vec::new();
1667        };
1668        let mut out = Vec::with_capacity(h);
1669        out.push(rata::row(
1670            w,
1671            vec![
1672                " trace ".bold(),
1673                Span::raw(t.id.clone()),
1674                format!("  ·  {} spans  ·  {}", t.spans.len(), dur(t.span_ns.max(0))).dim(),
1675            ],
1676        ));
1677        out.push(rata::rule(w, ""));
1678
1679        // Where each column ends: the tree, the service, the bar, the duration.
1680        // Ends rather than widths because every write is "fill up to here", and
1681        // the last one is `w`, so the row always adds up to the frame.
1682        let namew = (w / 3).clamp(16, 46);
1683        let svcw = (w / 6).clamp(8, 20);
1684        // `run` never draws below 40 columns, which leaves the bar five cells
1685        // once the name, service and duration have taken theirs.
1686        let ends = [namew, namew + svcw, w.saturating_sub(11), w];
1687
1688        let lines: Vec<String> = t
1689            .spans
1690            .iter()
1691            .enumerate()
1692            .flat_map(|(i, (s, depth))| {
1693                let indent = " ".repeat((depth + 2).min(namew));
1694                let mut rows = vec![span_bar(s, *depth, i == t.sel, ends, t)];
1695                for e in s["events"].as_vec().into_iter().flatten() {
1696                    let at = i64_of(&e["time_unix_nano"]) - t.t0;
1697                    rows.push(rata::row(
1698                        w,
1699                        vec![
1700                            Span::raw(indent.clone()),
1701                            "● ".yellow(),
1702                            Span::raw(e["name"].as_str().unwrap_or("event").to_owned()),
1703                            format!("  +{}", dur(at.max(0))).dim(),
1704                        ],
1705                    ));
1706                }
1707                for l in s["links"].as_vec().into_iter().flatten() {
1708                    rows.push(rata::row(
1709                        w,
1710                        vec![
1711                            Span::raw(indent.clone()),
1712                            "↗ ".blue(),
1713                            "trace ".dim(),
1714                            Span::raw(l["trace_id"].as_str().unwrap_or("?").to_owned()),
1715                        ],
1716                    ));
1717                }
1718                rows
1719            })
1720            .collect();
1721
1722        // Scroll so the selected span stays on screen. Its line number is not
1723        // its index — events and links push it down — so it is counted rather
1724        // than assumed.
1725        let selected_line = t
1726            .spans
1727            .iter()
1728            .take(t.sel)
1729            .map(|(s, _)| {
1730                1 + s["events"].as_vec().map_or(0, Vec::len)
1731                    + s["links"].as_vec().map_or(0, Vec::len)
1732            })
1733            .sum::<usize>();
1734        let vis = h.saturating_sub(2);
1735        let top = window_start(selected_line, vis, lines.len());
1736        out.extend(lines.into_iter().skip(top).take(vis));
1737        out
1738    }
1739}
1740
1741impl FrameView {
1742    fn new(y: &Yaml) -> FrameView {
1743        let mut services: Vec<(String, usize)> = Vec::new();
1744        for e in y["entities"].as_vec().into_iter().flatten() {
1745            let name = e["name"].as_str().unwrap_or("unknown").to_owned();
1746            match services.iter_mut().find(|(n, _)| *n == name) {
1747                Some((_, n)) => *n += 1,
1748                None => services.push((name, 1)),
1749            }
1750        }
1751        // The engine returns entities sorted by key, which is a hash — so a
1752        // name-ordered list is the only one that reads the same twice.
1753        services.sort_by(|a, b| a.0.cmp(&b.0));
1754        FrameView {
1755            // `from`/`to` are int64 and so arrive as strings (section 7.6).
1756            from: i64_of(&y["from"]),
1757            to: i64_of(&y["to"]),
1758            truncated: y["truncated"].as_bool().unwrap_or(false),
1759            services,
1760            traces: y["traces"]
1761                .as_vec()
1762                .into_iter()
1763                .flatten()
1764                .filter_map(|t| t.as_str().map(str::to_owned))
1765                .collect(),
1766        }
1767    }
1768
1769    fn len(&self) -> usize {
1770        self.services.len() + self.traces.len()
1771    }
1772}
1773
1774impl MapView {
1775    /// Depth-first from `entry`, children by descending call volume.
1776    ///
1777    /// Volume order rather than name order because the first thing anyone wants
1778    /// out of a service map is the hot path, and it should be the first thing
1779    /// they read. A service reachable by two paths is drawn under the first one
1780    /// reached and not again: a tree with the same subtree in it twice is a tree
1781    /// nobody can count spans off.
1782    fn new(y: &Yaml) -> MapView {
1783        let nodes = y["nodes"].as_vec().map_or(&[][..], Vec::as_slice);
1784        let edges = y["edges"].as_vec().map_or(&[][..], Vec::as_slice);
1785        // `entry` is synthetic and so is not in `nodes`, but the tree has to
1786        // start somewhere and a map that hides where traffic arrives cannot be
1787        // read. No `spans` or `errors`: it is a caller, not a service.
1788        let entry = {
1789            let mut h = yaml_rust2::yaml::Hash::new();
1790            for k in ["key", "name"] {
1791                h.insert(Yaml::String(k.into()), Yaml::String(ENTRY_KEY.into()));
1792            }
1793            Yaml::Hash(h)
1794        };
1795
1796        let mut rows: Vec<(usize, Yaml)> = Vec::with_capacity(nodes.len() + 1);
1797        if nodes.is_empty() {
1798            return MapView {
1799                rows,
1800                unresolved: 0,
1801            };
1802        }
1803        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
1804        let mut stack = vec![(ENTRY_KEY.to_owned(), 0usize)];
1805        while let Some((key, depth)) = stack.pop() {
1806            if !seen.insert(key.clone()) {
1807                continue;
1808            }
1809            let node = match key == ENTRY_KEY {
1810                true => &entry,
1811                false => match nodes.iter().find(|n| n["key"].as_str() == Some(&key)) {
1812                    Some(n) => n,
1813                    // An edge naming a node the sample never reached. Skipping
1814                    // it loses nothing: its own spans are not in `nodes` either.
1815                    None => continue,
1816                },
1817            };
1818            rows.push((depth, node.clone()));
1819            let mut kids: Vec<(&Yaml, u64)> = edges
1820                .iter()
1821                .filter(|e| e["from"].as_str() == Some(&key))
1822                .map(|e| (e, e["calls"].as_i64().unwrap_or(0).max(0) as u64))
1823                .collect();
1824            // Reversed onto a stack, so the busiest child comes off first.
1825            kids.sort_by_key(|(e, calls)| (*calls, e["to"].as_str().unwrap_or("").to_owned()));
1826            stack.extend(
1827                kids.iter()
1828                    .filter_map(|(e, _)| Some((e["to"].as_str()?.to_owned(), depth + 1))),
1829            );
1830        }
1831        // A cycle, or a service whose only callers were outside the window.
1832        // Appended flat rather than dropped: a map that silently omits a node
1833        // reads as "this service is idle".
1834        for n in nodes {
1835            if !n["key"].as_str().is_some_and(|k| seen.contains(k)) {
1836                rows.push((0, n.clone()));
1837            }
1838        }
1839        MapView {
1840            rows,
1841            unresolved: y["unresolved"].as_i64().unwrap_or(0),
1842        }
1843    }
1844}
1845
1846impl Trace {
1847    fn new(id: String, spans: &[Yaml]) -> Trace {
1848        let t0 = spans
1849            .iter()
1850            .map(|s| i64_of(&s["start_time_unix_nano"]))
1851            .min()
1852            .unwrap_or(0);
1853        let t1 = spans
1854            .iter()
1855            .map(|s| i64_of(&s["start_time_unix_nano"]) + i64_of(&s["duration_nano"]))
1856            .max()
1857            .unwrap_or(t0 + 1);
1858
1859        // Depth-first from each root, children ordered by start time — the
1860        // order a waterfall is read in. A span whose parent is not in the set
1861        // (sampled away, or emitted by a service whose data went elsewhere) is
1862        // a root too, otherwise it would be dropped from a view whose whole job
1863        // is to show everything about one request.
1864        let ids: std::collections::HashSet<&str> =
1865            spans.iter().filter_map(|s| s["span_id"].as_str()).collect();
1866        let mut order: Vec<usize> = (0..spans.len()).collect();
1867        order.sort_by_key(|&i| i64_of(&spans[i]["start_time_unix_nano"]));
1868
1869        let mut out = Vec::with_capacity(spans.len());
1870        let mut stack: Vec<(usize, usize)> = order
1871            .iter()
1872            .rev()
1873            .filter(|&&i| {
1874                !spans[i]["parent_span_id"]
1875                    .as_str()
1876                    .is_some_and(|p| ids.contains(p))
1877            })
1878            .map(|&i| (i, 0))
1879            .collect();
1880        while let Some((i, depth)) = stack.pop() {
1881            out.push((spans[i].clone(), depth));
1882            let me = spans[i]["span_id"].as_str().unwrap_or("");
1883            stack.extend(
1884                order
1885                    .iter()
1886                    .rev()
1887                    .filter(|&&c| spans[c]["parent_span_id"].as_str() == Some(me) && c != i)
1888                    .map(|&c| (c, depth + 1)),
1889            );
1890        }
1891        // A parent cycle would drop spans rather than loop, but it must not
1892        // silently lose them: anything unvisited goes on the end flat.
1893        if out.len() < spans.len() {
1894            let seen: std::collections::HashSet<String> = out
1895                .iter()
1896                .filter_map(|(s, _)| s["span_id"].as_str().map(str::to_owned))
1897                .collect();
1898            for &i in &order {
1899                if !spans[i]["span_id"]
1900                    .as_str()
1901                    .is_some_and(|s| seen.contains(s))
1902                {
1903                    out.push((spans[i].clone(), 0));
1904                }
1905            }
1906        }
1907
1908        Trace {
1909            id,
1910            spans: out,
1911            t0,
1912            span_ns: t1 - t0,
1913            sel: 0,
1914        }
1915    }
1916}
1917
1918// ---- row renderers --------------------------------------------------------
1919
1920fn span_row(row: &Yaml, w: usize, sel: bool, scale: i64) -> String {
1921    let d = i64_of(&row["duration_nano"]);
1922    let error = row["status_code"].as_i64() == Some(2);
1923    let name = format!("{:<30}", clip(row["name"].as_str().unwrap_or(""), 30));
1924    let mut spans = vec![
1925        Span::raw(format!(" {} ", hms(i64_of(&row["start_time_unix_nano"])))),
1926        Span::raw(format!("{:>9} ", dur(d))),
1927        match sel {
1928            true => Span::raw(format!("{:<16}", clip(service(row), 16))),
1929            false => format!("{:<16}", clip(service(row), 16)).dim(),
1930        },
1931        Span::raw(" "),
1932        match (sel, error) {
1933            (false, true) => name.red(),
1934            _ => Span::raw(name),
1935        },
1936    ];
1937    if error {
1938        spans.push(match sel {
1939            true => Span::raw(" ERROR"),
1940            false => " ERROR".red(),
1941        });
1942    }
1943    // A bar against the widest span in the result, so the outliers in a page of
1944    // results are visible without opening any of them.
1945    let used: usize = spans.iter().map(Span::width).sum();
1946    let bar = (d as f64 / scale as f64 * w.saturating_sub(used + 2) as f64) as usize;
1947    spans.push(Span::raw(" "));
1948    spans.push(match sel {
1949        true => Span::raw("▂".repeat(bar.max(1))),
1950        false => "▂".repeat(bar.max(1)).blue(),
1951    });
1952    rata::row_styled(w, rata::hl(sel), spans)
1953}
1954
1955#[allow(clippy::too_many_arguments)]
1956/// One span's row: name, service, bar, duration, each clipped to its column.
1957///
1958/// `ends` is the column boundaries from [`App::waterfall`]. Each cell is clipped
1959/// to its own column, so an over-long span name eats into its own column and
1960/// nothing else — without that it would push the bar right and shove the
1961/// duration off the screen.
1962fn span_bar(s: &Yaml, depth: usize, sel: bool, ends: [usize; 4], t: &Trace) -> String {
1963    let start = i64_of(&s["start_time_unix_nano"]) - t.t0;
1964    let d = i64_of(&s["duration_nano"]);
1965    let error = s["status_code"].as_i64() == Some(2);
1966
1967    let indent = " ".repeat(depth.min(ends[0] / 2));
1968    let name = format!(" {indent}{}", s["name"].as_str().unwrap_or(""));
1969
1970    // Both offset and length come from the same scale, so a zero-duration span
1971    // still gets one cell and lands in the right place rather than vanishing.
1972    let barw = ends[2] - ends[1];
1973    let scale = |ns: i64| (ns as f64 / t.span_ns.max(1) as f64 * barw as f64) as usize;
1974    let off = scale(start).min(barw.saturating_sub(1));
1975    let len = scale(d).clamp(1, barw - off);
1976
1977    let durw = ends[3] - ends[2] - 1;
1978    rata::columns(
1979        ends[3],
1980        rata::hl(sel),
1981        vec![
1982            (
1983                ends[0] as u16,
1984                vec![match (sel, error) {
1985                    (false, true) => name.red(),
1986                    _ => Span::raw(name),
1987                }],
1988            ),
1989            (
1990                (ends[1] - ends[0]) as u16,
1991                vec![format!(" {}", service(s)).dim()],
1992            ),
1993            (
1994                barw as u16,
1995                vec![
1996                    Span::raw(" ".repeat(off)),
1997                    match (sel, error) {
1998                        (true, _) => Span::raw("█".repeat(len)),
1999                        (_, true) => "█".repeat(len).red(),
2000                        _ => "█".repeat(len).green(),
2001                    },
2002                ],
2003            ),
2004            (
2005                (ends[3] - ends[2]) as u16,
2006                vec![format!("{:>durw$} ", dur(d)).dim()],
2007            ),
2008        ],
2009    )
2010}
2011
2012/// The key list, under headings.
2013///
2014/// Headings rather than one column of thirty rows, because the question this
2015/// pane is opened with is never "what does `c` do" — it is "how do I get to
2016/// the thing I can see" or "how do I get out", and those are four keys each in
2017/// a list where every row looks like every other one.
2018fn help(w: usize) -> Vec<String> {
2019    const TEXT: &[(&str, &[(&str, &str)])] = &[
2020        (
2021            " move around ",
2022            &[
2023                ("1 2 3 / h l", "logs, traces, metrics"),
2024                ("↑ ↓ / j k", "move the selection"),
2025                ("PgUp PgDn g G", "page, top, bottom"),
2026                ("tab", "metrics: switch between names and series"),
2027            ],
2028        ),
2029        (
2030            " open something ",
2031            &[
2032                ("enter", "open the selection (metrics: load the series)"),
2033                ("t", "the trace this row points at"),
2034                ("c", "the frame around this filter: its services and traces"),
2035                (
2036                    "m",
2037                    "the service map, as a call tree from where traffic arrives",
2038                ),
2039                ("a", "alert rules and what each one is doing right now"),
2040                (
2041                    "d",
2042                    "node diagnostics: disk, memory, ingest and query counters",
2043                ),
2044            ],
2045        ),
2046        (
2047            " get back out ",
2048            &[
2049                ("esc", "leave the pane you are in, one step at a time"),
2050                ("q", "the same, and quit from the list"),
2051            ],
2052        ),
2053        (
2054            " change the question ",
2055            &[
2056                ("/", "edit the filter, enter to apply"),
2057                ("[ ]", "shrink or grow the time window"),
2058                ("+ -", "halve or double the row limit"),
2059                ("f", "follow: re-run the query every 3s and keep the cursor"),
2060                ("r", "re-run the query"),
2061            ],
2062        ),
2063        (
2064            " filter syntax ",
2065            &[
2066                ("", "space-separated terms, all AND-ed"),
2067                (
2068                    "service.name=checkout",
2069                    "an attribute, matched at all three levels",
2070                ),
2071                (
2072                    "severity_number>=17",
2073                    "a root column: = != < <= > >= and ~ for contains",
2074                ),
2075                (
2076                    "body~\"connection refused\"",
2077                    "quote a value that has spaces in it",
2078                ),
2079                (
2080                    "refused",
2081                    "a word on its own searches body, or a span's name",
2082                ),
2083            ],
2084        ),
2085        (
2086            " reading a directory ",
2087            &[
2088                ("", "queries run in-process; no server needs to be up"),
2089                (
2090                    "",
2091                    "a and d need --addr: they report a process, not a directory",
2092                ),
2093            ],
2094        ),
2095    ];
2096    TEXT.iter()
2097        .flat_map(|(head, rows)| {
2098            std::iter::once(rata::rule(w, head)).chain(
2099                rows.iter()
2100                    .map(move |(k, v)| rata::row(w, vec![format!("  {k:<28}").bold(), (*v).dim()])),
2101            )
2102        })
2103        .collect()
2104}
2105
2106// ---- small helpers --------------------------------------------------------
2107
2108fn body_h(h: usize) -> usize {
2109    h.saturating_sub(4).max(1)
2110}
2111
2112/// First visible index of a list scrolled to keep `sel` on screen.
2113fn window_start(sel: usize, height: usize, len: usize) -> usize {
2114    if len <= height {
2115        return 0;
2116    }
2117    sel.saturating_sub(height / 2).min(len - height)
2118}
2119
2120fn array(y: &Yaml) -> Vec<Yaml> {
2121    y.as_vec().cloned().unwrap_or_default()
2122}
2123
2124/// A mapping's entries as `(key, rendered value)`, in the order they arrived.
2125fn pairs(y: &Yaml) -> Vec<(String, String)> {
2126    y.as_hash()
2127        .map(|h| {
2128            h.iter()
2129                .filter_map(|(k, v)| Some((k.as_str()?.to_owned(), text(v))))
2130                .collect()
2131        })
2132        .unwrap_or_default()
2133}
2134
2135/// One value on one line.
2136///
2137/// Nested values are rendered inline rather than summarised as `[2 items]`: an
2138/// array attribute, a kvlist attribute and a structured body are decoded by the
2139/// engine at some cost, and the detail pane is the one place the reader asked to
2140/// see them. `Row` clips the line at the pane width, so this only has to be
2141/// compact, not fitted.
2142///
2143/// ponytail: the whole value is built and then clipped, so a thousand-element
2144/// array costs a string nobody sees, once per frame. Depth is capped because
2145/// nesting is what makes that unbounded; cap the element count too if a payload
2146/// that wide ever turns up.
2147fn text(y: &Yaml) -> String {
2148    nested(y, 4)
2149}
2150
2151fn nested(y: &Yaml, depth: usize) -> String {
2152    match y {
2153        Yaml::String(s) => s.clone(),
2154        Yaml::Integer(i) => i.to_string(),
2155        Yaml::Real(r) => r.clone(),
2156        Yaml::Boolean(b) => b.to_string(),
2157        Yaml::Null => "null".into(),
2158        Yaml::Array(a) if depth == 0 => format!("[{} items]", a.len()),
2159        Yaml::Hash(h) if depth == 0 => format!("{{{} keys}}", h.len()),
2160        Yaml::Array(a) => {
2161            let items: Vec<String> = a.iter().map(|v| nested(v, depth - 1)).collect();
2162            format!("[{}]", items.join(", "))
2163        }
2164        Yaml::Hash(h) => {
2165            let items: Vec<String> = h
2166                .iter()
2167                // A non-string key cannot happen in decoded OTLP, but rendering
2168                // it beats dropping the pair it belongs to.
2169                .map(|(k, v)| format!("{}: {}", nested(k, 0), nested(v, depth - 1)))
2170                .collect();
2171            format!("{{{}}}", items.join(", "))
2172        }
2173        _ => String::new(),
2174    }
2175}
2176
2177/// A 64-bit integer out of a response, whichever way it was encoded.
2178///
2179/// The API renders an int64 as a JSON *string* (section 7.6) — `from`, `to`, `avg_nano`
2180/// — because 1.7e18 does not survive a double, and a counter small enough to be
2181/// safe is rendered as a number. Both shapes reach here.
2182fn i64_of(y: &Yaml) -> i64 {
2183    y.as_i64()
2184        .or_else(|| y.as_str()?.parse().ok())
2185        .unwrap_or_default()
2186}
2187
2188/// The filter term that selects one service, for a name picked out of the frame
2189/// or map pane.
2190///
2191/// Always quoted, because [`tokens`] splits on whitespace and a service name is
2192/// free to contain some. A name carrying a double quote has no equality
2193/// spelling at all — the tokeniser toggles on one and there is no escape — so it
2194/// degrades to a `contains` on the part before it, which is a true term rather
2195/// than one that mis-parses into a different filter.
2196fn service_term(name: &str) -> String {
2197    match name.split_once('"') {
2198        Some((head, _)) => format!("service.name~\"{head}\""),
2199        None => format!("service.name=\"{name}\""),
2200    }
2201}
2202
2203/// One service in the map: where it sits in the call tree, and what it did.
2204fn map_row(n: &Yaml, depth: usize, sel: bool, w: usize) -> String {
2205    let entry = n["key"].as_str() == Some(ENTRY_KEY);
2206    let errors = n["errors"].as_i64().unwrap_or(0);
2207    // The three count columns are 44 wide together, and they are the point of
2208    // the pane — the name yields to them rather than pushing `avg` off the edge
2209    // at 80 columns.
2210    let namew = w.saturating_sub(44).clamp(16, 40);
2211
2212    // Two columns a level, capped so a deep chain eats its own column rather
2213    // than pushing the counts off the right-hand edge.
2214    let indent = "  ".repeat(depth.min(namew / 4));
2215    let name = format!(" {indent}{}", n["name"].as_str().unwrap_or("?"));
2216    let mut counts = Vec::new();
2217    if !entry {
2218        counts.push(format!("{:>9} spans  ", n["spans"].as_i64().unwrap_or(0)).dim());
2219        counts.push(match errors {
2220            // The dash sits in the count column and the word is dropped, so a
2221            // clean service lines its zero up under the counts above it.
2222            0 => format!("{:>5}{:9}", "-", "").dim(),
2223            e if sel => Span::raw(format!("{e:>5} errors  ")),
2224            e => format!("{e:>5} errors  ").red(),
2225        });
2226        counts.push(format!("{:>9} avg", dur(i64_of(&n["avg_nano"]))).dim());
2227    }
2228    rata::columns(
2229        w,
2230        rata::hl(sel),
2231        vec![
2232            (
2233                namew as u16,
2234                vec![match (sel, entry, errors > 0) {
2235                    (true, ..) => Span::raw(name),
2236                    (_, true, _) => name.dim(),
2237                    (_, _, true) => name.red(),
2238                    _ => Span::raw(name),
2239                }],
2240            ),
2241            (w.saturating_sub(namew) as u16, counts),
2242        ],
2243    )
2244}
2245
2246fn num(y: &Yaml) -> Option<f64> {
2247    match y {
2248        Yaml::Integer(i) => Some(*i as f64),
2249        Yaml::Real(r) => r.parse().ok(),
2250        // An integer point crosses the wire quoted (section 7.6, `Json::i64_str`), so
2251        // a counter arrives here as a string and a double does not. Refusing
2252        // the string draws "no points" over a series that has plenty.
2253        Yaml::String(s) => s.parse().ok(),
2254        _ => None,
2255    }
2256}
2257
2258fn service(row: &Yaml) -> &str {
2259    row["attributes"]["service.name"].as_str().unwrap_or("-")
2260}
2261
2262fn kind(k: i64) -> &'static str {
2263    match k {
2264        1 => "internal",
2265        2 => "server",
2266        3 => "client",
2267        4 => "producer",
2268        5 => "consumer",
2269        _ => "unspecified",
2270    }
2271}
2272
2273fn clip(s: &str, n: usize) -> String {
2274    match n > 0 && s.chars().count() > n {
2275        true => s.chars().take(n.saturating_sub(1)).collect::<String>() + "…",
2276        false => s.to_owned(),
2277    }
2278}
2279
2280/// Local wall-clock time of a nanosecond timestamp.
2281///
2282/// `localtime_r` rather than a date crate: `libc` is already here, and the only
2283/// hard part of civil time — the zone — is exactly the part a hand-rolled
2284/// version would get wrong.
2285fn hms(ns: i64) -> String {
2286    let (tm, ms) = civil(ns);
2287    format!(
2288        "{:02}:{:02}:{:02}.{ms:03}",
2289        tm.tm_hour, tm.tm_min, tm.tm_sec
2290    )
2291}
2292
2293pub(crate) fn stamp(ns: i64) -> String {
2294    let (tm, ms) = civil(ns);
2295    format!(
2296        "{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{ms:03}",
2297        tm.tm_year + 1900,
2298        tm.tm_mon + 1,
2299        tm.tm_mday,
2300        tm.tm_hour,
2301        tm.tm_min,
2302        tm.tm_sec
2303    )
2304}
2305
2306fn civil(ns: i64) -> (libc::tm, i64) {
2307    let secs = ns.div_euclid(1_000_000_000) as libc::time_t;
2308    let ms = ns.rem_euclid(1_000_000_000) / 1_000_000;
2309    // SAFETY: `tm` is integers plus a `tm_zone` pointer, and null is a valid
2310    // value for a raw pointer, so all-zero is a valid `tm`. It has to be: the
2311    // return value is discarded below, and `localtime_r` returns NULL without
2312    // writing anything for a `time_t` it cannot represent. The zeroed struct
2313    // then renders as 1900-01-01 — a wrong timestamp, not uninitialised memory.
2314    let mut tm: libc::tm = unsafe { std::mem::zeroed() };
2315    // SAFETY: both arguments are live, correctly typed locals. The `_r` form
2316    // writes only into `tm` and returns no pointer into shared state, so unlike
2317    // `localtime` nothing here can be clobbered by another thread's call.
2318    unsafe { libc::localtime_r(&secs, &mut tm) };
2319    (tm, ms)
2320}
2321
2322fn dur(ns: i64) -> String {
2323    match ns {
2324        n if n >= 60_000_000_000 => format!(
2325            "{}m{:02}s",
2326            n / 60_000_000_000,
2327            n % 60_000_000_000 / 1_000_000_000
2328        ),
2329        n if n >= 1_000_000_000 => format!("{:.2}s", n as f64 / 1e9),
2330        n if n >= 1_000_000 => format!("{:.2}ms", n as f64 / 1e6),
2331        n if n >= 1_000 => format!("{:.1}µs", n as f64 / 1e3),
2332        n => format!("{n}ns"),
2333    }
2334}
2335
2336fn ms(d: std::time::Duration) -> String {
2337    match d.as_secs_f64() {
2338        s if s >= 1.0 => format!("{s:.2}s"),
2339        s => format!("{:.1}ms", s * 1e3),
2340    }
2341}
2342
2343/// A number at human precision: metric values span counters in the millions and
2344/// ratios below one, and neither reads well under the other's format.
2345fn g(v: f64) -> String {
2346    match v.abs() {
2347        0.0 => "0".into(),
2348        x if x >= 1e6 => format!("{:.1}M", v / 1e6),
2349        x if x >= 1e3 => format!("{:.1}k", v / 1e3),
2350        x if x >= 1.0 => format!("{v:.1}"),
2351        _ => format!("{v:.3}"),
2352    }
2353}
2354
2355/// One `label   value` line of the diagnostics pane.
2356fn kv(w: usize, k: &str, v: &str) -> String {
2357    rata::row(w, vec![format!("  {k:<16}").dim(), Span::raw(v.to_owned())])
2358}
2359
2360/// An age in seconds, at the precision someone reading it cares about.
2361///
2362/// Not [`dur`]: that one formats a span *inside* a request, where the
2363/// interesting range is nanoseconds to seconds. This one formats how long a
2364/// process or a block has been around, where it is seconds to days — and 187
2365/// minutes is not a readable way to say three hours.
2366fn since(secs: i64) -> String {
2367    match secs {
2368        s if s < 0 => "0s".into(),
2369        s if s < 60 => format!("{s}s"),
2370        s if s < 3_600 => format!("{}m {:02}s", s / 60, s % 60),
2371        s if s < 86_400 => format!("{}h {:02}m", s / 3_600, s % 3_600 / 60),
2372        s => format!("{}d {:02}h", s / 86_400, s % 86_400 / 3_600),
2373    }
2374}
2375
2376/// Binary units, because every other tool an operator has open uses them.
2377fn bytes(b: f64) -> String {
2378    const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
2379    let (mut b, mut i) = (b, 0);
2380    while b >= 1024.0 && i < UNITS.len() - 1 {
2381        b /= 1024.0;
2382        i += 1;
2383    }
2384    match i {
2385        0 => format!("{b:.0} {}", UNITS[0]),
2386        _ => format!("{b:.1} {}", UNITS[i]),
2387    }
2388}
2389
2390/// The right-hand side of an alert row: where the number sits against the line.
2391fn alert_value(a: &Yaml) -> String {
2392    let (value, threshold) = (
2393        num(&a["value"]).unwrap_or(0.0),
2394        num(&a["threshold"]).unwrap_or(0.0),
2395    );
2396    let op = a["op"].as_str().unwrap_or(">");
2397    let head = match a["metric"].as_str() {
2398        Some("ratio") => format!("{:.2}% {op} {:.2}%", value * 100.0, threshold * 100.0),
2399        _ => format!("{} {op} {}", tally(value), tally(threshold)),
2400    };
2401    let matched = tally(num(&a["matched"]).unwrap_or(0.0));
2402    match num(&a["total"]) {
2403        Some(t) => format!("{head}   {matched} of {}", tally(t)),
2404        None => format!("{head}   {matched} records"),
2405    }
2406}
2407
2408/// A record count. [`g`] is for metric values, where 5 means "about five" and a
2409/// decimal is information; here it means five records and a decimal is noise.
2410fn tally(v: f64) -> String {
2411    match v.abs() < 1e4 {
2412        true => format!("{v:.0}"),
2413        false => g(v),
2414    }
2415}
2416
2417fn stats_line(s: &Yaml) -> String {
2418    format!(
2419        "{}/{} blocks · {} rows scanned · {} matched",
2420        s["blocks_scanned"].as_i64().unwrap_or(0),
2421        s["blocks_total"].as_i64().unwrap_or(0),
2422        s["rows_scanned"].as_i64().unwrap_or(0),
2423        s["rows_matched"].as_i64().unwrap_or(0),
2424    )
2425}
2426
2427/// Eight levels of block, scaled between the run's own min and max.
2428///
2429/// Relative rather than absolute because a flat series at 8 191 and a flat
2430/// series at 3 are the same shape, and the shape is what a sparkline is for —
2431/// the numbers are printed beside it.
2432fn spark(v: &[f64], w: usize) -> String {
2433    const BARS: [char; 8] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
2434    if v.is_empty() || w == 0 {
2435        return String::new();
2436    }
2437    let (lo, hi) = (
2438        v.iter().cloned().fold(f64::INFINITY, f64::min),
2439        v.iter().cloned().fold(f64::NEG_INFINITY, f64::max),
2440    );
2441    let span = (hi - lo).max(f64::MIN_POSITIVE);
2442    // More points than columns: average each column's bucket rather than
2443    // sampling one of them, so a spike between two samples is not invisible.
2444    (0..w.min(v.len()))
2445        .map(|i| {
2446            let (a, b) = (
2447                i * v.len() / w.min(v.len()),
2448                (i + 1) * v.len() / w.min(v.len()),
2449            );
2450            let bucket = &v[a..b.max(a + 1).min(v.len())];
2451            let peak = bucket.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
2452            let n = ((peak - lo) / span * 7.0).round().clamp(0.0, 7.0) as usize;
2453            BARS[n]
2454        })
2455        .collect()
2456}
2457
2458fn trace_query(id: &str) -> String {
2459    let mut j = Json::new();
2460    j.obj(|j| {
2461        j.key("signal");
2462        j.str("traces");
2463        // Deliberately wider than the view's own window. A trace reached from a
2464        // metric exemplar or an old log line is frequently outside it, and
2465        // `trace_id = <hex>` is the one filter with a Bloom sidecar behind it —
2466        // this opens one block out of all of retention, not all of them.
2467        j.key("from");
2468        j.str("-3650d");
2469        j.key("to");
2470        j.str("now");
2471        j.key("limit");
2472        j.i64(2_000);
2473        j.key("where");
2474        j.arr(|j| {
2475            j.obj(|j| {
2476                j.key("field");
2477                j.str("trace_id");
2478                j.key("eq");
2479                j.str(id);
2480            });
2481        });
2482    });
2483    j.into_string()
2484}
2485
2486const OPS: [(&str, &str); 7] = [
2487    (">=", "gte"),
2488    ("<=", "lte"),
2489    ("!=", "ne"),
2490    ("=", "eq"),
2491    ("~", "contains"),
2492    (">", "gt"),
2493    ("<", "lt"),
2494];
2495
2496/// One piece of a filter line: a `key op value`, or a word with no operator.
2497///
2498/// A bare word is kept rather than discarded because only the caller knows what
2499/// it should mean — see [`Tab::free_text`].
2500#[derive(Debug, PartialEq)]
2501enum Part {
2502    Term(String, &'static str, String),
2503    Word(String),
2504}
2505
2506/// Split the filter line into query terms.
2507///
2508/// `service.name=checkout severity_number>=17 body~"connection refused"`. It is
2509/// deliberately not the API's KYAML grammar: that one is for programs, and no
2510/// one types `{"attr":"service.name","eq":"checkout"}` into a filter box. Both
2511/// end up as the same [`Term`](mira_core::query::Term) either way.
2512fn parse_filter(s: &str) -> Vec<Part> {
2513    let mut out = Vec::new();
2514    for tok in tokens(s) {
2515        // Earliest operator wins, longest at that position — otherwise `>=`
2516        // parses as `>` with a value of `=17`.
2517        let mut best: Option<(usize, usize, &'static str)> = None;
2518        for (sym, op) in OPS {
2519            if let Some(p) = tok.find(sym) {
2520                let better = best.is_none_or(|(bp, bl, _)| p < bp || (p == bp && sym.len() > bl));
2521                if better {
2522                    best = Some((p, sym.len(), op));
2523                }
2524            }
2525        }
2526        match best {
2527            // A half-written term (`k=`, `=v`) is dropped: the operator says
2528            // what was meant and it is not there yet.
2529            Some((p, l, op)) => {
2530                let (k, v) = (tok[..p].trim(), tok[p + l..].trim());
2531                if !k.is_empty() && !v.is_empty() {
2532                    out.push(Part::Term(k.to_owned(), op, v.to_owned()));
2533                }
2534            }
2535            None => out.push(Part::Word(tok)),
2536        }
2537    }
2538    out
2539}
2540
2541/// Whitespace-separated, except inside double quotes.
2542fn tokens(s: &str) -> Vec<String> {
2543    let (mut out, mut cur, mut quoted) = (Vec::new(), String::new(), false);
2544    for c in s.chars() {
2545        match c {
2546            '"' => quoted = !quoted,
2547            c if c.is_whitespace() && !quoted => {
2548                if !cur.is_empty() {
2549                    out.push(std::mem::take(&mut cur));
2550                }
2551            }
2552            c => cur.push(c),
2553        }
2554    }
2555    if !cur.is_empty() {
2556        out.push(cur);
2557    }
2558    out
2559}
2560
2561/// Type a filter value the way its text reads.
2562///
2563/// Ids stay strings whatever they look like: a 16-hex-digit span id made
2564/// entirely of decimal digits parses as an integer, and comparing a
2565/// `FixedSizeBinary` column against one matches nothing at all — silently,
2566/// because an inapplicable term is defined to return no rows rather than an
2567/// error.
2568fn scalar(j: &mut Json, key: &str, v: &str) {
2569    if v == "true" || v == "false" {
2570        return j.bool(v == "true");
2571    }
2572    if !key.ends_with("_id") && !key.ends_with(".id") {
2573        if let Ok(n) = v.parse::<i64>() {
2574            return j.i64(n);
2575        }
2576        if let Ok(f) = v.parse::<f64>() {
2577            return j.f64(f);
2578        }
2579    }
2580    j.str(v);
2581}
2582
2583#[cfg(test)]
2584mod tests {
2585    use super::*;
2586
2587    fn term(k: &str, op: &'static str, v: &str) -> Part {
2588        Part::Term(k.into(), op, v.into())
2589    }
2590
2591    #[test]
2592    fn filter_terms_split_on_the_longest_operator() {
2593        let f = parse_filter("service.name=checkout severity_number>=17 http.route~/api");
2594        assert_eq!(
2595            f,
2596            vec![
2597                term("service.name", "eq", "checkout"),
2598                term("severity_number", "gte", "17"),
2599                term("http.route", "contains", "/api"),
2600            ]
2601        );
2602        // `!=` must not be read as `=` with a key ending in `!`.
2603        assert_eq!(parse_filter("k!=v"), vec![term("k", "ne", "v")]);
2604        // A word with no operator survives parsing; what it means is the tab's
2605        // business, not this function's.
2606        assert_eq!(
2607            parse_filter("justawordse"),
2608            vec![Part::Word("justawordse".into())]
2609        );
2610        // A half-written term is still dropped: the operator says what was
2611        // meant, and it is not there yet.
2612        assert!(parse_filter("=v k=").is_empty());
2613    }
2614
2615    #[test]
2616    fn a_quoted_value_keeps_its_spaces() {
2617        assert_eq!(
2618            parse_filter("body~\"connection refused\" a=b"),
2619            vec![
2620                term("body", "contains", "connection refused"),
2621                term("a", "eq", "b"),
2622            ]
2623        );
2624    }
2625
2626    /// The finding this fixes: a word with no operator used to be dropped on
2627    /// the floor while the filter bar went on displaying it, so the rows looked
2628    /// filtered and were not.
2629    #[test]
2630    fn a_bare_word_searches_the_tabs_message_column() {
2631        use mira_core::query::{Op, Target, Value};
2632
2633        let mut app = App::new(Source::Local("/nonexistent".into()));
2634        app.filter = "\"connection refused\" service.name=checkout".into();
2635        let q = crate::api::parse_search(&app.rows_query(), 0).unwrap();
2636        assert_eq!(q.terms.len(), 2);
2637        assert!(matches!(&q.terms[0].target, Target::Field(k) if k == "body"));
2638        assert_eq!(q.terms[0].op, Op::Contains);
2639        assert_eq!(q.terms[0].value, Value::Str("connection refused".into()));
2640
2641        // On traces the message column is the span name, not the body.
2642        app.tab = Tab::Traces;
2643        let q = crate::api::parse_search(&app.rows_query(), 0).unwrap();
2644        assert!(matches!(&q.terms[0].target, Target::Field(k) if k == "name"));
2645
2646        // A word that reads as a number stays text: `body` is a string column
2647        // and an integer there would match nothing, silently.
2648        app.tab = Tab::Logs;
2649        app.filter = "500".into();
2650        let q = crate::api::parse_search(&app.rows_query(), 0).unwrap();
2651        assert_eq!(q.terms[0].value, Value::Str("500".into()));
2652    }
2653
2654    /// Metrics has no message column, so the word is named in the status line
2655    /// instead of silently doing nothing.
2656    #[test]
2657    fn a_bare_word_on_the_metrics_tab_says_it_was_ignored() {
2658        let mut app = App::new(Source::Local("/nonexistent".into()));
2659        app.tab = Tab::Metrics;
2660        app.filter = "refused pod=a".into();
2661        assert_eq!(app.ignored_word().as_deref(), Some("refused"));
2662
2663        // The rest of the line still applies — the word is dropped from the
2664        // query, not the whole filter.
2665        let q = crate::api::parse_series(&app.series_query(), 0).unwrap();
2666        assert_eq!(q.terms.len(), 1);
2667
2668        // The word is looked for past the terms, not just at the front: a
2669        // search that stopped at the first part would report `pod=a`, which is
2670        // the one term that *was* applied.
2671        app.filter = "pod=a refused".into();
2672        assert_eq!(app.ignored_word().as_deref(), Some("refused"));
2673
2674        // And no tab with a message column ever reports one.
2675        for tab in [Tab::Logs, Tab::Traces] {
2676            app.tab = tab;
2677            assert_eq!(app.ignored_word(), None);
2678        }
2679    }
2680
2681    /// The filter box has to produce a document the API's own parser accepts,
2682    /// and has to route each term to `field` or `attr` correctly — an `attr`
2683    /// term against a root column matches nothing, silently.
2684    #[test]
2685    fn the_filter_compiles_to_a_query_the_api_parses() {
2686        let mut app = App::new(Source::Local("/nonexistent".into()));
2687        app.tab = Tab::Traces;
2688        app.filter =
2689            "service.name=checkout duration_nano>=500000 trace_id=00112233445566778899aabbccddeeff"
2690                .into();
2691        let body = app.rows_query();
2692        let q = crate::api::parse_search(&body, 1_000_000_000_000_000_000).unwrap();
2693
2694        use mira_core::query::{Op, Signal, Target, Value};
2695        assert_eq!(q.signal, Signal::Traces);
2696        assert_eq!(q.limit, 200);
2697        assert_eq!(q.from, 1_000_000_000_000_000_000 - 3_600_000_000_000);
2698        assert_eq!(q.terms.len(), 3);
2699        // Not a root column of `spans`, so it has to be an attribute.
2700        assert!(matches!(&q.terms[0].target, Target::Attr(k) if k == "service.name"));
2701        assert!(matches!(&q.terms[1].target, Target::Field(k) if k == "duration_nano"));
2702        assert_eq!(q.terms[1].op, Op::Gte);
2703        assert_eq!(q.terms[1].value, Value::Int(500_000));
2704        // An id stays a string even though this one is all hex.
2705        assert!(matches!(&q.terms[2].value, Value::Str(s) if s.len() == 32));
2706
2707        // The other two spellings a typed value arrives in. An attribute
2708        // compared against the *string* `"true"` matches nothing at all — OTLP
2709        // decodes a bool attribute to a bool — and `0.5` truncated to an
2710        // integer would make `>=0.5` mean `>=0`.
2711        app.filter = "ok=true ratio>=0.5 span.id=00000000000000042".into();
2712        let q = crate::api::parse_search(&app.rows_query(), 0).unwrap();
2713        assert_eq!(q.terms[0].value, Value::Bool(true));
2714        assert_eq!(q.terms[1].value, Value::Double(0.5));
2715        // ...and an id made entirely of digits is still an id.
2716        assert!(matches!(&q.terms[2].value, Value::Str(_)));
2717    }
2718
2719    /// The same key is a field on one signal and an attribute on another, and
2720    /// the tab is the only thing that knows which.
2721    #[test]
2722    fn the_signal_decides_whether_a_key_is_a_column() {
2723        let mut app = App::new(Source::Local("/nonexistent".into()));
2724        app.filter = "name=checkout".into();
2725        let logs = crate::api::parse_search(&app.rows_query(), 0).unwrap();
2726        app.tab = Tab::Traces;
2727        let traces = crate::api::parse_search(&app.rows_query(), 0).unwrap();
2728        assert!(matches!(&logs.terms[0].target, Target::Attr(_)));
2729        assert!(matches!(&traces.terms[0].target, Target::Field(_)));
2730        use mira_core::query::Target;
2731    }
2732
2733    /// Every root column the engine can compare has to be in `fields`, or the
2734    /// filter box sends it as `attr` and the Bloom filter prunes it to nothing.
2735    /// Pinned against the schema so the next column added there cannot repeat
2736    /// what happened to `event_name`.
2737    ///
2738    /// The browser UI keeps a second copy of the same list and, being
2739    /// JavaScript, cannot read `schema.rs` — so it is pinned here too rather
2740    /// than against literals of its own. `include_str!` is what makes that
2741    /// work: the file is a compile-time input, so adding a column to the
2742    /// schema fails this test until *both* filter boxes know about it.
2743    #[test]
2744    fn the_field_list_is_the_schema() {
2745        // Left out on purpose: `id`, `resource_id` and `scope_id` are
2746        // block-local numbers that mean nothing to whoever is typing, and
2747        // `body_ser` is Binary, which `field_pred` has no comparison for.
2748        let skip = ["id", "resource_id", "scope_id", "body_ser"];
2749        let js = include_str!("../ui/src/lib/api.js");
2750        for (tab, key, schema) in [
2751            (Tab::Logs, "logs", &mira_core::schema::LOGS),
2752            (Tab::Traces, "traces", &mira_core::schema::SPANS),
2753        ] {
2754            let mut want: Vec<&str> = schema
2755                .fields()
2756                .iter()
2757                .map(|f| f.name().as_str())
2758                .filter(|n| !skip.contains(n))
2759                .collect();
2760            let mut got = tab.fields().to_vec();
2761            // Every odd field of a split on `'` is a quoted element, which is
2762            // enough parsing for a list of bare identifiers.
2763            let arr = js
2764                .split_once(&format!("\n  {key}: ["))
2765                .expect("FIELDS key")
2766                .1;
2767            let mut browser: Vec<&str> = arr[..arr.find(']').expect("closing bracket")]
2768                .split('\'')
2769                .skip(1)
2770                .step_by(2)
2771                .collect();
2772            want.sort_unstable();
2773            got.sort_unstable();
2774            browser.sort_unstable();
2775            assert_eq!(got, want, "{tab:?}");
2776            assert_eq!(browser, want, "{tab:?} in ui/src/lib/api.js");
2777        }
2778    }
2779
2780    /// An array or kvlist attribute is decoded by the engine at real cost, and
2781    /// the detail pane is where the reader asked to see it — `[2 items]` there
2782    /// throws the answer away.
2783    #[test]
2784    fn nested_values_render_inline_down_to_a_depth() {
2785        let v = |s: &str| text(&crate::api::parse(s).unwrap()["v"]);
2786        assert_eq!(v(r#"{"v":["mira","serve"]}"#), "[mira, serve]");
2787        assert_eq!(v(r#"{"v":{"role":"user","n":2}}"#), "{role: user, n: 2}");
2788        assert_eq!(v(r#"{"v":[{"type":"text"}]}"#), "[{type: text}]");
2789        // Capped, so a pathological nest cannot spend a frame building a line
2790        // that gets clipped at the pane width anyway.
2791        assert_eq!(v(r#"{"v":[[[[["deep"]]]]]}"#), "[[[[[1 items]]]]]");
2792        // Every scalar an OTLP attribute can decode to, each printed as itself.
2793        assert_eq!(v(r#"{"v":[1.5,true,null]}"#), "[1.5, true, null]");
2794        // A hash at the cap is summarised by size, the same as an array is.
2795        assert_eq!(v(r#"{"v":[[[[{"a":1,"b":2}]]]]}"#), "[[[[{2 keys}]]]]");
2796        // A key the response does not carry at all. The loader answers
2797        // `BadValue`, and this pane prints what it is handed — so the empty
2798        // string is what keeps `BadValue` off the screen.
2799        assert_eq!(v("{}"), "");
2800    }
2801
2802    /// The number formatters, each at the boundary it exists for.
2803    ///
2804    /// They are pure and tiny, and every one of them is a place where a wrong
2805    /// unit reads as a right answer — `1.83` where `1.83 ms` was meant is the
2806    /// whole story of a diagnostics pane nobody trusts.
2807    #[test]
2808    fn each_formatter_covers_the_range_it_was_written_for() {
2809        // `dur` measures a span inside a request: nanoseconds to minutes.
2810        assert_eq!(dur(940), "940ns");
2811        assert_eq!(dur(1_500), "1.5µs");
2812        assert_eq!(dur(2_500_000), "2.50ms");
2813        assert_eq!(dur(1_250_000_000), "1.25s");
2814        assert_eq!(dur(90_000_000_000), "1m30s");
2815
2816        // `since` measures how long something has been around: seconds to days.
2817        assert_eq!(since(-1), "0s");
2818        assert_eq!(since(41), "41s");
2819        assert_eq!(since(125), "2m 05s");
2820        assert_eq!(since(7_384), "2h 03m");
2821        assert_eq!(since(93_784), "1d 02h");
2822
2823        assert_eq!(ms(std::time::Duration::from_micros(1_830)), "1.8ms");
2824        assert_eq!(ms(std::time::Duration::from_millis(2_500)), "2.50s");
2825
2826        // A metric value: counters in the millions and ratios below one share
2827        // one column, so neither may be printed in the other's format.
2828        assert_eq!(g(0.0), "0");
2829        assert_eq!(g(0.0481), "0.048");
2830        assert_eq!(g(12.5), "12.5");
2831        assert_eq!(g(12_040.0), "12.0k");
2832        assert_eq!(g(1_204_000.0), "1.2M");
2833
2834        assert_eq!(bytes(512.0), "512 B");
2835        assert_eq!(bytes(1536.0), "1.5 KiB");
2836        assert_eq!(bytes(1.5 * 1024f64.powi(4)), "1.5 TiB");
2837        // Past the last unit there is nothing left to divide by, and the answer
2838        // is a big number rather than a panic.
2839        assert_eq!(bytes(4096.0 * 1024f64.powi(4)), "4096.0 TiB");
2840
2841        // The OTLP `SpanKind` enum. Zero and out-of-range are the same answer,
2842        // because the spec's own zero *is* unspecified.
2843        let kinds: Vec<&str> = (0i64..7).map(kind).collect();
2844        assert_eq!(
2845            kinds,
2846            [
2847                "unspecified",
2848                "internal",
2849                "server",
2850                "client",
2851                "producer",
2852                "consumer",
2853                "unspecified",
2854            ]
2855        );
2856
2857        // Severity bands are the OTLP numbers, not a guess at `severity_text`.
2858        use ratatui::style::Color;
2859        assert_eq!(rata::sev(21).fg, Some(Color::Red));
2860        assert_eq!(rata::sev(13).fg, Some(Color::Yellow));
2861        assert_eq!(rata::sev(9).fg, Some(Color::Green));
2862        assert_eq!(rata::sev(1).add_modifier, Modifier::DIM);
2863    }
2864
2865    #[test]
2866    fn the_trace_query_is_the_bloom_indexed_shape() {
2867        let q =
2868            crate::api::parse_search(&trace_query("abababababababababababababababab"), 0).unwrap();
2869        use mira_core::query::{Op, Target};
2870        assert_eq!(q.terms.len(), 1);
2871        assert!(matches!(&q.terms[0].target, Target::Field(f) if f == "trace_id"));
2872        assert_eq!(q.terms[0].op, Op::Eq);
2873    }
2874
2875    /// A waterfall is read parent-then-children, and the child order is by
2876    /// start time. Reconstructing that from `parent_span_id` is the only real
2877    /// logic in the trace view.
2878    #[test]
2879    fn spans_order_depth_first_with_orphans_kept() {
2880        let doc = crate::api::parse(
2881            // Quoted, as the server writes them (section 7.6).
2882            r#"{"rows":[
2883              {"span_id":"02","parent_span_id":"01","start_time_unix_nano":"30","duration_nano":"5"},
2884              {"span_id":"01","start_time_unix_nano":"10","duration_nano":"100"},
2885              {"span_id":"03","parent_span_id":"01","start_time_unix_nano":"20","duration_nano":"5"},
2886              {"span_id":"04","parent_span_id":"03","start_time_unix_nano":"21","duration_nano":"1"},
2887              {"span_id":"09","parent_span_id":"ff","start_time_unix_nano":"90","duration_nano":"1"}
2888            ]}"#,
2889        )
2890        .unwrap();
2891        let t = Trace::new("abc".into(), &array(&doc["rows"]));
2892        let seen: Vec<(&str, usize)> = t
2893            .spans
2894            .iter()
2895            .map(|(s, d)| (s["span_id"].as_str().unwrap(), *d))
2896            .collect();
2897        assert_eq!(
2898            seen,
2899            vec![
2900                ("01", 0),
2901                // 03 starts before 02, and 04 hangs off 03.
2902                ("03", 1),
2903                ("04", 2),
2904                ("02", 1),
2905                // Parent never arrived; it is still part of the trace.
2906                ("09", 0),
2907            ]
2908        );
2909        assert_eq!(t.t0, 10);
2910        assert_eq!(t.span_ns, 100);
2911    }
2912
2913    /// A cyclic `parent_span_id` is corrupt data, not a reason to hang or to
2914    /// quietly show fewer spans than the trace has.
2915    #[test]
2916    fn a_parent_cycle_still_shows_every_span() {
2917        let doc = crate::api::parse(
2918            r#"{"rows":[
2919              {"span_id":"01","parent_span_id":"02","start_time_unix_nano":10,"duration_nano":1},
2920              {"span_id":"02","parent_span_id":"01","start_time_unix_nano":20,"duration_nano":1}
2921            ]}"#,
2922        )
2923        .unwrap();
2924        let t = Trace::new("abc".into(), &array(&doc["rows"]));
2925        assert_eq!(t.spans.len(), 2);
2926    }
2927
2928    #[test]
2929    fn sparkline_scales_between_the_runs_own_bounds() {
2930        assert_eq!(
2931            spark(&[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], 8),
2932            "▁▂▃▄▅▆▇█"
2933        );
2934        // Flat is flat, not a division by zero.
2935        assert_eq!(spark(&[5.0; 4], 4), "▁▁▁▁");
2936        assert_eq!(spark(&[], 8), "");
2937        // More points than columns: each column takes its bucket's peak, so the
2938        // spike survives.
2939        assert!(spark(&[0.0, 0.0, 9.0, 0.0], 2).ends_with('█'));
2940    }
2941
2942    /// Every 64-bit field crosses the wire as a JSON string (section 7.6), and
2943    /// `Yaml::as_i64` says `None` to a string. Each `unwrap_or(0)` behind one
2944    /// of those reads is therefore a pane that renders — clock at the epoch,
2945    /// bars of zero width, `no points` over a full series — rather than a pane
2946    /// that fails, which is why this is asserted against the wire spelling and
2947    /// not against the shape a fixture finds convenient.
2948    #[test]
2949    fn a_quoted_64_bit_field_still_reaches_the_screen() {
2950        let row = &crate::api::parse(
2951            r#"{"time_unix_nano":"1788877362987743417","severity_text":"INFO",
2952                "start_time_unix_nano":"1788877362987743417","duration_nano":"5000000",
2953                "name":"GET /x","body":"hello"}"#,
2954        )
2955        .unwrap();
2956
2957        // Not 00:00:00 in UTC nor 01:00:00 in CET — the epoch under either.
2958        let list = rata::log_list(std::slice::from_ref(row), 60, 1, 1, 0);
2959        let clock = strip(&list[0]);
2960        assert!(!clock.contains(&hms(0)), "{clock:?}");
2961        assert!(clock.contains(&hms(1_788_877_362_987_743_417)), "{clock:?}");
2962
2963        // A bar drawn against a scale it is the whole of is a full bar.
2964        let span = strip(&span_row(row, 90, false, i64_of(&row["duration_nano"])));
2965        assert!(span.contains("5.00ms"), "{span:?}");
2966        assert!(span.matches('▂').count() > 1, "{span:?}");
2967
2968        // An integer point is quoted; a double is not. Both chart.
2969        assert_eq!(num(&Yaml::String("350".into())), Some(350.0));
2970        let mut app = App::new(Source::Local("/nonexistent".into()));
2971        app.series = array(
2972            &crate::api::parse(
2973                r#"{"series":[{"name":"m","attributes":{},"points":[["1","10"],["2","0"]]}]}"#,
2974            )
2975            .unwrap()["series"],
2976        );
2977        let chart = strip(&app.series_lines(80)[1]);
2978        assert!(!chart.contains("no points"), "{chart:?}");
2979        assert!(chart.contains('█'), "{chart:?}");
2980    }
2981
2982    /// `max_points` truncation keeps the newest points, so a capped sparkline
2983    /// is the tail of the window drawn under a filter bar that still says
2984    /// `last 24h`. The engine reports the count; the only failure is not
2985    /// showing it.
2986    #[test]
2987    fn a_truncated_sparkline_says_how_many_points_are_missing() {
2988        let mut app = App::new(Source::Local("/nonexistent".into()));
2989        let series = |extra: &str| {
2990            // A full sparkline and a wide range, so the badge is the field
2991            // that would be clipped if its width were not reserved.
2992            let pts: Vec<String> = (0..400)
2993                .map(|i| format!("[{i},{}]", (i - 200) * 1000))
2994                .collect();
2995            array(
2996                &crate::api::parse(&format!(
2997                    r#"{{"series":[{{"name":"m","attributes":{{}},{extra}"points":[{}]}}]}}"#,
2998                    pts.join(",")
2999                ))
3000                .unwrap()["series"],
3001            )
3002        };
3003
3004        app.series = series(r#""dropped_points":8240,"#);
3005        let capped = strip(&app.series_lines(80)[1]);
3006        assert!(capped.contains("+8240 dropped"), "{capped:?}");
3007
3008        // Reserved out of the bar rather than appended past the edge: `Row`
3009        // clips at the right margin, and this is the field that must not be
3010        // the one it clips.
3011        assert!(capped.trim_end().ends_with("+8240 dropped"), "{capped:?}");
3012
3013        // And no badge at all when the whole window fitted, rather than a `+0`.
3014        app.series = series("");
3015        let whole = strip(&app.series_lines(80)[1]);
3016        assert!(!whole.contains("dropped"), "{whole:?}");
3017    }
3018
3019    /// Every pane clamps its own cursor, and an empty result is the case that
3020    /// gets it wrong.
3021    #[test]
3022    fn cursors_stay_in_range_on_an_empty_result() {
3023        let mut app = App::new(Source::Local("/nonexistent".into()));
3024        app.move_by(5);
3025        app.move_to(usize::MAX);
3026        assert_eq!(app.sel, 0);
3027        app.rows = vec![Yaml::Null, Yaml::Null, Yaml::Null];
3028        app.move_to(usize::MAX);
3029        assert_eq!(app.sel, 2);
3030        app.move_by(10);
3031        assert_eq!(app.sel, 2);
3032        app.move_by(-10);
3033        assert_eq!(app.sel, 0);
3034
3035        // The scrolling panes report `usize::MAX` for their length, which is a
3036        // negative `isize`. Clamping there used to panic on the first `j`.
3037        for mode in [Mode::Detail, Mode::Help] {
3038            app.mode = mode;
3039            app.scroll = 0;
3040            app.move_by(3);
3041            assert_eq!(app.scroll, 3, "{mode:?}");
3042            app.move_by(-9);
3043            assert_eq!(app.scroll, 0, "{mode:?}");
3044        }
3045    }
3046
3047    /// The map is a graph on the wire and a tree on screen, and every way that
3048    /// flattening can go wrong loses a service silently.
3049    #[test]
3050    fn the_map_flattens_to_a_tree_without_dropping_a_service() {
3051        let node =
3052            |k: &str, n: &str| format!(r#"{{"key":"{k}","name":"{n}","spans":1,"errors":0}}"#);
3053        let edge = |a: &str, b: &str, c: u64| format!(r#"{{"from":"{a}","to":"{b}","calls":{c}}}"#);
3054        let map = |nodes: &[String], edges: &[String]| {
3055            let doc = format!(
3056                r#"{{"nodes":[{}],"edges":[{}],"unresolved":7}}"#,
3057                nodes.join(","),
3058                edges.join(",")
3059            );
3060            MapView::new(&crate::api::parse(&doc).unwrap())
3061        };
3062        let names = |m: &MapView| -> Vec<(usize, String)> {
3063            m.rows
3064                .iter()
3065                .map(|(d, n)| (*d, n["name"].as_str().unwrap_or("?").to_owned()))
3066                .collect()
3067        };
3068
3069        // Busiest branch first, because the hot path is what a map is opened
3070        // for. `entry` is on top even though it is not one of the nodes.
3071        let m = map(
3072            &[node("1", "gw"), node("2", "slow"), node("3", "hot")],
3073            &[
3074                edge("entry", "1", 10),
3075                edge("1", "2", 1),
3076                edge("1", "3", 99),
3077            ],
3078        );
3079        assert_eq!(
3080            names(&m),
3081            [
3082                (0, "entry".into()),
3083                (1, "gw".into()),
3084                (2, "hot".into()),
3085                (2, "slow".into())
3086            ]
3087        );
3088        assert_eq!(m.unresolved, 7);
3089
3090        // A retry loop. Drawn once, at the depth it was first reached — a tree
3091        // that re-expands a cycle does not terminate.
3092        let m = map(
3093            &[node("1", "a"), node("2", "b")],
3094            &[edge("entry", "1", 1), edge("1", "2", 1), edge("2", "1", 1)],
3095        );
3096        assert_eq!(
3097            names(&m),
3098            [(0, "entry".into()), (1, "a".into()), (2, "b".into())]
3099        );
3100
3101        // A service whose only callers were outside the window is unreachable
3102        // from `entry`. It goes on the end flat rather than vanishing: a map
3103        // that omits a node reads as "this service is idle".
3104        let m = map(
3105            &[node("1", "a"), node("9", "orphan")],
3106            &[edge("entry", "1", 1)],
3107        );
3108        assert_eq!(
3109            names(&m),
3110            [(0, "entry".into()), (1, "a".into()), (0, "orphan".into())]
3111        );
3112
3113        // The span budget can cut a sample mid-trace, so an edge can name a
3114        // node that is not in `nodes` at all.
3115        let m = map(
3116            &[node("1", "a")],
3117            &[edge("entry", "1", 1), edge("1", "404", 1)],
3118        );
3119        assert_eq!(names(&m), [(0, "entry".into()), (1, "a".into())]);
3120
3121        // Nothing at all: `Job::Map` reports it rather than opening the pane,
3122        // and the header's `len() - 1` must not underflow if it ever does.
3123        assert!(map(&[], &[]).rows.is_empty());
3124    }
3125
3126    /// The cursor's row is drawn in reverse, so the error count on it is not
3127    /// also red: red under a reverse is the one combination that comes back
3128    /// unreadable on a terminal honouring both, and the count is what the row
3129    /// is being looked at for.
3130    #[test]
3131    fn the_selected_service_drops_the_red_its_highlight_would_fight() {
3132        let doc = crate::api::parse(
3133            r#"{"nodes":[{"key":"1","name":"checkout","spans":4,"errors":2,
3134                          "avg_nano":"22000000"}],
3135                "edges":[{"from":"entry","to":"1","calls":4}],"unresolved":0}"#,
3136        )
3137        .unwrap();
3138        let mut app = App::new(Source::Local("/nonexistent".into()));
3139        app.map = Some(MapView::new(&doc));
3140        app.mode = Mode::Map;
3141
3142        let errors = |app: &App| {
3143            app.map_pane(80, 10)
3144                .into_iter()
3145                .find(|l| strip(l).contains("2 errors"))
3146                .expect("the service with errors is on screen")
3147        };
3148        // `entry` is row 0, so the service is the unselected one here.
3149        app.psel = 0;
3150        assert!(errors(&app).contains("\x1b[31m"), "{:?}", errors(&app));
3151        app.psel = 1;
3152        assert!(!errors(&app).contains("\x1b[31m"), "{:?}", errors(&app));
3153    }
3154
3155    /// What the two new panes do with Enter. Everything either pane offers has
3156    /// to land back in an ordinary query — that is the point of the algebra's
3157    /// closure, and a selection that goes nowhere is the way to lose it.
3158    #[test]
3159    fn every_line_of_the_frame_and_map_leads_back_into_a_query() {
3160        let doc = crate::api::parse(
3161            r#"{"frame":{"from":"1000","to":"5000","truncated":false,
3162                 "entities":[{"key":"7","name":"checkout"},{"key":"8","name":"checkout"},
3163                             {"key":"9","name":"api"}],
3164                 "traces":["abababababababababababababababab"]},
3165               "map":{"nodes":[{"key":"7","name":"checkout","spans":2,"errors":1,
3166                                "avg_nano":"3000"}],
3167                 "edges":[{"from":"entry","to":"7","calls":2}],"unresolved":0}}"#,
3168        )
3169        .unwrap();
3170        let mut app = App::new(Source::Local("/nonexistent".into()));
3171        app.frame = Some(FrameView::new(&doc["frame"]));
3172        app.map = Some(MapView::new(&doc["map"]));
3173
3174        // Two entity keys, one name: an entity is an instance (section 7.2), and the
3175        // count is the only thing that says a service has replicas. Sorted by
3176        // name, because the engine sorts by key and a key is a hash.
3177        let f = app.frame.as_ref().unwrap();
3178        assert_eq!(f.services, [("api".into(), 1), ("checkout".into(), 2)]);
3179        assert_eq!(f.len(), 3);
3180
3181        app.mode = Mode::Frame;
3182        app.psel = 1;
3183        assert!(matches!(app.pick(), Some(Pick::Service(s)) if s == "checkout"));
3184        // Past the services, the same cursor indexes the traces.
3185        app.psel = 2;
3186        assert!(matches!(app.pick(), Some(Pick::Trace(t)) if t.starts_with("abab")));
3187        app.follow_pick();
3188        assert!(matches!(app.job, Some(Job::Trace(_))));
3189        // And `t` follows the pane's own selection, not the list behind it.
3190        app.job = None;
3191        app.open_trace();
3192        assert!(matches!(app.job, Some(Job::Trace(_))));
3193
3194        // A service is anded onto the filter and hands the reader back to the
3195        // list, so the next thing they do is an ordinary query.
3196        app.psel = 0;
3197        app.filter = "body~timeout".into();
3198        app.follow_pick();
3199        assert_eq!(app.filter, r#"body~timeout service.name="api""#);
3200        assert_eq!(app.mode, Mode::List);
3201        // Twice is a double-press.
3202        app.mode = Mode::Frame;
3203        app.follow_pick();
3204        assert_eq!(app.filter, r#"body~timeout service.name="api""#);
3205
3206        // `entry` is the synthetic caller of every root span, so there is no
3207        // service behind it to filter on and Enter must do nothing.
3208        app.mode = Mode::Map;
3209        app.psel = 0;
3210        assert!(app.pick().is_none());
3211        app.psel = 1;
3212        assert!(matches!(app.pick(), Some(Pick::Service(s)) if s == "checkout"));
3213
3214        // Only those two panes have a pick at all. The record list's cursor is
3215        // still set behind them, and answering with *that* row's service would
3216        // make Enter act on something nobody is pointing at.
3217        for mode in [Mode::List, Mode::Detail, Mode::Trace, Mode::Alerts] {
3218            app.mode = mode;
3219            assert!(app.pick().is_none(), "{mode:?}");
3220        }
3221
3222        // The filter box splits on whitespace and toggles on `"`, so a name
3223        // carrying either has to survive the round trip into a real term.
3224        assert_eq!(service_term("a b"), r#"service.name="a b""#);
3225        assert_eq!(
3226            parse_filter(&service_term("a b")),
3227            [term("service.name", "eq", "a b")]
3228        );
3229        // No equality spelling for an embedded quote; the prefix is a true
3230        // term. `parse_filter` trims it, so it is `say` rather than `say `.
3231        assert_eq!(
3232            parse_filter(&service_term(r#"say "hi""#)),
3233            [term("service.name", "contains", "say")]
3234        );
3235    }
3236
3237    /// The two node panes, from the keystroke to the pixels.
3238    ///
3239    /// A layout test proves nothing here: `Row` clips at `max` rather than
3240    /// overflowing, so a pane that has silently lost its numbers still passes
3241    /// `every_view_fits_the_frame_at_any_size` with the right line count. This
3242    /// one reads the numbers back off the screen.
3243    #[test]
3244    fn the_node_panes_show_the_numbers_the_endpoints_answered() {
3245        const ROWS: &str = r#"{"rows":[],"stats":{"blocks_total":0,"blocks_scanned":0,
3246                               "rows_scanned":0,"rows_matched":0}}"#;
3247        const ALERTS: &str = r#"{"alerts":[
3248            {"name":"checkout-error-rate","state":"firing","severity":"critical",
3249             "metric":"ratio","op":">","threshold":0.05,"value":0.5,"matched":5,"total":10,
3250             "over_nano":"60000000000","for_nano":"0","since":"1","firing_since":"1",
3251             "evaluated_at":"2","signal":"traces",
3252             "filter":"attr:service.name=checkout field:status_code=2",
3253             "link":"https://m/#/traces?q=x","error":null},
3254            {"name":"quiet","state":"ok","severity":"warning","metric":"count","op":">=",
3255             "threshold":1.0,"value":0.0,"matched":0,"total":null,"over_nano":"300000000000",
3256             "for_nano":"0","since":null,"firing_since":null,"evaluated_at":"2",
3257             "signal":"logs","filter":"","link":"","error":null}],
3258            "every_nano":"5000000000"}"#;
3259        const STATS: &str = r#"{"uptime_s":93784,"peak_rss_bytes":441450496,
3260            "free_fraction":0.07,"queries":{"count":12040,"mean_ms":1.83,"max_ms":412.5},
3261            "signals":{"logs":{"shed":3,"failed":0,"refused":1,"blocks_published":71,
3262              "rows":1204000,"bytes":158000000,"blocks_on_disk":69,"open_block_age_s":12,
3263              "stalled_s":41}}}"#;
3264
3265        // One reply per connection, in the order this session asks: the first
3266        // list query, `a`, the requery Enter fires, then `d`.
3267        let addr = source::serve([ROWS, ALERTS, ROWS, STATS].map(source::ok).to_vec());
3268        let mut app = App::new(Source::Remote(addr));
3269        settle(&mut app);
3270
3271        let a = strip(&press(&mut app, Key::Char('a')));
3272        assert_eq!(app.mode, Mode::Alerts);
3273        assert!(a.contains("2 rules"), "{a}");
3274        assert!(a.contains("1 firing"), "{a}");
3275        // The ratio reads as a percentage against its threshold, with the two
3276        // counts behind it — the whole of why the rule fired, on one line.
3277        assert!(a.contains("50.00% > 5.00%"), "{a}");
3278        assert!(a.contains("5 of 10"), "{a}");
3279        // A count rule has no denominator and must not invent one.
3280        assert!(a.contains("0 records") && !a.contains("0 of 0"), "{a}");
3281        assert!(
3282            a.contains("attr:service.name=checkout field:status_code=2"),
3283            "{a}"
3284        );
3285        assert!(a.contains("(no filter — every record)"), "{a}");
3286        assert!(a.contains("over 1m00s"), "{a}");
3287
3288        // Enter lands on the rows the rule counted: its signal's tab, its terms
3289        // in the filter box, and a query already in flight.
3290        press(&mut app, Key::Enter);
3291        assert_eq!(app.tab, Tab::Traces);
3292        assert_eq!(app.filter, "attr:service.name=checkout field:status_code=2");
3293        assert_eq!(app.mode, Mode::List);
3294
3295        let d = strip(&press(&mut app, Key::Char('d')));
3296        assert_eq!(app.mode, Mode::Diag);
3297        assert!(d.contains("up 1d 02h"), "{d}");
3298        assert!(d.contains("peak rss 421.0 MiB"), "{d}");
3299        assert!(d.contains("disk 7% free"), "{d}");
3300        assert!(d.contains("12.0k") && d.contains("1.83 ms"), "{d}");
3301        assert!(
3302            d.contains("69 on disk") && d.contains("71 published"),
3303            "{d}"
3304        );
3305        assert!(
3306            d.contains("1.2M"),
3307            "a million rows is not printed in full: {d}"
3308        );
3309        // The cost-per-GB axis on this node's own data: 158 MB over 1.204M rows.
3310        assert!(d.contains("150.7 MiB") && d.contains("131 B/row"), "{d}");
3311        assert!(d.contains("3 shed") && d.contains("1 refused"), "{d}");
3312        // Stalled is the readiness condition; it is never left off when set.
3313        assert!(d.contains("cannot store this signal"), "{d}");
3314        // A signal the document did not mention is skipped, not drawn empty —
3315        // its section rule is what is absent, not the word, which is also a tab.
3316        assert!(!d.contains("── metrics") && !d.contains("── traces"), "{d}");
3317    }
3318
3319    /// Both panes report a process. A directory is not one, and saying so is
3320    /// better than an empty screen that looks like "no rules, all healthy".
3321    #[test]
3322    fn the_node_panes_refuse_a_directory_by_name() {
3323        let mut app = App::new(Source::Local("/nonexistent".into()));
3324        app.job = None;
3325        for (k, want) in [('a', "alerts"), ('d', "stats")] {
3326            let f = strip(&press(&mut app, Key::Char(k)));
3327            assert!(app.err, "{k} should have failed");
3328            assert!(f.contains(want) && f.contains("--addr"), "{f}");
3329            assert_eq!(app.mode, Mode::List, "and must not open the pane");
3330        }
3331    }
3332
3333    /// Painting must never panic and never overrun, whatever the terminal size
3334    /// or the mode — a panic here leaves the user's shell in raw mode.
3335    #[test]
3336    fn every_view_fits_the_frame_at_any_size() {
3337        let doc = crate::api::parse(
3338            // Every 64-bit field is quoted, because that is how it arrives:
3339            // `query.rs` writes `Int64`, `UInt64` and `Timestamp` through
3340            // `Json::i64_str` (section 7.6). A fixture that spells them bare tests a
3341            // response the server never sends.
3342            r#"{"rows":[{"time_unix_nano":"1788877362987743417","severity_number":17,
3343                 "severity_text":"ERROR","body":"boom","duration_nano":"5000000",
3344                 "status_code":2,"name":"GET /x","span_id":"01",
3345                 "trace_id":"abababababababababababababababab",
3346                 "events":[{"name":"ev","time_unix_nano":"1788877362987743500"}],
3347                 "links":[{"trace_id":"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd"}],
3348                 "attributes":{"service.name":"checkout"}}],
3349               "series":[{"name":"m","attributes":{"service.name":"c"},
3350                 "points":[["1","2"],["2","3"]],
3351                 "exemplars":[{"trace_id":"abababababababababababababababab"}]}],
3352               "names":[{"name":"http.server.duration","unit":"ms","kind":"histogram"}],
3353               "frame":{"from":"1788877362987743417","to":"1788877372987743417",
3354                 "entities":[{"key":"1","name":"checkout"},{"key":"2","name":"checkout"},
3355                             {"key":"3","name":"a-very-long-service-name-indeed"}],
3356                 "traces":["abababababababababababababababab"],"truncated":true},
3357               "map":{"nodes":[{"key":"1","name":"frontend","spans":9,"errors":0,
3358                                "avg_nano":"1000000"},
3359                               {"key":"2","name":"checkout","spans":4,"errors":2,
3360                                "avg_nano":"22000000"}],
3361                 "edges":[{"from":"entry","to":"1","calls":9,"errors":0,
3362                           "avg_nano":"1000000","max_nano":"2000000"},
3363                          {"from":"1","to":"2","calls":4,"errors":2,
3364                           "avg_nano":"22000000","max_nano":"90000000"}],
3365                 "unresolved":3},
3366               "alerts":[{"name":"checkout-error-rate","state":"firing","severity":"critical",
3367                 "metric":"ratio","op":">","threshold":0.05,"value":0.5,"matched":5,"total":10,
3368                 "over_nano":"60000000000","for_nano":"0","since":"1788877362987743417",
3369                 "firing_since":"1788877362987743417","evaluated_at":"1788877372987743417",
3370                 "signal":"logs","filter":"attr:service.name=checkout field:severity_number>=17",
3371                 "link":"https://m/#/logs?q=x","error":null},
3372                {"name":"a-rule-whose-name-is-far-too-long-to-fit-in-any-column","state":"ok",
3373                 "severity":"warning","metric":"count","op":">=","threshold":1.0,"value":0.0,
3374                 "matched":0,"total":null,"over_nano":"300000000000","for_nano":"120000000000",
3375                 "since":null,"firing_since":null,"evaluated_at":"1788877372987743417",
3376                 "signal":"traces","filter":"","link":"","error":"block directory unreadable"}]}"#,
3377        )
3378        .unwrap();
3379        // The diagnostics pane renders the stats document as it arrives, so the
3380        // fixture is one: absent counters are `null` there, never zero.
3381        let diag = crate::api::parse(
3382            r#"{"uptime_s":93784,"peak_rss_bytes":441450496,"free_fraction":0.07,
3383                "queries":{"count":12040,"mean_ms":1.83,"max_ms":412.5},
3384                "signals":{"logs":{"shed":3,"failed":0,"refused":1,"blocks_published":71,
3385                             "rows":1204000,"bytes":158000000,"blocks_on_disk":69,
3386                             "open_block_age_s":12,"stalled_s":41},
3387                           "traces":{"shed":0,"failed":0,"refused":0,"blocks_published":0,
3388                             "rows":0,"bytes":0,"blocks_on_disk":null,
3389                             "open_block_age_s":null,"stalled_s":null}}}"#,
3390        )
3391        .unwrap();
3392        let mut app = App::new(Source::Local("/nonexistent".into()));
3393        app.rows = array(&doc["rows"]);
3394        app.series = array(&doc["series"]);
3395        app.names = array(&doc["names"]);
3396        app.trace = Some(Trace::new("ab".into(), &array(&doc["rows"])));
3397        app.frame = Some(FrameView::new(&doc["frame"]));
3398        app.map = Some(MapView::new(&doc["map"]));
3399        app.alerts = array(&doc["alerts"]);
3400        app.diag = Some(diag);
3401        app.stats = "x".into();
3402
3403        for (w, h) in [(40, 8), (80, 24), (200, 60), (41, 9)] {
3404            for tab in [Tab::Logs, Tab::Traces, Tab::Metrics] {
3405                for mode in [
3406                    Mode::List,
3407                    Mode::Filter,
3408                    Mode::Detail,
3409                    Mode::Trace,
3410                    Mode::Span,
3411                    Mode::Frame,
3412                    Mode::Map,
3413                    Mode::Alerts,
3414                    Mode::Diag,
3415                    Mode::Help,
3416                ] {
3417                    app.tab = tab;
3418                    app.mode = mode;
3419                    let f = app.frame(w, h);
3420                    assert_eq!(f.len(), h, "row count at {w}x{h}");
3421                    for line in &f {
3422                        let visible = line
3423                            .chars()
3424                            .scan(false, |esc, c| {
3425                                Some(match (*esc, c) {
3426                                    (_, '\x1b') => {
3427                                        *esc = true;
3428                                        None
3429                                    }
3430                                    (true, c) => {
3431                                        *esc = !c.is_ascii_alphabetic();
3432                                        None
3433                                    }
3434                                    (false, c) => Some(c),
3435                                })
3436                            })
3437                            .flatten()
3438                            .count();
3439                        assert!(visible <= w, "line of {visible} columns at width {w}");
3440                    }
3441                }
3442            }
3443        }
3444
3445        // Under the minimum there is no frame to fit. Drawing the 40-column one
3446        // anyway wraps every row — `Term::draw` has no cursor addressing — and
3447        // scrolls its own top off the screen for good, so it says so instead,
3448        // at the width the terminal actually has.
3449        for (w, h) in [(30, 6), (80, 7), (39, 24), (0, 0)] {
3450            let f = app.frame(w, h);
3451            assert_eq!(f.len(), 1, "{w}x{h} is one line, not a frame");
3452            assert!(strip(&f[0]).chars().count() <= w, "{w}x{h}");
3453        }
3454        assert_eq!(
3455            strip(&app.frame(30, 6)[0]),
3456            "terminal too small — need 40x8"
3457        );
3458    }
3459
3460    const W: usize = 100;
3461    const H: usize = 24;
3462
3463    /// A block directory with all three signals in it, timestamped now, because
3464    /// every query the TUI issues is relative to the clock.
3465    fn store(name: &str) -> std::path::PathBuf {
3466        use mira_proto::collector::metrics::v1::ExportMetricsServiceRequest;
3467        use mira_proto::collector::trace::v1::ExportTraceServiceRequest;
3468        use mira_proto::metrics::v1::metric::Data;
3469        use mira_proto::metrics::v1::{
3470            AggregationTemporality, Exemplar, Gauge, Metric, NumberDataPoint, ResourceMetrics,
3471            ScopeMetrics, Sum, exemplar, number_data_point,
3472        };
3473        use mira_proto::trace::v1::{ResourceSpans, ScopeSpans, Span};
3474
3475        let dir = std::env::temp_dir().join(format!("mira-tui-{name}-{}", std::process::id()));
3476        let _ = std::fs::remove_dir_all(&dir);
3477        let now = crate::api::now_nanos() as u64;
3478        let node = mira_core::block::node_id("a");
3479
3480        let mut b = mira_core::logs::LogsBuilder::new();
3481        b.append_request(&crate::e2e::logs_export(
3482            "checkout",
3483            now - 60_000_000_000,
3484            5,
3485        ))
3486        .unwrap();
3487        mira_core::block::publish(&dir, "logs", node, 0, 0, &b.finish().unwrap()).unwrap();
3488
3489        // The same trace id `logs_export` stamps on its records, so `t` on a log
3490        // line has somewhere to go.
3491        let trace_id = vec![0xabu8; 16];
3492        let mut b = mira_core::traces::TracesBuilder::new();
3493        b.append_request(&ExportTraceServiceRequest {
3494            resource_spans: vec![ResourceSpans {
3495                scope_spans: vec![ScopeSpans {
3496                    spans: (0..4u64)
3497                        .map(|i| Span {
3498                            trace_id: trace_id.clone().into(),
3499                            span_id: vec![i as u8 + 1; 8].into(),
3500                            // A tree, not a list: the waterfall's indenting and
3501                            // its parent lookup are the point of the view.
3502                            parent_span_id: match i {
3503                                0 => Vec::new(),
3504                                _ => vec![i as u8; 8],
3505                            }
3506                            .into(),
3507                            name: format!("GET /checkout/{i}"),
3508                            start_time_unix_nano: now - 60_000_000_000 + i * 1_000_000,
3509                            end_time_unix_nano: now - 59_000_000_000 + i * 1_000_000,
3510                            ..Default::default()
3511                        })
3512                        .collect(),
3513                    ..Default::default()
3514                }],
3515                ..Default::default()
3516            }],
3517        })
3518        .unwrap();
3519        mira_core::block::publish(&dir, "traces", node, 0, 0, &b.finish().unwrap()).unwrap();
3520
3521        let point = |i: u64| NumberDataPoint {
3522            time_unix_nano: now - 60_000_000_000 + i * 1_000_000_000,
3523            value: Some(number_data_point::Value::AsDouble(i as f64 * 1.5)),
3524            exemplars: vec![Exemplar {
3525                time_unix_nano: now - 60_000_000_000,
3526                trace_id: trace_id.clone().into(),
3527                value: Some(exemplar::Value::AsDouble(1.0)),
3528                ..Default::default()
3529            }],
3530            ..Default::default()
3531        };
3532        let mut b = mira_core::metrics::MetricsBuilder::new();
3533        b.append_request(&ExportMetricsServiceRequest {
3534            resource_metrics: vec![ResourceMetrics {
3535                scope_metrics: vec![ScopeMetrics {
3536                    metrics: vec![
3537                        Metric {
3538                            name: "http.server.duration".into(),
3539                            unit: "ms".into(),
3540                            data: Some(Data::Gauge(Gauge {
3541                                data_points: (0..6).map(point).collect(),
3542                            })),
3543                            ..Default::default()
3544                        },
3545                        Metric {
3546                            name: "http.server.requests".into(),
3547                            unit: "1".into(),
3548                            data: Some(Data::Sum(Sum {
3549                                aggregation_temporality: AggregationTemporality::Cumulative as i32,
3550                                is_monotonic: true,
3551                                data_points: (0..6).map(point).collect(),
3552                            })),
3553                            ..Default::default()
3554                        },
3555                    ],
3556                    ..Default::default()
3557                }],
3558                ..Default::default()
3559            }],
3560        })
3561        .unwrap();
3562        mira_core::block::publish(&dir, "metrics", node, 0, 0, &b.finish().unwrap()).unwrap();
3563        dir
3564    }
3565
3566    /// One turn of the loop in [`run`], minus the terminal.
3567    ///
3568    /// The order matters and is the reason it is a helper rather than a call to
3569    /// `key`: the frame is painted *before* the deferred job runs, so the screen
3570    /// that says "running" is on it while the query blocks. Anything asserting on
3571    /// what the user sees has to go through the same sequence.
3572    fn settle(app: &mut App) -> String {
3573        let mut f = app.frame(W, H);
3574        // Bounded so a job that queues itself fails the test instead of hanging
3575        // it. Eight is three more than the longest real sequence.
3576        let mut left = 8;
3577        while let Some(job) = app.job.take() {
3578            assert!(left > 0, "a job kept queueing another one");
3579            left -= 1;
3580            app.run(job, H);
3581            f = app.frame(W, H);
3582        }
3583        f.join("\n")
3584    }
3585
3586    fn press(app: &mut App, k: Key) -> String {
3587        assert!(app.key(k, H), "quit on {k:?}");
3588        settle(app)
3589    }
3590
3591    fn typed(app: &mut App, s: &str) -> String {
3592        let mut out = String::new();
3593        for c in s.chars() {
3594            out = press(app, Key::Char(c));
3595        }
3596        out
3597    }
3598
3599    pub(super) fn strip(s: &str) -> String {
3600        let mut out = String::new();
3601        let mut it = s.chars();
3602        while let Some(c) = it.next() {
3603            if c == '\x1b' {
3604                for c in it.by_ref() {
3605                    if c.is_ascii_alphabetic() {
3606                        break;
3607                    }
3608                }
3609            } else {
3610                out.push(c);
3611            }
3612        }
3613        out
3614    }
3615
3616    /// The whole app driven by keystrokes against a real block directory, which
3617    /// is what `mira mira --data-dir` does with no server anywhere. `run` itself
3618    /// is not here — it is this loop plus a `Term`, and a `Term` needs a pty.
3619    #[test]
3620    fn a_session_walks_the_three_tabs_and_lands_on_a_trace() {
3621        let dir = store("session");
3622        let mut app = App::new(Source::Local(dir));
3623
3624        // Opening screen: the logs tab, already loaded, with no key pressed.
3625        let f = strip(&settle(&mut app));
3626        assert!(f.contains("checkout handled request"), "{f}");
3627        assert!(f.contains("ERROR"), "{f}");
3628        assert_eq!(app.rows.len(), 5);
3629
3630        // Detail, scrolled, and back. Esc leaves the mode, it does not quit.
3631        let f = strip(&press(&mut app, Key::Enter));
3632        assert_eq!(app.mode, Mode::Detail);
3633        assert!(f.contains("service.name"), "{f}");
3634        press(&mut app, Key::Char('j'));
3635        assert_eq!(app.scroll, 1);
3636        press(&mut app, Key::Esc);
3637        assert_eq!(app.mode, Mode::List);
3638
3639        // `l` walks right through the tabs; each arrival reloads.
3640        let f = strip(&press(&mut app, Key::Char('l')));
3641        assert_eq!(app.tab, Tab::Traces);
3642        assert!(f.contains("GET /checkout/"), "{f}");
3643        assert_eq!(app.rows.len(), 4);
3644
3645        // Metrics loads names, then loads the first series without being asked —
3646        // the two-job sequence `settle` exists to drain.
3647        let f = strip(&press(&mut app, Key::Char('l')));
3648        assert_eq!(app.tab, Tab::Metrics);
3649        assert!(f.contains("http.server.duration"), "{f}");
3650        assert!(!app.series.is_empty(), "the first name loaded its series");
3651
3652        // Tab moves the arrow keys from the name list to the series list.
3653        assert!(!app.on_series);
3654        press(&mut app, Key::Tab);
3655        assert!(app.on_series);
3656        press(&mut app, Key::Tab);
3657        press(&mut app, Key::Char('j'));
3658        assert_eq!(app.nsel, 1);
3659        let f = strip(&press(&mut app, Key::Enter));
3660        assert!(f.contains("http.server.requests"), "{f}");
3661
3662        // A metric exemplar carries the trace id of the request that produced
3663        // the measurement, and `t` follows it. Three tabs, one key.
3664        press(&mut app, Key::Tab);
3665        let f = strip(&press(&mut app, Key::Char('t')));
3666        assert_eq!(app.mode, Mode::Trace);
3667        let t = app.trace.as_ref().unwrap();
3668        assert_eq!(t.id, "abababababababababababababababab");
3669        assert_eq!(t.spans.len(), 4);
3670        assert!(f.contains("GET /checkout/0"), "{f}");
3671        // Indented: the waterfall is a tree, not a list.
3672        assert!(f.contains("  GET /checkout/1"), "{f}");
3673
3674        press(&mut app, Key::Down);
3675        assert_eq!(app.trace.as_ref().unwrap().sel, 1);
3676        // `t` inside a trace is a no-op rather than a reload of the same trace.
3677        press(&mut app, Key::Char('t'));
3678        assert_eq!(app.mode, Mode::Trace);
3679
3680        // Enter opens the selected span. The waterfall draws a span's shape;
3681        // its attributes and its status message exist nowhere else, and the
3682        // span is not in `self.rows` — this trace came from an exemplar.
3683        let f = strip(&press(&mut app, Key::Enter));
3684        assert_eq!(app.mode, Mode::Span);
3685        assert!(f.contains("GET /checkout/1"), "{f}");
3686        assert!(f.contains("duration_nano"), "{f}");
3687        press(&mut app, Key::Char('j'));
3688        assert_eq!(app.scroll, 1, "the span detail scrolls like any other");
3689        // Back to the waterfall it was opened from, not to the list.
3690        press(&mut app, Key::Esc);
3691        assert_eq!(app.mode, Mode::Trace);
3692        // `q` leaves the mode. Only `q` on the list quits.
3693        press(&mut app, Key::Char('q'));
3694        assert_eq!(app.mode, Mode::List);
3695
3696        // Help is a toggle, and Esc closes it too.
3697        let f = strip(&press(&mut app, Key::Char('?')));
3698        assert_eq!(app.mode, Mode::Help);
3699        assert!(f.contains("the trace this row points at"), "{f}");
3700        // Under a heading: the keys are grouped by what a reader is trying to
3701        // do, not listed alphabetically.
3702        assert!(f.contains("open something"), "{f}");
3703        assert!(f.contains("get back out"), "{f}");
3704        press(&mut app, Key::Char('?'));
3705        assert_eq!(app.mode, Mode::List);
3706
3707        assert!(!app.key(Key::Char('q'), H), "q on the list quits");
3708    }
3709
3710    /// The filter bar: typed, edited, applied, and undone. Applying it is the
3711    /// only thing here that costs a query, which is why Esc restores the text
3712    /// rather than re-running with the old one.
3713    #[test]
3714    fn the_filter_bar_edits_a_query_and_esc_puts_it_back() {
3715        let dir = store("filter");
3716        let mut app = App::new(Source::Local(dir));
3717        settle(&mut app);
3718
3719        press(&mut app, Key::Char('/'));
3720        assert_eq!(app.mode, Mode::Filter);
3721        typed(&mut app, "severity_text=WARN xx");
3722        assert_eq!(app.filter, "severity_text=WARN xx");
3723        press(&mut app, Key::Ctrl('w'));
3724        assert_eq!(app.filter, "severity_text=WARN ");
3725        press(&mut app, Key::Backspace);
3726        press(&mut app, Key::Backspace);
3727        assert_eq!(app.filter, "severity_text=WAR");
3728        typed(&mut app, "N");
3729
3730        let f = strip(&press(&mut app, Key::Enter));
3731        assert_eq!(app.mode, Mode::List);
3732        assert!(app.rows.is_empty());
3733        assert!(f.contains("no rows in this window"), "{f}");
3734        // The body says it too, and says what to do about it. A blank pane
3735        // with one phrase in the footer reads as broken rather than empty.
3736        assert!(f.contains("no records matched"), "{f}");
3737        assert!(f.contains("last 1h · severity_text=WARN"), "{f}");
3738        assert!(f.contains("] widens the window"), "{f}");
3739
3740        // Esc restores the text that was there before `/`, so an abandoned edit
3741        // leaves the view exactly as it was found.
3742        press(&mut app, Key::Char('/'));
3743        typed(&mut app, " and more");
3744        press(&mut app, Key::Esc);
3745        assert_eq!(app.filter, "severity_text=WARN");
3746        assert_eq!(app.mode, Mode::List);
3747
3748        press(&mut app, Key::Char('/'));
3749        press(&mut app, Key::Ctrl('u'));
3750        press(&mut app, Key::Enter);
3751        assert_eq!(app.rows.len(), 5, "an empty filter is every row back");
3752
3753        // A bare word on the metrics tab has no text column to search, so it is
3754        // reported rather than quietly dropped.
3755        press(&mut app, Key::Char('3'));
3756        press(&mut app, Key::Char('/'));
3757        typed(&mut app, "checkout");
3758        let f = strip(&press(&mut app, Key::Enter));
3759        assert!(f.contains("ignored"), "{f}");
3760    }
3761
3762    /// A directory nothing was ever written to, which is what a first run
3763    /// against the wrong `--data-dir` looks like.
3764    ///
3765    /// It is a different pane from a filter that matched nothing, and the
3766    /// advice is the opposite: widening the window here would never help.
3767    #[test]
3768    fn an_empty_directory_says_it_is_empty_rather_than_drawing_a_blank_pane() {
3769        let dir = std::env::temp_dir().join(format!("mira-tui-void-{}", std::process::id()));
3770        let _ = std::fs::remove_dir_all(&dir);
3771        std::fs::create_dir_all(&dir).unwrap();
3772
3773        let mut app = App::new(Source::Local(dir.clone()));
3774        let f = strip(&settle(&mut app));
3775        assert_eq!(app.blocks, 0);
3776        assert!(f.contains("nothing has been written here"), "{f}");
3777        assert!(f.contains("0 blocks"), "{f}");
3778        assert!(f.contains("--data-dir"), "{f}");
3779        assert!(!f.contains("widens the window"), "{f}");
3780
3781        // The metrics pane is a different renderer and goes to the same place.
3782        let f = strip(&press(&mut app, Key::Char('3')));
3783        assert!(f.contains("nothing has been written here"), "{f}");
3784
3785        let _ = std::fs::remove_dir_all(&dir);
3786    }
3787
3788    /// The key bar names the pane Esc goes back to, and sheds the panes — not
3789    /// the way out of them — when the terminal is too narrow for all of it.
3790    #[test]
3791    fn the_key_bar_names_where_esc_goes_and_sheds_keys_when_it_will_not_fit() {
3792        let dir = store("hints");
3793        let mut app = App::new(Source::Local(dir));
3794        settle(&mut app);
3795
3796        let wide = strip(&app.hints(130));
3797        assert!(wide.contains("a alerts"), "{wide}");
3798        assert!(wide.trim_end().ends_with("? help  q quit"), "{wide}");
3799        // 80 columns cannot hold the whole bar. What has to go is the panes,
3800        // which `?` lists anyway — never `? help` or `q quit`.
3801        let narrow = strip(&app.hints(80));
3802        assert!(narrow.contains("? help  q quit"), "{narrow}");
3803        assert!(!narrow.contains("a alerts"), "{narrow}");
3804
3805        press(&mut app, Key::Enter);
3806        assert_eq!(app.mode, Mode::Detail);
3807        assert!(strip(&app.hints(W)).contains("esc → logs"));
3808        // A trace opened from the logs tab goes back to the logs tab, and the
3809        // bar says which one rather than "esc back".
3810        press(&mut app, Key::Char('t'));
3811        assert_eq!(app.mode, Mode::Trace);
3812        assert!(strip(&app.hints(W)).contains("esc → logs"));
3813        press(&mut app, Key::Enter);
3814        assert_eq!(app.mode, Mode::Span);
3815        assert!(strip(&app.hints(W)).contains("esc → waterfall"));
3816
3817        press(&mut app, Key::Char('q'));
3818        press(&mut app, Key::Char('q'));
3819        press(&mut app, Key::Char('2'));
3820        press(&mut app, Key::Char('?'));
3821        let help = strip(&app.hints(W));
3822        assert!(help.contains("esc → traces"), "{help}");
3823        // The list is longer than a 24-row terminal, so the bar has to say the
3824        // pane scrolls.
3825        assert!(help.contains("↑↓ scroll"), "{help}");
3826    }
3827
3828    /// The controls that change the query rather than the view, and the two
3829    /// things that can go wrong: a selection that points at nothing to follow,
3830    /// and a store that cannot be read.
3831    #[test]
3832    fn the_window_and_limit_keys_requery_and_failures_stay_on_screen() {
3833        let dir = store("window");
3834        let mut app = App::new(Source::Local(dir.clone()));
3835        settle(&mut app);
3836
3837        assert_eq!(app.win, 2);
3838        press(&mut app, Key::Char('['));
3839        assert_eq!(app.win, 1);
3840        for _ in 0..9 {
3841            press(&mut app, Key::Char(']'));
3842        }
3843        assert_eq!(app.win, WINDOWS.len() - 1, "clamped at the widest window");
3844        let f = strip(&press(&mut app, Key::Char('[')));
3845        assert!(f.contains("7d"), "{f}");
3846
3847        assert_eq!(app.limit, 200);
3848        press(&mut app, Key::Char('+'));
3849        assert_eq!(app.limit, 400);
3850        press(&mut app, Key::Char('-'));
3851        press(&mut app, Key::Char('-'));
3852        assert_eq!(app.limit, 100);
3853        press(&mut app, Key::Char('r'));
3854        assert_eq!(app.rows.len(), 5);
3855
3856        // Paging and the jump keys share one clamp across every pane.
3857        press(&mut app, Key::End);
3858        assert_eq!(app.sel, 4);
3859        press(&mut app, Key::PageUp);
3860        assert_eq!(app.sel, 0);
3861        press(&mut app, Key::PageDown);
3862        assert_eq!(app.sel, 4);
3863        press(&mut app, Key::Home);
3864        assert_eq!(app.sel, 0);
3865
3866        // A span row has a trace id; a row that does not exist has nothing.
3867        app.rows.clear();
3868        let f = strip(&press(&mut app, Key::Char('t')));
3869        assert!(app.err);
3870        assert!(f.contains("nothing here carries a trace id"), "{f}");
3871
3872        // The store going away under the session is a message on the status
3873        // bar, not a panic and not a blank screen.
3874        std::fs::remove_dir_all(&dir).unwrap();
3875        std::fs::write(&dir, b"not a directory").unwrap();
3876        let f = strip(&press(&mut app, Key::Char('r')));
3877        assert!(app.err, "{f}");
3878        assert!(
3879            f.contains("logs"),
3880            "the failure names what it could not read: {f}"
3881        );
3882    }
3883
3884    /// The two panes built out of the frame algebra, reached the way a reader
3885    /// reaches them.
3886    ///
3887    /// `every_line_of_the_frame_and_map_leads_back_into_a_query` drives `pick`
3888    /// against a fixture, which proves what Enter means but not that either key
3889    /// sends a document the engine answers. This one presses the keys against a
3890    /// real block directory, so the query is the one `/api/v1/correlate` and
3891    /// `/api/v1/map` actually run.
3892    #[test]
3893    fn the_frame_and_map_panes_open_from_a_keystroke() {
3894        let dir = store("panes");
3895        let mut app = App::new(Source::Local(dir));
3896        settle(&mut app);
3897
3898        // Metrics is not an anchor: a frame widens out from records and a
3899        // series is not one. Said, rather than sent and returned empty.
3900        press(&mut app, Key::Char('3'));
3901        let f = strip(&press(&mut app, Key::Char('c')));
3902        assert!(app.err, "{f}");
3903        assert!(f.contains("switch tab first"), "{f}");
3904        assert_eq!(app.mode, Mode::List);
3905
3906        // `h` walks the tabs the way `l` does not, and a digit jumps.
3907        press(&mut app, Key::Char('h'));
3908        assert_eq!(app.tab, Tab::Traces);
3909        press(&mut app, Key::Char('h'));
3910        assert_eq!(app.tab, Tab::Logs);
3911        press(&mut app, Key::Char('1'));
3912        assert_eq!(app.tab, Tab::Logs, "the tab already on is not a reload");
3913        press(&mut app, Key::Char('2'));
3914        assert_eq!(app.tab, Tab::Traces);
3915
3916        let f = strip(&press(&mut app, Key::Char('c')));
3917        assert_eq!(app.mode, Mode::Frame);
3918        assert!(f.contains("services") && f.contains("checkout"), "{f}");
3919        assert!(f.contains("traces"), "{f}");
3920
3921        // The pane owns its own cursor, and it clamps like every other one.
3922        let last = app.frame.as_ref().unwrap().len() - 1;
3923        press(&mut app, Key::Char('G'));
3924        assert_eq!(app.psel, last);
3925        press(&mut app, Key::Char('j'));
3926        assert_eq!(
3927            app.psel, last,
3928            "clamped at the end of the pane, not the list"
3929        );
3930        press(&mut app, Key::Char('k'));
3931        press(&mut app, Key::Char('g'));
3932        assert_eq!(app.psel, 0);
3933
3934        // No services on the frame: `peers` reports who the anchor set talks
3935        // *to*, and this corpus is one service talking to itself. So the whole
3936        // pane is its traces, and Enter on one opens the waterfall.
3937        assert!(app.frame.as_ref().unwrap().services.is_empty());
3938        let f = strip(&press(&mut app, Key::Enter));
3939        assert_eq!(app.mode, Mode::Trace, "{f}");
3940        press(&mut app, Key::Char('q'));
3941        assert_eq!(app.mode, Mode::List);
3942
3943        // The map runs over the same window and does have a service in it: it
3944        // is built from `parent_span_id` at read time, so one service calling
3945        // itself is still an edge.
3946        let f = strip(&press(&mut app, Key::Char('m')));
3947        assert_eq!(app.mode, Mode::Map);
3948        assert!(f.contains("map"), "{f}");
3949
3950        // The cursor starts on `entry`, the synthetic caller of every root
3951        // span. There is no service behind it and no trace under it, so both
3952        // keys that act on a selection have to decline rather than act on the
3953        // row below or on the record list behind the pane.
3954        assert_eq!(app.psel, 0);
3955        press(&mut app, Key::Enter);
3956        assert_eq!(app.mode, Mode::Map, "enter on entry opens nothing");
3957        assert!(
3958            app.filter.is_empty(),
3959            "and filters on nothing: {}",
3960            app.filter
3961        );
3962        let f = strip(&press(&mut app, Key::Char('t')));
3963        assert_eq!(app.mode, Mode::Map, "{f}");
3964        assert!(f.contains("nothing here carries a trace id"), "{f}");
3965
3966        // Off `entry`, which is synthetic, and onto the service under it.
3967        press(&mut app, Key::Char('j'));
3968        press(&mut app, Key::Enter);
3969        assert_eq!(app.mode, Mode::List);
3970        assert!(app.filter.contains("service.name="), "{}", app.filter);
3971
3972        // Follow belongs to the record list, and the bar says when it is on.
3973        app.filter.clear();
3974        let f = strip(&press(&mut app, Key::Char('f')));
3975        assert!(app.tail, "{f}");
3976        assert!(f.contains("follow"), "{f}");
3977        press(&mut app, Key::Char('f'));
3978        assert!(!app.tail);
3979        press(&mut app, Key::Char('3'));
3980        let f = strip(&press(&mut app, Key::Char('f')));
3981        assert!(app.err, "{f}");
3982        assert!(f.contains("logs or traces list"), "{f}");
3983
3984        // Nothing matched. The frame does not open on an empty answer: an empty
3985        // frame drawn as a frame reads as "these are all the services".
3986        press(&mut app, Key::Char('2'));
3987        app.filter = "service.name=nosuchservice".into();
3988        let f = strip(&press(&mut app, Key::Char('c')));
3989        assert_eq!(app.mode, Mode::List, "{f}");
3990        assert!(f.contains("no frame to widen"), "{f}");
3991
3992        // The map answers for the window and not for the filter — `/api/v1/map`
3993        // takes no `where` — so the only way to empty it is an empty store. Not
3994        // an error: a directory with logs and no spans is an ordinary one.
3995        let empty = std::env::temp_dir().join("mira-tui-nomap");
3996        std::fs::create_dir_all(&empty).unwrap();
3997        let mut app = App::new(Source::Local(empty));
3998        settle(&mut app);
3999        let f = strip(&press(&mut app, Key::Char('m')));
4000        assert_eq!(app.mode, Mode::List, "{f}");
4001        assert!(f.contains("there is no map"), "{f}");
4002
4003        // And the metrics tab over the same empty store. An empty name list is
4004        // not an error either, but it has to say which of the two it is: the
4005        // pane otherwise sits blank next to a chart area, which reads as a
4006        // metric that failed to load rather than a window with no metrics in it.
4007        let f = strip(&press(&mut app, Key::Char('3')));
4008        assert_eq!(app.tab, Tab::Metrics);
4009        assert!(f.contains("no metrics in this window"), "{f}");
4010        assert!(app.names.is_empty() && app.series.is_empty(), "{f}");
4011    }
4012
4013    /// A mode outlives the data behind it: the query that would have filled the
4014    /// pane failed, or the pane was open when the store went away. The frame
4015    /// draws whatever mode is set, so each pane checks its own `Option` — and
4016    /// the failure this prevents is the previous pane's rows drawn under the
4017    /// new pane's header, which is a screenful of numbers about something else.
4018    #[test]
4019    fn a_pane_whose_data_never_arrived_draws_nothing_rather_than_something_else() {
4020        let mut app = App::new(Source::Local("/nonexistent".into()));
4021        app.job = None;
4022        app.stats = "0/0 blocks".into();
4023        for (mode, header) in [
4024            (Mode::Frame, " frame "),
4025            (Mode::Map, " map "),
4026            (Mode::Diag, " node "),
4027            (Mode::Trace, " trace "),
4028        ] {
4029            app.mode = mode;
4030            let f = app.frame(W, H);
4031            assert_eq!(f.len(), H, "{mode:?} still owes the terminal every row");
4032            let text = strip(&f.join("\n"));
4033            assert!(!text.contains(header), "{mode:?} drew a header: {text}");
4034        }
4035        // The detail pane says so instead of drawing nothing, because it is the
4036        // one pane opened *on* a selection — blank there reads as a record with
4037        // no fields rather than as no record.
4038        app.mode = Mode::Detail;
4039        let text = strip(&app.frame(W, H).join("\n"));
4040        assert!(text.contains("nothing selected"), "{text}");
4041    }
4042
4043    /// The one number on the node pane that is a reason to wake someone up, and
4044    /// the colour is the whole of the signal: a node with 7% of its disk left
4045    /// drawn in the same grey as one with 90% is a page nobody makes.
4046    ///
4047    /// Both boundaries are in the table, because `<` and `<=` are one keystroke
4048    /// apart and only a value sitting exactly on 0.1 or 0.2 tells them apart.
4049    /// Zero is there because a full disk is the case the colour exists for, and
4050    /// it is the one an operator sees at the worst possible moment.
4051    #[test]
4052    fn the_disk_line_is_coloured_by_how_close_the_node_is_to_full() {
4053        let mut app = App::new(Source::Local("/nonexistent".into()));
4054        for (doc, style, text) in [
4055            (r#"{"free_fraction":0.0}"#, term::RED, "disk 0% free"),
4056            (r#"{"free_fraction":0.07}"#, term::RED, "disk 7% free"),
4057            (r#"{"free_fraction":0.1}"#, term::YELLOW, "disk 10% free"),
4058            (r#"{"free_fraction":0.15}"#, term::YELLOW, "disk 15% free"),
4059            (r#"{"free_fraction":0.2}"#, term::DIM, "disk 20% free"),
4060            (r#"{"free_fraction":0.9}"#, term::DIM, "disk 90% free"),
4061            // Absent is neither full nor empty: `statfs` would not answer, and
4062            // a percentage invented for that case is the one number here that
4063            // must never be made up.
4064            (r#"{"free_fraction":null}"#, term::DIM, "disk unreadable"),
4065        ] {
4066            app.diag = Some(crate::api::parse(doc).unwrap());
4067            let head = app.diag_pane(W).remove(0);
4068            assert!(strip(&head).contains(text), "{head:?}");
4069            // The style in force over the figure, not the bytes immediately
4070            // before it: runs that share a style are coalesced into one escape,
4071            // so a grey figure after grey text carries no escape of its own.
4072            let run = head
4073                .split(term::RESET)
4074                .find(|r| r.contains(text))
4075                .unwrap_or_default();
4076            assert!(run.starts_with(style), "{head:?}");
4077        }
4078    }
4079
4080    /// A volume with no write barrier is a durability fact, and the header is
4081    /// where a node's durability facts live. It is absent at zero on purpose:
4082    /// a line that reads "0" on every healthy node is a line the eye learns to
4083    /// skip, which is exactly the wrong training for the one node it matters on.
4084    #[test]
4085    fn degraded_syncs_appear_only_once_there_are_some() {
4086        let mut app = App::new(Source::Local("/nonexistent".into()));
4087        for (doc, want) in [
4088            (r#"{"degraded_syncs":0}"#, None),
4089            (r#"{}"#, None),
4090            (r#"{"degraded_syncs":1}"#, Some("degraded syncs 1")),
4091            (r#"{"degraded_syncs":41000}"#, Some("degraded syncs 41.0k")),
4092        ] {
4093            app.diag = Some(crate::api::parse(doc).unwrap());
4094            let head = app.diag_pane(W).remove(0);
4095            match want {
4096                Some(text) => {
4097                    assert!(strip(&head).contains(text), "{head:?}");
4098                    assert!(
4099                        head.contains(&format!("{}  ·  {text}", term::YELLOW)),
4100                        "{head:?}"
4101                    );
4102                }
4103                None => assert!(!strip(&head).contains("degraded"), "{head:?}"),
4104            }
4105        }
4106    }
4107
4108    /// A series the engine answered with no points in the window. An empty
4109    /// sparkline and a flat one at zero are the same picture and opposite
4110    /// facts — nothing reported, versus reported as nothing.
4111    #[test]
4112    fn a_series_with_no_points_says_so_rather_than_drawing_a_flat_line() {
4113        let mut app = App::new(Source::Local("/nonexistent".into()));
4114        app.series = array(
4115            &crate::api::parse(
4116                r#"{"series":[{"name":"m","attributes":{"pod":"a"},"points":[],
4117                              "exemplars":[]}]}"#,
4118            )
4119            .unwrap()["series"],
4120        );
4121        let lines = app.series_lines(60);
4122        let chart = strip(&lines[1]);
4123        assert!(chart.contains("no points"), "{chart:?}");
4124        assert!(!chart.contains('▁') && !chart.contains('█'), "{chart:?}");
4125        // The three-line shape holds anyway, or the caller's `ssel * 3` window
4126        // lands on the wrong series.
4127        assert_eq!(lines.len(), 3);
4128        assert!(strip(&lines[0]).contains("pod=a"), "{:?}", lines[0]);
4129    }
4130
4131    /// A failed span is red in both places it is drawn — and is not, under the
4132    /// cursor, because red on reverse-video is the one combination that
4133    /// disappears on a light terminal. The badge stays either way: colour is
4134    /// how the eye finds the row, the word is how the reader confirms it.
4135    #[test]
4136    fn a_failed_span_is_red_in_the_list_and_the_waterfall_unless_it_is_selected() {
4137        let rows = array(
4138            &crate::api::parse(
4139                r#"{"rows":[
4140                 {"span_id":"01","name":"GET /ok","start_time_unix_nano":"10",
4141                  "duration_nano":"1000000","status_code":1},
4142                 {"span_id":"02","parent_span_id":"01","name":"POST /pay",
4143                  "start_time_unix_nano":"20","duration_nano":"2000000","status_code":2}]}"#,
4144            )
4145            .unwrap()["rows"],
4146        );
4147        let (ok, bad) = (&rows[0], &rows[1]);
4148
4149        let line = span_row(bad, W, false, 2_000_000);
4150        assert!(line.contains(&format!("{}POST", term::RED)), "{line:?}");
4151        assert!(strip(&line).contains("ERROR"), "{line:?}");
4152        let sel = span_row(bad, W, true, 2_000_000);
4153        assert!(!sel.contains(term::RED), "{sel:?}");
4154        assert!(strip(&sel).contains("ERROR"), "{sel:?}");
4155        let fine = span_row(ok, W, false, 2_000_000);
4156        assert!(!fine.contains(term::RED), "{fine:?}");
4157        assert!(!strip(&fine).contains("ERROR"), "{fine:?}");
4158
4159        // The waterfall, whose selection is its own and whose bar takes the
4160        // same colour as the name — a green bar on a failed span would be the
4161        // pane contradicting itself.
4162        let t = Trace::new("ab".into(), &rows);
4163        let ends = [16, 24, W - 11, W];
4164        let bar = span_bar(bad, 1, false, ends, &t);
4165        assert!(bar.contains(&format!("{}  POST", term::RED)), "{bar:?}");
4166        assert!(strip(&bar).contains("POST /pay"), "{bar:?}");
4167        assert!(bar.contains(&format!("{}█", term::RED)), "{bar:?}");
4168        let bar = span_bar(ok, 0, false, ends, &t);
4169        assert!(!bar.contains(term::RED), "{bar:?}");
4170        assert!(bar.contains(&format!("{}█", term::GREEN)), "{bar:?}");
4171    }
4172
4173    /// An event's own attributes are the payload of the event — an exception's
4174    /// type and stacktrace live nowhere else — and the detail pane is the only
4175    /// screen that ever shows them. Rendering the event and dropping them
4176    /// throws away the reason the reader opened the record.
4177    #[test]
4178    fn an_events_own_attributes_are_indented_under_it_in_the_detail_pane() {
4179        let row = crate::api::parse(
4180            r#"{"body":"boom","attributes":{"service.name":"checkout"},
4181                "events":[{"name":"exception","time_unix_nano":"10",
4182                           "attributes":{"exception.type":"IOError"}}],
4183                "links":[{"trace_id":"abab","attributes":{"rel":"follows"}}]}"#,
4184        )
4185        .unwrap();
4186        let text = rata::detail(&row, 80)
4187            .iter()
4188            .map(|l| strip(l))
4189            .collect::<Vec<_>>()
4190            .join("\n");
4191
4192        assert!(text.contains("exception.type"), "{text}");
4193        assert!(text.contains("IOError"), "{text}");
4194        // Indented one level further than the event's own fields, so a reader
4195        // can tell whose attribute it is.
4196        assert!(text.contains("    rel "), "{text}");
4197        assert!(text.contains("follows"), "{text}");
4198        // And rendered as lines rather than as one inline map next to the key,
4199        // which is what the top-level `attributes` skip is there to prevent.
4200        assert!(!text.contains("{exception.type"), "{text}");
4201    }
4202
4203    /// Two lists, one set of arrow keys, and the keys that do nothing at all.
4204    ///
4205    /// Every `_ => {}` in the key handler exists so a stray keystroke is not a
4206    /// quit, a reload or a mode change — the arms around each one all have side
4207    /// effects. The cursor arms are the other half: the metrics tab keeps two
4208    /// indices, and moving the wrong one scrolls a pane nobody is looking at.
4209    #[test]
4210    fn an_unbound_key_changes_nothing_and_each_pane_moves_its_own_cursor() {
4211        let dir = store("keys");
4212        let mut app = App::new(Source::Local(dir));
4213        settle(&mut app);
4214
4215        // The tab ring closes in both directions; these are the two arms the
4216        // walk in `the_frame_and_map_panes_open_from_a_keystroke` never reaches.
4217        press(&mut app, Key::Char('h'));
4218        assert_eq!(app.tab, Tab::Metrics, "h off the left of the ring wraps");
4219        press(&mut app, Key::Char('l'));
4220        assert_eq!(app.tab, Tab::Logs, "and l off the right wraps back");
4221
4222        // A key with no binding leaves the screen byte for byte as it was.
4223        let before = strip(&app.frame(W, H).join("\n"));
4224        for k in [Key::BackTab, Key::Char('z'), Key::Char('#')] {
4225            let f = strip(&press(&mut app, k));
4226            assert_eq!(f, before, "{k:?} changed the screen");
4227        }
4228
4229        // Enter in a pane with nothing to open is one of them.
4230        press(&mut app, Key::Char('?'));
4231        assert_eq!(app.mode, Mode::Help);
4232        press(&mut app, Key::Enter);
4233        assert_eq!(app.mode, Mode::Help, "enter in help opens nothing");
4234        press(&mut app, Key::Esc);
4235
4236        // In the filter box, so is every key that is neither text nor an edit:
4237        // an arrow key typed into the filter would be a query for `\x1b[A`.
4238        press(&mut app, Key::Char('/'));
4239        typed(&mut app, "abc");
4240        press(&mut app, Key::Up);
4241        press(&mut app, Key::PageDown);
4242        assert_eq!(app.filter, "abc");
4243        assert_eq!(app.mode, Mode::Filter);
4244        press(&mut app, Key::Esc);
4245        assert!(app.filter.is_empty());
4246
4247        // `q` backs out one pane at a time and only quits from the list. ^C
4248        // quits from wherever the reader is, which is the whole difference
4249        // between them, and the pane it is pressed in must not swallow it.
4250        press(&mut app, Key::Enter);
4251        assert_eq!(app.mode, Mode::Detail);
4252        assert!(!app.key(Key::Ctrl('c'), H), "^C quits from a detail pane");
4253        press(&mut app, Key::Esc);
4254
4255        // The metrics tab: `tab` decides which of its two lists the arrows
4256        // drive, and each keeps its own index while the other one holds still.
4257        press(&mut app, Key::Char('3'));
4258        assert!(!app.on_series);
4259        press(&mut app, Key::Char('j'));
4260        assert_eq!(app.nsel, 1, "the names list moves first");
4261        // Two series under one name, because this corpus has one apiece and a
4262        // cursor with nowhere to go proves nothing about which one moved.
4263        app.series = array(
4264            &crate::api::parse(
4265                r#"{"series":[{"name":"m","attributes":{"pod":"a"},"points":[["1","1"]]},
4266                              {"name":"m","attributes":{"pod":"b"},"points":[["1","2"]]}]}"#,
4267            )
4268            .unwrap()["series"],
4269        );
4270        press(&mut app, Key::Tab);
4271        assert!(app.on_series);
4272        press(&mut app, Key::Char('j'));
4273        assert_eq!((app.nsel, app.ssel), (1, 1), "the series cursor moved");
4274        press(&mut app, Key::Char('G'));
4275        assert_eq!(app.ssel, 1, "and clamps at the last series");
4276
4277        // A record whose trace id is not in this store. Only the store can say
4278        // so, and it says it on the status bar rather than opening an empty
4279        // waterfall that reads as a trace with no spans in it.
4280        press(&mut app, Key::Char('1'));
4281        app.rows = array(
4282            &crate::api::parse(
4283                r#"{"rows":[{"trace_id":"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd","body":"x"}]}"#,
4284            )
4285            .unwrap()["rows"],
4286        );
4287        let f = strip(&press(&mut app, Key::Char('t')));
4288        assert!(app.err, "{f}");
4289        assert!(f.contains("no spans found for trace cdcd"), "{f}");
4290        assert_eq!(app.mode, Mode::List, "and the waterfall does not open");
4291    }
4292
4293    /// The alert pane's own cursor, and the two answers that are not a list of
4294    /// rules: a node with no rules file, and Enter pressed on nothing.
4295    ///
4296    /// An empty pane must not read as "all clear" — a node evaluating no rules
4297    /// pages nobody, and that is the one thing an alerting screen cannot let a
4298    /// reader assume.
4299    #[test]
4300    fn the_alert_pane_moves_its_own_cursor_and_says_when_there_are_no_rules() {
4301        const ROWS: &str = r#"{"rows":[],"stats":{"blocks_total":0,"blocks_scanned":0,
4302                               "rows_scanned":0,"rows_matched":0}}"#;
4303        const TWO: &str = r#"{"alerts":[
4304            {"name":"first","state":"firing","severity":"critical","metric":"count","op":">",
4305             "threshold":1.0,"value":9.0,"matched":9,"total":null,"over_nano":"60000000000",
4306             "for_nano":"0","since":"1","firing_since":"1","evaluated_at":"2","signal":"traces",
4307             "filter":"field:status_code=2","link":"","error":null},
4308            {"name":"second","state":"ok","severity":"warning","metric":"count","op":">=",
4309             "threshold":1.0,"value":0.0,"matched":0,"total":null,"over_nano":"300000000000",
4310             "for_nano":"0","since":null,"firing_since":null,"evaluated_at":"2",
4311             "signal":"logs","filter":"attr:pod=a","link":"","error":null}],
4312            "every_nano":"5000000000"}"#;
4313
4314        // One reply per connection, in the order this session asks for them:
4315        // the opening list query, `a`, the requery Enter fires, `a` again.
4316        let addr = source::serve(
4317            [ROWS, TWO, ROWS, r#"{"alerts":[]}"#]
4318                .map(source::ok)
4319                .to_vec(),
4320        );
4321        let mut app = App::new(Source::Remote(addr));
4322        settle(&mut app);
4323
4324        press(&mut app, Key::Char('a'));
4325        assert_eq!(app.mode, Mode::Alerts);
4326        let f = press(&mut app, Key::Char('j'));
4327        assert_eq!(app.psel, 1, "the pane owns the cursor, not the record list");
4328        // Read back off the screen: the highlight is on the second rule, which
4329        // is what Enter is about to act on.
4330        let row = f
4331            .lines()
4332            .find(|l| strip(l).contains("second"))
4333            .unwrap_or_default();
4334        assert!(row.contains(term::REV), "{row:?}");
4335
4336        // Enter follows the *selected* rule: its signal picks the tab and its
4337        // filter is already spelled in the filter bar's own grammar.
4338        press(&mut app, Key::Enter);
4339        assert_eq!(app.tab, Tab::Logs, "the second rule is a logs rule");
4340        assert_eq!(app.filter, "attr:pod=a");
4341        assert_eq!(app.mode, Mode::List);
4342
4343        // A node with no rules file at all.
4344        let f = strip(&press(&mut app, Key::Char('a')));
4345        assert_eq!(app.mode, Mode::Alerts, "{f}");
4346        assert!(f.contains("0 rules") && f.contains("0 firing"), "{f}");
4347        assert!(f.contains("evaluates no rules"), "{f}");
4348        // ...where Enter has nothing under the cursor to follow, and must leave
4349        // the tab and the filter exactly as the reader left them.
4350        press(&mut app, Key::Enter);
4351        assert_eq!(app.mode, Mode::Alerts, "enter on no rule opens nothing");
4352        assert_eq!((app.tab, app.filter.as_str()), (Tab::Logs, "attr:pod=a"));
4353    }
4354
4355    /// The name of the test below, as `--exact` wants it.
4356    const RUN_SELF: &str = "tui::tests::the_event_loop_follows_a_growing_store_and_quits_on_q";
4357
4358    /// [`run`] itself: `mira mira --data-dir`, on a real terminal, following a
4359    /// block directory that grows under it.
4360    ///
4361    /// Everything else in this file tests the app without the loop, because a
4362    /// `Term` needs a pty. This is the loop: draw *before* the deferred query so
4363    /// the "running" frame is on screen while the query blocks, a poll that
4364    /// times out into a re-query rather than a reload, and `q` returning from
4365    /// `run` rather than exiting the process — which is what leaves the `Term`
4366    /// to be dropped and the user's terminal to be handed back.
4367    ///
4368    /// Follow mode is proved by data rather than by the indicator: the parent
4369    /// publishes a block stamped two seconds into the future, so `to: now`
4370    /// excludes it from the opening query *and* from the reload `f` fires, and
4371    /// only a tick that ran later can put it on screen. A loop that never timed
4372    /// out would sit on the older frame until `q`.
4373    #[test]
4374    fn the_event_loop_follows_a_growing_store_and_quits_on_q() {
4375        if let Some(dir) = std::env::var_os("MIRA_TUI_PTY_DIR") {
4376            // The child. It ends by returning from `run`, not by panicking:
4377            // the exit path is part of what is under test, and the harness
4378            // line it then prints to the pty is what the parent reads it off.
4379            return run(Source::Local(dir.into())).unwrap();
4380        }
4381        let dir = store("pty");
4382        let ahead = crate::api::now_nanos() as u64 + 2_000_000_000;
4383        let mut b = mira_core::logs::LogsBuilder::new();
4384        b.append_request(&crate::e2e::logs_export("mira-tail-tick", ahead, 1))
4385            .unwrap();
4386        let node = mira_core::block::node_id("b");
4387        mira_core::block::publish(&dir, "logs", node, 0, 0, &b.finish().unwrap()).unwrap();
4388
4389        let crate::term::tests::Pty {
4390            screen,
4391            err,
4392            stalled,
4393            trailing,
4394        } = crate::term::tests::drive(
4395            RUN_SELF,
4396            &[("MIRA_TUI_PTY_DIR", dir.as_os_str())],
4397            &[
4398                // The opening screen — drawn, queried, drawn again — then `f`.
4399                ("checkout handled request 4", b"f"),
4400                // The reload it fires, which still cannot see the future block.
4401                ("● follow", b""),
4402                // ...and the tick three seconds later, which can. `q` from the
4403                // list is the quit.
4404                ("mira-tail-tick handled request 0", b"q"),
4405            ],
4406            "\x1b[?25h\x1b[?1049l",
4407        );
4408        assert!(
4409            stalled.is_none(),
4410            "child stalled at {stalled:?}: {err}\nscreen:\n{screen:?}"
4411        );
4412        // `q` returned from `run`; it did not `exit`, panic or die of a signal.
4413        // The harness line is printed after the alternate screen was already
4414        // handed back, which is why it is on the pty at all.
4415        assert!(err.is_empty(), "{err}");
4416        assert!(screen.contains("1 passed"), "{screen:?}");
4417        assert!(trailing, "terminal not restored: {screen:?}");
4418        // The screen the reader would have been looking at: the tick's row is
4419        // above the rows that were already there, not instead of them.
4420        let tick = screen.find("mira-tail-tick").unwrap();
4421        let old = screen.rfind("checkout handled request 4").unwrap();
4422        assert!(tick < old, "the tick replaced the window: {screen:?}");
4423    }
4424}