Skip to main content

nmbrs_tui/
app.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! TUI application: event loop, terminal setup, frame rendering.
5//!
6//! The TUI runs on a dedicated std::thread (not tokio) to avoid
7//! blocking the async runtime. It reads from two sources:
8//! - cadence-window `MetricSet` snapshots from the metrics store
9//! - immutable `Arc<RunState>` snapshots published by the
10//!   [`crate::run_state_actor`] (phase progress from executor)
11//!
12//! All mutations the TUI needs to make to display state (latency
13//! frames, sparkline samples) are sent as
14//! [`crate::run_state_actor::RunStateCmd`] messages — never via
15//! a write lock. See SRD-02 §"Display and Diagnostic Decoupling".
16
17use std::io;
18use std::sync::{Arc, mpsc};
19use std::time::{Duration, Instant};
20
21use crossterm::ExecutableCommand;
22use crossterm::event::{
23    self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind, KeyModifiers,
24    MouseButton, MouseEvent, MouseEventKind,
25};
26use crossterm::terminal::{self, EnterAlternateScreen, LeaveAlternateScreen};
27use ratatui::prelude::*;
28use ratatui::widgets::*;
29
30use crate::run_state_actor::{RunStateCmd, RunStateHandle};
31use crate::state::{PhaseStatus, RunState};
32use crate::widgets::{self, colors};
33use nmbrs_metrics::metrics_query::MetricsQuery;
34use nmbrs_metrics::snapshot::MetricSet;
35
36/// Which scrollable pane currently owns mouse-wheel input.
37#[derive(Clone, Copy, PartialEq, Eq)]
38enum FocusedPane {
39    Tree,
40}
41
42/// Level of detail for the scenario tree rendering. Cycled by the
43/// left/right arrow keys.
44#[derive(Clone, Copy, PartialEq, Eq, Debug)]
45enum TreeLod {
46    /// Nothing — tree pane renders empty. Left-arrow below
47    /// ActivePhase reaches this state, letting the operator
48    /// reclaim the screen area when they don't want a tree at all.
49    Hidden,
50    /// Chromeless single-phase dashboard. The scenario-tree
51    /// frame/title disappears; the panel renders the currently
52    /// running phase's detail block directly, with the panel's
53    /// own title naming the phase. No tree rows, no scope
54    /// headers, no indent markers, no per-phase expansion chrome.
55    /// When multiple phases are running their detail blocks stack
56    /// vertically in the same panel (same as Focus, minus the
57    /// tree decorations).
58    ///
59    /// Positioned between `Hidden` and `Minimal` in the cycle —
60    /// the most compact view that still shows live data.
61    ActivePhase,
62    /// Phase lines only — no scope/closure headers, no detail blocks.
63    /// Useful for a compact skim of what ran in what order.
64    Minimal,
65    /// Dynamic "dashboard" mode: only running phases are visible,
66    /// each expanded to its full detail block. Scope headers are
67    /// suppressed. With exactly one phase running the screen reads
68    /// as a single-phase status dashboard; with two or more, the
69    /// layout auto-widens to cover every running phase — still no
70    /// scope headers or pending/completed noise. When zero phases
71    /// are running it shows a "waiting for phase…" placeholder
72    /// (or a final-state banner if the scenario is done).
73    ///
74    /// See SRD 62 §"LOD controls govern phase expansion" and
75    /// §"Design notes → Scenario done? is a component-tree query".
76    Focus,
77    /// Phases + scope headers, with at most one entry optionally
78    /// expanded via Enter. This is the default view.
79    Default,
80    /// Everything expanded: phases, scope headers, and the full detail
81    /// block under every phase that has summary data.
82    Maximal,
83}
84
85impl TreeLod {
86    /// Next step toward Maximal, clamped at the top.
87    fn next(self) -> Self {
88        match self {
89            Self::Hidden => Self::ActivePhase,
90            Self::ActivePhase => Self::Minimal,
91            Self::Minimal => Self::Focus,
92            Self::Focus => Self::Default,
93            Self::Default => Self::Maximal,
94            Self::Maximal => Self::Maximal,
95        }
96    }
97
98    /// Previous step toward Hidden, clamped at the bottom.
99    fn prev(self) -> Self {
100        match self {
101            Self::Maximal => Self::Default,
102            Self::Default => Self::Focus,
103            Self::Focus => Self::Minimal,
104            Self::Minimal => Self::ActivePhase,
105            Self::ActivePhase => Self::Hidden,
106            Self::Hidden => Self::Hidden,
107        }
108    }
109
110    fn label(self) -> &'static str {
111        match self {
112            Self::Hidden => "off",
113            Self::ActivePhase => "phase",
114            Self::Minimal => "min",
115            Self::Focus => "focus",
116            Self::Default => "def",
117            Self::Maximal => "max",
118        }
119    }
120}
121
122/// TUI application.
123pub struct App {
124    pub should_quit: bool,
125    /// If true, the entire nmbrs process should exit after the TUI
126    /// cleans up its terminal state. Set by triple-tapping `q`.
127    pub should_exit_process: bool,
128    /// True when the user pressed Ctrl+C. The event loop stops on
129    /// the next iteration; `run()` re-raises SIGINT after the
130    /// terminal has been restored so the process sees a real
131    /// interrupt signal with standard exit semantics.
132    ctrl_c_received: bool,
133    /// Set when the user pressed Ctrl-T inside the TUI to hand
134    /// the terminal back to line-mode (`tui=terminal`) display.
135    /// The sink supervisor reads this on the App thread's join
136    /// to decide whether to bring `LogOnlySink` back up
137    /// (`true` — toggle) or treat the run as fully complete
138    /// (`false` — natural exit / Ctrl-C / triple-q). Public so
139    /// the supervisor can read after `App::run()` returns.
140    pub yielded_to_terminal: bool,
141    /// External-quit hook the sink supervisor sets when it wants
142    /// to pull the TUI down without a user keystroke (e.g. the
143    /// run completed and the supervisor is shutting down all
144    /// sinks). The event loop polls this each iteration alongside
145    /// the existing `should_quit` flag.
146    pub external_quit: Arc<std::sync::atomic::AtomicBool>,
147    pub tick_rate: Duration,
148    /// Whether the log panel is visible (toggled with `l` key).
149    pub show_log: bool,
150    /// Minimum severity rendered in the log panel. Defaults to
151    /// `Info` so high-cadence Debug instrumentation
152    /// (per-fiber-exit, cadence-ingest tracing) doesn't drown
153    /// the signal. Cycled by the `D` key:
154    /// `Info → Debug → Warn → Error → Info`.
155    pub log_level_filter: crate::state::LogSeverity,
156    frame_rx: mpsc::Receiver<MetricSet>,
157    run_state: RunStateHandle,
158    /// Scrollable pane currently owning mouse-wheel input. Set by
159    /// left-clicking inside a pane's rect.
160    focused: Option<FocusedPane>,
161    /// Scenario-tree scroll offset in lines from the top. `None` means
162    /// follow the tail automatically (default). Set to a concrete offset
163    /// the first time the user scrolls or clicks the tree.
164    tree_scroll: Option<usize>,
165    /// Current animated scroll position (fractional so tweening reads
166    /// smooth). The actual render uses `.floor()` of this. In sync with
167    /// `tree_scroll` when no animation is in flight.
168    tree_display: f32,
169    /// Active scroll animation: `(from, to, started_at, duration)`.
170    /// Each mouse-wheel event starts or retargets this so the viewport
171    /// glides into place instead of teleporting.
172    tree_anim: Option<(f32, f32, Instant, Duration)>,
173    /// Index into `state.phases` of the selected phase entry. Only
174    /// meaningful when `focused == Some(Tree)`. When focus is active
175    /// this is always `Some` — a selection is always present.
176    tree_selected: Option<usize>,
177    /// If true, selection auto-follows the most recently active phase
178    /// (Running > latest Completed). Flipped to false as soon as the
179    /// user moves the selection manually.
180    tree_selection_auto: bool,
181    /// Index into `state.phases` of the currently expanded entry (if
182    /// any). At most one entry is expanded at a time, keeping the
183    /// tree compact. Enter toggles, Escape collapses.
184    tree_expanded: Option<usize>,
185    /// Index into `state.phases` of the currently *drilled* phase —
186    /// i.e. the user pressed Right on an already-expanded phase to
187    /// open its stanza op list. At most one phase is drilled at a
188    /// time, and a drilled phase is always also expanded. Left
189    /// arrow exits drill mode and parks the cursor back on the
190    /// parent phase. None when no phase is drilled.
191    tree_drilled: Option<usize>,
192    /// Cursor position within the drilled phase's op list. Index
193    /// into `phase.op_names`. Only meaningful when `tree_drilled`
194    /// is `Some`.
195    drill_op_idx: usize,
196    /// Last-known tree panel rect — cached each frame so keyboard
197    /// handlers can compute viewport geometry (visible rows, tail
198    /// offset) without having to reach back into the crossterm
199    /// backend for the terminal size.
200    last_tree_rect: Rect,
201    /// Current level of detail for the scenario tree. Left/right
202    /// arrow keys cycle through [`TreeLod`].
203    tree_lod: TreeLod,
204    /// Whether the one-shot startup reset has already run. Flipped on
205    /// the first frame that has at least one selectable phase entry so
206    /// the user doesn't have to press Space to get the initial focus.
207    startup_reset_done: bool,
208    /// Whether the help overlay is currently visible. Toggled by `?`
209    /// and dismissed by `Esc`.
210    show_help: bool,
211    /// Running count of consecutive recent `q` presses, tracked so
212    /// three rapid taps can hard-exit the whole process rather than
213    /// just dismissing the TUI. Reset whenever the gap since the last
214    /// tap exceeds [`Self::Q_TAP_WINDOW_MS`].
215    q_tap_count: u32,
216    /// Timestamp of the previous `q` press, used to decide whether the
217    /// current press continues an existing tap streak or starts a
218    /// fresh one.
219    q_tap_last: Option<Instant>,
220    /// When true, the TUI freezes its metrics / anim state so the
221    /// user can read values without them shifting. The screen keeps
222    /// redrawing (so a PAUSED banner renders and keys stay live), but
223    /// `drain_frames`, scroll-anim ticking, and auto-selection refresh
224    /// are skipped. Toggled with `p`.
225    paused: bool,
226    /// Frozen snapshot of [`RunState`], populated when the user
227    /// toggles pause on. While `Some`, every `draw`-time read of
228    /// `run_state` routes to this `Arc<RunState>` instead of
229    /// loading from the live snapshot, so observer-driven
230    /// mutations (ops/s, latency percentiles, relevancy, new log
231    /// entries) don't leak into the rendered frame. Cleared on
232    /// unpause. Pause now costs zero — the snapshot is already
233    /// an `Arc`, so freezing it is just retaining one reference.
234    frozen_state: Option<Arc<RunState>>,
235    /// Shift+P sets this; the event loop captures the just-drawn
236    /// buffer after the next `terminal.draw()` and writes it to a
237    /// dump file. Read-after-draw is the only way to capture the
238    /// front buffer — `current_buffer_mut` returns the back buffer
239    /// (reset to empty after each draw).
240    dump_requested: bool,
241    /// Shared `MetricsQuery` access layer (SRD-42). Tree-detail
242    /// renderers reach through here for per-cadence percentile
243    /// snapshots when a phase wants a retrospective window.
244    metrics_query: Arc<MetricsQuery>,
245    /// Control-edit prompt state. `None` when no prompt is
246    /// visible; `Some(...)` when the user has pressed `e` to
247    /// enter edit mode. The prompt accepts `name=value` entries
248    /// and submits them via [`Self::submit_control_edit`].
249    /// See SRD 23 §"TUI surface (sketch)".
250    edit_prompt: Option<ControlEditPrompt>,
251    /// Synchronous-render coordination surface shared with the
252    /// run-state actor. The event loop checks
253    /// [`crate::run_state_actor::FrameSync::force_redraw`] before
254    /// computing each iteration's poll timeout; when set, the
255    /// next draw fires immediately, bypassing `tick_rate`. After
256    /// every successful draw the loop calls
257    /// [`crate::run_state_actor::FrameSync::signal_post_draw`] to
258    /// drain queued ack channels — that's the round-trip that
259    /// lets the executor block on
260    /// [`crate::run_state_actor::RunStateHandle::flush_frame`]
261    /// until the just-completed phase is on screen. SRD 02
262    /// §"Display and Diagnostic Decoupling" carries the broader
263    /// ArcSwap / actor model this builds on.
264    frame_sync: crate::run_state_actor::FrameSync,
265    /// SRD-63 Push 5b: stateful readout binder for the TUI
266    /// surface. Carries focus index per slot, per-(slot,
267    /// body) LOD overrides, and the held-key
268    /// content-mode-toggle flag. Tab / Shift-Tab cycle focus;
269    /// `+` / `-` cycle the focused body's LOD; `\` toggles
270    /// the explanation overlay (ContentMode::Explanation
271    /// while held).
272    ///
273    /// Bindings are seeded from the workload's `readouts:`
274    /// block + the per-event built-in defaults; the binder
275    /// state is preserved across event fires so cycling
276    /// focus or LOD on one phase doesn't reset when the
277    /// next refresh arrives.
278    ///
279    /// Wrapped in `RefCell` so render paths that take
280    /// `&self` can fire the binder; the App is single-
281    /// threaded so a runtime borrow check is safe.
282    readout_binder: std::cell::RefCell<nmbrs_runtime::readouts::TuiReadoutBinder>,
283    /// Monotonic frame counter — passed to the readout
284    /// engine as the `refresh_tick` so animated readouts
285    /// (the spinner glyph in `phase_status`) advance
286    /// frame-by-frame.
287    frame_tick: std::cell::Cell<u64>,
288}
289
290/// Inline control-edit prompt state. Populated when the user
291/// presses `e`; dismissed on `Esc` or `Enter`. While present the
292/// event loop routes character / backspace / enter / escape
293/// keys to the prompt rather than the scenario-tree navigation.
294#[derive(Clone, Debug)]
295pub struct ControlEditPrompt {
296    /// Accumulated text the user is typing. The intended form
297    /// is `name=value` (e.g. `rate=500` or `concurrency=64`).
298    pub buffer: String,
299    /// Latest submit outcome. Shown inline under the prompt.
300    /// `Ok("applied")` on success; `Err(msg)` on parse /
301    /// validation / final-scope rejection.
302    pub last_result: Option<Result<String, String>>,
303}
304
305impl ControlEditPrompt {
306    fn new() -> Self {
307        Self {
308            buffer: String::new(),
309            last_result: None,
310        }
311    }
312}
313
314/// Dispatch a control write from the TUI event loop.
315///
316/// Walks up the runner-installed session root for a control
317/// matching `name`, then spawns a tokio task that calls
318/// `set_f64` on the erased control with
319/// [`nmbrs_metrics::controls::ControlOrigin::Tui`]. Returns
320/// `Ok(())` if the write was dispatched (not necessarily
321/// committed — the applier runs in the background). Returns
322/// `Err(msg)` if the session root is not installed or no
323/// control by that name exists via walk-up.
324///
325/// This is the TUI-side counterpart to the Polydat `control_set`
326/// node (SRD 23 §"Mutation entry points → TUI").
327pub fn write_control_f64_from_tui(name: String, value: f64) -> Result<(), String> {
328    let root = nmbrs_runtime::polydat_nodes::runtime_context::session_root_handle()
329        .ok_or_else(|| "no session root installed — TUI cannot resolve controls".to_string())?;
330    let erased = {
331        let Ok(guard) = root.read() else {
332            return Err("session root is poisoned".into());
333        };
334        guard
335            .find_control_erased_up(&name)
336            .ok_or_else(|| format!("no control named '{name}' via walk-up"))?
337    };
338    if !erased.accepts_f64_writes() {
339        return Err(format!(
340            "control '{name}' was not declared f64-writable \
341             (add ControlBuilder::from_f64 to its declaration)",
342        ));
343    }
344    // The write is async; spawn onto the current tokio runtime.
345    // Errors from the applier path surface in the session log,
346    // not inline — the TUI is intentionally non-blocking here
347    // so a slow applier doesn't freeze the UI.
348    tokio::spawn(async move {
349        let origin = nmbrs_metrics::controls::ControlOrigin::Tui;
350        if let Err(e) = erased.set_f64(value, origin).await {
351            eprintln!("control write from TUI: {name}={value} failed: {e}");
352        }
353    });
354    Ok(())
355}
356
357/// Build the per-phase latency rows for the tree's expanded detail
358/// block. Mirrors the old top-level Latency panel (the `Percentiles`
359/// variant): one `range` row showing the axis endpoints and a
360/// distribution bar with cross-bar peak markers, plus one row per
361/// percentile showing its value and a bar anchored at 0..max_val.
362/// Rows that would render with zero value are suppressed.
363///
364/// `peak_5s` / `peak_10s` are the rolling max latencies from the
365/// phase's [`nmbrs_metrics::summaries::peak_tracker::PeakTracker`]s.
366/// `None` means "no data yet" (e.g. completed phase, or phase
367/// that hasn't received any frames) — no marker renders in that
368/// case.
369// The six percentile/min/max nanos plus the two rolling peaks are
370// each an independent metric the renderer plots; grouping them into
371// a struct would only move the same eight values across the call.
372#[allow(clippy::too_many_arguments)]
373fn latency_detail_lines(
374    min_ns: u64,
375    p50_ns: u64,
376    p90_ns: u64,
377    p99_ns: u64,
378    p999_ns: u64,
379    max_ns: u64,
380    peak_5s: Option<u64>,
381    peak_10s: Option<u64>,
382) -> Vec<Line<'static>> {
383    let max_val = max_ns
384        .max(p999_ns)
385        .max(p99_ns)
386        .max(p90_ns)
387        .max(p50_ns)
388        .max(1);
389    // Fixed bar width so the detail block lines up predictably
390    // regardless of terminal size. 60 cells is wide enough to show
391    // percentile spread without eating the whole 120-col budget.
392    let bar_w: usize = 60;
393    let pos = |nanos: u64| -> usize {
394        if max_val == 0 {
395            return 0;
396        }
397        ((nanos as f64 / max_val as f64) * bar_w as f64).round() as usize
398    };
399
400    let mut out: Vec<Line<'static>> = Vec::new();
401
402    // Range row: colored distribution bar with segment transitions
403    // at each percentile boundary.
404    let mut cells: Vec<(char, ratatui::style::Color)> = vec![('╌', colors::BORDER); bar_w];
405    let points = [
406        (0u64, colors::LAT_P50),
407        (p50_ns, colors::LAT_P50),
408        (p90_ns, colors::LAT_P90),
409        (p99_ns, colors::LAT_P99),
410        (p999_ns, colors::LAT_MAX),
411        (max_ns, colors::LAT_MAX),
412    ];
413    for w in points.windows(2) {
414        let start = pos(w[0].0).min(bar_w);
415        let end = pos(w[1].0).min(bar_w);
416        for c in cells.iter_mut().take(end).skip(start) {
417            c.0 = '━';
418            c.1 = w[1].1;
419        }
420    }
421    // Peak markers from the phase's PeakTracker summaries —
422    //   ╪  5s peak
423    //   ╫  10s peak
424    //   ╬  both peaks share the same cell (collapsed)
425    let peak_pos = |nanos: u64| -> Option<usize> {
426        if nanos == 0 || bar_w == 0 {
427            return None;
428        }
429        Some(pos(nanos).min(bar_w.saturating_sub(1)))
430    };
431    let p5 = peak_5s.and_then(peak_pos);
432    let p10 = peak_10s.and_then(peak_pos);
433    match (p5, p10) {
434        (Some(a), Some(b)) if a == b => {
435            cells[a] = ('╬', colors::EMPHASIS);
436        }
437        _ => {
438            if let Some(p) = p10 {
439                cells[p] = ('╫', colors::LAT_MAX);
440            }
441            if let Some(p) = p5 {
442                cells[p] = ('╪', colors::EMPHASIS);
443            }
444        }
445    }
446    // Group adjacent cells of the same color into one span so the
447    // render is O(bands) not O(cells).
448    let range_label = if min_ns > 0 {
449        format!(
450            "{}..{}",
451            widgets::format_nanos(min_ns),
452            widgets::format_nanos(max_val)
453        )
454    } else {
455        format!("0..{}", widgets::format_nanos(max_val))
456    };
457    let mut spans: Vec<Span<'static>> = vec![
458        Span::styled(" range", Style::default().fg(colors::DIM)),
459        Span::styled(
460            format!(" {:>14}  ", range_label),
461            Style::default().fg(colors::DIM),
462        ),
463    ];
464    let mut i = 0;
465    while i < cells.len() {
466        let col = cells[i].1;
467        let mut j = i;
468        let mut run = String::new();
469        while j < cells.len() && cells[j].1 == col {
470            run.push(cells[j].0);
471            j += 1;
472        }
473        spans.push(Span::styled(run, Style::default().fg(col)));
474        i = j;
475    }
476    out.push(Line::from(spans));
477
478    // One row per percentile; skip if the value is zero (no data).
479    let rows: [(&str, u64, ratatui::style::Color); 6] = [
480        ("min ", min_ns, colors::LAT_P50),
481        ("p50 ", p50_ns, colors::LAT_P50),
482        ("p90 ", p90_ns, colors::LAT_P90),
483        ("p99 ", p99_ns, colors::LAT_P99),
484        ("p999", p999_ns, colors::LAT_MAX),
485        ("max ", max_ns, colors::LAT_MAX),
486    ];
487    for (label, nanos, color) in rows.iter() {
488        if *nanos == 0 {
489            continue;
490        }
491        let frac = *nanos as f64 / max_val as f64;
492        let bar = widgets::bar_str(frac.min(1.0), bar_w);
493        out.push(Line::from(vec![
494            Span::styled(format!(" {label}"), Style::default().fg(colors::DIM)),
495            Span::styled(
496                format!(" {:>14}  ", widgets::format_nanos(*nanos)),
497                Style::default().fg(*color).bold(),
498            ),
499            Span::styled(bar, Style::default().fg(*color)),
500        ]));
501    }
502    out
503}
504
505/// Plural-form label for cursor counts. `ops_finished` ticks once
506/// per cycle = once per cursor position, so the natural unit is the
507/// cursor name pluralized. Falls back to `cycles` when the phase
508/// declares no cursor.
509fn cursor_count_label(cursor_name: &str) -> String {
510    let name = cursor_name.trim();
511    if name.is_empty() || name == "?" {
512        return "cycles".to_string();
513    }
514    if name.ends_with('s') {
515        name.to_string()
516    } else {
517        format!("{name}s")
518    }
519}
520
521/// Per-second form of [`cursor_count_label`] (e.g. `row` → `rows/s`).
522fn cursor_rate_label(cursor_name: &str) -> String {
523    format!("{}/s", cursor_count_label(cursor_name))
524}
525
526/// Wall-clock-driven spinner glyph for active phases.
527///
528/// Picks a frame from `throbber_widgets_tui::symbols::throbber::BRAILLE_SIX`
529/// every 250 ms — matching the TUI's 4 Hz redraw cadence so a
530/// new render always shows the next frame, not the same one
531/// twice in a row. Indexed by `now_millis / 250` with no per-
532/// frame state, so concurrent Running phases tick in lockstep
533/// rather than chaotically. `BRAILLE_SIX` gives a dense rotation
534/// that still degrades gracefully (renders as dots) on partial-
535/// glyph fonts.
536fn spinner_frame() -> &'static str {
537    use throbber_widgets_tui::symbols::throbber::BRAILLE_SIX;
538    let elapsed = std::time::SystemTime::now()
539        .duration_since(std::time::UNIX_EPOCH)
540        .map(|d| d.as_millis())
541        .unwrap_or(0);
542    let idx = ((elapsed / 250) as usize) % BRAILLE_SIX.symbols.len();
543    BRAILLE_SIX.symbols[idx]
544}
545
546/// Health-tint color for a phase entry in the scenario tree.
547///
548/// Running phases always render yellow — error counts aren't
549/// meaningful mid-flight. Completed phases grade green → orange →
550/// red as the observed error rate rises past the clean/warning/bad
551/// thresholds. The hue gradient was picked for colorblind safety;
552/// paired with the phase glyph (`▶` / `✓` / `✗`) the meaning is
553/// redundant-encoded.
554fn phase_health_color(phase: &crate::state::PhaseEntry) -> ratatui::style::Color {
555    match &phase.status {
556        PhaseStatus::Running => colors::PHASE_RUNNING_TINT,
557        PhaseStatus::Pending => colors::PHASE_PENDING,
558        PhaseStatus::Failed(_) => colors::PHASE_FAILED,
559        PhaseStatus::Completed => {
560            // Error *rate*, not raw count: a 1M-op phase with 100
561            // errors (0.01%) is effectively clean, but a 500-op phase
562            // with 100 errors (20%) is degraded. `errors / ops_finished`
563            // falls to zero for 0-error runs without special-casing.
564            let Some(sm) = phase.summary.as_ref() else {
565                return colors::PHASE_DONE;
566            };
567            if sm.errors == 0 {
568                return colors::PHASE_DONE;
569            }
570            let denom = sm.ops_finished.max(1);
571            let rate = sm.errors as f64 / denom as f64;
572            // Thresholds: < 1% warn, ≥ 5% bad. Between 1%-5% = warn.
573            if rate >= 0.05 {
574                colors::PHASE_DONE_BAD
575            } else {
576                colors::PHASE_DONE_WARN
577            }
578        }
579    }
580}
581
582impl App {
583    /// Create with a metrics channel and a [`RunStateHandle`]
584    /// (snapshot reader + command sender — see SRD-02 §"Display
585    /// and Diagnostic Decoupling").
586    pub fn new(
587        frame_rx: mpsc::Receiver<MetricSet>,
588        run_state: RunStateHandle,
589        metrics_query: Arc<MetricsQuery>,
590    ) -> Self {
591        let frame_sync = run_state.frame_sync();
592        Self {
593            should_quit: false,
594            should_exit_process: false,
595            ctrl_c_received: false,
596            yielded_to_terminal: false,
597            external_quit: Arc::new(std::sync::atomic::AtomicBool::new(false)),
598            tick_rate: Duration::from_millis(250),
599            show_log: false,
600            log_level_filter: crate::state::LogSeverity::Info,
601            frame_rx,
602            run_state,
603            focused: None,
604            tree_scroll: None,
605            tree_display: 0.0,
606            tree_anim: None,
607            tree_selected: None,
608            tree_selection_auto: true,
609            tree_expanded: None,
610            tree_drilled: None,
611            drill_op_idx: 0,
612            last_tree_rect: Rect::new(0, 0, 0, 0),
613            tree_lod: TreeLod::Default,
614            startup_reset_done: false,
615            show_help: false,
616            q_tap_count: 0,
617            q_tap_last: None,
618            paused: false,
619            frozen_state: None,
620            dump_requested: false,
621            metrics_query,
622            edit_prompt: None,
623            frame_sync,
624            readout_binder: std::cell::RefCell::new(
625                nmbrs_runtime::readouts::TuiReadoutBinder::new(),
626            ),
627            frame_tick: std::cell::Cell::new(0),
628        }
629    }
630
631    /// Borrow the current control-edit prompt (if visible).
632    /// Widgets use this to render the inline prompt bar.
633    pub fn edit_prompt(&self) -> Option<&ControlEditPrompt> {
634        self.edit_prompt.as_ref()
635    }
636
637    /// Whether the TUI is currently in edit mode. Event loops
638    /// in edit mode route character input to the prompt buffer
639    /// instead of navigation.
640    pub fn is_editing(&self) -> bool {
641        self.edit_prompt.is_some()
642    }
643
644    /// Open the inline control-edit prompt. The prompt accepts
645    /// `name=value` text; submit via [`Self::submit_control_edit`].
646    pub fn open_control_edit_prompt(&mut self) {
647        self.edit_prompt = Some(ControlEditPrompt::new());
648    }
649
650    /// Close the prompt without submitting.
651    pub fn close_control_edit_prompt(&mut self) {
652        self.edit_prompt = None;
653    }
654
655    /// Append a character to the edit buffer. No-op when not
656    /// in edit mode.
657    pub fn edit_push_char(&mut self, c: char) {
658        if let Some(p) = self.edit_prompt.as_mut() {
659            p.buffer.push(c);
660        }
661    }
662
663    /// Remove the last character from the edit buffer.
664    pub fn edit_pop_char(&mut self) {
665        if let Some(p) = self.edit_prompt.as_mut() {
666            p.buffer.pop();
667        }
668    }
669
670    /// Submit the current edit buffer. Parses `name=value`,
671    /// dispatches a non-blocking `set_f64` against the named
672    /// control through the session-root globals installed by
673    /// the runner. Records the outcome on the prompt for
674    /// inline display.
675    ///
676    /// Returns the parsed `(name, value)` on successful
677    /// dispatch so tests can assert.
678    pub fn submit_control_edit(&mut self) -> Option<(String, f64)> {
679        let p = self.edit_prompt.as_mut()?;
680        let buf = p.buffer.trim().to_string();
681        // Parse name=value.
682        let (name, value_str) = match buf.split_once('=') {
683            Some((n, v)) => (n.trim().to_string(), v.trim().to_string()),
684            None => {
685                p.last_result = Some(Err("expected 'name=value' (e.g. rate=500)".into()));
686                return None;
687            }
688        };
689        if name.is_empty() {
690            p.last_result = Some(Err("missing control name".into()));
691            return None;
692        }
693        let value: f64 = match value_str.parse() {
694            Ok(v) => v,
695            Err(e) => {
696                p.last_result = Some(Err(format!("parse error: {e}")));
697                return None;
698            }
699        };
700        match write_control_f64_from_tui(name.clone(), value) {
701            Ok(()) => {
702                p.last_result = Some(Ok(format!("submitted {name}={value}")));
703                // Clear the buffer so subsequent edits start
704                // fresh; the prompt stays open so the user can
705                // keep adjusting.
706                p.buffer.clear();
707                Some((name, value))
708            }
709            Err(e) => {
710                p.last_result = Some(Err(e));
711                None
712            }
713        }
714    }
715
716    /// Set the tree LOD directly. Production code changes LOD
717    /// through left/right arrow keybinds via [`Self::adjust_tree_lod`];
718    /// tests use this helper to render a specific view without
719    /// routing a synthetic key event.
720    ///
721    /// Accepted labels match [`TreeLod::label`]: `"off"`,
722    /// `"phase"`, `"min"`, `"focus"`, `"def"`, `"max"`. Unknown
723    /// labels leave the current LOD unchanged.
724    pub fn set_tree_lod_label(&mut self, label: &str) {
725        let next = match label {
726            "off" | "hidden" => Some(TreeLod::Hidden),
727            "phase" | "active" => Some(TreeLod::ActivePhase),
728            "min" | "minimal" => Some(TreeLod::Minimal),
729            "focus" => Some(TreeLod::Focus),
730            "def" | "default" => Some(TreeLod::Default),
731            "max" | "maximal" => Some(TreeLod::Maximal),
732            _ => None,
733        };
734        if let Some(lod) = next {
735            self.tree_lod = lod;
736        }
737    }
738
739    /// Smoothstep easing — S-curve between 0 and 1. Used for scroll
740    /// animations so the viewport eases in and out instead of lurching.
741    #[inline]
742    fn smoothstep(t: f32) -> f32 {
743        let t = t.clamp(0.0, 1.0);
744        t * t * (3.0 - 2.0 * t)
745    }
746
747    /// Per-scroll-wheel step in lines. Small so a single tick feels like
748    /// a proportionate motion rather than a jump.
749    const SCROLL_STEP: i32 = 3;
750
751    /// Duration of a single scroll tween. Short enough to feel snappy,
752    /// long enough that a rendered transition is visible.
753    const SCROLL_ANIM_MS: u64 = 140;
754
755    /// Max gap (ms) between `q` presses to count as part of the same
756    /// tap streak. Three taps inside this window hard-exits the
757    /// process; isolated taps still just dismiss the TUI.
758    const Q_TAP_WINDOW_MS: u128 = 600;
759
760    /// Number of `q` presses inside [`Q_TAP_WINDOW_MS`] that triggers a
761    /// full process exit.
762    const Q_TAP_EXIT_COUNT: u32 = 3;
763
764    /// Run the TUI event loop. Blocks until quit or run completes.
765    ///
766    /// Terminal cleanup is guaranteed across every exit path —
767    /// normal return, propagated `?` error, and panic — via a
768    /// [`TerminalGuard`] (Drop-based) and a panic hook installed
769    /// for the duration of the run. Either mechanism restores raw
770    /// mode, leaves the alternate screen, and disables mouse
771    /// capture before control returns to the shell.
772    ///
773    /// The event loop also intercepts `Ctrl+C` as a distinct
774    /// signal from `q`. Ctrl+C tears the TUI down and then raises
775    /// SIGINT to the current process so the signal propagates
776    /// through any runtime handlers the rest of the process has
777    /// installed (tokio `ctrl_c`, shell-level exit codes, etc.)
778    /// with standard interrupt semantics.
779    pub fn run(&mut self) -> io::Result<()> {
780        install_tui_panic_hook();
781        let _guard = TerminalGuard::enter()?;
782        let backend = CrosstermBackend::new(io::stderr());
783        let mut terminal = Terminal::new(backend)?;
784
785        let result = self.event_loop(&mut terminal);
786
787        // Drop `_guard` here explicitly so the terminal is
788        // restored BEFORE any post-run action (process exit,
789        // SIGINT re-raise) fires.
790        drop(_guard);
791
792        // Triple-tap q requests a full process exit. Do it here,
793        // after the terminal has been restored, so the shell
794        // doesn't inherit raw mode or an alternate-screen buffer.
795        if self.should_exit_process {
796            std::process::exit(130);
797        }
798
799        // Ctrl+C: re-raise SIGINT now that the terminal is clean.
800        // Raise, not exit — so higher-level signal handlers (e.g.
801        // tokio::signal::ctrl_c futures the runner may have
802        // registered) see a real signal, not a clean early return.
803        if self.ctrl_c_received {
804            // SAFETY: `raise` is async-signal-safe and standard
805            // C library. SIGINT's default disposition terminates
806            // the process with exit code 130 if no handler is
807            // installed, matching what a Ctrl+C outside the TUI
808            // would have done.
809            unsafe {
810                libc::raise(libc::SIGINT);
811            }
812        }
813
814        result
815    }
816
817    fn event_loop(
818        &mut self,
819        terminal: &mut Terminal<CrosstermBackend<io::Stderr>>,
820    ) -> io::Result<()> {
821        let mut last_drain = Instant::now();
822
823        loop {
824            // Advance any in-flight scroll tween BEFORE drawing so the
825            // intermediate eased offset is what gets rendered.
826            let size = terminal.size()?;
827            let tree_rect = self.tree_rect(Rect::new(0, 0, size.width, size.height));
828            // Detect a viewport resize so auto-track mode can re-pin
829            // the active phase to the top. Without this, the per-frame
830            // `min(tail)` clamp below silently pulls a Space-set
831            // top-pinned target down whenever the new visible height
832            // exceeds (total - target_line) — exactly what the user
833            // sees when they grow the terminal after pressing Space.
834            let tree_rect_resized = tree_rect.height != self.last_tree_rect.height
835                || tree_rect.width != self.last_tree_rect.width;
836            self.last_tree_rect = tree_rect;
837            let visible = tree_rect.height.saturating_sub(2) as usize;
838            // Tail = max scroll position. Must be based on the
839            // actual rendered-line count (phase headers + every
840            // detail row of every expanded phase), NOT the raw
841            // phase-entry count — expanded phases contribute many
842            // lines each. Using the raw count here would cap the
843            // scroll target too low, leaving the selection marker
844            // stuck below the visible area.
845            let total = self.total_rendered_lines();
846            let tail = total.saturating_sub(visible);
847            // Re-sync the viewport with the selection each frame.
848            // Line counts can drift between when a key handler
849            // called `scroll_selection_into_view` and when this
850            // frame renders (latency bars / relevancy rows /
851            // throughput sparkline can all appear or disappear as
852            // state updates). Re-evaluating here is idempotent
853            // when the selection is already on-screen and cheap
854            // when it isn't.
855            if !self.paused {
856                // After a resize, re-pin the active phase to the top
857                // when auto-tracking is on. The Space-bar reset arms
858                // this mode; the user's intent is "keep the active
859                // phase anchored", which the standard
860                // `scroll_selection_into_view` won't preserve through
861                // a viewport-height change because it short-circuits
862                // when the selection is still nominally on-screen.
863                if tree_rect_resized && self.tree_selection_auto {
864                    self.scroll_selection_to_top();
865                }
866                self.scroll_selection_into_view();
867            }
868            // Explicit `Some(N)` targets are honored as-is so a Space-
869            // pinned selection stays at the top row of the viewport
870            // even when N > tail — the renderer pads the bottom with
871            // empty rows rather than letting the selection drift to
872            // keep the panel "filled". `None` still means auto-tail
873            // (scroll to bottom), so the auto-tracking + scrollback
874            // resume paths keep their existing semantics.
875            let target = self.tree_scroll.map(|s| s as f32).unwrap_or(tail as f32);
876            // Pause freezes the state the user is looking at — skip
877            // the anim tick and auto-tracking refresh so nothing
878            // shifts. The frame still redraws so the PAUSED banner
879            // can render and key input stays live.
880            if !self.paused {
881                self.advance_scroll_anim(target);
882                // One-shot: when the first selectable phase appears AND
883                // the layout has settled, run the same state change as
884                // pressing Space so the user never sees the idle
885                // "waiting for phase" state with no tree focus.
886                if !self.startup_reset_done && self.default_tree_selection().is_some() {
887                    let layout_ready = {
888                        let s = self.run_state.load();
889                        s.active_phases.values().any(|a| a.cursor_extent > 0)
890                            || s.phases.iter().any(|p| p.summary.is_some())
891                    };
892                    if layout_ready {
893                        self.reset_tree_to_active();
894                        self.startup_reset_done = true;
895                    }
896                }
897                self.refresh_auto_selection();
898            }
899
900            let completed = terminal.draw(|frame| self.draw(frame))?;
901            // Drain any FrameAck waiters now that a frame has
902            // been produced. `signal_post_draw` also clears the
903            // `force_redraw` flag so the loop returns to its
904            // normal `tick_rate` cadence on the next iteration.
905            // SRD 02 §"Display and Diagnostic Decoupling": the
906            // round trip is one-shot per request, no busy spin.
907            self.frame_sync.signal_post_draw();
908            // If the user pressed Shift+P, dump the just-rendered
909            // buffer now — CompletedFrame holds a reference to the
910            // freshly-flushed front buffer (the one the user can see).
911            if self.dump_requested {
912                let area = completed.area;
913                // Borrow the buffer via a dedicated scope so the
914                // completed-frame lifetime doesn't conflict with the
915                // rest of the loop.
916                let mut text = String::new();
917                let ts = nmbrs_runtime::session::now_log_timestamp();
918                let w = area.width as usize;
919                let h = area.height as usize;
920                text.push_str(&format!("# nmbrs-tui screen dump — {ts}\n"));
921                text.push_str(&format!("# dimensions: {w}x{h}\n"));
922                for y in area.y..(area.y + area.height) {
923                    for x in area.x..(area.x + area.width) {
924                        text.push_str(completed.buffer[(x, y)].symbol());
925                    }
926                    text.push('\n');
927                }
928                self.write_dump(text, &ts);
929                self.dump_requested = false;
930            }
931            let last_draw = Instant::now();
932
933            // While a scroll animation is in flight, target ~60Hz so the
934            // tween reads as motion; otherwise sit at the baseline 4Hz
935            // metrics tick. `last_draw` tracks the independent draw
936            // cadence so the drain_frames schedule below stays stable.
937            //
938            // A pending FrameAck (from `RunStateHandle::flush_frame`)
939            // collapses the timeout to zero so the next iteration
940            // draws immediately and signals the waiting caller —
941            // bypassing `tick_rate` for the one frame the executor
942            // is blocked on. The flag self-clears in
943            // `signal_post_draw` after the draw completes.
944            let force = self
945                .frame_sync
946                .force_redraw
947                .load(std::sync::atomic::Ordering::Acquire);
948            let effective_rate = if force {
949                Duration::ZERO
950            } else if self.tree_anim.is_some() {
951                Duration::from_millis(16)
952            } else {
953                self.tick_rate
954            };
955            let timeout = effective_rate
956                .checked_sub(last_draw.elapsed())
957                .unwrap_or(Duration::ZERO);
958
959            if event::poll(timeout)? {
960                match event::read()? {
961                    Event::Key(key) if key.kind == KeyEventKind::Press => {
962                        // Ctrl+C: raw-mode terminals don't get a
963                        // real SIGINT, so the app has to catch the
964                        // key event itself. Flag the state, break
965                        // out of the event loop, and let `run()`
966                        // raise SIGINT after terminal teardown so
967                        // the signal propagates with standard
968                        // interrupt semantics.
969                        if key.modifiers.contains(KeyModifiers::CONTROL)
970                            && matches!(key.code, KeyCode::Char('c') | KeyCode::Char('C'))
971                        {
972                            self.ctrl_c_received = true;
973                            self.should_quit = true;
974                            break;
975                        }
976                        // Ctrl-T: yield the screen back to terminal
977                        // mode. The sink supervisor (in `nmbrs/run`)
978                        // is watching `yielded_to_terminal`; it
979                        // brings up `LogOnlySink` again on the next
980                        // `event_loop` exit.
981                        if key.modifiers.contains(KeyModifiers::CONTROL)
982                            && matches!(key.code, KeyCode::Char('t') | KeyCode::Char('T'))
983                        {
984                            self.yielded_to_terminal = true;
985                            self.should_quit = true;
986                            break;
987                        }
988                        // Ctrl+L follows the long-standing terminal
989                        // convention of "refresh screen", handled as a
990                        // dedicated branch so it doesn't collapse into
991                        // the plain `l` log toggle.
992                        if key.modifiers.contains(KeyModifiers::CONTROL)
993                            && matches!(key.code, KeyCode::Char('l') | KeyCode::Char('L'))
994                        {
995                            let _ = terminal.clear();
996                            continue;
997                        }
998                        // Edit mode captures input first so the
999                        // user can type `name=value` into the
1000                        // prompt without navigation keybinds
1001                        // eating the characters. Esc / Enter
1002                        // close or submit respectively.
1003                        if self.is_editing() {
1004                            match key.code {
1005                                KeyCode::Esc => self.close_control_edit_prompt(),
1006                                KeyCode::Enter => {
1007                                    let _ = self.submit_control_edit();
1008                                }
1009                                KeyCode::Backspace => self.edit_pop_char(),
1010                                KeyCode::Char(c) => self.edit_push_char(c),
1011                                _ => {}
1012                            }
1013                            continue;
1014                        }
1015                        match key.code {
1016                            KeyCode::Char('q') => self.handle_q_tap(),
1017                            KeyCode::Esc => self.handle_escape(),
1018                            KeyCode::Char('l') => self.show_log = !self.show_log,
1019                            KeyCode::Char('D') => self.cycle_log_level_filter(),
1020                            KeyCode::Char('p') => self.toggle_pause(),
1021                            KeyCode::Char('P') => self.dump_requested = true,
1022                            KeyCode::Char('?') => self.show_help = !self.show_help,
1023                            KeyCode::Char('e') => self.open_control_edit_prompt(),
1024                            KeyCode::Up => self.move_tree_selection(-1),
1025                            KeyCode::Down => self.move_tree_selection(1),
1026                            KeyCode::Left => self.tree_left_arrow(),
1027                            KeyCode::Right => self.tree_right_arrow(),
1028                            KeyCode::Enter => self.toggle_tree_expansion(),
1029                            KeyCode::Char(' ') => self.reset_tree_to_active(),
1030                            // SRD-63 Push 5b: readout-binder
1031                            // navigation. Tab cycles focus
1032                            // forward through the readouts in
1033                            // the most-recently-fired event slot;
1034                            // Shift-Tab cycles backward; +/-
1035                            // cycle the focused body's LOD.
1036                            KeyCode::Tab => self.cycle_readout_focus_next(),
1037                            KeyCode::BackTab => self.cycle_readout_focus_prev(),
1038                            KeyCode::Char('+') => self.cycle_readout_lod_up(),
1039                            KeyCode::Char('-') => self.cycle_readout_lod_down(),
1040                            // SRD-63 Push 7b: explanation overlay
1041                            // toggle. crossterm's standard polling
1042                            // doesn't reliably surface key-release,
1043                            // so the held-key behavior from the
1044                            // SRD is approximated with a press-
1045                            // toggle: tap `\` to flip into
1046                            // explanation mode, tap again to
1047                            // flip back. Visible in the binder
1048                            // via `overlay_held()`; readouts
1049                            // render with `ContentMode::Explanation`
1050                            // while the flag is set.
1051                            KeyCode::Char('\\') => self.toggle_readout_overlay(),
1052                            _ => {}
1053                        }
1054                    }
1055                    Event::Mouse(me) => {
1056                        let size = terminal.size()?;
1057                        self.handle_mouse(me, Rect::new(0, 0, size.width, size.height));
1058                    }
1059                    _ => {}
1060                }
1061            }
1062
1063            // Apply any pending q-tap dismiss once the triple window
1064            // has elapsed without a third tap.
1065            self.poll_q_tap_timeout();
1066
1067            // Check if run finished
1068            {
1069                let state = self.run_state.load();
1070                if state.finished {
1071                    // Show final state for a moment then exit
1072                    std::thread::sleep(Duration::from_millis(500));
1073                    self.should_quit = true;
1074                }
1075            }
1076
1077            // External-quit hook: the sink supervisor sets this
1078            // when it wants to pull the TUI down without a user
1079            // keystroke (e.g. shutdown during the toggle hand-off
1080            // back to terminal mode). Treated as a normal exit;
1081            // the supervisor reads `yielded_to_terminal`
1082            // separately to decide whether to bring up
1083            // LogOnlySink afterwards.
1084            if self
1085                .external_quit
1086                .load(std::sync::atomic::Ordering::Acquire)
1087            {
1088                self.should_quit = true;
1089            }
1090
1091            if self.should_quit {
1092                break;
1093            }
1094
1095            if !self.paused && last_drain.elapsed() >= self.tick_rate {
1096                self.drain_frames();
1097                last_drain = Instant::now();
1098            }
1099        }
1100
1101        Ok(())
1102    }
1103
1104    /// Compute the scenario-tree panel rect for a given terminal size.
1105    /// Kept in sync with the layout in `draw()` — Header / Scenario /
1106    /// Footer, with an optional log split under the Scenario section.
1107    fn tree_rect(&self, area: Rect) -> Rect {
1108        let sections = Layout::default()
1109            .direction(Direction::Vertical)
1110            .constraints([
1111                Constraint::Length(3), // header
1112                Constraint::Min(3),    // scenario (+ log panel)
1113                Constraint::Length(1), // footer
1114            ])
1115            .split(area);
1116        if self.show_log {
1117            let bottom = Layout::default()
1118                .direction(Direction::Vertical)
1119                .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
1120                .split(sections[1]);
1121            bottom[0]
1122        } else {
1123            sections[1]
1124        }
1125    }
1126
1127    /// Is (col, row) inside `rect`?
1128    fn rect_contains(rect: Rect, col: u16, row: u16) -> bool {
1129        col >= rect.x && col < rect.x + rect.width && row >= rect.y && row < rect.y + rect.height
1130    }
1131
1132    /// Dispatch a mouse event to the focused scrollable pane.
1133    fn handle_mouse(&mut self, me: MouseEvent, area: Rect) {
1134        let tree = self.tree_rect(area);
1135        match me.kind {
1136            MouseEventKind::Down(MouseButton::Left) => {
1137                if Self::rect_contains(tree, me.column, me.row) {
1138                    // Take focus. On first grab, seed the scroll offset
1139                    // at the current auto-tail position so the view
1140                    // doesn't jump — the user expects the tree to stay
1141                    // put at the moment they clicked.
1142                    let tail = self.tree_tail_offset(tree);
1143                    if self.tree_scroll.is_none() {
1144                        self.tree_scroll = Some(tail);
1145                        self.tree_display = tail as f32;
1146                    }
1147                    let was_unfocused = self.focused != Some(FocusedPane::Tree);
1148                    self.focused = Some(FocusedPane::Tree);
1149
1150                    // Figure out which tree entry sits under the click
1151                    // and select it. The row inside the tree panel maps
1152                    // to rendered-line index plus the current scroll
1153                    // offset; the rendered-line → entry mapping accounts
1154                    // for expanded detail blocks.
1155                    let inner_y = me.row.saturating_sub(tree.y + 1); // minus border
1156                    let start = self.tree_display.round().max(0.0) as usize;
1157                    let clicked_line = start + inner_y as usize;
1158                    if let Some(idx) = self.line_to_entry_index(clicked_line) {
1159                        self.tree_selected = Some(idx);
1160                        self.tree_selection_auto = false;
1161                    } else if was_unfocused {
1162                        // Empty area click — just take focus, seed default.
1163                        self.tree_selected = self.default_tree_selection();
1164                    }
1165                } else {
1166                    self.focused = None;
1167                    self.tree_selected = None;
1168                    self.tree_selection_auto = true;
1169                    self.tree_expanded = None;
1170                }
1171            }
1172            // Direction follows the "content tracks the wheel" convention:
1173            // rolling the wheel up moves the viewport down (reveals later
1174            // content) and vice versa. Matches typical IDE / pager
1175            // trackpad behavior on macOS and browsers with natural scroll.
1176            MouseEventKind::ScrollUp => {
1177                if self.focused == Some(FocusedPane::Tree) {
1178                    let tail = self.tree_tail_offset(tree);
1179                    let current = self.tree_scroll.unwrap_or(tail);
1180                    let next = (current as i32 + Self::SCROLL_STEP).clamp(0, tail as i32) as usize;
1181                    // At the bottom — snap back to auto-follow so new
1182                    // entries keep scrolling into view.
1183                    let target_opt = if next >= tail { None } else { Some(next) };
1184                    self.retarget_tree_scroll(target_opt, tail);
1185                }
1186            }
1187            MouseEventKind::ScrollDown => {
1188                if self.focused == Some(FocusedPane::Tree) {
1189                    let tail = self.tree_tail_offset(tree);
1190                    let current = self.tree_scroll.unwrap_or(tail);
1191                    let next = (current as i32 - Self::SCROLL_STEP).max(0) as usize;
1192                    self.retarget_tree_scroll(Some(next), tail);
1193                }
1194            }
1195            _ => {}
1196        }
1197    }
1198
1199    /// Update the scroll target and start (or retarget) the tween from
1200    /// the current displayed position. A fresh mouse-wheel event mid-
1201    /// animation keeps the visual position put and just re-aims — it
1202    /// doesn't snap back to the previous starting point.
1203    fn retarget_tree_scroll(&mut self, target: Option<usize>, tail: usize) {
1204        self.tree_scroll = target;
1205        let target_f = target.unwrap_or(tail) as f32;
1206        self.tree_anim = Some((
1207            self.tree_display,
1208            target_f,
1209            Instant::now(),
1210            Duration::from_millis(Self::SCROLL_ANIM_MS),
1211        ));
1212    }
1213
1214    /// Persist a rendered screen dump to disk. Writes two files in
1215    /// the current session directory (via `logs/latest`):
1216    ///   - `tui_{ts}.dump` — a timestamped archive (one per dump)
1217    ///   - `tui.dump`       — a stable-named copy of the latest dump
1218    ///
1219    /// `Session::new` no longer pre-creates the convenience
1220    /// `logs/tui.dump` symlink — that would dangle for any run
1221    /// that never produces a dump. We create it here, at the
1222    /// moment the stable-named copy actually lands.
1223    fn write_dump(&mut self, text: String, ts: &str) {
1224        let logs_dir = nmbrs_runtime::session::default_sessions_root();
1225        let session_dir = nmbrs_runtime::session::latest_session_dir();
1226        // `sessions/latest` exists as a symlink once Session::new has
1227        // run. If it's not there yet (very early failure), fall back
1228        // to the sessions root so the timestamped archive still lands
1229        // somewhere visible.
1230        let target_dir = if session_dir.exists() {
1231            &session_dir
1232        } else {
1233            &logs_dir
1234        };
1235        let fname_ts = ts.replace([':', ' ', '.'], "_").replace('-', "");
1236        let archive_name = format!("tui_{fname_ts}.dump");
1237        let archive_path = target_dir.join(&archive_name);
1238        let stable_path = target_dir.join("tui.dump");
1239        let archive_result = std::fs::write(&archive_path, &text);
1240        let stable_result = std::fs::write(&stable_path, &text);
1241        match (archive_result, stable_result) {
1242            (Ok(()), Ok(())) => {
1243                nmbrs_runtime::observer::log(
1244                    nmbrs_runtime::observer::LogLevel::Info,
1245                    &format!(
1246                        "tui dump written to {} (also {})",
1247                        archive_path.display(),
1248                        stable_path.display()
1249                    ),
1250                );
1251                // Convenience symlink lives at `logs/tui.dump`.
1252                nmbrs_runtime::session::Session::link_artifact("tui.dump");
1253            }
1254            (Err(e), _) | (_, Err(e)) => {
1255                nmbrs_runtime::observer::log(
1256                    nmbrs_runtime::observer::LogLevel::Warn,
1257                    &format!("failed to write tui dump {}: {e}", archive_path.display()),
1258                );
1259            }
1260        }
1261    }
1262
1263    /// Handle a `q` keypress.
1264    ///
1265    /// Single/double tap → dismisses the TUI (same as Esc at top level),
1266    /// but the dismiss is DEFERRED until the triple-tap window expires.
1267    /// Otherwise a fast third tap would arrive after the TUI was already
1268    /// tearing down, never triggering the process-exit path the user
1269    /// Toggle the paused flag. On pause, clones the live `RunState`
1270    /// into `self.frozen_state` so subsequent `draw` calls render
1271    /// from the snapshot instead of the live store — otherwise
1272    /// observer updates (ops/s, latency, phase progress) continue
1273    /// to leak into the rendered frame even though `drain_frames`
1274    /// has stopped. On unpause, the snapshot is dropped and the
1275    /// next draw picks up the live state again.
1276    fn toggle_pause(&mut self) {
1277        if self.paused {
1278            self.paused = false;
1279            self.frozen_state = None;
1280        } else {
1281            // Snapshots are already immutable Arcs — pause just
1282            // retains the current one. Future actor publishes
1283            // build new Arcs without touching this one, so the
1284            // frozen view stays stable until unpaused.
1285            self.frozen_state = Some(self.run_state.load());
1286            self.paused = true;
1287        }
1288    }
1289
1290    /// actually wanted. The loop calls `poll_q_tap_timeout` every frame
1291    /// to apply the deferred action once the streak is confirmed.
1292    ///
1293    /// Triple tap inside [`Q_TAP_WINDOW_MS`] fires immediately: hard-
1294    /// exit the whole nmbrs process after the terminal is restored.
1295    fn handle_q_tap(&mut self) {
1296        let now = Instant::now();
1297        let in_streak = self
1298            .q_tap_last
1299            .map(|prev| now.duration_since(prev).as_millis() <= Self::Q_TAP_WINDOW_MS)
1300            .unwrap_or(false);
1301        self.q_tap_count = if in_streak { self.q_tap_count + 1 } else { 1 };
1302        self.q_tap_last = Some(now);
1303        if self.q_tap_count >= Self::Q_TAP_EXIT_COUNT {
1304            // Triple confirmed — act now.
1305            self.should_exit_process = true;
1306            self.should_quit = true;
1307        }
1308        // Otherwise wait. poll_q_tap_timeout applies the dismiss once
1309        // we're confident no further tap is coming.
1310    }
1311
1312    /// Called each event-loop iteration. If a q-tap streak is open and
1313    /// the window has expired with 1 or 2 presses, apply the deferred
1314    /// TUI dismiss. Three-press streaks already acted inline.
1315    fn poll_q_tap_timeout(&mut self) {
1316        let Some(last) = self.q_tap_last else {
1317            return;
1318        };
1319        if self.q_tap_count == 0 {
1320            return;
1321        }
1322        if last.elapsed().as_millis() < Self::Q_TAP_WINDOW_MS {
1323            return;
1324        }
1325        if self.q_tap_count < Self::Q_TAP_EXIT_COUNT {
1326            self.should_quit = true;
1327        }
1328        self.q_tap_count = 0;
1329        self.q_tap_last = None;
1330    }
1331
1332    /// Escape is a cascading dismiss:
1333    /// 1) If the help overlay is up, close it.
1334    /// 2) If an entry is expanded, collapse it.
1335    /// 3) Otherwise if the tree has focus, release focus + selection.
1336    /// 4) Otherwise quit the TUI (matches `q`).
1337    fn handle_escape(&mut self) {
1338        if self.show_help {
1339            self.show_help = false;
1340        } else if self.tree_expanded.is_some() {
1341            self.tree_expanded = None;
1342        } else if self.focused == Some(FocusedPane::Tree) {
1343            self.focused = None;
1344            self.tree_selected = None;
1345            self.tree_selection_auto = true;
1346        } else {
1347            self.should_quit = true;
1348        }
1349    }
1350
1351    /// Move the tree selection by `delta` phase entries, skipping scope
1352    /// headers. Grabs tree focus if it wasn't already held, and seeds
1353    /// the selection with the most-recently-active phase on first use.
1354    /// Any manual movement disables auto-tracking so the selection
1355    /// stops drifting with newly-running phases.
1356    fn move_tree_selection(&mut self, delta: i32) {
1357        if self.focused != Some(FocusedPane::Tree) {
1358            self.focused = Some(FocusedPane::Tree);
1359        }
1360        // Drill mode: Up/Down move within the drilled phase's op
1361        // list. The cursor stays on the parent phase row in the
1362        // outer tree; only `drill_op_idx` advances.
1363        if let Some(drilled) = self.tree_drilled {
1364            let n = {
1365                let s = self.run_state.load();
1366                s.phases.get(drilled).map(|p| p.op_names.len()).unwrap_or(0)
1367            };
1368            if n == 0 {
1369                // Phase has no op data — exit drill mode rather
1370                // than getting stuck in an empty navigator.
1371                self.tree_drilled = None;
1372                return;
1373            }
1374            let cur = self.drill_op_idx as i64;
1375            let next = (cur + delta as i64).clamp(0, n as i64 - 1) as usize;
1376            self.drill_op_idx = next;
1377            return;
1378        }
1379        if self.tree_selected.is_none() {
1380            self.tree_selected = self.default_tree_selection();
1381        }
1382        self.tree_selection_auto = false;
1383        if let Some(start) = self.tree_selected
1384            && let Some(next) = self.step_selectable_for_lod(start, delta)
1385        {
1386            self.tree_selected = Some(next);
1387        }
1388        self.scroll_selection_into_view();
1389    }
1390
1391    /// Right arrow: drill into a phase's stanza op list when the
1392    /// selected phase is already expanded; otherwise fall back to
1393    /// the LOD-up behavior (more detail).
1394    fn tree_right_arrow(&mut self) {
1395        // If already drilled, no-op (Right has no further meaning
1396        // inside the op list).
1397        if self.tree_drilled.is_some() {
1398            return;
1399        }
1400        let Some(sel) = self.tree_selected else {
1401            self.adjust_tree_lod(1);
1402            return;
1403        };
1404        // Drill only when the selected phase is currently expanded
1405        // AND has op_names to show. Otherwise fall through to LOD.
1406        if self.tree_expanded == Some(sel) {
1407            let has_ops = {
1408                let s = self.run_state.load();
1409                s.phases
1410                    .get(sel)
1411                    .map(|p| p.kind == crate::state::EntryKind::Phase && !p.op_names.is_empty())
1412                    .unwrap_or(false)
1413            };
1414            if has_ops {
1415                self.tree_drilled = Some(sel);
1416                self.drill_op_idx = 0;
1417                self.scroll_selection_into_view();
1418                return;
1419            }
1420        }
1421        self.adjust_tree_lod(1);
1422    }
1423
1424    /// Left arrow: exit drill mode (close the stanza op list, park
1425    /// cursor back on the parent phase) when drilled; otherwise
1426    /// fall back to the LOD-down behavior (less detail).
1427    fn tree_left_arrow(&mut self) {
1428        if self.tree_drilled.is_some() {
1429            self.tree_drilled = None;
1430            self.drill_op_idx = 0;
1431            self.scroll_selection_into_view();
1432            return;
1433        }
1434        self.adjust_tree_lod(-1);
1435    }
1436
1437    /// LOD-aware step. Skips over entries that render zero rows
1438    /// (scope headers in Minimal/Focus, pending/completed phases
1439    /// in Focus) so the selection never parks at an invisible
1440    /// line index — which would cause `scroll_selection_into_view`
1441    /// to silently bail and leave the viewport out of sync with
1442    /// `tree_selected`.
1443    fn step_selectable_for_lod(&self, start: usize, delta: i32) -> Option<usize> {
1444        let s = self.run_state.load();
1445        let len = s.phases.len() as i32;
1446        if len == 0 {
1447            return None;
1448        }
1449        let step = if delta >= 0 { 1 } else { -1 };
1450        let mut idx = start as i32 + step;
1451        while idx >= 0 && idx < len {
1452            let i = idx as usize;
1453            let phase = &s.phases[i];
1454            if phase.kind == crate::state::EntryKind::Phase && self.rendered_lines_for(i, phase) > 0
1455            {
1456                return Some(i);
1457            }
1458            idx += step;
1459        }
1460        None
1461    }
1462
1463    /// If the currently selected entry's rendered line sits outside the
1464    /// visible viewport, retarget the scroll animation so it just comes
1465    /// into view. Top-aligned if the selection is above the window,
1466    /// bottom-aligned if below. No-op when already in view.
1467    fn scroll_selection_into_view(&mut self) {
1468        let Some(sel) = self.tree_selected else {
1469            return;
1470        };
1471        let visible = self.last_tree_rect.height.saturating_sub(2) as usize;
1472        if visible == 0 {
1473            return;
1474        }
1475
1476        // Rendered-line index of the selected entry, accounting for any
1477        // currently expanded detail block above it.
1478        let Some(line) = self.entry_to_line_index(sel) else {
1479            return;
1480        };
1481
1482        let total = self.total_rendered_lines();
1483        let tail = total.saturating_sub(visible);
1484        let current_top = self.tree_scroll.unwrap_or(tail);
1485        let current_bottom = current_top.saturating_add(visible).saturating_sub(1);
1486
1487        let new_top = if line < current_top {
1488            // Selection is above the viewport — bring it to the top.
1489            line
1490        } else if line > current_bottom {
1491            // Selection is below the viewport — pin it to the bottom row.
1492            line.saturating_sub(visible.saturating_sub(1))
1493        } else {
1494            return; // already visible
1495        };
1496        let clamped = new_top.min(tail);
1497        let target = if clamped >= tail { None } else { Some(clamped) };
1498        self.retarget_tree_scroll(target, tail);
1499    }
1500
1501    /// Total number of rendered lines in the tree (phase rows + detail
1502    /// rows of any expanded entry). Matches the iteration in `draw_tree`.
1503    fn total_rendered_lines(&self) -> usize {
1504        let s = self.run_state.load();
1505        s.phases
1506            .iter()
1507            .enumerate()
1508            .map(|(i, p)| self.rendered_lines_for(i, p))
1509            .sum()
1510    }
1511
1512    /// Inverse of [`line_to_entry_index`]: given a `state.phases` index,
1513    /// return its rendered-line index (0-based, pre-scroll). `None` if
1514    /// the entry doesn't exist.
1515    fn entry_to_line_index(&self, entry: usize) -> Option<usize> {
1516        let s = self.run_state.load();
1517        if entry >= s.phases.len() {
1518            return None;
1519        }
1520        // Entries that render zero rows (scope headers in Minimal) have
1521        // no line position — treat them as absent for navigation.
1522        if self.rendered_lines_for(entry, &s.phases[entry]) == 0 {
1523            return None;
1524        }
1525        let mut cursor = 0usize;
1526        for (i, phase) in s.phases.iter().enumerate() {
1527            if i == entry {
1528                return Some(cursor);
1529            }
1530            cursor += self.rendered_lines_for(i, phase);
1531        }
1532        None
1533    }
1534
1535    /// Default tree selection when focus is first grabbed: the most
1536    /// recently active phase. Prefers the current Running entry, falls
1537    /// back to the latest Completed entry, then the first Phase.
1538    fn default_tree_selection(&self) -> Option<usize> {
1539        let s = self.run_state.load();
1540        let phases: &[crate::state::PhaseEntry] = &s.phases;
1541        // Only consider entries that actually render under the
1542        // current LOD — Focus hides non-running phases, so the
1543        // default selection can't usefully land on one.
1544        let renderable = |(i, p): &(usize, &crate::state::PhaseEntry)| {
1545            p.kind == crate::state::EntryKind::Phase && self.rendered_lines_for(*i, p) > 0
1546        };
1547        phases
1548            .iter()
1549            .enumerate()
1550            .filter(renderable)
1551            .rfind(|(_, p)| matches!(p.status, crate::state::PhaseStatus::Running))
1552            .or_else(|| {
1553                phases
1554                    .iter()
1555                    .enumerate()
1556                    .filter(renderable)
1557                    .rfind(|(_, p)| matches!(p.status, crate::state::PhaseStatus::Completed))
1558            })
1559            .or_else(|| phases.iter().enumerate().find(renderable))
1560            .map(|(i, _)| i)
1561    }
1562
1563    /// Cycle the tree level of detail. Positive `delta` increases LOD
1564    /// (more detail), negative decreases. Clamped at the ends.
1565    ///
1566    /// Grabs tree focus if not held, and scrolls the current selection
1567    /// back into view since the rendered-line coordinates shift when
1568    /// the detail model changes.
1569    fn adjust_tree_lod(&mut self, delta: i32) {
1570        if self.focused != Some(FocusedPane::Tree) {
1571            self.focused = Some(FocusedPane::Tree);
1572        }
1573        if self.tree_selected.is_none() {
1574            self.tree_selected = self.default_tree_selection();
1575            self.tree_selection_auto = false;
1576        }
1577        self.tree_lod = if delta > 0 {
1578            self.tree_lod.next()
1579        } else {
1580            self.tree_lod.prev()
1581        };
1582        self.scroll_selection_into_view();
1583    }
1584
1585    /// Number of rendered lines an entry contributes under the current
1586    /// LOD + expansion state. Rules:
1587    ///   * Scope entry in Minimal or Focus → hidden (0 rows).
1588    ///   * Focus mode also hides non-running phases.
1589    ///   * Phase entry in Maximal or Focus → 1 + full detail block.
1590    ///   * Any phase the user has explicitly pinned via Enter → 1 +
1591    ///     detail, regardless of LOD.
1592    ///   * Otherwise → 1 row.
1593    fn rendered_lines_for(&self, entry_idx: usize, phase: &crate::state::PhaseEntry) -> usize {
1594        // Hidden and ActivePhase LODs don't render any tree rows.
1595        // Return 0 so total_rendered_lines / entry_to_line_index
1596        // behave as "no scrollable tree content" and the event
1597        // loop's tail calc disables scroll animation in those LODs.
1598        if matches!(self.tree_lod, TreeLod::Hidden | TreeLod::ActivePhase) {
1599            return 0;
1600        }
1601        if matches!(self.tree_lod, TreeLod::Minimal | TreeLod::Focus)
1602            && phase.kind == crate::state::EntryKind::Scope
1603        {
1604            return 0;
1605        }
1606        if self.tree_lod == TreeLod::Focus
1607            && phase.kind == crate::state::EntryKind::Phase
1608            && !matches!(phase.status, crate::state::PhaseStatus::Running)
1609        {
1610            return 0;
1611        }
1612        if phase.kind != crate::state::EntryKind::Phase {
1613            return 1;
1614        }
1615        let expanded = self.tree_expanded == Some(entry_idx)
1616            || self.tree_lod == TreeLod::Maximal
1617            || self.tree_lod == TreeLod::Focus;
1618        // Op-level status rows (SRD-63) render whenever the phase row
1619        // renders, independent of expand/drill — counted in both
1620        // branches so scroll/hit-test math matches draw_tree.
1621        let op_rows = self.op_rows_for(phase);
1622        if expanded {
1623            // Drilled phases also render a header row + one row
1624            // per op name. Counted here so scroll math, mouse
1625            // hit-testing, and tail-offset calculation all stay
1626            // in sync with what `draw_tree` actually emits.
1627            let drill_rows = if self.tree_drilled == Some(entry_idx) {
1628                1 + phase.op_names.len()
1629            } else {
1630                0
1631            };
1632            1 + self.detail_line_count_for(phase) + drill_rows + op_rows
1633        } else {
1634            1 + op_rows
1635        }
1636    }
1637
1638    /// Number of op-level status rows a phase contributes (SRD-63):
1639    /// one per `readout: visible` op recorded under the phase. They
1640    /// render whenever the phase row renders (not gated by expand /
1641    /// drill), so they're added to both branches of
1642    /// `rendered_lines_for` to keep scroll / hit-test math consistent.
1643    fn op_rows_for(&self, phase: &crate::state::PhaseEntry) -> usize {
1644        self.run_state
1645            .load()
1646            .phase_ops
1647            .get(&phase.node_id)
1648            .map(|v| v.len())
1649            .unwrap_or(0)
1650    }
1651
1652    /// Count of detail lines for a phase using live state when the
1653    /// phase is currently running. Keeps line-offset math in
1654    /// `total_rendered_lines` / `entry_to_line_index` /
1655    /// `line_to_entry_index` consistent with `draw_tree` output.
1656    fn detail_line_count_for(&self, phase: &crate::state::PhaseEntry) -> usize {
1657        {
1658            let s = self.run_state.load();
1659            if let Some(a) = s.active_phase(&phase.name, &phase.labels) {
1660                // Clone the active snapshot out of the read guard so we
1661                // can drop the lock before calling format_phase_detail.
1662                let a = a.clone();
1663                drop(s);
1664                return self.format_phase_detail_with_live(phase, Some(&a)).len();
1665            }
1666        }
1667        self.format_phase_detail(phase).len()
1668    }
1669
1670    /// Whether a detail block is rendered below the given phase. The
1671    /// user-pinned expansion (via Enter) always wins: even in Minimal
1672    /// mode the selected phase can still be drilled into. Otherwise
1673    /// Default LOD renders no details, Maximal renders them for every
1674    /// phase that has data.
1675    fn show_detail_for(&self, entry_idx: usize, phase: &crate::state::PhaseEntry) -> bool {
1676        if phase.kind != crate::state::EntryKind::Phase {
1677            return false;
1678        }
1679        if self.tree_expanded == Some(entry_idx) {
1680            return true;
1681        }
1682        match self.tree_lod {
1683            TreeLod::Hidden => false,
1684            // ActivePhase uses the dedicated panel renderer — the
1685            // tree-detail path isn't exercised under this LOD.
1686            TreeLod::ActivePhase => false,
1687            TreeLod::Minimal => false,
1688            TreeLod::Default => false,
1689            TreeLod::Focus => matches!(phase.status, crate::state::PhaseStatus::Running),
1690            TreeLod::Maximal => !self.format_phase_detail(phase).is_empty(),
1691        }
1692    }
1693
1694    /// Toggle expansion of the currently selected phase. Scope entries
1695    /// and missing selections are ignored. Works in every LOD: a
1696    /// user-pinned expansion overrides the LOD baseline, so in Minimal
1697    /// or Maximal the selected phase still gets its full detail block.
1698    fn toggle_tree_expansion(&mut self) {
1699        let Some(sel) = self.tree_selected else {
1700            return;
1701        };
1702        let is_phase = {
1703            let s = self.run_state.load();
1704            s.phases
1705                .get(sel)
1706                .map(|p| p.kind == crate::state::EntryKind::Phase)
1707                .unwrap_or(false)
1708        };
1709        if !is_phase {
1710            return;
1711        }
1712        self.tree_expanded = match self.tree_expanded {
1713            Some(i) if i == sel => None,
1714            _ => Some(sel),
1715        };
1716        // Collapsing a phase that's currently drilled also exits
1717        // the drill view — the op list belongs to the open
1718        // detail block, so it shouldn't render once that block
1719        // closes.
1720        if self.tree_expanded.is_none() {
1721            self.tree_drilled = None;
1722            self.drill_op_idx = 0;
1723        }
1724    }
1725
1726    /// Map a rendered-line index (0-based within the full rendered tree,
1727    /// pre-scroll) back to the `state.phases` index it represents. When
1728    /// a phase is expanded, its entry "owns" the detail lines below it,
1729    /// so clicks on those rows select the parent phase. Returns `None`
1730    /// if the line sits beyond the last entry.
1731    fn line_to_entry_index(&self, line: usize) -> Option<usize> {
1732        let s = self.run_state.load();
1733        let mut cursor = 0usize;
1734        for (i, phase) in s.phases.iter().enumerate() {
1735            let rendered_rows = self.rendered_lines_for(i, phase);
1736            if rendered_rows == 0 {
1737                continue;
1738            }
1739            if line < cursor + rendered_rows {
1740                return Some(i);
1741            }
1742            cursor += rendered_rows;
1743        }
1744        None
1745    }
1746
1747    /// Refresh the selection to track the most recently active phase
1748    /// when the user hasn't manually moved it. Called each frame so the
1749    /// marker drifts along with the workload's progress. When the
1750    /// tracked selection *changes*, the viewport re-pins the new row to
1751    /// the top edge so the active phase is always the anchor.
1752    fn refresh_auto_selection(&mut self) {
1753        if self.focused != Some(FocusedPane::Tree) || !self.tree_selection_auto {
1754            return;
1755        }
1756        let prev = self.tree_selected;
1757        if let Some(i) = self.default_tree_selection() {
1758            self.tree_selected = Some(i);
1759            if prev != Some(i) {
1760                // Move the expansion to follow the new active phase
1761                // FIRST — expansion state feeds into the line-index
1762                // math, so if the previously expanded phase is still
1763                // marked as expanded while we compute the new scroll
1764                // target, the target lands below the real position by
1765                // the old phase's detail-block height.
1766                if self.tree_expanded.is_some() {
1767                    self.tree_expanded = Some(i);
1768                }
1769                // Now re-pin to top with the correct expansion state.
1770                self.scroll_selection_to_top();
1771            }
1772        }
1773    }
1774
1775    /// Pin the currently selected entry's rendered line to the top of
1776    /// the tree viewport by retargeting the scroll animation.
1777    fn scroll_selection_to_top(&mut self) {
1778        let Some(sel) = self.tree_selected else {
1779            return;
1780        };
1781        let Some(line) = self.entry_to_line_index(sel) else {
1782            return;
1783        };
1784        let visible = self.last_tree_rect.height.saturating_sub(2) as usize;
1785        if visible == 0 {
1786            return;
1787        }
1788        let total = self.total_rendered_lines();
1789        let tail = total.saturating_sub(visible);
1790        // Always pin the selected entry's first line to the top row
1791        // of the viewport, even when content is shorter than the
1792        // panel — the user-visible meaning of "scroll to top" is
1793        // *anchor*, not *fill*. The viewport pads with empty rows
1794        // when (line + visible) > total. Capped at `total` so the
1795        // line index is at least within the buffer; the loop's
1796        // skip+render naturally handles "no rows to draw" past
1797        // the end. `tail` is still passed for the anim fallback
1798        // when target is None, used by other call sites.
1799        let target = Some(line.min(total));
1800        self.retarget_tree_scroll(target, tail);
1801    }
1802
1803    /// Space-bar reset: pivot the tree view around the most recently
1804    /// active phase. Takes focus, seeds selection to the active phase,
1805    /// forces LOD back to Default, expands the selection, enables
1806    /// auto-tracking, and pins it to the top of the window.
1807    fn reset_tree_to_active(&mut self) {
1808        self.focused = Some(FocusedPane::Tree);
1809        self.tree_lod = TreeLod::Default;
1810        self.tree_selection_auto = true;
1811        if let Some(i) = self.default_tree_selection() {
1812            self.tree_selected = Some(i);
1813            self.tree_expanded = Some(i);
1814        }
1815        self.scroll_selection_to_top();
1816    }
1817
1818    /// Build the detail lines shown when a phase is expanded. The
1819    /// caller adds the indent/gutter prefix. If `live` is supplied the
1820    /// detail reads from that live snapshot (matches the non-TUI
1821    /// progress bar exactly); otherwise it reads from
1822    /// `phase.summary` (captured at phase_completed time).
1823    fn format_phase_detail(&self, phase: &crate::state::PhaseEntry) -> Vec<Line<'static>> {
1824        self.format_phase_detail_with_live(phase, None)
1825    }
1826
1827    fn format_phase_detail_with_live(
1828        &self,
1829        phase: &crate::state::PhaseEntry,
1830        live: Option<&crate::state::ActivePhase>,
1831    ) -> Vec<Line<'static>> {
1832        let mut out: Vec<Line<'static>> = Vec::new();
1833
1834        // SRD-63 Push 5b: route the headline status row through
1835        // the readout engine. `phase_status` for live phases
1836        // (binder.fire under EventType::Update; ContentMode flips
1837        // to Explanation when the `\` overlay-toggle is active);
1838        // `phase_outcome` / `phase_summary` for terminal states.
1839        // Tab / Shift-Tab cycle focus through bound bodies; +
1840        // / - cycle the focused body's LOD. The binder's per-
1841        // (slot, body) state persists across frames so the
1842        // operator's selection survives every refresh.
1843        let refresh_tick = self.frame_tick.get();
1844        let (readout_lines, _evt) = crate::readout_panel::render_phase_readouts(
1845            &mut self.readout_binder.borrow_mut(),
1846            phase,
1847            live,
1848            refresh_tick,
1849        );
1850        out.extend(readout_lines);
1851
1852        // Status line — duplicates the parent row but gives us a first
1853        // detail line when a phase has no summary yet (pending).
1854        let status_text = match &phase.status {
1855            PhaseStatus::Pending => "pending — not yet started".to_string(),
1856            PhaseStatus::Running => "running…".to_string(),
1857            PhaseStatus::Completed => {
1858                let dur = phase
1859                    .duration_secs
1860                    .map(|d| format!(" in {d:.2}s"))
1861                    .unwrap_or_default();
1862                format!("completed{dur}")
1863            }
1864            PhaseStatus::Failed(err) => format!("failed: {err}"),
1865        };
1866        out.push(Line::from(Span::styled(
1867            status_text,
1868            Style::default().fg(colors::DIM),
1869        )));
1870
1871        if !phase.labels.is_empty() {
1872            out.push(Line::from(Span::styled(
1873                format!("bindings: {}", phase.labels),
1874                Style::default().fg(colors::TEXT),
1875            )));
1876        }
1877
1878        if phase.op_count > 0 {
1879            // Structural metadata — count of op-template
1880            // entries under the phase's `ops:` key. Distinct
1881            // from "ops" (per-cycle executions) which are
1882            // counted by the throughput rows above; "active"
1883            // would be misleading here since this is a static
1884            // declaration count, not a runtime quantity.
1885            out.push(Line::from(Span::styled(
1886                format!("op templates: {}", phase.op_count),
1887                Style::default().fg(colors::TEXT),
1888            )));
1889        }
1890
1891        // Extract the same fields the non-TUI progress bar prints, from
1892        // whichever source is available. `live` wins when the phase is
1893        // currently running; otherwise the completion snapshot.
1894        struct Snap {
1895            ops_started: u64,
1896            ops_finished: u64,
1897            ops_ok: u64,
1898            errors: u64,
1899            retries: u64,
1900            fibers: usize,
1901            ops_per_sec: f64,
1902            cursor_name: String,
1903            cursor_extent: u64,
1904            adapter_counters: Vec<(String, u64, f64)>,
1905            rows_per_batch: f64,
1906        }
1907        let snap: Option<Snap> = if let Some(a) = live {
1908            Some(Snap {
1909                ops_started: a.ops_started,
1910                ops_finished: a.ops_finished,
1911                ops_ok: a.ops_ok,
1912                errors: a.errors,
1913                retries: a.retries,
1914                fibers: a.fibers,
1915                ops_per_sec: a.ops_per_sec,
1916                cursor_name: a.cursor_name.clone(),
1917                cursor_extent: a.cursor_extent,
1918                adapter_counters: a.adapter_counters.clone(),
1919                rows_per_batch: a.rows_per_batch,
1920            })
1921        } else {
1922            phase.summary.as_ref().map(|sm| Snap {
1923                ops_started: sm.ops_started,
1924                ops_finished: sm.ops_finished,
1925                ops_ok: sm.ops_ok,
1926                errors: sm.errors,
1927                retries: sm.retries,
1928                fibers: sm.fibers,
1929                ops_per_sec: sm.ops_per_sec,
1930                cursor_name: sm.cursor_name.clone(),
1931                cursor_extent: sm.cursor_extent,
1932                adapter_counters: sm.adapter_counters.clone(),
1933                rows_per_batch: sm.rows_per_batch,
1934            })
1935        };
1936
1937        if let Some(s) = snap {
1938            // Labeled tuple + visual bar. "82.9K of 83.0K" on its own is
1939            // ambiguous; spelling out pending/active/complete and
1940            // anchoring on the cursor name makes the scale obvious.
1941            let active = s.ops_started.saturating_sub(s.ops_finished);
1942            let pending = s.cursor_extent.saturating_sub(s.ops_started);
1943            let complete = s.ops_finished;
1944            // Percentage matches the "N of M" display on the same
1945            // line — both are ops_finished / extent. Previously
1946            // this used ops_started, which showed 100% while
1947            // "complete of extent" was still < extent (in-flight
1948            // ops made the two disagree).
1949            let pct = if s.cursor_extent > 0 {
1950                complete as f64 * 100.0 / s.cursor_extent as f64
1951            } else {
1952                0.0
1953            };
1954
1955            // Cursor row: identity + absolute ratio on one line,
1956            // then a two-line-tall thick progress bar below.
1957            // The bar matches the 60-cell width of the latency
1958            // bars further down so the two visually anchor on
1959            // the same column. Full-block glyphs make the bar
1960            // read as "the most prominent thing in this block"
1961            // — appropriate, since cursor progress is the
1962            // primary phase-completion signal.
1963            // Wider than the latency bars below (60 cells)
1964            // because the cursor row is the headline progress
1965            // signal and the Braille per-pip resolution
1966            // (8 pips/cell × 100 cells = 800 sub-positions) is
1967            // worth the extra horizontal real estate.
1968            const CURSOR_BAR_W: usize = 100;
1969            let (bar_filled, bar_unfilled) = widgets::bar_str_braille(pct / 100.0, CURSOR_BAR_W);
1970            let cursor_label = if s.cursor_name.is_empty() {
1971                "cursor".to_string()
1972            } else {
1973                format!("cursor {}", s.cursor_name)
1974            };
1975            out.push(Line::from(Span::styled(
1976                format!(
1977                    "{cursor_label}:  {} of {}  ({:.2}%)",
1978                    widgets::format_count(complete),
1979                    widgets::format_count(s.cursor_extent),
1980                    pct
1981                ),
1982                Style::default().fg(colors::TEXT),
1983            )));
1984            // Two-span line: bright Braille pips for the
1985            // filled portion, dim baseline track (`⣀`) for the
1986            // remaining work. Lets the operator gauge progress
1987            // against total at a glance — without the baseline
1988            // track the bar's full width was invisible until
1989            // a fill appeared.
1990            out.push(Line::from(vec![
1991                Span::styled(bar_filled, Style::default().fg(colors::PROGRESS_HIGH)),
1992                Span::styled(bar_unfilled, Style::default().fg(colors::DIM)),
1993            ]));
1994
1995            // Line 2: named breakdown of the same numbers.
1996            out.push(Line::from(Span::styled(
1997                format!(
1998                    "  pending: {}  •  active: {}  •  complete: {}  (extent: {})",
1999                    widgets::format_count(pending),
2000                    widgets::format_count(active),
2001                    widgets::format_count(complete),
2002                    widgets::format_count(s.cursor_extent)
2003                ),
2004                Style::default().fg(colors::DIM),
2005            )));
2006
2007            // Line 3: throughput + reliability + concurrency.
2008            // The rate labeled here is the cursor-advance rate —
2009            // `ops_finished` increments once per cycle, which is
2010            // once per position of the declared cursor. Naming it
2011            // after the cursor ("row/s", "q/s", …) keeps the
2012            // label honest with the adjacent `cursor row:` line
2013            // above. Falls back to "cycles/s" when no cursor is
2014            // declared. Domain-level counters (rows_inserted/s
2015            // for batched writes, where the cycle rate ≠ the row
2016            // rate) still show separately under `adapter:` below.
2017            let throughput_label = cursor_rate_label(&s.cursor_name);
2018            // Smoothed rate via the phase's Ewma summary when
2019            // live; completed phases use the snapshot's raw
2020            // ops_per_sec (no EWMA retained post-phase).
2021            let rate_display = live
2022                .and_then(|a| a.rate_ewma.peek())
2023                .unwrap_or(s.ops_per_sec);
2024            out.push(Line::from(Span::styled(
2025                format!("{throughput_label}: {}   ok: {:.1}%   errors: {}   retries: {}   concurrency: {}",
2026                    widgets::format_rate(rate_display),
2027                    if s.ops_finished > 0 {
2028                        s.ops_ok as f64 * 100.0 / s.ops_finished as f64
2029                    } else { 100.0 },
2030                    s.errors,
2031                    s.retries,
2032                    s.fibers),
2033                Style::default().fg(colors::TEXT),
2034            )));
2035
2036            // Latency percentile bars — render the existing per-row
2037            // visualization (from the retired top-level Latency panel)
2038            // inline under this phase's detail. Running phases pull
2039            // live values from the TUI's drained state; completed
2040            // phases use their `summary.*_nanos` snapshot.
2041            let (min_ns, p50_ns, p90_ns, p99_ns, p999_ns, max_ns, lat_src) = if live.is_some() {
2042                let sr = self.run_state.load();
2043                (
2044                    sr.min_nanos,
2045                    sr.p50_nanos,
2046                    sr.p90_nanos,
2047                    sr.p99_nanos,
2048                    sr.p999_nanos,
2049                    sr.max_nanos,
2050                    "live",
2051                )
2052            } else if let Some(ref sm) = phase.summary {
2053                // `summary` only captures min/p50/p99/max today —
2054                // p90/p999 default to 0 and the bar renderer
2055                // skips zero-valued rows.
2056                (
2057                    sm.min_nanos,
2058                    sm.p50_nanos,
2059                    0,
2060                    sm.p99_nanos,
2061                    0,
2062                    sm.max_nanos,
2063                    "summary",
2064                )
2065            } else {
2066                (0, 0, 0, 0, 0, 0, "")
2067            };
2068            let _ = lat_src;
2069            // Peak cross-bar markers come from the phase's
2070            // PeakTracker summaries when live; completed phases
2071            // have no live trackers, so peaks are omitted.
2072            let now = std::time::Instant::now();
2073            let peak_5s = live.and_then(|a| a.latency_peak_5s.peek(now));
2074            let peak_10s = live.and_then(|a| a.latency_peak_10s.peek(now));
2075            if max_ns > 0 || p99_ns > 0 || p50_ns > 0 {
2076                out.extend(latency_detail_lines(
2077                    min_ns, p50_ns, p90_ns, p99_ns, p999_ns, max_ns, peak_5s, peak_10s,
2078                ));
2079            }
2080
2081            // Throughput sparkline. Two sources, one render:
2082            //   - Live phase → snapshot of the live
2083            //     `Arc<BinomialSummary>` (updates every frame).
2084            //   - Completed phase → frozen `throughput_samples`
2085            //     captured at phase_completed time.
2086            // Failed / pending phases render nothing (no samples).
2087            // The sparkline is the *durable artifact* per
2088            // SRD 62 §"Per-phase sparkline": scrolling back to
2089            // a completed phase must still show its curve.
2090            let (tp_samples, tp_cursor_name): (Vec<f64>, String) = if let Some(a) = live {
2091                (a.throughput_summary.snapshot(), a.cursor_name.clone())
2092            } else if let Some(ref sm) = phase.summary {
2093                (sm.throughput_samples.clone(), sm.cursor_name.clone())
2094            } else {
2095                (Vec::new(), String::new())
2096            };
2097            if !tp_samples.is_empty() {
2098                let spark = widgets::sparkline_str(&tp_samples, 60);
2099                let latest = tp_samples.last().copied().unwrap_or(0.0);
2100                let rate_label = cursor_rate_label(&tp_cursor_name);
2101                out.push(Line::from(vec![
2102                    Span::styled(" rate ", Style::default().fg(colors::DIM)),
2103                    Span::styled(
2104                        format!(" {:>14}  ", widgets::format_rate(latest)),
2105                        Style::default().fg(colors::SPARK).bold(),
2106                    ),
2107                    Span::styled(spark, Style::default().fg(colors::SPARK)),
2108                    Span::styled(format!("  {rate_label}"), Style::default().fg(colors::DIM)),
2109                ]));
2110            }
2111
2112            if phase
2113                .summary
2114                .as_ref()
2115                .map(|sm| sm.p50_nanos > 0 || sm.p99_nanos > 0 || sm.max_nanos > 0)
2116                .unwrap_or(false)
2117                && let Some(ref sm) = phase.summary
2118            {
2119                out.push(Line::from(Span::styled(
2120                    format!(
2121                        "latency: min {}  p50 {}  p99 {}  max {}",
2122                        widgets::format_nanos(sm.min_nanos),
2123                        widgets::format_nanos(sm.p50_nanos),
2124                        widgets::format_nanos(sm.p99_nanos),
2125                        widgets::format_nanos(sm.max_nanos)
2126                    ),
2127                    Style::default().fg(colors::LAT_P50),
2128                )));
2129            }
2130
2131            // Relevancy aggregates (recall / precision / f1 / …), one
2132            // line per metric. Shows the moving-window mean (last N
2133            // cycles for the phase's op template) and the running
2134            // all-time mean across the phase. For ANN workloads this
2135            // is a KEY metric — kept separate so it's impossible to
2136            // miss in the expanded view.
2137            let relevancy: &[(String, f64, f64, u64, usize)] = if let Some(a) = live {
2138                &a.relevancy
2139            } else if let Some(ref sm) = phase.summary {
2140                &sm.relevancy
2141            } else {
2142                &[]
2143            };
2144            for (name, window_mean, total_mean, total_count, window_len) in relevancy {
2145                out.push(Line::from(Span::styled(
2146                    format!(
2147                        "{name}: all-time {:.4}  •  last {window_len}: {:.4}  (n={total_count})",
2148                        total_mean, window_mean
2149                    ),
2150                    Style::default().fg(colors::EMPHASIS),
2151                )));
2152            }
2153
2154            // Adapter-specific status counters with rates (rows/s etc.),
2155            // same series the progress bar prefixes after the core stats.
2156            if !s.adapter_counters.is_empty() {
2157                let mut parts: Vec<String> = Vec::new();
2158                for (name, total, rate) in &s.adapter_counters {
2159                    // Internal counters (`_batch_writes`) back a derived metric
2160                    // only — never their own chip. See `is_internal_counter`.
2161                    if nmbrs_runtime::is_internal_counter(name) {
2162                        continue;
2163                    }
2164                    parts.push(format!(
2165                        "{name}: {} @ {}/s",
2166                        widgets::format_count(*total),
2167                        widgets::format_rate(*rate)
2168                    ));
2169                }
2170                out.push(Line::from(Span::styled(
2171                    format!("adapter: {}", parts.join("   ")),
2172                    Style::default().fg(colors::DIM),
2173                )));
2174            }
2175
2176            if s.rows_per_batch > 1.0 {
2177                out.push(Line::from(Span::styled(
2178                    format!("rows/batch: {:.1}", s.rows_per_batch),
2179                    Style::default().fg(colors::DIM),
2180                )));
2181            }
2182        }
2183
2184        out
2185    }
2186
2187    /// Offset that would put the tail (last entries) at the bottom of
2188    /// the tree view — i.e. the auto-follow position.
2189    fn tree_tail_offset(&self, tree_rect: Rect) -> usize {
2190        let visible = tree_rect.height.saturating_sub(2) as usize; // minus borders
2191        let total = self.run_state.load().phases.len();
2192        total.saturating_sub(visible)
2193    }
2194
2195    /// Drain pending base-cadence metrics frames. Updates the live
2196    /// latency values, history rings, and sparkline samples.
2197    ///
2198    /// Per-cadence windowed percentiles (10s / 1m / etc.) no longer
2199    /// flow through this channel — they're read directly from the
2200    /// shared [`MetricsQuery`] at render time, so we don't duplicate
2201    /// state.
2202    fn drain_frames(&mut self) {
2203        while let Ok(frame) = self.frame_rx.try_recv() {
2204            // Translate every frame ingest into actor commands —
2205            // never take a write lock on shared state. The actor
2206            // applies the LatencyFrame mutation, then the
2207            // SparklineSamples mutation; the TUI sees the
2208            // combined effect on the next snapshot load.
2209            if let Some(w) = extract_latency_from_frame(&frame) {
2210                self.run_state.send(RunStateCmd::LatencyFrame {
2211                    min: w.min,
2212                    p50: w.p50,
2213                    p90: w.p90,
2214                    p99: w.p99,
2215                    p999: w.p999,
2216                    max: w.max,
2217                });
2218            }
2219
2220            // Sparkline samples — derived from the snapshot's
2221            // first active phase. The adapter-counter sparkline
2222            // tracks the FIRST counter the active dispenser
2223            // reports, whatever its name. If no counter is
2224            // reported, the secondary sparkline stays empty.
2225            let snap = self.run_state.load();
2226            let (ops_sample, rows_sample, rows_name) = if let Some(active) = snap.first_active() {
2227                let (rate, name) = active
2228                    .adapter_counters
2229                    .first()
2230                    .map(|(n, _, r)| (*r, Some(n.clone())))
2231                    .unwrap_or((0.0, None));
2232                let sample: Option<f64> = name.as_ref().map(|_| rate);
2233                (Some(active.ops_per_sec), sample, name)
2234            } else {
2235                (None::<f64>, None::<f64>, None::<String>)
2236            };
2237            self.run_state.send(RunStateCmd::SparklineSamples {
2238                ops: ops_sample,
2239                rows: rows_sample,
2240                rows_label: rows_name,
2241            });
2242        }
2243    }
2244
2245    /// Render one frame. Public for testing with TestBackend.
2246    ///
2247    /// While paused, every read routes through the snapshot clone
2248    /// in `self.frozen_state` instead of the live state. Live
2249    /// observer updates keep flowing into `self.run_state` — they
2250    /// just don't affect the rendered frame until the user resumes.
2251    pub fn draw(&self, frame: &mut Frame) {
2252        // Advance the frame tick before any render reads it —
2253        // the readout engine's `phase_status` spinner uses it
2254        // to cycle Braille frames at the TUI's tick rate.
2255        self.frame_tick.set(self.frame_tick.get().wrapping_add(1));
2256        // Prefer the frozen snapshot when paused. Otherwise load
2257        // the live snapshot — a single atomic op that cannot
2258        // wait on any writer (SRD-02 §"Display and Diagnostic
2259        // Decoupling").
2260        let live_snap;
2261        let state: &RunState = if let Some(ref frozen) = self.frozen_state {
2262            frozen.as_ref()
2263        } else {
2264            live_snap = self.run_state.load();
2265            live_snap.as_ref()
2266        };
2267        let area = frame.area();
2268
2269        // Top-level layout — SRD 62 §"Panel composition".
2270        //
2271        // Phase, Latency, and Throughput are no longer top-level
2272        // panels; their content lives inside per-phase detail blocks
2273        // in the scenario tree. The canvas is a 4-section vertical
2274        // stack: Header, optional Log, Scenario (tree), Footer.
2275        let sections = Layout::default()
2276            .direction(Direction::Vertical)
2277            .constraints([
2278                Constraint::Length(3), // header
2279                Constraint::Min(3),    // scenario (+ log panel)
2280                Constraint::Length(1), // footer
2281            ])
2282            .split(area);
2283
2284        self.draw_header(frame, sections[0], state);
2285
2286        // Bottom section routing:
2287        //   - tree hidden (LOD:off): always show the log in the full
2288        //     section so something useful is there and the hint in
2289        //     the log title tells the user how to restore the tree.
2290        //   - tree visible + log off: tree takes the whole section.
2291        //   - tree visible + log on: split 50/50.
2292        if self.tree_lod == TreeLod::Hidden {
2293            self.draw_log(frame, sections[1], state);
2294        } else if self.show_log {
2295            let bottom = Layout::default()
2296                .direction(Direction::Vertical)
2297                .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
2298                .split(sections[1]);
2299            self.draw_tree(frame, bottom[0], state);
2300            self.draw_log(frame, bottom[1], state);
2301        } else {
2302            self.draw_tree(frame, sections[1], state);
2303        }
2304
2305        self.draw_footer(frame, sections[2]);
2306
2307        // Paused banner, top-right of the header row. Small and
2308        // readable, doesn't displace other header content.
2309        if self.paused {
2310            let banner = " ⏸ PAUSED (p to resume) ";
2311            let w = banner.chars().count() as u16;
2312            if sections[0].width > w + 2 {
2313                let x = sections[0].x + sections[0].width - w - 1;
2314                let r = Rect {
2315                    x,
2316                    y: sections[0].y,
2317                    width: w,
2318                    height: 1,
2319                };
2320                frame.render_widget(Clear, r);
2321                frame.render_widget(
2322                    Paragraph::new(Span::styled(
2323                        banner,
2324                        Style::default().fg(colors::PHASE_FAILED).bold(),
2325                    )),
2326                    r,
2327                );
2328            }
2329        }
2330
2331        // Control-edit prompt renders above the footer as a
2332        // 2-line overlay (input line + result line). We clear
2333        // the region first so the footer text doesn't bleed
2334        // through. See SRD 23 §"TUI surface (sketch)".
2335        if let Some(ref prompt) = self.edit_prompt {
2336            let h = 2u16;
2337            if area.height > h + 1 {
2338                let r = Rect {
2339                    x: area.x,
2340                    y: area.y + area.height - h - 1,
2341                    width: area.width,
2342                    height: h,
2343                };
2344                frame.render_widget(Clear, r);
2345                let input_line = format!("  edit control › {}_", prompt.buffer);
2346                let result_line = match &prompt.last_result {
2347                    None => "     (name=value, Enter submits, Esc cancels)".to_string(),
2348                    Some(Ok(msg)) => format!("     ✓ {msg}"),
2349                    Some(Err(msg)) => format!("     ✗ {msg}"),
2350                };
2351                let rows = Layout::default()
2352                    .direction(Direction::Vertical)
2353                    .constraints([Constraint::Length(1), Constraint::Length(1)])
2354                    .split(r);
2355                frame.render_widget(
2356                    Paragraph::new(Span::styled(input_line, Style::default().bold())),
2357                    rows[0],
2358                );
2359                let result_style = match &prompt.last_result {
2360                    Some(Err(_)) => Style::default().fg(colors::PHASE_FAILED),
2361                    Some(Ok(_)) => Style::default().fg(colors::PHASE_DONE),
2362                    None => Style::default(),
2363                };
2364                frame.render_widget(
2365                    Paragraph::new(Span::styled(result_line, result_style)),
2366                    rows[1],
2367                );
2368            }
2369        }
2370
2371        // Help overlay is rendered last so it sits above everything.
2372        if self.show_help {
2373            self.draw_help(frame, area);
2374        }
2375    }
2376
2377    /// Centered help overlay listing every key binding. Dismissed with
2378    /// `?` (toggle) or `Esc`.
2379    fn draw_help(&self, frame: &mut Frame, area: Rect) {
2380        let entries: &[(&str, &str)] = &[
2381            ("q", "dismiss TUI (single tap); triple-tap to exit nmbrs"),
2382            ("C-c", "interrupt: restores the terminal and sends SIGINT"),
2383            ("?", "toggle this help panel"),
2384            ("␣", "focus tree, snap LOD=Default, track active phase"),
2385            ("↑ / ↓", "move tree selection"),
2386            ("← / →", "decrease / increase tree level of detail"),
2387            ("⏎", "expand / collapse selected phase"),
2388            ("esc", "close help, then collapse, then unfocus, then quit"),
2389            ("l", "toggle log panel"),
2390            ("C-l", "force a full screen redraw"),
2391            ("p", "pause / resume the display"),
2392            (
2393                "P",
2394                "dump the current screen to logs/<session>/tui_<ts>.dump",
2395            ),
2396            ("click", "focus tree at the clicked phase"),
2397            (
2398                "wheel",
2399                "scroll tree (tweened); snaps back to tail at bottom",
2400            ),
2401            ("╪", "latency range: peak over the last 5s"),
2402            ("╫", "latency range: peak over the last 10s"),
2403            ("╬", "latency range: 5s + 10s peaks on the same cell"),
2404        ];
2405
2406        // Size the panel around the content: widest "key" + " │ " + widest desc.
2407        let key_w = entries
2408            .iter()
2409            .map(|(k, _)| k.chars().count())
2410            .max()
2411            .unwrap_or(3);
2412        let desc_w = entries
2413            .iter()
2414            .map(|(_, d)| d.chars().count())
2415            .max()
2416            .unwrap_or(0);
2417        let inner_w = key_w + 3 + desc_w; // "key │ desc"
2418        let panel_w = (inner_w as u16 + 4).min(area.width.saturating_sub(4));
2419        let panel_h = (entries.len() as u16 + 4).min(area.height.saturating_sub(2));
2420
2421        let x = area.x + area.width.saturating_sub(panel_w) / 2;
2422        let y = area.y + area.height.saturating_sub(panel_h) / 2;
2423        let rect = Rect {
2424            x,
2425            y,
2426            width: panel_w,
2427            height: panel_h,
2428        };
2429
2430        // Clear underneath so the overlay reads cleanly over whatever
2431        // was drawn below.
2432        frame.render_widget(Clear, rect);
2433
2434        let block = Block::default()
2435            .borders(Borders::ALL)
2436            .border_style(Style::default().fg(colors::EMPHASIS))
2437            .title(Span::styled(
2438                " Help ",
2439                Style::default().fg(colors::EMPHASIS).bold(),
2440            ));
2441        let inner = block.inner(rect);
2442        frame.render_widget(block, rect);
2443
2444        let mut lines: Vec<Line> = Vec::with_capacity(entries.len());
2445        for (key, desc) in entries {
2446            lines.push(Line::from(vec![
2447                Span::styled(
2448                    format!(" {:key_w$} ", key, key_w = key_w),
2449                    Style::default().fg(colors::EMPHASIS).bold(),
2450                ),
2451                Span::styled("│ ", Style::default().fg(colors::BORDER)),
2452                Span::styled(*desc, Style::default().fg(colors::TEXT)),
2453            ]));
2454        }
2455        frame.render_widget(Paragraph::new(lines), inner);
2456    }
2457
2458    fn draw_header(&self, frame: &mut Frame, area: Rect, state: &RunState) {
2459        let elapsed_s = state.elapsed_secs();
2460        let elapsed = widgets::format_elapsed(elapsed_s);
2461
2462        // Phase ETA: based on cursor progress in whichever phase is
2463        // currently running (first one, by map iteration order).
2464        // Multi-phase scenarios will need a per-phase ETA attached
2465        // to each phase's detail block; header only shows one.
2466        let phase_eta = state.first_active().and_then(|a| {
2467            if a.ops_finished > 0 && a.cursor_extent > 0 {
2468                let phase_elapsed = (state.elapsed_secs() - a.session_started).max(0.0);
2469                let fraction = a.ops_finished as f64 / a.cursor_extent as f64;
2470                if fraction > 0.01 {
2471                    let total_est = phase_elapsed / fraction;
2472                    Some(widgets::format_elapsed(total_est - phase_elapsed))
2473                } else {
2474                    None
2475                }
2476            } else {
2477                None
2478            }
2479        });
2480
2481        let block = Block::default()
2482            .borders(Borders::ALL)
2483            .border_style(Style::default().fg(colors::BORDER))
2484            .title(Span::styled(
2485                " nmbrs ",
2486                Style::default().fg(colors::EMPHASIS).bold(),
2487            ));
2488
2489        let mut spans = vec![
2490            Span::styled(" workload: ", Style::default().fg(colors::DIM)),
2491            Span::styled(&state.workload_file, Style::default().fg(colors::TEXT)),
2492            Span::styled("  scenario: ", Style::default().fg(colors::DIM)),
2493            Span::styled(&state.scenario_name, Style::default().fg(colors::TEXT)),
2494            Span::styled("  elapsed: ", Style::default().fg(colors::DIM)),
2495            Span::styled(elapsed, Style::default().fg(colors::EMPHASIS).bold()),
2496        ];
2497
2498        // Phase-progress counter: how far along the pre-mapped
2499        // plan are we? `current` is the largest `seq` of any
2500        // phase that's reached Running, Completed, or Failed —
2501        // i.e. the phase number the runtime is on (or just
2502        // finished). `total` comes from the pre-mapped tree.
2503        // Hidden until the pre-map has installed (`total > 0`)
2504        // so we don't print `phase 0/0` during scenario startup.
2505        let total = state.total_phases();
2506        if total > 0 {
2507            let current = state
2508                .phases
2509                .iter()
2510                .filter(|p| p.kind == crate::state::EntryKind::Phase)
2511                .filter(|p| !matches!(p.status, PhaseStatus::Pending))
2512                .filter_map(|p| p.seq)
2513                .max()
2514                .unwrap_or(0);
2515            spans.push(Span::styled("  phase ", Style::default().fg(colors::DIM)));
2516            spans.push(Span::styled(
2517                format!("{current}/{total}"),
2518                Style::default().fg(colors::EMPHASIS).bold(),
2519            ));
2520        }
2521
2522        if let Some(eta) = phase_eta {
2523            spans.push(Span::styled(
2524                "  phase ETA: ",
2525                Style::default().fg(colors::DIM),
2526            ));
2527            spans.push(Span::styled(eta, Style::default().fg(colors::PHASE_ACTIVE)));
2528        }
2529        let line1 = Line::from(spans);
2530
2531        let para = Paragraph::new(line1).block(block);
2532        frame.render_widget(para, area);
2533    }
2534
2535    /// Build the fixed-width left status margin for a tree row: three
2536    /// consistent slots — a count, this leaf's cumulative time, and the
2537    /// session's cumulative time — followed (by the caller) with the `│`
2538    /// divider that separates the timing/progress margin from the semantic
2539    /// view. For a phase leaf the slots read as `[N/T]`, the phase's total
2540    /// time, and the session clock at this phase. Times persist after the
2541    /// leaf finishes (completed/failed use the frozen values); a running
2542    /// leaf shows live values; pending shows `—`. Scope rows (containers,
2543    /// not leaves) get a blank margin of the same width so the `│` column
2544    /// stays aligned down the whole tree. The slot *types* are uniform;
2545    /// their *meaning* specializes per leaf kind (and, later, per op).
2546    fn status_margin(&self, phase: &crate::state::PhaseEntry, state: &RunState) -> String {
2547        use crate::state::{EntryKind, PhaseStatus};
2548        let total = state.total_phases();
2549        if phase.kind == EntryKind::Scope {
2550            // Containers, not leaves — fully blank margin, same width.
2551            return " ".repeat(Self::margin_width(total));
2552        }
2553        let count = match phase.seq {
2554            Some(seq) => format!("[{seq}/{total}]"),
2555            None => String::new(),
2556        };
2557        let (leaf, sess): (Option<f64>, Option<f64>) = match &phase.status {
2558            PhaseStatus::Running => (
2559                state
2560                    .active_phase(&phase.name, &phase.labels)
2561                    .map(|a| (state.elapsed_secs() - a.session_started).max(0.0)),
2562                Some(state.elapsed_secs()),
2563            ),
2564            PhaseStatus::Completed | PhaseStatus::Failed(_) => {
2565                (phase.duration_secs, phase.session_elapsed)
2566            }
2567            PhaseStatus::Pending => (None, None),
2568        };
2569        Self::margin_fmt(total, &count, leaf, sess)
2570    }
2571
2572    /// Op-leaf variant of the status margin (SRD-63). Same three slots and the
2573    /// same fixed width as the phase margin (so the `│` column stays aligned),
2574    /// specialized: count = `[i/N]` within the phase, leaf-time = the op's
2575    /// execution time, session-time = the session clock at the op.
2576    fn op_status_margin(
2577        &self,
2578        op: &crate::state::OpEntry,
2579        op_total: usize,
2580        state: &RunState,
2581    ) -> String {
2582        use crate::state::PhaseStatus;
2583        let count = format!("[{}/{}]", op.seq + 1, op_total);
2584        let (leaf, sess): (Option<f64>, Option<f64>) = match &op.status {
2585            PhaseStatus::Running => (
2586                Some((state.elapsed_secs() - op.session_started).max(0.0)),
2587                Some(state.elapsed_secs()),
2588            ),
2589            PhaseStatus::Completed | PhaseStatus::Failed(_) => {
2590                (op.duration_secs, op.session_elapsed)
2591            }
2592            PhaseStatus::Pending => (None, None),
2593        };
2594        Self::margin_fmt(state.total_phases(), &count, leaf, sess)
2595    }
2596
2597    /// Fixed total width of the status margin, driven by `total_phases`'
2598    /// digit width so every row's divider aligns.
2599    fn margin_width(total_phases: usize) -> usize {
2600        let tw = total_phases.to_string().len().max(1);
2601        // Mark · " " · count · " " · leaf(8) · " " · session(8) — must track
2602        // `widgets::margin_body_width`, which the log-only surface uses, or the
2603        // two surfaces stop aligning with each other.
2604        widgets::TIMING_MARK.chars().count() + 1 + (tw * 2 + 3) + 1 + 8 + 1 + 8
2605    }
2606
2607    /// Format the margin from parts: `count` left-padded to the fixed count
2608    /// field, then the two right-aligned time slots (`—` when absent).
2609    fn margin_fmt(
2610        total_phases: usize,
2611        count: &str,
2612        leaf: Option<f64>,
2613        sess: Option<f64>,
2614    ) -> String {
2615        let tw = total_phases.to_string().len().max(1);
2616        let count_w = tw * 2 + 3;
2617        let leaf_s = leaf
2618            .map(widgets::format_dur_compact)
2619            .unwrap_or_else(|| "—".into());
2620        let sess_s = sess
2621            .map(widgets::format_dur_compact)
2622            .unwrap_or_else(|| "—".into());
2623        format!(
2624            "{} {count:<count_w$} {leaf_s:>8} {sess_s:>8}",
2625            widgets::TIMING_MARK
2626        )
2627    }
2628
2629    fn draw_tree(&self, frame: &mut Frame, area: Rect, state: &RunState) {
2630        // ActivePhase LOD renders as a chromeless single-phase
2631        // dashboard — no tree rows, no scope headers, title
2632        // repurposed to name the active phase(s). Delegates
2633        // entirely to a dedicated renderer so the tree path below
2634        // stays focused on the tree-shaped LODs.
2635        if self.tree_lod == TreeLod::ActivePhase {
2636            self.draw_active_phase_panel(frame, area, state);
2637            return;
2638        }
2639
2640        let has_focus = self.focused == Some(FocusedPane::Tree);
2641        let title_style = if has_focus {
2642            Style::default().fg(colors::EMPHASIS).bold()
2643        } else {
2644            Style::default().fg(colors::TEXT)
2645        };
2646        let lod_tag = format!(" [LOD:{}] ", self.tree_lod.label());
2647        let block = Block::default()
2648            .borders(Borders::ALL)
2649            .border_style(Style::default().fg(if has_focus {
2650                colors::EMPHASIS
2651            } else {
2652                colors::BORDER
2653            }))
2654            .title(Line::from(vec![
2655                Span::styled(" Scenario Tree ", title_style),
2656                Span::styled(lod_tag, Style::default().fg(colors::DIM)),
2657            ]));
2658
2659        let inner = block.inner(area);
2660        frame.render_widget(block, area);
2661
2662        // Hidden LOD renders nothing — the block border + title stay
2663        // (so the user can see they're in a tree pane with LOD=off
2664        // and press right-arrow to re-reveal).
2665        if self.tree_lod == TreeLod::Hidden {
2666            return;
2667        }
2668
2669        let mut lines: Vec<Line> = Vec::new();
2670        // Focus-mode bookkeeping: if no running phases exist, we
2671        // need to show a waiting/done placeholder instead of an
2672        // empty canvas. Tracked here because we can emit it after
2673        // the regular iteration finds no running phases to render.
2674        let mut focus_emitted_any = false;
2675        for (i, phase) in state.phases.iter().enumerate() {
2676            // LOD gating:
2677            //   Minimal + Focus: omit scope headers.
2678            //   Focus also omits pending/completed/failed phases —
2679            //     only running ones render, each fully expanded.
2680            //   Default/Maximal show scopes as grouping anchors.
2681            if matches!(self.tree_lod, TreeLod::Minimal | TreeLod::Focus)
2682                && phase.kind == crate::state::EntryKind::Scope
2683            {
2684                continue;
2685            }
2686            if self.tree_lod == TreeLod::Focus
2687                && phase.kind == crate::state::EntryKind::Phase
2688                && !matches!(phase.status, crate::state::PhaseStatus::Running)
2689            {
2690                continue;
2691            }
2692
2693            // Indentation: at Minimal / Focus LOD, scopes are
2694            // hidden, so preserving `phase.depth` would make
2695            // children of hidden scopes look like descendants of
2696            // the previous visible phase. Flatten to depth 0 —
2697            // dimensional labels already disambiguate the
2698            // iterations, so the hierarchy isn't lost.
2699            let effective_depth = if matches!(self.tree_lod, TreeLod::Minimal | TreeLod::Focus) {
2700                0
2701            } else {
2702                phase.depth
2703            };
2704            focus_emitted_any = true;
2705            let indent = "  ".repeat(effective_depth);
2706            // Two-column left margin: selection marker + its trailing space.
2707            // `●` in column 0 means "this entry has focus". Non-selected
2708            // entries render two spaces, so the following content lines up
2709            // the same either way.
2710            let is_selected = has_focus && self.tree_selected == Some(i);
2711            let marker: Span = if is_selected {
2712                Span::styled("● ", Style::default().fg(colors::EMPHASIS).bold())
2713            } else {
2714                Span::raw("  ")
2715            };
2716
2717            // Scope headers render as a distinct line: no status glyph,
2718            // italic-ish group label. Keeps the hierarchy visible without
2719            // making peer phases look like children of each other.
2720            //
2721            // Scope nodes carry their description in `phase.name`
2722            // (e.g. `"for_each profile in [...]"`); `phase.labels`
2723            // is always empty for scopes (see scene_tree::NodeKind
2724            // doc). Earlier code rendered `labels` and got bare
2725            // `┬ ` lines.
2726            if phase.kind == crate::state::EntryKind::Scope {
2727                lines.push(Line::from(vec![
2728                    // Scopes are containers, not execution leaves — blank
2729                    // margin, but keep the divider so the `│` column stays
2730                    // unbroken down the tree.
2731                    Span::styled(
2732                        self.status_margin(phase, state),
2733                        Style::default().fg(colors::DIM),
2734                    ),
2735                    Span::styled(" │ ", Style::default().fg(colors::BORDER)),
2736                    marker,
2737                    Span::styled(format!("{indent}┬ "), Style::default().fg(colors::BORDER)),
2738                    Span::styled(&phase.name, Style::default().fg(colors::TEXT).italic()),
2739                ]));
2740                continue;
2741            }
2742
2743            // Health tint = line color. Running phases are always
2744            // yellow (they haven't finished, so error counts aren't
2745            // meaningful yet). Completed phases are green/orange/red
2746            // on a sliding scale keyed to the observed error rate,
2747            // so the user can see at a glance whether a phase went
2748            // clean, had blips, or degraded badly.
2749            let health_color = phase_health_color(phase);
2750            let running_spinner = spinner_frame();
2751            let (icon, icon_color) = match &phase.status {
2752                PhaseStatus::Completed => ("✓", health_color),
2753                PhaseStatus::Running => (running_spinner, health_color),
2754                PhaseStatus::Pending => ("○", colors::PHASE_PENDING),
2755                PhaseStatus::Failed(_) => ("✗", colors::PHASE_FAILED),
2756            };
2757            let is_running = matches!(phase.status, PhaseStatus::Running);
2758            let name_style = match &phase.status {
2759                PhaseStatus::Running => Style::default().fg(health_color).bold(),
2760                PhaseStatus::Completed => Style::default().fg(health_color),
2761                PhaseStatus::Failed(_) => Style::default().fg(colors::PHASE_FAILED).bold(),
2762                _ => Style::default().fg(colors::DIM),
2763            };
2764            // Labels stay dim for completed so the health color on the
2765            // phase name is the eye-catching cue; for running they pick
2766            // up the yellow tint too so the whole live line reads hot.
2767            let label_color = if is_running {
2768                health_color
2769            } else {
2770                colors::DIM
2771            };
2772
2773            // Left status margin: a fixed-width column of
2774            // count · leaf-time · session-time, then the `│` that
2775            // separates the timing/progress margin from the semantic
2776            // view. The `[N/T]` count and this leaf's cumulative time
2777            // live here now (persisted), not inline on the right.
2778            let mut spans = vec![
2779                Span::styled(
2780                    self.status_margin(phase, state),
2781                    Style::default().fg(colors::DIM),
2782                ),
2783                Span::styled(" │ ", Style::default().fg(colors::BORDER)),
2784                marker,
2785                Span::styled(format!("{indent}{icon} "), Style::default().fg(icon_color)),
2786            ];
2787
2788            spans.push(Span::styled(&phase.name, name_style));
2789
2790            if !phase.labels.is_empty() {
2791                spans.push(Span::styled(
2792                    format!(" ({})", phase.labels),
2793                    Style::default().fg(label_color),
2794                ));
2795            }
2796
2797            if phase.op_count > 0 {
2798                // Structural metadata — number of op-template
2799                // entries declared under the phase's `ops:` key
2800                // in the YAML. Bracketed so it reads as a phase
2801                // shape (next to `qs:N` throughput) rather than
2802                // a count of executed queries. Plural matches
2803                // the count.
2804                spans.push(Span::styled(
2805                    format!(
2806                        "  [{} op {}]",
2807                        phase.op_count,
2808                        if phase.op_count == 1 {
2809                            "template"
2810                        } else {
2811                            "templates"
2812                        }
2813                    ),
2814                    Style::default().fg(colors::DIM),
2815                ));
2816            }
2817
2818            match &phase.status {
2819                PhaseStatus::Completed => {
2820                    // This leaf's cumulative time now lives in the left
2821                    // status margin (persisted), not inline here.
2822                    // Attach the completion summary so the tree acts
2823                    // as a post-hoc record of what each phase produced.
2824                    // Ordered for "tell me the key story" reading:
2825                    //   1. cycles + rate (the engine-level throughput)
2826                    //   2. adapter-declared domain metrics with rates
2827                    //      (rows_inserted/s, etc. — the thing the
2828                    //      workload actually cares about)
2829                    //   3. relevancy metrics (recall/precision) — the
2830                    //      KEY metric for ANN/search workloads, so it
2831                    //      must be visible without expansion
2832                    //   4. latency percentiles
2833                    if let Some(ref sm) = phase.summary {
2834                        if sm.ops_finished > 0 {
2835                            // Label the cycle count/rate after the
2836                            // cursor name (`rows:N @R/s`) so it
2837                            // matches the phase detail's wording.
2838                            // Falls back to `cycles:` when the
2839                            // phase declares no cursor. Adapter
2840                            // counters (rows_inserted, etc.) show
2841                            // separately below.
2842                            let unit = cursor_count_label(&sm.cursor_name);
2843                            spans.push(Span::styled(
2844                                format!(
2845                                    "  {unit}:{} @{}/s",
2846                                    widgets::format_count(sm.ops_finished),
2847                                    widgets::format_rate(sm.ops_per_sec)
2848                                ),
2849                                Style::default().fg(colors::TEXT),
2850                            ));
2851                        }
2852                        // Adapter-declared workload counters with rates
2853                        // — this is "rows/s" for CQL INSERT workloads,
2854                        // "queries/s" for search workloads, etc.
2855                        for (name, total, rate) in &sm.adapter_counters {
2856                            if *total == 0 {
2857                                continue;
2858                            }
2859                            // `_batch_writes` and friends are derived-metric
2860                            // denominators — hidden from the chip row.
2861                            if nmbrs_runtime::is_internal_counter(name) {
2862                                continue;
2863                            }
2864                            spans.push(Span::styled(
2865                                format!(
2866                                    "  {name}:{}@{}/s",
2867                                    widgets::format_count(*total),
2868                                    widgets::format_rate(*rate)
2869                                ),
2870                                Style::default().fg(colors::PHASE_ACTIVE),
2871                            ));
2872                        }
2873                        // Relevancy (recall@k, precision@k, ...) — the
2874                        // headline metric for ANN workloads. Rendered
2875                        // in EMPHASIS + bold so it reads louder than
2876                        // plain counts.
2877                        for (name, _window_mean, total_mean, total_count, _window_len) in
2878                            &sm.relevancy
2879                        {
2880                            if *total_count == 0 {
2881                                continue;
2882                            }
2883                            spans.push(Span::styled(
2884                                format!("  {name}:{:.4}", total_mean),
2885                                Style::default().fg(colors::EMPHASIS).bold(),
2886                            ));
2887                        }
2888                        if sm.p50_nanos > 0 {
2889                            spans.push(Span::styled(
2890                                format!(
2891                                    "  p50:{}  p99:{}",
2892                                    widgets::format_nanos(sm.p50_nanos),
2893                                    widgets::format_nanos(sm.p99_nanos)
2894                                ),
2895                                Style::default().fg(colors::LAT_P50),
2896                            ));
2897                        }
2898                    }
2899                }
2900                PhaseStatus::Failed(err) => {
2901                    spans.push(Span::styled(
2902                        format!("  {err}"),
2903                        Style::default().fg(colors::PHASE_FAILED),
2904                    ));
2905                }
2906                _ => {}
2907            }
2908
2909            lines.push(Line::from(spans));
2910
2911            // Detail block: rendered under the phase when the user has
2912            // expanded it (Default LOD), or under every phase with data
2913            // (Maximal LOD). Same indent as the parent plus a pipe
2914            // gutter so the relationship is visible at a glance.
2915            if self.show_detail_for(i, phase) {
2916                // If this entry is the currently active phase, pull
2917                // live progress stats from the active-phases map;
2918                // otherwise fall back to the end-of-phase summary
2919                // snapshot.
2920                let live = state.active_phase(&phase.name, &phase.labels);
2921                // Detail pipe placement:
2922                //   phase icon sits at column 2+(depth*2); we want
2923                //   the continuation pipe one level deeper so it
2924                //   reads as "this belongs to the phase above"
2925                //   rather than drifting into the next sibling's
2926                //   indent column. `indent + 2 spaces` puts the
2927                //   pipe directly under the phase name's first
2928                //   character, matching the tree's visual rhythm.
2929                let detail_indent = format!("{indent}  ");
2930                for detail_line in self.format_phase_detail_with_live(phase, live) {
2931                    let mut spans: Vec<Span<'static>> =
2932                        Vec::with_capacity(detail_line.spans.len() + 2);
2933                    spans.push(Span::raw("  "));
2934                    spans.push(Span::styled(
2935                        format!("{detail_indent}│ "),
2936                        Style::default().fg(colors::BORDER),
2937                    ));
2938                    spans.extend(detail_line.spans);
2939                    lines.push(Line::from(spans));
2940                }
2941
2942                // Drill view: when the user has pressed Right
2943                // on this expanded phase, render the stanza op
2944                // list under the detail block. One header row
2945                // ("ops:") plus one row per op name; the row
2946                // matching `drill_op_idx` gets a `▸` cursor
2947                // glyph so the selection is visible inside the
2948                // sub-list. The drill row count must match
2949                // `rendered_lines_for` exactly so scroll math
2950                // stays consistent (see SRD 62 §"Tree scroll").
2951                if self.tree_drilled == Some(i) {
2952                    lines.push(Line::from(vec![
2953                        Span::raw("  "),
2954                        Span::styled(
2955                            format!("{detail_indent}│ "),
2956                            Style::default().fg(colors::BORDER),
2957                        ),
2958                        Span::styled("ops:", Style::default().fg(colors::DIM).italic()),
2959                    ]));
2960                    for (op_idx, op_name) in phase.op_names.iter().enumerate() {
2961                        let is_drill_sel = op_idx == self.drill_op_idx;
2962                        let cursor_glyph = if is_drill_sel { "▸ " } else { "  " };
2963                        let cursor_color = if is_drill_sel {
2964                            colors::EMPHASIS
2965                        } else {
2966                            colors::BORDER
2967                        };
2968                        let name_style = if is_drill_sel {
2969                            Style::default().fg(colors::TEXT).bold()
2970                        } else {
2971                            Style::default().fg(colors::TEXT)
2972                        };
2973                        lines.push(Line::from(vec![
2974                            Span::raw("  "),
2975                            Span::styled(
2976                                format!("{detail_indent}│ "),
2977                                Style::default().fg(colors::BORDER),
2978                            ),
2979                            Span::styled(cursor_glyph, Style::default().fg(cursor_color)),
2980                            Span::styled(op_name.clone(), name_style),
2981                        ]));
2982                    }
2983                }
2984            }
2985
2986            // Op-level status leaves (SRD-63): ops that declared
2987            // `readout: visible` surface as their own timed rows,
2988            // indented one level under the phase and rendered whenever
2989            // the phase row renders (independent of expand/drill) —
2990            // opting an op in is a request to always see its live
2991            // status. The `│` divider + margin columns match the phase
2992            // rows so timing/session numbers stay in the left margin.
2993            // Row count here must equal `op_rows_for`.
2994            if let Some(ops) = state.phase_ops.get(&phase.node_id) {
2995                let op_total = ops.len();
2996                for op in ops {
2997                    let (op_icon, op_color) = match &op.status {
2998                        PhaseStatus::Completed => ("✓", colors::PHASE_DONE),
2999                        PhaseStatus::Running => (spinner_frame(), colors::PHASE_ACTIVE),
3000                        PhaseStatus::Pending => ("○", colors::PHASE_PENDING),
3001                        PhaseStatus::Failed(_) => ("✗", colors::PHASE_FAILED),
3002                    };
3003                    let op_name_style = match &op.status {
3004                        PhaseStatus::Running => Style::default().fg(colors::PHASE_ACTIVE).bold(),
3005                        PhaseStatus::Completed => Style::default().fg(colors::TEXT),
3006                        PhaseStatus::Failed(_) => Style::default().fg(colors::PHASE_FAILED).bold(),
3007                        _ => Style::default().fg(colors::DIM),
3008                    };
3009                    let mut op_spans = vec![
3010                        Span::styled(
3011                            self.op_status_margin(op, op_total, state),
3012                            Style::default().fg(colors::DIM),
3013                        ),
3014                        Span::styled(" │ ", Style::default().fg(colors::BORDER)),
3015                        // Op rows aren't independently tree-selectable —
3016                        // blank marker column keeps content aligned with
3017                        // phase rows.
3018                        Span::raw("  "),
3019                        Span::styled(
3020                            format!("{indent}  {op_icon} "),
3021                            Style::default().fg(op_color),
3022                        ),
3023                        Span::styled(op.name.clone(), op_name_style),
3024                    ];
3025                    if let PhaseStatus::Failed(err) = &op.status {
3026                        op_spans.push(Span::styled(
3027                            format!("  {err}"),
3028                            Style::default().fg(colors::PHASE_FAILED),
3029                        ));
3030                    }
3031                    lines.push(Line::from(op_spans));
3032                }
3033            }
3034        }
3035
3036        // Focus LOD with zero running phases: emit a placeholder so
3037        // the canvas isn't empty. Live vs. done is a component-tree
3038        // question (SRD 62 §"Scenario done?"):
3039        //   Live   → running_phase_count > 0
3040        //   Waiting → any pre-mapped Pending phase (component tree
3041        //             doesn't know about pre-map; that info lives
3042        //             in state.phases from scenario_pre_mapped)
3043        //   Done   → neither — scenario has nothing left to do.
3044        if self.tree_lod == TreeLod::Focus && !focus_emitted_any {
3045            let live = self.metrics_query.running_phase_count() > 0;
3046            let any_pending = state.phases.iter().any(|p| {
3047                p.kind == crate::state::EntryKind::Phase
3048                    && matches!(p.status, crate::state::PhaseStatus::Pending)
3049            });
3050            let (glyph, msg, color) = if live {
3051                // Running phases exist in the component tree but
3052                // haven't appeared in `state.phases` yet — a tiny
3053                // race window during phase start. Show waiting.
3054                ("○", "waiting for phase…", colors::PHASE_PENDING)
3055            } else if any_pending {
3056                ("○", "waiting for phase…", colors::PHASE_PENDING)
3057            } else {
3058                ("✓", "scenario complete", colors::PHASE_DONE)
3059            };
3060            lines.push(Line::from(vec![
3061                Span::raw("  "),
3062                Span::styled(format!("{glyph} "), Style::default().fg(color)),
3063                Span::styled(msg, Style::default().fg(colors::DIM).italic()),
3064            ]));
3065        }
3066
3067        // Pick the visible window. Default to auto-tail; if the user
3068        // has grabbed scroll focus, honor their offset. `tree_display`
3069        // carries the fractional, eased position — advanced in the
3070        // event loop before each draw — so the viewport tweens between
3071        // targets instead of snapping. The clamp deliberately allows
3072        // `start > tail` so a Space-pinned selection sits at the top
3073        // row even when the content is shorter than the panel; the
3074        // renderer's `skip` past the end yields fewer than `visible`
3075        // lines and Paragraph leaves the trailing rows blank.
3076        let visible = inner.height as usize;
3077        let total = lines.len();
3078        let start = self.tree_display.round().max(0.0) as usize;
3079        let start = start.min(total);
3080        let visible_lines: Vec<Line> = lines.into_iter().skip(start).collect();
3081
3082        frame.render_widget(Paragraph::new(visible_lines), inner);
3083
3084        // Scrollbar on the right edge of the block, drawn only when the
3085        // content overflows. Gives the user a visual sense of where
3086        // they are in the list and how much is off-screen.
3087        if total > visible {
3088            let mut sb_state = ScrollbarState::new(total)
3089                .position(start)
3090                .viewport_content_length(visible);
3091            let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight)
3092                .begin_symbol(None)
3093                .end_symbol(None)
3094                .style(Style::default().fg(colors::BORDER))
3095                .thumb_style(Style::default().fg(colors::EMPHASIS));
3096            frame.render_stateful_widget(scrollbar, area, &mut sb_state);
3097        }
3098    }
3099
3100    /// Advance the scroll animation toward the current target. Called
3101    /// once per frame while `draw_tree` runs, so the render reflects the
3102    /// tween's current intermediate position. If the target changed out
3103    /// from under the anim (e.g. auto-tail shifted because a new phase
3104    /// was added), re-aim without resetting time.
3105    fn advance_scroll_anim(&mut self, target: f32) {
3106        match self.tree_anim {
3107            None => {
3108                // No anim — just sync the display to the target.
3109                self.tree_display = target;
3110            }
3111            Some((from, to, started, duration)) => {
3112                // If the live target drifted away from the anim's `to`,
3113                // rewrite `to`. Don't restart the clock; the motion just
3114                // glides to the new endpoint.
3115                let to = if (to - target).abs() > 0.01 {
3116                    target
3117                } else {
3118                    to
3119                };
3120                let t = (started.elapsed().as_secs_f32() / duration.as_secs_f32()).clamp(0.0, 1.0);
3121                let eased = Self::smoothstep(t);
3122                self.tree_display = from + (to - from) * eased;
3123                if t >= 1.0 {
3124                    self.tree_display = to;
3125                    self.tree_anim = None;
3126                } else {
3127                    self.tree_anim = Some((from, to, started, duration));
3128                }
3129            }
3130        }
3131    }
3132
3133    /// ActivePhase LOD renderer — a chromeless dashboard showing
3134    /// only the currently running phase(s)'s detail block(s).
3135    /// Replaces the scenario-tree panel for this LOD.
3136    ///
3137    /// Title is repurposed:
3138    ///   - one running phase  → " Phase: <name> (<labels>) "
3139    ///   - N running phases   → " Phases: <N> running "
3140    ///   - zero running       → placeholder banner inside the panel
3141    ///
3142    /// Detail rows come from the same `format_phase_detail_with_live`
3143    /// used by every other LOD, so the shape and contents match —
3144    /// just stripped of phase-header rows and tree-indent pipes.
3145    fn draw_active_phase_panel(&self, frame: &mut Frame, area: Rect, state: &RunState) {
3146        // Collect running phase entries in declaration order so the
3147        // panel reads top-to-bottom matching the tree in other LODs.
3148        let running: Vec<&crate::state::PhaseEntry> = state
3149            .phases
3150            .iter()
3151            .filter(|p| {
3152                p.kind == crate::state::EntryKind::Phase
3153                    && matches!(p.status, crate::state::PhaseStatus::Running)
3154            })
3155            .collect();
3156
3157        let has_focus = self.focused == Some(FocusedPane::Tree);
3158        let title_style = if has_focus {
3159            Style::default().fg(colors::EMPHASIS).bold()
3160        } else {
3161            Style::default().fg(colors::TEXT)
3162        };
3163        let lod_tag = format!(" [LOD:{}] ", self.tree_lod.label());
3164        let total = state.total_phases();
3165        let title_text = match running.len() {
3166            0 => " Phase ".to_string(),
3167            1 => {
3168                let p = running[0];
3169                let seq_prefix = match (p.seq, total) {
3170                    (Some(s), t) if t > 0 => format!("[{s}/{t}] ",),
3171                    _ => String::new(),
3172                };
3173                // Phase name + coordinates appear on the per-phase
3174                // header line in the body (`[name] (coords)` in
3175                // blue + yellow). The title carries only the
3176                // optional seq counter so it stays narrow.
3177                format!(" Phase {seq_prefix}")
3178            }
3179            n => format!(" Phases: {n} running "),
3180        };
3181        let block = Block::default()
3182            .borders(Borders::ALL)
3183            .border_style(Style::default().fg(if has_focus {
3184                colors::EMPHASIS
3185            } else {
3186                colors::BORDER
3187            }))
3188            .title(Line::from(vec![
3189                Span::styled(title_text, title_style),
3190                Span::styled(lod_tag, Style::default().fg(colors::DIM)),
3191            ]));
3192        let inner = block.inner(area);
3193        frame.render_widget(block, area);
3194
3195        // Build the content as a flat list of Lines. Each running
3196        // phase contributes its full detail block. Separator lines
3197        // appear between multiple phases; with one phase the detail
3198        // flows straight from the top of the panel.
3199        let mut lines: Vec<Line<'static>> = Vec::new();
3200        if running.is_empty() {
3201            // Empty state — same live/waiting/done logic as Focus.
3202            let live_count = self.metrics_query.running_phase_count();
3203            let any_pending = state.phases.iter().any(|p| {
3204                p.kind == crate::state::EntryKind::Phase
3205                    && matches!(p.status, crate::state::PhaseStatus::Pending)
3206            });
3207            let (glyph, msg, color) = if live_count > 0 || any_pending {
3208                ("○", "waiting for phase…", colors::PHASE_PENDING)
3209            } else {
3210                ("✓", "scenario complete", colors::PHASE_DONE)
3211            };
3212            lines.push(Line::from(vec![
3213                Span::raw("  "),
3214                Span::styled(format!("{glyph} "), Style::default().fg(color)),
3215                Span::styled(msg, Style::default().fg(colors::DIM).italic()),
3216            ]));
3217        } else {
3218            for (i, phase) in running.iter().enumerate() {
3219                // Blank-line separator between multiple running
3220                // phases — the per-phase header line below carries
3221                // the name (in blue) and coords (in yellow) so the
3222                // separator-with-name dash row is no longer needed.
3223                if i > 0 {
3224                    lines.push(Line::from(""));
3225                }
3226                // `[name] (root-first coords)` header line — phase
3227                // name in blue, coordinate tuple stack in yellow,
3228                // coordinates reordered root-first so outer scopes
3229                // lead. Combines the previous separate name-title
3230                // row and standalone-coords row into a single
3231                // scannable line that mirrors the terminal-mode
3232                // observer's phase row.
3233                let seq_prefix = match (phase.seq, total) {
3234                    (Some(s), t) if t > 0 => format!("[{s}/{t}] "),
3235                    _ => String::new(),
3236                };
3237                let mut header_spans = vec![
3238                    Span::raw("  "),
3239                    Span::styled(seq_prefix, Style::default().fg(colors::DIM)),
3240                    Span::styled(
3241                        format!("[{}]", phase.name),
3242                        Style::default().fg(colors::LOG_INFO).bold(),
3243                    ),
3244                ];
3245                if !phase.labels.is_empty() {
3246                    let root_first = crate::widgets::coords_root_first(&phase.labels);
3247                    header_spans.push(Span::raw(" "));
3248                    header_spans.push(Span::styled(
3249                        root_first,
3250                        Style::default().fg(colors::PHASE_RUNNING_TINT).bold(),
3251                    ));
3252                }
3253                lines.push(Line::from(header_spans));
3254                let live = state.active_phase(&phase.name, &phase.labels);
3255                for detail_line in self.format_phase_detail_with_live(phase, live) {
3256                    lines.push(detail_line);
3257                }
3258            }
3259        }
3260
3261        // Clip to the visible rows. No scroll tween in this LOD —
3262        // detail blocks are sized to fit typical phases at 120
3263        // cols, and a single phase rarely overflows the available
3264        // space. Wider scroll behavior is a Focus-LOD concern.
3265        let visible = inner.height as usize;
3266        let clipped: Vec<Line> = lines.into_iter().take(visible).collect();
3267        frame.render_widget(Paragraph::new(clipped), inner);
3268    }
3269
3270    fn draw_log(&self, frame: &mut Frame, area: Rect, state: &RunState) {
3271        // Title carries the current min-level filter so the
3272        // operator never has to wonder why a Debug entry didn't
3273        // appear; the `D` keybinding cycles the level.
3274        let level_label = match self.log_level_filter {
3275            crate::state::LogSeverity::Debug => "≥DBG",
3276            crate::state::LogSeverity::Info => "≥INF",
3277            crate::state::LogSeverity::Warn => "≥WRN",
3278            crate::state::LogSeverity::Error => "≥ERR",
3279        };
3280        let mut title: Vec<Span> = vec![
3281            Span::styled(" Log ", Style::default().fg(colors::LOG_INFO)),
3282            Span::styled(
3283                format!("[{level_label}] "),
3284                Style::default().fg(colors::DIM),
3285            ),
3286        ];
3287        if self.tree_lod == TreeLod::Hidden {
3288            // Tree-hidden hint: pinned to the right of the level
3289            // tag so the operator sees both pieces of context.
3290            title.extend([
3291                Span::styled("— tree hidden: ", Style::default().fg(colors::DIM)),
3292                Span::styled("→", Style::default().fg(colors::EMPHASIS).bold()),
3293                Span::styled(" to restore, ", Style::default().fg(colors::DIM)),
3294                Span::styled("?", Style::default().fg(colors::EMPHASIS).bold()),
3295                Span::styled(" for help ", Style::default().fg(colors::DIM)),
3296            ]);
3297        }
3298        let block = Block::default()
3299            .borders(Borders::ALL)
3300            .border_style(Style::default().fg(colors::BORDER))
3301            .title(Line::from(title));
3302
3303        let inner = block.inner(area);
3304        frame.render_widget(block, area);
3305
3306        // Filter first, then take the tail. Filtering after
3307        // tail-slicing would erase entries that would otherwise
3308        // be visible whenever the buffer happens to end in
3309        // below-threshold severities.
3310        //
3311        // SRD-81: the log panel is **diagnostics-only**. Phase
3312        // lifecycle / outcome renders are display projections that
3313        // belong in the tree / active-phase panel (rendered natively
3314        // via `TuiReadoutSink`), not here — a multi-line ANSI outcome
3315        // render would otherwise garble as a single un-split `Span`.
3316        let filtered: Vec<&crate::state::LogEntry> = state
3317            .log_messages
3318            .iter()
3319            .filter(|e| e.tag.attached.is_none())
3320            .filter(|e| e.severity >= self.log_level_filter)
3321            .collect();
3322        let visible = inner.height as usize;
3323        let start = filtered.len().saturating_sub(visible);
3324        let lines: Vec<Line> = filtered[start..]
3325            .iter()
3326            .map(|entry| {
3327                let (prefix, color) = match entry.severity {
3328                    crate::state::LogSeverity::Debug => ("DBG", colors::LOG_DEBUG),
3329                    crate::state::LogSeverity::Info => ("INF", colors::LOG_INFO),
3330                    crate::state::LogSeverity::Warn => ("WRN", colors::LOG_WARN),
3331                    crate::state::LogSeverity::Error => ("ERR", colors::LOG_ERROR),
3332                };
3333                Line::from(vec![
3334                    Span::styled(format!("  {prefix} "), Style::default().fg(color).bold()),
3335                    Span::styled(&entry.message, Style::default().fg(colors::TEXT)),
3336                ])
3337            })
3338            .collect();
3339
3340        frame.render_widget(Paragraph::new(lines), inner);
3341    }
3342
3343    /// Cycle the log panel's min-severity filter. Order:
3344    /// `Info → Debug → Warn → Error → Info`. Default is `Info`
3345    /// so high-cadence Debug entries stay hidden unless the
3346    /// operator opts in via the `D` keybinding.
3347    fn cycle_log_level_filter(&mut self) {
3348        use crate::state::LogSeverity::*;
3349        self.log_level_filter = match self.log_level_filter {
3350            Info => Debug,
3351            Debug => Warn,
3352            Warn => Error,
3353            Error => Info,
3354        };
3355    }
3356
3357    // ── SRD-63 Push 5b/7b: readout-binder navigation ──────
3358
3359    /// Cycle focus forward through the readouts bound to
3360    /// the most-recently-fired event slot. Public for the
3361    /// `Tab` keybind. No-op when the binder hasn't fired
3362    /// yet (no slot context).
3363    pub fn cycle_readout_focus_next(&mut self) {
3364        use nmbrs_runtime::readouts::{BinderKey, ReadoutBinder};
3365        self.readout_binder
3366            .borrow_mut()
3367            .on_key(BinderKey::CycleFocusNext);
3368    }
3369
3370    /// Cycle focus backward through the most-recent slot's
3371    /// readouts. Bound to Shift-Tab.
3372    pub fn cycle_readout_focus_prev(&mut self) {
3373        use nmbrs_runtime::readouts::{BinderKey, ReadoutBinder};
3374        self.readout_binder
3375            .borrow_mut()
3376            .on_key(BinderKey::CycleFocusPrev);
3377    }
3378
3379    /// Cycle the focused readout's LOD up
3380    /// (compact → labeled → expanded → compact). Bound to
3381    /// `+`. No-op when no readout is focused.
3382    pub fn cycle_readout_lod_up(&mut self) {
3383        use nmbrs_runtime::readouts::{BinderKey, ReadoutBinder};
3384        self.readout_binder
3385            .borrow_mut()
3386            .on_key(BinderKey::CycleLodUp);
3387    }
3388
3389    /// Cycle the focused readout's LOD down. Bound to `-`.
3390    pub fn cycle_readout_lod_down(&mut self) {
3391        use nmbrs_runtime::readouts::{BinderKey, ReadoutBinder};
3392        self.readout_binder
3393            .borrow_mut()
3394            .on_key(BinderKey::CycleLodDown);
3395    }
3396
3397    /// Toggle the explanation-overlay flag. While set, every
3398    /// readout fire emits `ContentMode::Explanation` instead
3399    /// of `Value`. Bound to `\`. The held-key semantics from
3400    /// SRD-63 are approximated as a press-toggle because
3401    /// crossterm's standard polling doesn't surface key-
3402    /// release reliably.
3403    pub fn toggle_readout_overlay(&mut self) {
3404        use nmbrs_runtime::readouts::{BinderKey, ReadoutBinder};
3405        let mut b = self.readout_binder.borrow_mut();
3406        let now = !b.overlay_held();
3407        b.on_key(BinderKey::OverlayHeld(now));
3408    }
3409
3410    /// Whether the explanation overlay is currently active.
3411    /// Surface code (footer, panel render path) reads this
3412    /// to render an indicator and to pass the right
3413    /// `ContentMode` when firing the binder.
3414    pub fn readout_overlay_active(&self) -> bool {
3415        self.readout_binder.borrow().overlay_held()
3416    }
3417
3418    fn draw_footer(&self, frame: &mut Frame, area: Rect) {
3419        let overlay = if self.readout_overlay_active() {
3420            " 📖 explain"
3421        } else {
3422            ""
3423        };
3424        let line = Line::from(vec![
3425            Span::styled(" q", Style::default().fg(colors::EMPHASIS).bold()),
3426            Span::styled(": quit  ", Style::default().fg(colors::DIM)),
3427            Span::styled("↑↓", Style::default().fg(colors::EMPHASIS).bold()),
3428            Span::styled(": select  ", Style::default().fg(colors::DIM)),
3429            Span::styled("←→", Style::default().fg(colors::EMPHASIS).bold()),
3430            Span::styled(": LOD  ", Style::default().fg(colors::DIM)),
3431            Span::styled("⏎", Style::default().fg(colors::EMPHASIS).bold()),
3432            Span::styled(": expand  ", Style::default().fg(colors::DIM)),
3433            Span::styled("␣", Style::default().fg(colors::EMPHASIS).bold()),
3434            Span::styled(": track active  ", Style::default().fg(colors::DIM)),
3435            // SRD-63 Push 5b/7b readout-binder navigation:
3436            Span::styled("⇥", Style::default().fg(colors::EMPHASIS).bold()),
3437            Span::styled(": readout focus  ", Style::default().fg(colors::DIM)),
3438            Span::styled("+/-", Style::default().fg(colors::EMPHASIS).bold()),
3439            Span::styled(": readout LOD  ", Style::default().fg(colors::DIM)),
3440            Span::styled("\\", Style::default().fg(colors::EMPHASIS).bold()),
3441            Span::styled(": explain  ", Style::default().fg(colors::DIM)),
3442            Span::styled("?", Style::default().fg(colors::EMPHASIS).bold()),
3443            Span::styled(": help  ", Style::default().fg(colors::DIM)),
3444            Span::styled("esc", Style::default().fg(colors::EMPHASIS).bold()),
3445            Span::styled(": collapse/unfocus  ", Style::default().fg(colors::DIM)),
3446            Span::styled("l", Style::default().fg(colors::EMPHASIS).bold()),
3447            Span::styled(": log  ", Style::default().fg(colors::DIM)),
3448            Span::styled("p", Style::default().fg(colors::EMPHASIS).bold()),
3449            Span::styled(": pause  ", Style::default().fg(colors::DIM)),
3450            Span::styled("P", Style::default().fg(colors::EMPHASIS).bold()),
3451            Span::styled(": dump", Style::default().fg(colors::DIM)),
3452            Span::styled(overlay, Style::default().fg(colors::EMPHASIS).bold()),
3453        ]);
3454        frame.render_widget(Paragraph::new(line), area);
3455    }
3456}
3457
3458/// Pull the cycles-servicetime percentiles out of a base-cadence
3459/// frame. Used to update live display fields and history rings —
3460/// per-cadence percentile data is served from `MetricsQuery`, not
3461/// this path.
3462struct LiveLatency {
3463    min: u64,
3464    p50: u64,
3465    p90: u64,
3466    p99: u64,
3467    p999: u64,
3468    max: u64,
3469}
3470
3471fn extract_latency_from_frame(snapshot: &MetricSet) -> Option<LiveLatency> {
3472    use nmbrs_metrics::snapshot::MetricValue;
3473    let family = snapshot.family("cycles_servicetime")?;
3474    for metric in family.metrics() {
3475        if let Some(point) = metric.point()
3476            && let MetricValue::Histogram(h) = point.value()
3477        {
3478            let r = &h.reservoir;
3479            return Some(LiveLatency {
3480                min: r.min(),
3481                p50: r.value_at_quantile(0.50),
3482                p90: r.value_at_quantile(0.90),
3483                p99: r.value_at_quantile(0.99),
3484                p999: r.value_at_quantile(0.999),
3485                max: r.max(),
3486            });
3487        }
3488    }
3489    None
3490}
3491
3492// =========================================================================
3493// Terminal teardown failsafe
3494// =========================================================================
3495
3496/// RAII guard for the TUI's terminal mode changes. Enabling raw
3497/// mode, entering the alternate screen, and turning on mouse
3498/// capture happen in [`Self::enter`]; reversing all three happens
3499/// in `Drop`. This gives every `?` error path, explicit `break`,
3500/// and panic a guaranteed cleanup opportunity — without it, a
3501/// failure mid-run would leave the user's shell in raw mode with
3502/// the alternate screen buffer still active.
3503struct TerminalGuard;
3504
3505impl TerminalGuard {
3506    fn enter() -> io::Result<Self> {
3507        // Capture the pre-raw termios so the signal handler can
3508        // restore it without going through crossterm (which is
3509        // not async-signal-safe). Without this, a SIGINT during
3510        // TUI mode leaves the terminal in raw + mouse-capture
3511        // state and the user's next keystrokes spew escape codes.
3512        save_pretui_termios();
3513        terminal::enable_raw_mode()?;
3514        io::stderr().execute(EnterAlternateScreen)?;
3515        io::stderr().execute(EnableMouseCapture)?;
3516        install_signal_terminal_restore();
3517        Ok(Self)
3518    }
3519}
3520
3521impl Drop for TerminalGuard {
3522    fn drop(&mut self) {
3523        // Best-effort — Drop can't return Result. Order matters:
3524        // mouse capture off first (it piggybacks on raw mode),
3525        // then leave the alternate screen, then raw mode off.
3526        let _ = io::stderr().execute(DisableMouseCapture);
3527        let _ = io::stderr().execute(LeaveAlternateScreen);
3528        let _ = terminal::disable_raw_mode();
3529    }
3530}
3531
3532// =====================================================================
3533// Signal handlers for terminal restoration
3534// =====================================================================
3535//
3536// When the process is killed by a signal we can intercept (SIGINT,
3537// SIGTERM, SIGHUP, SIGQUIT), the normal `Drop` for `TerminalGuard`
3538// never runs — the OS just terminates the process. Without
3539// intervention, the controlling terminal is left in raw mode with
3540// mouse capture and alternate-screen buffers still active. The
3541// shell that regains control then receives mouse-event escape
3542// codes for every cursor move, which is what the user reported.
3543//
3544// The fix is a Unix signal handler that does only async-signal-safe
3545// work (`write` + `tcsetattr`), then re-raises the signal with the
3546// default disposition so the process actually exits with the
3547// expected status. SIGKILL and SIGSTOP can't be intercepted —
3548// nothing to be done about those, but they're rare in practice.
3549
3550/// Non-Unix stub: there is no termios to save — crossterm's
3551/// `disable_raw_mode` restores the Windows console mode, and the
3552/// console host resets state when the process dies, so the
3553/// signal-handler restore dance below has no Windows analogue.
3554#[cfg(not(unix))]
3555pub(crate) fn save_pretui_termios() {}
3556
3557/// Non-Unix stub for the same reason as [`save_pretui_termios`].
3558#[cfg(not(unix))]
3559pub(crate) fn install_signal_terminal_restore() {}
3560
3561/// Original pre-TUI termios, captured before `enable_raw_mode` and
3562/// used by the signal handler to restore cooked-mode line
3563/// discipline. Wrapped in `OnceLock` so the first TUI startup wins.
3564#[cfg(unix)]
3565static PRETUI_TERMIOS: std::sync::OnceLock<libc::termios> = std::sync::OnceLock::new();
3566
3567#[cfg(unix)]
3568pub(crate) fn save_pretui_termios() {
3569    // tcgetattr on stderr (the TUI writes there). If this fails
3570    // (e.g. stderr isn't a tty), we skip — the signal handler will
3571    // still write the cleanup escape codes, which is enough to
3572    // make the user's shell usable even without a full termios
3573    // restore.
3574    let mut t: libc::termios = unsafe { std::mem::zeroed() };
3575    let rc = unsafe { libc::tcgetattr(libc::STDERR_FILENO, &mut t) };
3576    if rc == 0 {
3577        let _ = PRETUI_TERMIOS.set(t);
3578    }
3579}
3580
3581/// Install handlers for SIGINT, SIGTERM, SIGHUP, SIGQUIT that
3582/// restore the terminal and re-raise the signal. Idempotent.
3583///
3584/// Crate-public so the [`crate::key_watcher::KeyWatcher`] can
3585/// install it whenever raw mode is enabled — otherwise a Ctrl-C
3586/// → force-exit in `tui=terminal` mode (where only the watcher
3587/// is up, no `TerminalGuard`) leaves the shell in raw mode with
3588/// the user typing escape codes into their next prompt.
3589#[cfg(unix)]
3590pub(crate) fn install_signal_terminal_restore() {
3591    use std::sync::atomic::{AtomicBool, Ordering};
3592    static INSTALLED: AtomicBool = AtomicBool::new(false);
3593    if INSTALLED.swap(true, Ordering::SeqCst) {
3594        return;
3595    }
3596
3597    // Cast through a typed `extern "C" fn` first so the integer
3598    // cast is unambiguous (lints reject the direct `fn -> usize`).
3599    type SaHandler = extern "C" fn(libc::c_int, *mut libc::siginfo_t, *mut libc::c_void);
3600    let handler: SaHandler = signal_terminal_restore;
3601    let mut act: libc::sigaction = unsafe { std::mem::zeroed() };
3602    act.sa_sigaction = handler as usize;
3603    act.sa_flags = libc::SA_SIGINFO | libc::SA_RESTART;
3604    unsafe {
3605        libc::sigemptyset(&mut act.sa_mask);
3606        for sig in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP, libc::SIGQUIT] {
3607            libc::sigaction(sig, &act, std::ptr::null_mut());
3608        }
3609    }
3610}
3611
3612/// Async-signal-safe terminal-restore handler. The body uses only
3613/// `write`, `tcsetattr`, `signal`, and `raise` — all async-signal-safe.
3614#[cfg(unix)]
3615extern "C" fn signal_terminal_restore(
3616    sig: libc::c_int,
3617    _info: *mut libc::siginfo_t,
3618    _ucontext: *mut libc::c_void,
3619) {
3620    // Best-effort cleanup sequence. Order matches `TerminalGuard::drop`:
3621    //  1. disable mouse capture (all four reporting modes);
3622    //  2. leave the alternate screen;
3623    //  3. re-show the cursor (paranoid — TUIs sometimes hide it);
3624    //  4. reset SGR attributes (paranoid);
3625    //  5. restore the saved termios (cooked mode + signals).
3626    //
3627    // Each escape-sequence write goes via raw `write` to stderr,
3628    // which is async-signal-safe. crossterm's higher-level API
3629    // is not, so we hand-roll the sequences here.
3630    // `\x1b[999;1H` is the "park cursor at bottom-left"
3631    // idiom: terminals clamp the row to the actual last
3632    // visible row, so this lands on the bottom row of the
3633    // viewport regardless of terminal size. Followed by a
3634    // single `\r\n` so the cooked shell's next prompt prints
3635    // on a fresh line below whatever we just rendered (status
3636    // + prompt + log tail), and the user types into a clean
3637    // cell. Replaces the prior INLINE_STATUS_HEIGHT walk loop
3638    // — that approach drifted when scrolls had moved the
3639    // renderer's region around since the last height publish.
3640    const CLEANUP: &[u8] = concat!(
3641        "\x1b[?1000l", // disable basic mouse reporting
3642        "\x1b[?1002l", // disable button-event mouse reporting
3643        "\x1b[?1003l", // disable any-event mouse reporting
3644        "\x1b[?1006l", // disable SGR mouse reporting
3645        "\x1b[?1015l", // disable URXVT mouse reporting
3646        "\x1b[?1049l", // leave alternate screen
3647        "\x1b[?25h",   // show cursor
3648        "\x1b[0m",     // reset SGR
3649        "\x1b[999;1H", // park at absolute bottom-left (terminal clamps)
3650        "\r\n",        // fresh line for the shell prompt
3651    )
3652    .as_bytes();
3653    unsafe {
3654        libc::write(
3655            libc::STDERR_FILENO,
3656            CLEANUP.as_ptr() as *const libc::c_void,
3657            CLEANUP.len(),
3658        );
3659        if let Some(t) = PRETUI_TERMIOS.get() {
3660            libc::tcsetattr(libc::STDERR_FILENO, libc::TCSANOW, t);
3661        }
3662        // Re-raise with default disposition so the process actually
3663        // exits with the signal's standard status. SIG_DFL on the
3664        // signal we just received, then `raise(sig)` lets the
3665        // kernel terminate us as if no handler had been installed.
3666        let mut act: libc::sigaction = std::mem::zeroed();
3667        act.sa_sigaction = libc::SIG_DFL;
3668        libc::sigaction(sig, &act, std::ptr::null_mut());
3669        libc::raise(sig);
3670    }
3671}
3672
3673/// Install a process-global panic hook that restores the terminal
3674/// before the default panic message prints. The previous hook is
3675/// preserved and re-invoked, so crash backtraces (from
3676/// `RUST_BACKTRACE=1` or similar) still render — just onto a
3677/// clean tty instead of on top of the alternate-screen buffer.
3678///
3679/// Idempotent via an atomic flag: the TUI may be started multiple
3680/// times in a single process (e.g. dev reloads), but only the
3681/// first call wraps the panic hook.
3682///
3683/// On panic the hook does three things, in order:
3684/// 1. Restore the terminal so the panic message lands on a normal
3685///    tty rather than on top of the alternate screen.
3686/// 2. Append a structured `PANIC` entry to the session log file (if
3687///    one was set up). This is the *durable* record — it survives
3688///    even when the terminal output is lost to a re-entered alt
3689///    screen, a backgrounded session, or a parent process that
3690///    swallowed stderr.
3691/// 3. Run the previous (default) hook so stack traces still render.
3692pub(crate) fn install_tui_panic_hook() {
3693    use std::sync::atomic::{AtomicBool, Ordering};
3694    static INSTALLED: AtomicBool = AtomicBool::new(false);
3695    if INSTALLED.swap(true, Ordering::SeqCst) {
3696        return;
3697    }
3698    let prev = std::panic::take_hook();
3699    std::panic::set_hook(Box::new(move |info| {
3700        // Same best-effort cleanup sequence as TerminalGuard::drop.
3701        let _ = io::stderr().execute(DisableMouseCapture);
3702        let _ = io::stderr().execute(LeaveAlternateScreen);
3703        let _ = terminal::disable_raw_mode();
3704
3705        // Durable record: route panic into the session log so the
3706        // user can see what happened post-mortem even when the
3707        // terminal was repainted by a worker thread that out-raced
3708        // the cleanup. See SRD 41 §"Diagnostic Log Routing".
3709        let location = info
3710            .location()
3711            .map(|l| format!("{}:{}", l.file(), l.line()))
3712            .unwrap_or_else(|| "<unknown>".into());
3713        let message = info
3714            .payload()
3715            .downcast_ref::<&'static str>()
3716            .map(|s| (*s).to_string())
3717            .or_else(|| info.payload().downcast_ref::<String>().cloned())
3718            .unwrap_or_else(|| "<non-string panic payload>".into());
3719        let thread = std::thread::current()
3720            .name()
3721            .unwrap_or("<unnamed>")
3722            .to_string();
3723        nmbrs_runtime::observer::log(
3724            nmbrs_runtime::observer::LogLevel::Error,
3725            &format!("PANIC at {location} on thread '{thread}': {message}"),
3726        );
3727
3728        // Default hook prints to stderr (now on the normal screen
3729        // since we left the alternate screen above).
3730        prev(info);
3731
3732        // Force-exit to prevent the still-running TUI render thread
3733        // from redrawing over the panic message we just printed.
3734        // Without this, the user sees a flash of the panic followed
3735        // by the TUI redraw clobbering it. The session log entry
3736        // above is the durable record either way.
3737        //
3738        // We exit only when this is a non-main-thread panic (i.e.,
3739        // a worker / render thread). A main-thread panic will
3740        // unwind through `App::run` and the TerminalGuard drops
3741        // cleanly — letting that happen avoids cutting short any
3742        // pending tokio runtime cleanup. Worker panics, though,
3743        // are unrecoverable from the TUI's perspective.
3744        if std::thread::current().name() != Some("main") {
3745            std::process::exit(101);
3746        }
3747    }));
3748}