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 if self.focused == Some(FocusedPane::Tree) => {
1188 let tail = self.tree_tail_offset(tree);
1189 let current = self.tree_scroll.unwrap_or(tail);
1190 let next = (current as i32 - Self::SCROLL_STEP).max(0) as usize;
1191 self.retarget_tree_scroll(Some(next), tail);
1192 }
1193 _ => {}
1194 }
1195 }
1196
1197 /// Update the scroll target and start (or retarget) the tween from
1198 /// the current displayed position. A fresh mouse-wheel event mid-
1199 /// animation keeps the visual position put and just re-aims — it
1200 /// doesn't snap back to the previous starting point.
1201 fn retarget_tree_scroll(&mut self, target: Option<usize>, tail: usize) {
1202 self.tree_scroll = target;
1203 let target_f = target.unwrap_or(tail) as f32;
1204 self.tree_anim = Some((
1205 self.tree_display,
1206 target_f,
1207 Instant::now(),
1208 Duration::from_millis(Self::SCROLL_ANIM_MS),
1209 ));
1210 }
1211
1212 /// Persist a rendered screen dump to disk. Writes two files in
1213 /// the current session directory (via `logs/latest`):
1214 /// - `tui_{ts}.dump` — a timestamped archive (one per dump)
1215 /// - `tui.dump` — a stable-named copy of the latest dump
1216 ///
1217 /// `Session::new` no longer pre-creates the convenience
1218 /// `logs/tui.dump` symlink — that would dangle for any run
1219 /// that never produces a dump. We create it here, at the
1220 /// moment the stable-named copy actually lands.
1221 fn write_dump(&mut self, text: String, ts: &str) {
1222 let logs_dir = nmbrs_runtime::session::default_sessions_root();
1223 let session_dir = nmbrs_runtime::session::latest_session_dir();
1224 // `sessions/latest` exists as a symlink once Session::new has
1225 // run. If it's not there yet (very early failure), fall back
1226 // to the sessions root so the timestamped archive still lands
1227 // somewhere visible.
1228 let target_dir = if session_dir.exists() {
1229 &session_dir
1230 } else {
1231 &logs_dir
1232 };
1233 let fname_ts = ts.replace([':', ' ', '.'], "_").replace('-', "");
1234 let archive_name = format!("tui_{fname_ts}.dump");
1235 let archive_path = target_dir.join(&archive_name);
1236 let stable_path = target_dir.join("tui.dump");
1237 let archive_result = std::fs::write(&archive_path, &text);
1238 let stable_result = std::fs::write(&stable_path, &text);
1239 match (archive_result, stable_result) {
1240 (Ok(()), Ok(())) => {
1241 nmbrs_runtime::observer::log(
1242 nmbrs_runtime::observer::LogLevel::Info,
1243 &format!(
1244 "tui dump written to {} (also {})",
1245 archive_path.display(),
1246 stable_path.display()
1247 ),
1248 );
1249 // Convenience symlink lives at `logs/tui.dump`.
1250 nmbrs_runtime::session::Session::link_artifact("tui.dump");
1251 }
1252 (Err(e), _) | (_, Err(e)) => {
1253 nmbrs_runtime::observer::log(
1254 nmbrs_runtime::observer::LogLevel::Warn,
1255 &format!("failed to write tui dump {}: {e}", archive_path.display()),
1256 );
1257 }
1258 }
1259 }
1260
1261 /// Handle a `q` keypress.
1262 ///
1263 /// Single/double tap → dismisses the TUI (same as Esc at top level),
1264 /// but the dismiss is DEFERRED until the triple-tap window expires.
1265 /// Otherwise a fast third tap would arrive after the TUI was already
1266 /// tearing down, never triggering the process-exit path the user
1267 /// Toggle the paused flag. On pause, clones the live `RunState`
1268 /// into `self.frozen_state` so subsequent `draw` calls render
1269 /// from the snapshot instead of the live store — otherwise
1270 /// observer updates (ops/s, latency, phase progress) continue
1271 /// to leak into the rendered frame even though `drain_frames`
1272 /// has stopped. On unpause, the snapshot is dropped and the
1273 /// next draw picks up the live state again.
1274 fn toggle_pause(&mut self) {
1275 if self.paused {
1276 self.paused = false;
1277 self.frozen_state = None;
1278 } else {
1279 // Snapshots are already immutable Arcs — pause just
1280 // retains the current one. Future actor publishes
1281 // build new Arcs without touching this one, so the
1282 // frozen view stays stable until unpaused.
1283 self.frozen_state = Some(self.run_state.load());
1284 self.paused = true;
1285 }
1286 }
1287
1288 /// actually wanted. The loop calls `poll_q_tap_timeout` every frame
1289 /// to apply the deferred action once the streak is confirmed.
1290 ///
1291 /// Triple tap inside [`Q_TAP_WINDOW_MS`] fires immediately: hard-
1292 /// exit the whole nmbrs process after the terminal is restored.
1293 fn handle_q_tap(&mut self) {
1294 let now = Instant::now();
1295 let in_streak = self
1296 .q_tap_last
1297 .map(|prev| now.duration_since(prev).as_millis() <= Self::Q_TAP_WINDOW_MS)
1298 .unwrap_or(false);
1299 self.q_tap_count = if in_streak { self.q_tap_count + 1 } else { 1 };
1300 self.q_tap_last = Some(now);
1301 if self.q_tap_count >= Self::Q_TAP_EXIT_COUNT {
1302 // Triple confirmed — act now.
1303 self.should_exit_process = true;
1304 self.should_quit = true;
1305 }
1306 // Otherwise wait. poll_q_tap_timeout applies the dismiss once
1307 // we're confident no further tap is coming.
1308 }
1309
1310 /// Called each event-loop iteration. If a q-tap streak is open and
1311 /// the window has expired with 1 or 2 presses, apply the deferred
1312 /// TUI dismiss. Three-press streaks already acted inline.
1313 fn poll_q_tap_timeout(&mut self) {
1314 let Some(last) = self.q_tap_last else {
1315 return;
1316 };
1317 if self.q_tap_count == 0 {
1318 return;
1319 }
1320 if last.elapsed().as_millis() < Self::Q_TAP_WINDOW_MS {
1321 return;
1322 }
1323 if self.q_tap_count < Self::Q_TAP_EXIT_COUNT {
1324 self.should_quit = true;
1325 }
1326 self.q_tap_count = 0;
1327 self.q_tap_last = None;
1328 }
1329
1330 /// Escape is a cascading dismiss:
1331 /// 1) If the help overlay is up, close it.
1332 /// 2) If an entry is expanded, collapse it.
1333 /// 3) Otherwise if the tree has focus, release focus + selection.
1334 /// 4) Otherwise quit the TUI (matches `q`).
1335 fn handle_escape(&mut self) {
1336 if self.show_help {
1337 self.show_help = false;
1338 } else if self.tree_expanded.is_some() {
1339 self.tree_expanded = None;
1340 } else if self.focused == Some(FocusedPane::Tree) {
1341 self.focused = None;
1342 self.tree_selected = None;
1343 self.tree_selection_auto = true;
1344 } else {
1345 self.should_quit = true;
1346 }
1347 }
1348
1349 /// Move the tree selection by `delta` phase entries, skipping scope
1350 /// headers. Grabs tree focus if it wasn't already held, and seeds
1351 /// the selection with the most-recently-active phase on first use.
1352 /// Any manual movement disables auto-tracking so the selection
1353 /// stops drifting with newly-running phases.
1354 fn move_tree_selection(&mut self, delta: i32) {
1355 if self.focused != Some(FocusedPane::Tree) {
1356 self.focused = Some(FocusedPane::Tree);
1357 }
1358 // Drill mode: Up/Down move within the drilled phase's op
1359 // list. The cursor stays on the parent phase row in the
1360 // outer tree; only `drill_op_idx` advances.
1361 if let Some(drilled) = self.tree_drilled {
1362 let n = {
1363 let s = self.run_state.load();
1364 s.phases.get(drilled).map(|p| p.op_names.len()).unwrap_or(0)
1365 };
1366 if n == 0 {
1367 // Phase has no op data — exit drill mode rather
1368 // than getting stuck in an empty navigator.
1369 self.tree_drilled = None;
1370 return;
1371 }
1372 let cur = self.drill_op_idx as i64;
1373 let next = (cur + delta as i64).clamp(0, n as i64 - 1) as usize;
1374 self.drill_op_idx = next;
1375 return;
1376 }
1377 if self.tree_selected.is_none() {
1378 self.tree_selected = self.default_tree_selection();
1379 }
1380 self.tree_selection_auto = false;
1381 if let Some(start) = self.tree_selected
1382 && let Some(next) = self.step_selectable_for_lod(start, delta)
1383 {
1384 self.tree_selected = Some(next);
1385 }
1386 self.scroll_selection_into_view();
1387 }
1388
1389 /// Right arrow: drill into a phase's stanza op list when the
1390 /// selected phase is already expanded; otherwise fall back to
1391 /// the LOD-up behavior (more detail).
1392 fn tree_right_arrow(&mut self) {
1393 // If already drilled, no-op (Right has no further meaning
1394 // inside the op list).
1395 if self.tree_drilled.is_some() {
1396 return;
1397 }
1398 let Some(sel) = self.tree_selected else {
1399 self.adjust_tree_lod(1);
1400 return;
1401 };
1402 // Drill only when the selected phase is currently expanded
1403 // AND has op_names to show. Otherwise fall through to LOD.
1404 if self.tree_expanded == Some(sel) {
1405 let has_ops = {
1406 let s = self.run_state.load();
1407 s.phases
1408 .get(sel)
1409 .map(|p| p.kind == crate::state::EntryKind::Phase && !p.op_names.is_empty())
1410 .unwrap_or(false)
1411 };
1412 if has_ops {
1413 self.tree_drilled = Some(sel);
1414 self.drill_op_idx = 0;
1415 self.scroll_selection_into_view();
1416 return;
1417 }
1418 }
1419 self.adjust_tree_lod(1);
1420 }
1421
1422 /// Left arrow: exit drill mode (close the stanza op list, park
1423 /// cursor back on the parent phase) when drilled; otherwise
1424 /// fall back to the LOD-down behavior (less detail).
1425 fn tree_left_arrow(&mut self) {
1426 if self.tree_drilled.is_some() {
1427 self.tree_drilled = None;
1428 self.drill_op_idx = 0;
1429 self.scroll_selection_into_view();
1430 return;
1431 }
1432 self.adjust_tree_lod(-1);
1433 }
1434
1435 /// LOD-aware step. Skips over entries that render zero rows
1436 /// (scope headers in Minimal/Focus, pending/completed phases
1437 /// in Focus) so the selection never parks at an invisible
1438 /// line index — which would cause `scroll_selection_into_view`
1439 /// to silently bail and leave the viewport out of sync with
1440 /// `tree_selected`.
1441 fn step_selectable_for_lod(&self, start: usize, delta: i32) -> Option<usize> {
1442 let s = self.run_state.load();
1443 let len = s.phases.len() as i32;
1444 if len == 0 {
1445 return None;
1446 }
1447 let step = if delta >= 0 { 1 } else { -1 };
1448 let mut idx = start as i32 + step;
1449 while idx >= 0 && idx < len {
1450 let i = idx as usize;
1451 let phase = &s.phases[i];
1452 if phase.kind == crate::state::EntryKind::Phase && self.rendered_lines_for(i, phase) > 0
1453 {
1454 return Some(i);
1455 }
1456 idx += step;
1457 }
1458 None
1459 }
1460
1461 /// If the currently selected entry's rendered line sits outside the
1462 /// visible viewport, retarget the scroll animation so it just comes
1463 /// into view. Top-aligned if the selection is above the window,
1464 /// bottom-aligned if below. No-op when already in view.
1465 fn scroll_selection_into_view(&mut self) {
1466 let Some(sel) = self.tree_selected else {
1467 return;
1468 };
1469 let visible = self.last_tree_rect.height.saturating_sub(2) as usize;
1470 if visible == 0 {
1471 return;
1472 }
1473
1474 // Rendered-line index of the selected entry, accounting for any
1475 // currently expanded detail block above it.
1476 let Some(line) = self.entry_to_line_index(sel) else {
1477 return;
1478 };
1479
1480 let total = self.total_rendered_lines();
1481 let tail = total.saturating_sub(visible);
1482 let current_top = self.tree_scroll.unwrap_or(tail);
1483 let current_bottom = current_top.saturating_add(visible).saturating_sub(1);
1484
1485 let new_top = if line < current_top {
1486 // Selection is above the viewport — bring it to the top.
1487 line
1488 } else if line > current_bottom {
1489 // Selection is below the viewport — pin it to the bottom row.
1490 line.saturating_sub(visible.saturating_sub(1))
1491 } else {
1492 return; // already visible
1493 };
1494 let clamped = new_top.min(tail);
1495 let target = if clamped >= tail { None } else { Some(clamped) };
1496 self.retarget_tree_scroll(target, tail);
1497 }
1498
1499 /// Total number of rendered lines in the tree (phase rows + detail
1500 /// rows of any expanded entry). Matches the iteration in `draw_tree`.
1501 fn total_rendered_lines(&self) -> usize {
1502 let s = self.run_state.load();
1503 s.phases
1504 .iter()
1505 .enumerate()
1506 .map(|(i, p)| self.rendered_lines_for(i, p))
1507 .sum()
1508 }
1509
1510 /// Inverse of [`line_to_entry_index`]: given a `state.phases` index,
1511 /// return its rendered-line index (0-based, pre-scroll). `None` if
1512 /// the entry doesn't exist.
1513 fn entry_to_line_index(&self, entry: usize) -> Option<usize> {
1514 let s = self.run_state.load();
1515 if entry >= s.phases.len() {
1516 return None;
1517 }
1518 // Entries that render zero rows (scope headers in Minimal) have
1519 // no line position — treat them as absent for navigation.
1520 if self.rendered_lines_for(entry, &s.phases[entry]) == 0 {
1521 return None;
1522 }
1523 let mut cursor = 0usize;
1524 for (i, phase) in s.phases.iter().enumerate() {
1525 if i == entry {
1526 return Some(cursor);
1527 }
1528 cursor += self.rendered_lines_for(i, phase);
1529 }
1530 None
1531 }
1532
1533 /// Default tree selection when focus is first grabbed: the most
1534 /// recently active phase. Prefers the current Running entry, falls
1535 /// back to the latest Completed entry, then the first Phase.
1536 fn default_tree_selection(&self) -> Option<usize> {
1537 let s = self.run_state.load();
1538 let phases: &[crate::state::PhaseEntry] = &s.phases;
1539 // Only consider entries that actually render under the
1540 // current LOD — Focus hides non-running phases, so the
1541 // default selection can't usefully land on one.
1542 let renderable = |(i, p): &(usize, &crate::state::PhaseEntry)| {
1543 p.kind == crate::state::EntryKind::Phase && self.rendered_lines_for(*i, p) > 0
1544 };
1545 phases
1546 .iter()
1547 .enumerate()
1548 .filter(renderable)
1549 .rfind(|(_, p)| matches!(p.status, crate::state::PhaseStatus::Running))
1550 .or_else(|| {
1551 phases
1552 .iter()
1553 .enumerate()
1554 .filter(renderable)
1555 .rfind(|(_, p)| matches!(p.status, crate::state::PhaseStatus::Completed))
1556 })
1557 .or_else(|| phases.iter().enumerate().find(renderable))
1558 .map(|(i, _)| i)
1559 }
1560
1561 /// Cycle the tree level of detail. Positive `delta` increases LOD
1562 /// (more detail), negative decreases. Clamped at the ends.
1563 ///
1564 /// Grabs tree focus if not held, and scrolls the current selection
1565 /// back into view since the rendered-line coordinates shift when
1566 /// the detail model changes.
1567 fn adjust_tree_lod(&mut self, delta: i32) {
1568 if self.focused != Some(FocusedPane::Tree) {
1569 self.focused = Some(FocusedPane::Tree);
1570 }
1571 if self.tree_selected.is_none() {
1572 self.tree_selected = self.default_tree_selection();
1573 self.tree_selection_auto = false;
1574 }
1575 self.tree_lod = if delta > 0 {
1576 self.tree_lod.next()
1577 } else {
1578 self.tree_lod.prev()
1579 };
1580 self.scroll_selection_into_view();
1581 }
1582
1583 /// Number of rendered lines an entry contributes under the current
1584 /// LOD + expansion state. Rules:
1585 /// * Scope entry in Minimal or Focus → hidden (0 rows).
1586 /// * Focus mode also hides non-running phases.
1587 /// * Phase entry in Maximal or Focus → 1 + full detail block.
1588 /// * Any phase the user has explicitly pinned via Enter → 1 +
1589 /// detail, regardless of LOD.
1590 /// * Otherwise → 1 row.
1591 fn rendered_lines_for(&self, entry_idx: usize, phase: &crate::state::PhaseEntry) -> usize {
1592 // Hidden and ActivePhase LODs don't render any tree rows.
1593 // Return 0 so total_rendered_lines / entry_to_line_index
1594 // behave as "no scrollable tree content" and the event
1595 // loop's tail calc disables scroll animation in those LODs.
1596 if matches!(self.tree_lod, TreeLod::Hidden | TreeLod::ActivePhase) {
1597 return 0;
1598 }
1599 if matches!(self.tree_lod, TreeLod::Minimal | TreeLod::Focus)
1600 && phase.kind == crate::state::EntryKind::Scope
1601 {
1602 return 0;
1603 }
1604 if self.tree_lod == TreeLod::Focus
1605 && phase.kind == crate::state::EntryKind::Phase
1606 && !matches!(phase.status, crate::state::PhaseStatus::Running)
1607 {
1608 return 0;
1609 }
1610 if phase.kind != crate::state::EntryKind::Phase {
1611 return 1;
1612 }
1613 let expanded = self.tree_expanded == Some(entry_idx)
1614 || self.tree_lod == TreeLod::Maximal
1615 || self.tree_lod == TreeLod::Focus;
1616 // Op-level status rows (SRD-63) render whenever the phase row
1617 // renders, independent of expand/drill — counted in both
1618 // branches so scroll/hit-test math matches draw_tree.
1619 let op_rows = self.op_rows_for(phase);
1620 if expanded {
1621 // Drilled phases also render a header row + one row
1622 // per op name. Counted here so scroll math, mouse
1623 // hit-testing, and tail-offset calculation all stay
1624 // in sync with what `draw_tree` actually emits.
1625 let drill_rows = if self.tree_drilled == Some(entry_idx) {
1626 1 + phase.op_names.len()
1627 } else {
1628 0
1629 };
1630 1 + self.detail_line_count_for(phase) + drill_rows + op_rows
1631 } else {
1632 1 + op_rows
1633 }
1634 }
1635
1636 /// Number of op-level status rows a phase contributes (SRD-63):
1637 /// one per `readout: visible` op recorded under the phase. They
1638 /// render whenever the phase row renders (not gated by expand /
1639 /// drill), so they're added to both branches of
1640 /// `rendered_lines_for` to keep scroll / hit-test math consistent.
1641 fn op_rows_for(&self, phase: &crate::state::PhaseEntry) -> usize {
1642 self.run_state
1643 .load()
1644 .phase_ops
1645 .get(&phase.node_id)
1646 .map(|v| v.len())
1647 .unwrap_or(0)
1648 }
1649
1650 /// Count of detail lines for a phase using live state when the
1651 /// phase is currently running. Keeps line-offset math in
1652 /// `total_rendered_lines` / `entry_to_line_index` /
1653 /// `line_to_entry_index` consistent with `draw_tree` output.
1654 fn detail_line_count_for(&self, phase: &crate::state::PhaseEntry) -> usize {
1655 {
1656 let s = self.run_state.load();
1657 if let Some(a) = s.active_phase(&phase.name, &phase.labels) {
1658 // Clone the active snapshot out of the read guard so we
1659 // can drop the lock before calling format_phase_detail.
1660 let a = a.clone();
1661 drop(s);
1662 return self.format_phase_detail_with_live(phase, Some(&a)).len();
1663 }
1664 }
1665 self.format_phase_detail(phase).len()
1666 }
1667
1668 /// Whether a detail block is rendered below the given phase. The
1669 /// user-pinned expansion (via Enter) always wins: even in Minimal
1670 /// mode the selected phase can still be drilled into. Otherwise
1671 /// Default LOD renders no details, Maximal renders them for every
1672 /// phase that has data.
1673 fn show_detail_for(&self, entry_idx: usize, phase: &crate::state::PhaseEntry) -> bool {
1674 if phase.kind != crate::state::EntryKind::Phase {
1675 return false;
1676 }
1677 if self.tree_expanded == Some(entry_idx) {
1678 return true;
1679 }
1680 match self.tree_lod {
1681 TreeLod::Hidden => false,
1682 // ActivePhase uses the dedicated panel renderer — the
1683 // tree-detail path isn't exercised under this LOD.
1684 TreeLod::ActivePhase => false,
1685 TreeLod::Minimal => false,
1686 TreeLod::Default => false,
1687 TreeLod::Focus => matches!(phase.status, crate::state::PhaseStatus::Running),
1688 TreeLod::Maximal => !self.format_phase_detail(phase).is_empty(),
1689 }
1690 }
1691
1692 /// Toggle expansion of the currently selected phase. Scope entries
1693 /// and missing selections are ignored. Works in every LOD: a
1694 /// user-pinned expansion overrides the LOD baseline, so in Minimal
1695 /// or Maximal the selected phase still gets its full detail block.
1696 fn toggle_tree_expansion(&mut self) {
1697 let Some(sel) = self.tree_selected else {
1698 return;
1699 };
1700 let is_phase = {
1701 let s = self.run_state.load();
1702 s.phases
1703 .get(sel)
1704 .map(|p| p.kind == crate::state::EntryKind::Phase)
1705 .unwrap_or(false)
1706 };
1707 if !is_phase {
1708 return;
1709 }
1710 self.tree_expanded = match self.tree_expanded {
1711 Some(i) if i == sel => None,
1712 _ => Some(sel),
1713 };
1714 // Collapsing a phase that's currently drilled also exits
1715 // the drill view — the op list belongs to the open
1716 // detail block, so it shouldn't render once that block
1717 // closes.
1718 if self.tree_expanded.is_none() {
1719 self.tree_drilled = None;
1720 self.drill_op_idx = 0;
1721 }
1722 }
1723
1724 /// Map a rendered-line index (0-based within the full rendered tree,
1725 /// pre-scroll) back to the `state.phases` index it represents. When
1726 /// a phase is expanded, its entry "owns" the detail lines below it,
1727 /// so clicks on those rows select the parent phase. Returns `None`
1728 /// if the line sits beyond the last entry.
1729 fn line_to_entry_index(&self, line: usize) -> Option<usize> {
1730 let s = self.run_state.load();
1731 let mut cursor = 0usize;
1732 for (i, phase) in s.phases.iter().enumerate() {
1733 let rendered_rows = self.rendered_lines_for(i, phase);
1734 if rendered_rows == 0 {
1735 continue;
1736 }
1737 if line < cursor + rendered_rows {
1738 return Some(i);
1739 }
1740 cursor += rendered_rows;
1741 }
1742 None
1743 }
1744
1745 /// Refresh the selection to track the most recently active phase
1746 /// when the user hasn't manually moved it. Called each frame so the
1747 /// marker drifts along with the workload's progress. When the
1748 /// tracked selection *changes*, the viewport re-pins the new row to
1749 /// the top edge so the active phase is always the anchor.
1750 fn refresh_auto_selection(&mut self) {
1751 if self.focused != Some(FocusedPane::Tree) || !self.tree_selection_auto {
1752 return;
1753 }
1754 let prev = self.tree_selected;
1755 if let Some(i) = self.default_tree_selection() {
1756 self.tree_selected = Some(i);
1757 if prev != Some(i) {
1758 // Move the expansion to follow the new active phase
1759 // FIRST — expansion state feeds into the line-index
1760 // math, so if the previously expanded phase is still
1761 // marked as expanded while we compute the new scroll
1762 // target, the target lands below the real position by
1763 // the old phase's detail-block height.
1764 if self.tree_expanded.is_some() {
1765 self.tree_expanded = Some(i);
1766 }
1767 // Now re-pin to top with the correct expansion state.
1768 self.scroll_selection_to_top();
1769 }
1770 }
1771 }
1772
1773 /// Pin the currently selected entry's rendered line to the top of
1774 /// the tree viewport by retargeting the scroll animation.
1775 fn scroll_selection_to_top(&mut self) {
1776 let Some(sel) = self.tree_selected else {
1777 return;
1778 };
1779 let Some(line) = self.entry_to_line_index(sel) else {
1780 return;
1781 };
1782 let visible = self.last_tree_rect.height.saturating_sub(2) as usize;
1783 if visible == 0 {
1784 return;
1785 }
1786 let total = self.total_rendered_lines();
1787 let tail = total.saturating_sub(visible);
1788 // Always pin the selected entry's first line to the top row
1789 // of the viewport, even when content is shorter than the
1790 // panel — the user-visible meaning of "scroll to top" is
1791 // *anchor*, not *fill*. The viewport pads with empty rows
1792 // when (line + visible) > total. Capped at `total` so the
1793 // line index is at least within the buffer; the loop's
1794 // skip+render naturally handles "no rows to draw" past
1795 // the end. `tail` is still passed for the anim fallback
1796 // when target is None, used by other call sites.
1797 let target = Some(line.min(total));
1798 self.retarget_tree_scroll(target, tail);
1799 }
1800
1801 /// Space-bar reset: pivot the tree view around the most recently
1802 /// active phase. Takes focus, seeds selection to the active phase,
1803 /// forces LOD back to Default, expands the selection, enables
1804 /// auto-tracking, and pins it to the top of the window.
1805 fn reset_tree_to_active(&mut self) {
1806 self.focused = Some(FocusedPane::Tree);
1807 self.tree_lod = TreeLod::Default;
1808 self.tree_selection_auto = true;
1809 if let Some(i) = self.default_tree_selection() {
1810 self.tree_selected = Some(i);
1811 self.tree_expanded = Some(i);
1812 }
1813 self.scroll_selection_to_top();
1814 }
1815
1816 /// Build the detail lines shown when a phase is expanded. The
1817 /// caller adds the indent/gutter prefix. If `live` is supplied the
1818 /// detail reads from that live snapshot (matches the non-TUI
1819 /// progress bar exactly); otherwise it reads from
1820 /// `phase.summary` (captured at phase_completed time).
1821 fn format_phase_detail(&self, phase: &crate::state::PhaseEntry) -> Vec<Line<'static>> {
1822 self.format_phase_detail_with_live(phase, None)
1823 }
1824
1825 fn format_phase_detail_with_live(
1826 &self,
1827 phase: &crate::state::PhaseEntry,
1828 live: Option<&crate::state::ActivePhase>,
1829 ) -> Vec<Line<'static>> {
1830 let mut out: Vec<Line<'static>> = Vec::new();
1831
1832 // SRD-63 Push 5b: route the headline status row through
1833 // the readout engine. `phase_status` for live phases
1834 // (binder.fire under EventType::Update; ContentMode flips
1835 // to Explanation when the `\` overlay-toggle is active);
1836 // `phase_outcome` / `phase_summary` for terminal states.
1837 // Tab / Shift-Tab cycle focus through bound bodies; +
1838 // / - cycle the focused body's LOD. The binder's per-
1839 // (slot, body) state persists across frames so the
1840 // operator's selection survives every refresh.
1841 let refresh_tick = self.frame_tick.get();
1842 let (readout_lines, _evt) = crate::readout_panel::render_phase_readouts(
1843 &mut self.readout_binder.borrow_mut(),
1844 phase,
1845 live,
1846 refresh_tick,
1847 );
1848 out.extend(readout_lines);
1849
1850 // Status line — duplicates the parent row but gives us a first
1851 // detail line when a phase has no summary yet (pending).
1852 let status_text = match &phase.status {
1853 PhaseStatus::Pending => "pending — not yet started".to_string(),
1854 PhaseStatus::Running => "running…".to_string(),
1855 PhaseStatus::Completed => {
1856 let dur = phase
1857 .duration_secs
1858 .map(|d| format!(" in {d:.2}s"))
1859 .unwrap_or_default();
1860 format!("completed{dur}")
1861 }
1862 PhaseStatus::Failed(err) => format!("failed: {err}"),
1863 };
1864 out.push(Line::from(Span::styled(
1865 status_text,
1866 Style::default().fg(colors::DIM),
1867 )));
1868
1869 if !phase.labels.is_empty() {
1870 out.push(Line::from(Span::styled(
1871 format!("bindings: {}", phase.labels),
1872 Style::default().fg(colors::TEXT),
1873 )));
1874 }
1875
1876 if phase.op_count > 0 {
1877 // Structural metadata — count of op-template
1878 // entries under the phase's `ops:` key. Distinct
1879 // from "ops" (per-cycle executions) which are
1880 // counted by the throughput rows above; "active"
1881 // would be misleading here since this is a static
1882 // declaration count, not a runtime quantity.
1883 out.push(Line::from(Span::styled(
1884 format!("op templates: {}", phase.op_count),
1885 Style::default().fg(colors::TEXT),
1886 )));
1887 }
1888
1889 // Extract the same fields the non-TUI progress bar prints, from
1890 // whichever source is available. `live` wins when the phase is
1891 // currently running; otherwise the completion snapshot.
1892 struct Snap {
1893 ops_started: u64,
1894 ops_finished: u64,
1895 ops_ok: u64,
1896 errors: u64,
1897 retries: u64,
1898 fibers: usize,
1899 ops_per_sec: f64,
1900 cursor_name: String,
1901 cursor_extent: u64,
1902 adapter_counters: Vec<(String, u64, f64)>,
1903 rows_per_batch: f64,
1904 }
1905 let snap: Option<Snap> = if let Some(a) = live {
1906 Some(Snap {
1907 ops_started: a.ops_started,
1908 ops_finished: a.ops_finished,
1909 ops_ok: a.ops_ok,
1910 errors: a.errors,
1911 retries: a.retries,
1912 fibers: a.fibers,
1913 ops_per_sec: a.ops_per_sec,
1914 cursor_name: a.cursor_name.clone(),
1915 cursor_extent: a.cursor_extent,
1916 adapter_counters: a.adapter_counters.clone(),
1917 rows_per_batch: a.rows_per_batch,
1918 })
1919 } else {
1920 phase.summary.as_ref().map(|sm| Snap {
1921 ops_started: sm.ops_started,
1922 ops_finished: sm.ops_finished,
1923 ops_ok: sm.ops_ok,
1924 errors: sm.errors,
1925 retries: sm.retries,
1926 fibers: sm.fibers,
1927 ops_per_sec: sm.ops_per_sec,
1928 cursor_name: sm.cursor_name.clone(),
1929 cursor_extent: sm.cursor_extent,
1930 adapter_counters: sm.adapter_counters.clone(),
1931 rows_per_batch: sm.rows_per_batch,
1932 })
1933 };
1934
1935 if let Some(s) = snap {
1936 // Labeled tuple + visual bar. "82.9K of 83.0K" on its own is
1937 // ambiguous; spelling out pending/active/complete and
1938 // anchoring on the cursor name makes the scale obvious.
1939 let active = s.ops_started.saturating_sub(s.ops_finished);
1940 let pending = s.cursor_extent.saturating_sub(s.ops_started);
1941 let complete = s.ops_finished;
1942 // Percentage matches the "N of M" display on the same
1943 // line — both are ops_finished / extent. Previously
1944 // this used ops_started, which showed 100% while
1945 // "complete of extent" was still < extent (in-flight
1946 // ops made the two disagree).
1947 let pct = if s.cursor_extent > 0 {
1948 complete as f64 * 100.0 / s.cursor_extent as f64
1949 } else {
1950 0.0
1951 };
1952
1953 // Cursor row: identity + absolute ratio on one line,
1954 // then a two-line-tall thick progress bar below.
1955 // The bar matches the 60-cell width of the latency
1956 // bars further down so the two visually anchor on
1957 // the same column. Full-block glyphs make the bar
1958 // read as "the most prominent thing in this block"
1959 // — appropriate, since cursor progress is the
1960 // primary phase-completion signal.
1961 // Wider than the latency bars below (60 cells)
1962 // because the cursor row is the headline progress
1963 // signal and the Braille per-pip resolution
1964 // (8 pips/cell × 100 cells = 800 sub-positions) is
1965 // worth the extra horizontal real estate.
1966 const CURSOR_BAR_W: usize = 100;
1967 let (bar_filled, bar_unfilled) = widgets::bar_str_braille(pct / 100.0, CURSOR_BAR_W);
1968 let cursor_label = if s.cursor_name.is_empty() {
1969 "cursor".to_string()
1970 } else {
1971 format!("cursor {}", s.cursor_name)
1972 };
1973 out.push(Line::from(Span::styled(
1974 format!(
1975 "{cursor_label}: {} of {} ({:.2}%)",
1976 widgets::format_count(complete),
1977 widgets::format_count(s.cursor_extent),
1978 pct
1979 ),
1980 Style::default().fg(colors::TEXT),
1981 )));
1982 // Two-span line: bright Braille pips for the
1983 // filled portion, dim baseline track (`⣀`) for the
1984 // remaining work. Lets the operator gauge progress
1985 // against total at a glance — without the baseline
1986 // track the bar's full width was invisible until
1987 // a fill appeared.
1988 out.push(Line::from(vec![
1989 Span::styled(bar_filled, Style::default().fg(colors::PROGRESS_HIGH)),
1990 Span::styled(bar_unfilled, Style::default().fg(colors::DIM)),
1991 ]));
1992
1993 // Line 2: named breakdown of the same numbers.
1994 out.push(Line::from(Span::styled(
1995 format!(
1996 " pending: {} • active: {} • complete: {} (extent: {})",
1997 widgets::format_count(pending),
1998 widgets::format_count(active),
1999 widgets::format_count(complete),
2000 widgets::format_count(s.cursor_extent)
2001 ),
2002 Style::default().fg(colors::DIM),
2003 )));
2004
2005 // Line 3: throughput + reliability + concurrency.
2006 // The rate labeled here is the cursor-advance rate —
2007 // `ops_finished` increments once per cycle, which is
2008 // once per position of the declared cursor. Naming it
2009 // after the cursor ("row/s", "q/s", …) keeps the
2010 // label honest with the adjacent `cursor row:` line
2011 // above. Falls back to "cycles/s" when no cursor is
2012 // declared. Domain-level counters (rows_inserted/s
2013 // for batched writes, where the cycle rate ≠ the row
2014 // rate) still show separately under `adapter:` below.
2015 let throughput_label = cursor_rate_label(&s.cursor_name);
2016 // Smoothed rate via the phase's Ewma summary when
2017 // live; completed phases use the snapshot's raw
2018 // ops_per_sec (no EWMA retained post-phase).
2019 let rate_display = live
2020 .and_then(|a| a.rate_ewma.peek())
2021 .unwrap_or(s.ops_per_sec);
2022 out.push(Line::from(Span::styled(
2023 format!("{throughput_label}: {} ok: {:.1}% errors: {} retries: {} concurrency: {}",
2024 widgets::format_rate(rate_display),
2025 if s.ops_finished > 0 {
2026 s.ops_ok as f64 * 100.0 / s.ops_finished as f64
2027 } else { 100.0 },
2028 s.errors,
2029 s.retries,
2030 s.fibers),
2031 Style::default().fg(colors::TEXT),
2032 )));
2033
2034 // Latency percentile bars — render the existing per-row
2035 // visualization (from the retired top-level Latency panel)
2036 // inline under this phase's detail. Running phases pull
2037 // live values from the TUI's drained state; completed
2038 // phases use their `summary.*_nanos` snapshot.
2039 let (min_ns, p50_ns, p90_ns, p99_ns, p999_ns, max_ns, lat_src) = if live.is_some() {
2040 let sr = self.run_state.load();
2041 (
2042 sr.min_nanos,
2043 sr.p50_nanos,
2044 sr.p90_nanos,
2045 sr.p99_nanos,
2046 sr.p999_nanos,
2047 sr.max_nanos,
2048 "live",
2049 )
2050 } else if let Some(ref sm) = phase.summary {
2051 // `summary` only captures min/p50/p99/max today —
2052 // p90/p999 default to 0 and the bar renderer
2053 // skips zero-valued rows.
2054 (
2055 sm.min_nanos,
2056 sm.p50_nanos,
2057 0,
2058 sm.p99_nanos,
2059 0,
2060 sm.max_nanos,
2061 "summary",
2062 )
2063 } else {
2064 (0, 0, 0, 0, 0, 0, "")
2065 };
2066 let _ = lat_src;
2067 // Peak cross-bar markers come from the phase's
2068 // PeakTracker summaries when live; completed phases
2069 // have no live trackers, so peaks are omitted.
2070 let now = std::time::Instant::now();
2071 let peak_5s = live.and_then(|a| a.latency_peak_5s.peek(now));
2072 let peak_10s = live.and_then(|a| a.latency_peak_10s.peek(now));
2073 if max_ns > 0 || p99_ns > 0 || p50_ns > 0 {
2074 out.extend(latency_detail_lines(
2075 min_ns, p50_ns, p90_ns, p99_ns, p999_ns, max_ns, peak_5s, peak_10s,
2076 ));
2077 }
2078
2079 // Throughput sparkline. Two sources, one render:
2080 // - Live phase → snapshot of the live
2081 // `Arc<BinomialSummary>` (updates every frame).
2082 // - Completed phase → frozen `throughput_samples`
2083 // captured at phase_completed time.
2084 // Failed / pending phases render nothing (no samples).
2085 // The sparkline is the *durable artifact* per
2086 // SRD 62 §"Per-phase sparkline": scrolling back to
2087 // a completed phase must still show its curve.
2088 let (tp_samples, tp_cursor_name): (Vec<f64>, String) = if let Some(a) = live {
2089 (a.throughput_summary.snapshot(), a.cursor_name.clone())
2090 } else if let Some(ref sm) = phase.summary {
2091 (sm.throughput_samples.clone(), sm.cursor_name.clone())
2092 } else {
2093 (Vec::new(), String::new())
2094 };
2095 if !tp_samples.is_empty() {
2096 let spark = widgets::sparkline_str(&tp_samples, 60);
2097 let latest = tp_samples.last().copied().unwrap_or(0.0);
2098 let rate_label = cursor_rate_label(&tp_cursor_name);
2099 out.push(Line::from(vec![
2100 Span::styled(" rate ", Style::default().fg(colors::DIM)),
2101 Span::styled(
2102 format!(" {:>14} ", widgets::format_rate(latest)),
2103 Style::default().fg(colors::SPARK).bold(),
2104 ),
2105 Span::styled(spark, Style::default().fg(colors::SPARK)),
2106 Span::styled(format!(" {rate_label}"), Style::default().fg(colors::DIM)),
2107 ]));
2108 }
2109
2110 if phase
2111 .summary
2112 .as_ref()
2113 .map(|sm| sm.p50_nanos > 0 || sm.p99_nanos > 0 || sm.max_nanos > 0)
2114 .unwrap_or(false)
2115 && let Some(ref sm) = phase.summary
2116 {
2117 out.push(Line::from(Span::styled(
2118 format!(
2119 "latency: min {} p50 {} p99 {} max {}",
2120 widgets::format_nanos(sm.min_nanos),
2121 widgets::format_nanos(sm.p50_nanos),
2122 widgets::format_nanos(sm.p99_nanos),
2123 widgets::format_nanos(sm.max_nanos)
2124 ),
2125 Style::default().fg(colors::LAT_P50),
2126 )));
2127 }
2128
2129 // Relevancy aggregates (recall / precision / f1 / …), one
2130 // line per metric. Shows the moving-window mean (last N
2131 // cycles for the phase's op template) and the running
2132 // all-time mean across the phase. For ANN workloads this
2133 // is a KEY metric — kept separate so it's impossible to
2134 // miss in the expanded view.
2135 let relevancy: &[(String, f64, f64, u64, usize)] = if let Some(a) = live {
2136 &a.relevancy
2137 } else if let Some(ref sm) = phase.summary {
2138 &sm.relevancy
2139 } else {
2140 &[]
2141 };
2142 for (name, window_mean, total_mean, total_count, window_len) in relevancy {
2143 out.push(Line::from(Span::styled(
2144 format!(
2145 "{name}: all-time {:.4} • last {window_len}: {:.4} (n={total_count})",
2146 total_mean, window_mean
2147 ),
2148 Style::default().fg(colors::EMPHASIS),
2149 )));
2150 }
2151
2152 // Adapter-specific status counters with rates (rows/s etc.),
2153 // same series the progress bar prefixes after the core stats.
2154 if !s.adapter_counters.is_empty() {
2155 let mut parts: Vec<String> = Vec::new();
2156 for (name, total, rate) in &s.adapter_counters {
2157 // Internal counters (`_batch_writes`) back a derived metric
2158 // only — never their own chip. See `is_internal_counter`.
2159 if nmbrs_runtime::is_internal_counter(name) {
2160 continue;
2161 }
2162 parts.push(format!(
2163 "{name}: {} @ {}/s",
2164 widgets::format_count(*total),
2165 widgets::format_rate(*rate)
2166 ));
2167 }
2168 out.push(Line::from(Span::styled(
2169 format!("adapter: {}", parts.join(" ")),
2170 Style::default().fg(colors::DIM),
2171 )));
2172 }
2173
2174 if s.rows_per_batch > 1.0 {
2175 out.push(Line::from(Span::styled(
2176 format!("rows/batch: {:.1}", s.rows_per_batch),
2177 Style::default().fg(colors::DIM),
2178 )));
2179 }
2180 }
2181
2182 out
2183 }
2184
2185 /// Offset that would put the tail (last entries) at the bottom of
2186 /// the tree view — i.e. the auto-follow position.
2187 fn tree_tail_offset(&self, tree_rect: Rect) -> usize {
2188 let visible = tree_rect.height.saturating_sub(2) as usize; // minus borders
2189 let total = self.run_state.load().phases.len();
2190 total.saturating_sub(visible)
2191 }
2192
2193 /// Drain pending base-cadence metrics frames. Updates the live
2194 /// latency values, history rings, and sparkline samples.
2195 ///
2196 /// Per-cadence windowed percentiles (10s / 1m / etc.) no longer
2197 /// flow through this channel — they're read directly from the
2198 /// shared [`MetricsQuery`] at render time, so we don't duplicate
2199 /// state.
2200 fn drain_frames(&mut self) {
2201 while let Ok(frame) = self.frame_rx.try_recv() {
2202 // Translate every frame ingest into actor commands —
2203 // never take a write lock on shared state. The actor
2204 // applies the LatencyFrame mutation, then the
2205 // SparklineSamples mutation; the TUI sees the
2206 // combined effect on the next snapshot load.
2207 if let Some(w) = extract_latency_from_frame(&frame) {
2208 self.run_state.send(RunStateCmd::LatencyFrame {
2209 min: w.min,
2210 p50: w.p50,
2211 p90: w.p90,
2212 p99: w.p99,
2213 p999: w.p999,
2214 max: w.max,
2215 });
2216 }
2217
2218 // Sparkline samples — derived from the snapshot's
2219 // first active phase. The adapter-counter sparkline
2220 // tracks the FIRST counter the active dispenser
2221 // reports, whatever its name. If no counter is
2222 // reported, the secondary sparkline stays empty.
2223 let snap = self.run_state.load();
2224 let (ops_sample, rows_sample, rows_name) = if let Some(active) = snap.first_active() {
2225 let (rate, name) = active
2226 .adapter_counters
2227 .first()
2228 .map(|(n, _, r)| (*r, Some(n.clone())))
2229 .unwrap_or((0.0, None));
2230 let sample: Option<f64> = name.as_ref().map(|_| rate);
2231 (Some(active.ops_per_sec), sample, name)
2232 } else {
2233 (None::<f64>, None::<f64>, None::<String>)
2234 };
2235 self.run_state.send(RunStateCmd::SparklineSamples {
2236 ops: ops_sample,
2237 rows: rows_sample,
2238 rows_label: rows_name,
2239 });
2240 }
2241 }
2242
2243 /// Render one frame. Public for testing with TestBackend.
2244 ///
2245 /// While paused, every read routes through the snapshot clone
2246 /// in `self.frozen_state` instead of the live state. Live
2247 /// observer updates keep flowing into `self.run_state` — they
2248 /// just don't affect the rendered frame until the user resumes.
2249 pub fn draw(&self, frame: &mut Frame) {
2250 // Advance the frame tick before any render reads it —
2251 // the readout engine's `phase_status` spinner uses it
2252 // to cycle Braille frames at the TUI's tick rate.
2253 self.frame_tick.set(self.frame_tick.get().wrapping_add(1));
2254 // Prefer the frozen snapshot when paused. Otherwise load
2255 // the live snapshot — a single atomic op that cannot
2256 // wait on any writer (SRD-02 §"Display and Diagnostic
2257 // Decoupling").
2258 let live_snap;
2259 let state: &RunState = if let Some(ref frozen) = self.frozen_state {
2260 frozen.as_ref()
2261 } else {
2262 live_snap = self.run_state.load();
2263 live_snap.as_ref()
2264 };
2265 let area = frame.area();
2266
2267 // Top-level layout — SRD 62 §"Panel composition".
2268 //
2269 // Phase, Latency, and Throughput are no longer top-level
2270 // panels; their content lives inside per-phase detail blocks
2271 // in the scenario tree. The canvas is a 4-section vertical
2272 // stack: Header, optional Log, Scenario (tree), Footer.
2273 let sections = Layout::default()
2274 .direction(Direction::Vertical)
2275 .constraints([
2276 Constraint::Length(3), // header
2277 Constraint::Min(3), // scenario (+ log panel)
2278 Constraint::Length(1), // footer
2279 ])
2280 .split(area);
2281
2282 self.draw_header(frame, sections[0], state);
2283
2284 // Bottom section routing:
2285 // - tree hidden (LOD:off): always show the log in the full
2286 // section so something useful is there and the hint in
2287 // the log title tells the user how to restore the tree.
2288 // - tree visible + log off: tree takes the whole section.
2289 // - tree visible + log on: split 50/50.
2290 if self.tree_lod == TreeLod::Hidden {
2291 self.draw_log(frame, sections[1], state);
2292 } else if self.show_log {
2293 let bottom = Layout::default()
2294 .direction(Direction::Vertical)
2295 .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
2296 .split(sections[1]);
2297 self.draw_tree(frame, bottom[0], state);
2298 self.draw_log(frame, bottom[1], state);
2299 } else {
2300 self.draw_tree(frame, sections[1], state);
2301 }
2302
2303 self.draw_footer(frame, sections[2]);
2304
2305 // Paused banner, top-right of the header row. Small and
2306 // readable, doesn't displace other header content.
2307 if self.paused {
2308 let banner = " ⏸ PAUSED (p to resume) ";
2309 let w = banner.chars().count() as u16;
2310 if sections[0].width > w + 2 {
2311 let x = sections[0].x + sections[0].width - w - 1;
2312 let r = Rect {
2313 x,
2314 y: sections[0].y,
2315 width: w,
2316 height: 1,
2317 };
2318 frame.render_widget(Clear, r);
2319 frame.render_widget(
2320 Paragraph::new(Span::styled(
2321 banner,
2322 Style::default().fg(colors::PHASE_FAILED).bold(),
2323 )),
2324 r,
2325 );
2326 }
2327 }
2328
2329 // Control-edit prompt renders above the footer as a
2330 // 2-line overlay (input line + result line). We clear
2331 // the region first so the footer text doesn't bleed
2332 // through. See SRD 23 §"TUI surface (sketch)".
2333 if let Some(ref prompt) = self.edit_prompt {
2334 let h = 2u16;
2335 if area.height > h + 1 {
2336 let r = Rect {
2337 x: area.x,
2338 y: area.y + area.height - h - 1,
2339 width: area.width,
2340 height: h,
2341 };
2342 frame.render_widget(Clear, r);
2343 let input_line = format!(" edit control › {}_", prompt.buffer);
2344 let result_line = match &prompt.last_result {
2345 None => " (name=value, Enter submits, Esc cancels)".to_string(),
2346 Some(Ok(msg)) => format!(" ✓ {msg}"),
2347 Some(Err(msg)) => format!(" ✗ {msg}"),
2348 };
2349 let rows = Layout::default()
2350 .direction(Direction::Vertical)
2351 .constraints([Constraint::Length(1), Constraint::Length(1)])
2352 .split(r);
2353 frame.render_widget(
2354 Paragraph::new(Span::styled(input_line, Style::default().bold())),
2355 rows[0],
2356 );
2357 let result_style = match &prompt.last_result {
2358 Some(Err(_)) => Style::default().fg(colors::PHASE_FAILED),
2359 Some(Ok(_)) => Style::default().fg(colors::PHASE_DONE),
2360 None => Style::default(),
2361 };
2362 frame.render_widget(
2363 Paragraph::new(Span::styled(result_line, result_style)),
2364 rows[1],
2365 );
2366 }
2367 }
2368
2369 // Help overlay is rendered last so it sits above everything.
2370 if self.show_help {
2371 self.draw_help(frame, area);
2372 }
2373 }
2374
2375 /// Centered help overlay listing every key binding. Dismissed with
2376 /// `?` (toggle) or `Esc`.
2377 fn draw_help(&self, frame: &mut Frame, area: Rect) {
2378 let entries: &[(&str, &str)] = &[
2379 ("q", "dismiss TUI (single tap); triple-tap to exit nmbrs"),
2380 ("C-c", "interrupt: restores the terminal and sends SIGINT"),
2381 ("?", "toggle this help panel"),
2382 ("␣", "focus tree, snap LOD=Default, track active phase"),
2383 ("↑ / ↓", "move tree selection"),
2384 ("← / →", "decrease / increase tree level of detail"),
2385 ("⏎", "expand / collapse selected phase"),
2386 ("esc", "close help, then collapse, then unfocus, then quit"),
2387 ("l", "toggle log panel"),
2388 ("C-l", "force a full screen redraw"),
2389 ("p", "pause / resume the display"),
2390 (
2391 "P",
2392 "dump the current screen to logs/<session>/tui_<ts>.dump",
2393 ),
2394 ("click", "focus tree at the clicked phase"),
2395 (
2396 "wheel",
2397 "scroll tree (tweened); snaps back to tail at bottom",
2398 ),
2399 ("╪", "latency range: peak over the last 5s"),
2400 ("╫", "latency range: peak over the last 10s"),
2401 ("╬", "latency range: 5s + 10s peaks on the same cell"),
2402 ];
2403
2404 // Size the panel around the content: widest "key" + " │ " + widest desc.
2405 let key_w = entries
2406 .iter()
2407 .map(|(k, _)| k.chars().count())
2408 .max()
2409 .unwrap_or(3);
2410 let desc_w = entries
2411 .iter()
2412 .map(|(_, d)| d.chars().count())
2413 .max()
2414 .unwrap_or(0);
2415 let inner_w = key_w + 3 + desc_w; // "key │ desc"
2416 let panel_w = (inner_w as u16 + 4).min(area.width.saturating_sub(4));
2417 let panel_h = (entries.len() as u16 + 4).min(area.height.saturating_sub(2));
2418
2419 let x = area.x + area.width.saturating_sub(panel_w) / 2;
2420 let y = area.y + area.height.saturating_sub(panel_h) / 2;
2421 let rect = Rect {
2422 x,
2423 y,
2424 width: panel_w,
2425 height: panel_h,
2426 };
2427
2428 // Clear underneath so the overlay reads cleanly over whatever
2429 // was drawn below.
2430 frame.render_widget(Clear, rect);
2431
2432 let block = Block::default()
2433 .borders(Borders::ALL)
2434 .border_style(Style::default().fg(colors::EMPHASIS))
2435 .title(Span::styled(
2436 " Help ",
2437 Style::default().fg(colors::EMPHASIS).bold(),
2438 ));
2439 let inner = block.inner(rect);
2440 frame.render_widget(block, rect);
2441
2442 let mut lines: Vec<Line> = Vec::with_capacity(entries.len());
2443 for (key, desc) in entries {
2444 lines.push(Line::from(vec![
2445 Span::styled(
2446 format!(" {:key_w$} ", key, key_w = key_w),
2447 Style::default().fg(colors::EMPHASIS).bold(),
2448 ),
2449 Span::styled("│ ", Style::default().fg(colors::BORDER)),
2450 Span::styled(*desc, Style::default().fg(colors::TEXT)),
2451 ]));
2452 }
2453 frame.render_widget(Paragraph::new(lines), inner);
2454 }
2455
2456 fn draw_header(&self, frame: &mut Frame, area: Rect, state: &RunState) {
2457 let elapsed_s = state.elapsed_secs();
2458 let elapsed = widgets::format_elapsed(elapsed_s);
2459
2460 // Phase ETA: based on cursor progress in whichever phase is
2461 // currently running (first one, by map iteration order).
2462 // Multi-phase scenarios will need a per-phase ETA attached
2463 // to each phase's detail block; header only shows one.
2464 let phase_eta = state.first_active().and_then(|a| {
2465 if a.ops_finished > 0 && a.cursor_extent > 0 {
2466 let phase_elapsed = (state.elapsed_secs() - a.session_started).max(0.0);
2467 let fraction = a.ops_finished as f64 / a.cursor_extent as f64;
2468 if fraction > 0.01 {
2469 let total_est = phase_elapsed / fraction;
2470 Some(widgets::format_elapsed(total_est - phase_elapsed))
2471 } else {
2472 None
2473 }
2474 } else {
2475 None
2476 }
2477 });
2478
2479 let block = Block::default()
2480 .borders(Borders::ALL)
2481 .border_style(Style::default().fg(colors::BORDER))
2482 .title(Span::styled(
2483 " nmbrs ",
2484 Style::default().fg(colors::EMPHASIS).bold(),
2485 ));
2486
2487 let mut spans = vec![
2488 Span::styled(" workload: ", Style::default().fg(colors::DIM)),
2489 Span::styled(&state.workload_file, Style::default().fg(colors::TEXT)),
2490 Span::styled(" scenario: ", Style::default().fg(colors::DIM)),
2491 Span::styled(&state.scenario_name, Style::default().fg(colors::TEXT)),
2492 Span::styled(" elapsed: ", Style::default().fg(colors::DIM)),
2493 Span::styled(elapsed, Style::default().fg(colors::EMPHASIS).bold()),
2494 ];
2495
2496 // Phase-progress counter: how far along the pre-mapped
2497 // plan are we? `current` is the largest `seq` of any
2498 // phase that's reached Running, Completed, or Failed —
2499 // i.e. the phase number the runtime is on (or just
2500 // finished). `total` comes from the pre-mapped tree.
2501 // Hidden until the pre-map has installed (`total > 0`)
2502 // so we don't print `phase 0/0` during scenario startup.
2503 let total = state.total_phases();
2504 if total > 0 {
2505 let current = state
2506 .phases
2507 .iter()
2508 .filter(|p| p.kind == crate::state::EntryKind::Phase)
2509 .filter(|p| !matches!(p.status, PhaseStatus::Pending))
2510 .filter_map(|p| p.seq)
2511 .max()
2512 .unwrap_or(0);
2513 spans.push(Span::styled(" phase ", Style::default().fg(colors::DIM)));
2514 spans.push(Span::styled(
2515 format!("{current}/{total}"),
2516 Style::default().fg(colors::EMPHASIS).bold(),
2517 ));
2518 }
2519
2520 if let Some(eta) = phase_eta {
2521 spans.push(Span::styled(
2522 " phase ETA: ",
2523 Style::default().fg(colors::DIM),
2524 ));
2525 spans.push(Span::styled(eta, Style::default().fg(colors::PHASE_ACTIVE)));
2526 }
2527 let line1 = Line::from(spans);
2528
2529 let para = Paragraph::new(line1).block(block);
2530 frame.render_widget(para, area);
2531 }
2532
2533 /// Build the fixed-width left status margin for a tree row: three
2534 /// consistent slots — a count, this leaf's cumulative time, and the
2535 /// session's cumulative time — followed (by the caller) with the `│`
2536 /// divider that separates the timing/progress margin from the semantic
2537 /// view. For a phase leaf the slots read as `[N/T]`, the phase's total
2538 /// time, and the session clock at this phase. Times persist after the
2539 /// leaf finishes (completed/failed use the frozen values); a running
2540 /// leaf shows live values; pending shows `—`. Scope rows (containers,
2541 /// not leaves) get a blank margin of the same width so the `│` column
2542 /// stays aligned down the whole tree. The slot *types* are uniform;
2543 /// their *meaning* specializes per leaf kind (and, later, per op).
2544 fn status_margin(&self, phase: &crate::state::PhaseEntry, state: &RunState) -> String {
2545 use crate::state::{EntryKind, PhaseStatus};
2546 let total = state.total_phases();
2547 if phase.kind == EntryKind::Scope {
2548 // Containers, not leaves — fully blank margin, same width.
2549 return " ".repeat(Self::margin_width(total));
2550 }
2551 let count = match phase.seq {
2552 Some(seq) => format!("[{seq}/{total}]"),
2553 None => String::new(),
2554 };
2555 let (leaf, sess): (Option<f64>, Option<f64>) = match &phase.status {
2556 PhaseStatus::Running => (
2557 state
2558 .active_phase(&phase.name, &phase.labels)
2559 .map(|a| (state.elapsed_secs() - a.session_started).max(0.0)),
2560 Some(state.elapsed_secs()),
2561 ),
2562 PhaseStatus::Completed | PhaseStatus::Failed(_) => {
2563 (phase.duration_secs, phase.session_elapsed)
2564 }
2565 PhaseStatus::Pending => (None, None),
2566 };
2567 Self::margin_fmt(total, &count, leaf, sess)
2568 }
2569
2570 /// Op-leaf variant of the status margin (SRD-63). Same three slots and the
2571 /// same fixed width as the phase margin (so the `│` column stays aligned),
2572 /// specialized: count = `[i/N]` within the phase, leaf-time = the op's
2573 /// execution time, session-time = the session clock at the op.
2574 fn op_status_margin(
2575 &self,
2576 op: &crate::state::OpEntry,
2577 op_total: usize,
2578 state: &RunState,
2579 ) -> String {
2580 use crate::state::PhaseStatus;
2581 let count = format!("[{}/{}]", op.seq + 1, op_total);
2582 let (leaf, sess): (Option<f64>, Option<f64>) = match &op.status {
2583 PhaseStatus::Running => (
2584 Some((state.elapsed_secs() - op.session_started).max(0.0)),
2585 Some(state.elapsed_secs()),
2586 ),
2587 PhaseStatus::Completed | PhaseStatus::Failed(_) => {
2588 (op.duration_secs, op.session_elapsed)
2589 }
2590 PhaseStatus::Pending => (None, None),
2591 };
2592 Self::margin_fmt(state.total_phases(), &count, leaf, sess)
2593 }
2594
2595 /// Fixed total width of the status margin, driven by `total_phases`'
2596 /// digit width so every row's divider aligns.
2597 fn margin_width(total_phases: usize) -> usize {
2598 let tw = total_phases.to_string().len().max(1);
2599 // Mark · " " · count · " " · leaf(8) · " " · session(8) — must track
2600 // `widgets::margin_body_width`, which the log-only surface uses, or the
2601 // two surfaces stop aligning with each other.
2602 widgets::TIMING_MARK.chars().count() + 1 + (tw * 2 + 3) + 1 + 8 + 1 + 8
2603 }
2604
2605 /// Format the margin from parts: `count` left-padded to the fixed count
2606 /// field, then the two right-aligned time slots (`—` when absent).
2607 fn margin_fmt(
2608 total_phases: usize,
2609 count: &str,
2610 leaf: Option<f64>,
2611 sess: Option<f64>,
2612 ) -> String {
2613 let tw = total_phases.to_string().len().max(1);
2614 let count_w = tw * 2 + 3;
2615 let leaf_s = leaf
2616 .map(widgets::format_dur_compact)
2617 .unwrap_or_else(|| "—".into());
2618 let sess_s = sess
2619 .map(widgets::format_dur_compact)
2620 .unwrap_or_else(|| "—".into());
2621 format!(
2622 "{} {count:<count_w$} {leaf_s:>8} {sess_s:>8}",
2623 widgets::TIMING_MARK
2624 )
2625 }
2626
2627 fn draw_tree(&self, frame: &mut Frame, area: Rect, state: &RunState) {
2628 // ActivePhase LOD renders as a chromeless single-phase
2629 // dashboard — no tree rows, no scope headers, title
2630 // repurposed to name the active phase(s). Delegates
2631 // entirely to a dedicated renderer so the tree path below
2632 // stays focused on the tree-shaped LODs.
2633 if self.tree_lod == TreeLod::ActivePhase {
2634 self.draw_active_phase_panel(frame, area, state);
2635 return;
2636 }
2637
2638 let has_focus = self.focused == Some(FocusedPane::Tree);
2639 let title_style = if has_focus {
2640 Style::default().fg(colors::EMPHASIS).bold()
2641 } else {
2642 Style::default().fg(colors::TEXT)
2643 };
2644 let lod_tag = format!(" [LOD:{}] ", self.tree_lod.label());
2645 let block = Block::default()
2646 .borders(Borders::ALL)
2647 .border_style(Style::default().fg(if has_focus {
2648 colors::EMPHASIS
2649 } else {
2650 colors::BORDER
2651 }))
2652 .title(Line::from(vec![
2653 Span::styled(" Scenario Tree ", title_style),
2654 Span::styled(lod_tag, Style::default().fg(colors::DIM)),
2655 ]));
2656
2657 let inner = block.inner(area);
2658 frame.render_widget(block, area);
2659
2660 // Hidden LOD renders nothing — the block border + title stay
2661 // (so the user can see they're in a tree pane with LOD=off
2662 // and press right-arrow to re-reveal).
2663 if self.tree_lod == TreeLod::Hidden {
2664 return;
2665 }
2666
2667 let mut lines: Vec<Line> = Vec::new();
2668 // Focus-mode bookkeeping: if no running phases exist, we
2669 // need to show a waiting/done placeholder instead of an
2670 // empty canvas. Tracked here because we can emit it after
2671 // the regular iteration finds no running phases to render.
2672 let mut focus_emitted_any = false;
2673 for (i, phase) in state.phases.iter().enumerate() {
2674 // LOD gating:
2675 // Minimal + Focus: omit scope headers.
2676 // Focus also omits pending/completed/failed phases —
2677 // only running ones render, each fully expanded.
2678 // Default/Maximal show scopes as grouping anchors.
2679 if matches!(self.tree_lod, TreeLod::Minimal | TreeLod::Focus)
2680 && phase.kind == crate::state::EntryKind::Scope
2681 {
2682 continue;
2683 }
2684 if self.tree_lod == TreeLod::Focus
2685 && phase.kind == crate::state::EntryKind::Phase
2686 && !matches!(phase.status, crate::state::PhaseStatus::Running)
2687 {
2688 continue;
2689 }
2690
2691 // Indentation: at Minimal / Focus LOD, scopes are
2692 // hidden, so preserving `phase.depth` would make
2693 // children of hidden scopes look like descendants of
2694 // the previous visible phase. Flatten to depth 0 —
2695 // dimensional labels already disambiguate the
2696 // iterations, so the hierarchy isn't lost.
2697 let effective_depth = if matches!(self.tree_lod, TreeLod::Minimal | TreeLod::Focus) {
2698 0
2699 } else {
2700 phase.depth
2701 };
2702 focus_emitted_any = true;
2703 let indent = " ".repeat(effective_depth);
2704 // Two-column left margin: selection marker + its trailing space.
2705 // `●` in column 0 means "this entry has focus". Non-selected
2706 // entries render two spaces, so the following content lines up
2707 // the same either way.
2708 let is_selected = has_focus && self.tree_selected == Some(i);
2709 let marker: Span = if is_selected {
2710 Span::styled("● ", Style::default().fg(colors::EMPHASIS).bold())
2711 } else {
2712 Span::raw(" ")
2713 };
2714
2715 // Scope headers render as a distinct line: no status glyph,
2716 // italic-ish group label. Keeps the hierarchy visible without
2717 // making peer phases look like children of each other.
2718 //
2719 // Scope nodes carry their description in `phase.name`
2720 // (e.g. `"for_each profile in [...]"`); `phase.labels`
2721 // is always empty for scopes (see scene_tree::NodeKind
2722 // doc). Earlier code rendered `labels` and got bare
2723 // `┬ ` lines.
2724 if phase.kind == crate::state::EntryKind::Scope {
2725 lines.push(Line::from(vec![
2726 // Scopes are containers, not execution leaves — blank
2727 // margin, but keep the divider so the `│` column stays
2728 // unbroken down the tree.
2729 Span::styled(
2730 self.status_margin(phase, state),
2731 Style::default().fg(colors::DIM),
2732 ),
2733 Span::styled(" │ ", Style::default().fg(colors::BORDER)),
2734 marker,
2735 Span::styled(format!("{indent}┬ "), Style::default().fg(colors::BORDER)),
2736 Span::styled(&phase.name, Style::default().fg(colors::TEXT).italic()),
2737 ]));
2738 continue;
2739 }
2740
2741 // Health tint = line color. Running phases are always
2742 // yellow (they haven't finished, so error counts aren't
2743 // meaningful yet). Completed phases are green/orange/red
2744 // on a sliding scale keyed to the observed error rate,
2745 // so the user can see at a glance whether a phase went
2746 // clean, had blips, or degraded badly.
2747 let health_color = phase_health_color(phase);
2748 let running_spinner = spinner_frame();
2749 let (icon, icon_color) = match &phase.status {
2750 PhaseStatus::Completed => ("✓", health_color),
2751 PhaseStatus::Running => (running_spinner, health_color),
2752 PhaseStatus::Pending => ("○", colors::PHASE_PENDING),
2753 PhaseStatus::Failed(_) => ("✗", colors::PHASE_FAILED),
2754 };
2755 let is_running = matches!(phase.status, PhaseStatus::Running);
2756 let name_style = match &phase.status {
2757 PhaseStatus::Running => Style::default().fg(health_color).bold(),
2758 PhaseStatus::Completed => Style::default().fg(health_color),
2759 PhaseStatus::Failed(_) => Style::default().fg(colors::PHASE_FAILED).bold(),
2760 _ => Style::default().fg(colors::DIM),
2761 };
2762 // Labels stay dim for completed so the health color on the
2763 // phase name is the eye-catching cue; for running they pick
2764 // up the yellow tint too so the whole live line reads hot.
2765 let label_color = if is_running {
2766 health_color
2767 } else {
2768 colors::DIM
2769 };
2770
2771 // Left status margin: a fixed-width column of
2772 // count · leaf-time · session-time, then the `│` that
2773 // separates the timing/progress margin from the semantic
2774 // view. The `[N/T]` count and this leaf's cumulative time
2775 // live here now (persisted), not inline on the right.
2776 let mut spans = vec![
2777 Span::styled(
2778 self.status_margin(phase, state),
2779 Style::default().fg(colors::DIM),
2780 ),
2781 Span::styled(" │ ", Style::default().fg(colors::BORDER)),
2782 marker,
2783 Span::styled(format!("{indent}{icon} "), Style::default().fg(icon_color)),
2784 ];
2785
2786 spans.push(Span::styled(&phase.name, name_style));
2787
2788 if !phase.labels.is_empty() {
2789 spans.push(Span::styled(
2790 format!(" ({})", phase.labels),
2791 Style::default().fg(label_color),
2792 ));
2793 }
2794
2795 if phase.op_count > 0 {
2796 // Structural metadata — number of op-template
2797 // entries declared under the phase's `ops:` key
2798 // in the YAML. Bracketed so it reads as a phase
2799 // shape (next to `qs:N` throughput) rather than
2800 // a count of executed queries. Plural matches
2801 // the count.
2802 spans.push(Span::styled(
2803 format!(
2804 " [{} op {}]",
2805 phase.op_count,
2806 if phase.op_count == 1 {
2807 "template"
2808 } else {
2809 "templates"
2810 }
2811 ),
2812 Style::default().fg(colors::DIM),
2813 ));
2814 }
2815
2816 match &phase.status {
2817 PhaseStatus::Completed => {
2818 // This leaf's cumulative time now lives in the left
2819 // status margin (persisted), not inline here.
2820 // Attach the completion summary so the tree acts
2821 // as a post-hoc record of what each phase produced.
2822 // Ordered for "tell me the key story" reading:
2823 // 1. cycles + rate (the engine-level throughput)
2824 // 2. adapter-declared domain metrics with rates
2825 // (rows_inserted/s, etc. — the thing the
2826 // workload actually cares about)
2827 // 3. relevancy metrics (recall/precision) — the
2828 // KEY metric for ANN/search workloads, so it
2829 // must be visible without expansion
2830 // 4. latency percentiles
2831 if let Some(ref sm) = phase.summary {
2832 if sm.ops_finished > 0 {
2833 // Label the cycle count/rate after the
2834 // cursor name (`rows:N @R/s`) so it
2835 // matches the phase detail's wording.
2836 // Falls back to `cycles:` when the
2837 // phase declares no cursor. Adapter
2838 // counters (rows_inserted, etc.) show
2839 // separately below.
2840 let unit = cursor_count_label(&sm.cursor_name);
2841 spans.push(Span::styled(
2842 format!(
2843 " {unit}:{} @{}/s",
2844 widgets::format_count(sm.ops_finished),
2845 widgets::format_rate(sm.ops_per_sec)
2846 ),
2847 Style::default().fg(colors::TEXT),
2848 ));
2849 }
2850 // Adapter-declared workload counters with rates
2851 // — this is "rows/s" for CQL INSERT workloads,
2852 // "queries/s" for search workloads, etc.
2853 for (name, total, rate) in &sm.adapter_counters {
2854 if *total == 0 {
2855 continue;
2856 }
2857 // `_batch_writes` and friends are derived-metric
2858 // denominators — hidden from the chip row.
2859 if nmbrs_runtime::is_internal_counter(name) {
2860 continue;
2861 }
2862 spans.push(Span::styled(
2863 format!(
2864 " {name}:{}@{}/s",
2865 widgets::format_count(*total),
2866 widgets::format_rate(*rate)
2867 ),
2868 Style::default().fg(colors::PHASE_ACTIVE),
2869 ));
2870 }
2871 // Relevancy (recall@k, precision@k, ...) — the
2872 // headline metric for ANN workloads. Rendered
2873 // in EMPHASIS + bold so it reads louder than
2874 // plain counts.
2875 for (name, _window_mean, total_mean, total_count, _window_len) in
2876 &sm.relevancy
2877 {
2878 if *total_count == 0 {
2879 continue;
2880 }
2881 spans.push(Span::styled(
2882 format!(" {name}:{:.4}", total_mean),
2883 Style::default().fg(colors::EMPHASIS).bold(),
2884 ));
2885 }
2886 if sm.p50_nanos > 0 {
2887 spans.push(Span::styled(
2888 format!(
2889 " p50:{} p99:{}",
2890 widgets::format_nanos(sm.p50_nanos),
2891 widgets::format_nanos(sm.p99_nanos)
2892 ),
2893 Style::default().fg(colors::LAT_P50),
2894 ));
2895 }
2896 }
2897 }
2898 PhaseStatus::Failed(err) => {
2899 spans.push(Span::styled(
2900 format!(" {err}"),
2901 Style::default().fg(colors::PHASE_FAILED),
2902 ));
2903 }
2904 _ => {}
2905 }
2906
2907 lines.push(Line::from(spans));
2908
2909 // Detail block: rendered under the phase when the user has
2910 // expanded it (Default LOD), or under every phase with data
2911 // (Maximal LOD). Same indent as the parent plus a pipe
2912 // gutter so the relationship is visible at a glance.
2913 if self.show_detail_for(i, phase) {
2914 // If this entry is the currently active phase, pull
2915 // live progress stats from the active-phases map;
2916 // otherwise fall back to the end-of-phase summary
2917 // snapshot.
2918 let live = state.active_phase(&phase.name, &phase.labels);
2919 // Detail pipe placement:
2920 // phase icon sits at column 2+(depth*2); we want
2921 // the continuation pipe one level deeper so it
2922 // reads as "this belongs to the phase above"
2923 // rather than drifting into the next sibling's
2924 // indent column. `indent + 2 spaces` puts the
2925 // pipe directly under the phase name's first
2926 // character, matching the tree's visual rhythm.
2927 let detail_indent = format!("{indent} ");
2928 for detail_line in self.format_phase_detail_with_live(phase, live) {
2929 let mut spans: Vec<Span<'static>> =
2930 Vec::with_capacity(detail_line.spans.len() + 2);
2931 spans.push(Span::raw(" "));
2932 spans.push(Span::styled(
2933 format!("{detail_indent}│ "),
2934 Style::default().fg(colors::BORDER),
2935 ));
2936 spans.extend(detail_line.spans);
2937 lines.push(Line::from(spans));
2938 }
2939
2940 // Drill view: when the user has pressed Right
2941 // on this expanded phase, render the stanza op
2942 // list under the detail block. One header row
2943 // ("ops:") plus one row per op name; the row
2944 // matching `drill_op_idx` gets a `▸` cursor
2945 // glyph so the selection is visible inside the
2946 // sub-list. The drill row count must match
2947 // `rendered_lines_for` exactly so scroll math
2948 // stays consistent (see SRD 62 §"Tree scroll").
2949 if self.tree_drilled == Some(i) {
2950 lines.push(Line::from(vec![
2951 Span::raw(" "),
2952 Span::styled(
2953 format!("{detail_indent}│ "),
2954 Style::default().fg(colors::BORDER),
2955 ),
2956 Span::styled("ops:", Style::default().fg(colors::DIM).italic()),
2957 ]));
2958 for (op_idx, op_name) in phase.op_names.iter().enumerate() {
2959 let is_drill_sel = op_idx == self.drill_op_idx;
2960 let cursor_glyph = if is_drill_sel { "▸ " } else { " " };
2961 let cursor_color = if is_drill_sel {
2962 colors::EMPHASIS
2963 } else {
2964 colors::BORDER
2965 };
2966 let name_style = if is_drill_sel {
2967 Style::default().fg(colors::TEXT).bold()
2968 } else {
2969 Style::default().fg(colors::TEXT)
2970 };
2971 lines.push(Line::from(vec![
2972 Span::raw(" "),
2973 Span::styled(
2974 format!("{detail_indent}│ "),
2975 Style::default().fg(colors::BORDER),
2976 ),
2977 Span::styled(cursor_glyph, Style::default().fg(cursor_color)),
2978 Span::styled(op_name.clone(), name_style),
2979 ]));
2980 }
2981 }
2982 }
2983
2984 // Op-level status leaves (SRD-63): ops that declared
2985 // `readout: visible` surface as their own timed rows,
2986 // indented one level under the phase and rendered whenever
2987 // the phase row renders (independent of expand/drill) —
2988 // opting an op in is a request to always see its live
2989 // status. The `│` divider + margin columns match the phase
2990 // rows so timing/session numbers stay in the left margin.
2991 // Row count here must equal `op_rows_for`.
2992 if let Some(ops) = state.phase_ops.get(&phase.node_id) {
2993 let op_total = ops.len();
2994 for op in ops {
2995 let (op_icon, op_color) = match &op.status {
2996 PhaseStatus::Completed => ("✓", colors::PHASE_DONE),
2997 PhaseStatus::Running => (spinner_frame(), colors::PHASE_ACTIVE),
2998 PhaseStatus::Pending => ("○", colors::PHASE_PENDING),
2999 PhaseStatus::Failed(_) => ("✗", colors::PHASE_FAILED),
3000 };
3001 let op_name_style = match &op.status {
3002 PhaseStatus::Running => Style::default().fg(colors::PHASE_ACTIVE).bold(),
3003 PhaseStatus::Completed => Style::default().fg(colors::TEXT),
3004 PhaseStatus::Failed(_) => Style::default().fg(colors::PHASE_FAILED).bold(),
3005 _ => Style::default().fg(colors::DIM),
3006 };
3007 let mut op_spans = vec![
3008 Span::styled(
3009 self.op_status_margin(op, op_total, state),
3010 Style::default().fg(colors::DIM),
3011 ),
3012 Span::styled(" │ ", Style::default().fg(colors::BORDER)),
3013 // Op rows aren't independently tree-selectable —
3014 // blank marker column keeps content aligned with
3015 // phase rows.
3016 Span::raw(" "),
3017 Span::styled(
3018 format!("{indent} {op_icon} "),
3019 Style::default().fg(op_color),
3020 ),
3021 Span::styled(op.name.clone(), op_name_style),
3022 ];
3023 if let PhaseStatus::Failed(err) = &op.status {
3024 op_spans.push(Span::styled(
3025 format!(" {err}"),
3026 Style::default().fg(colors::PHASE_FAILED),
3027 ));
3028 }
3029 lines.push(Line::from(op_spans));
3030 }
3031 }
3032 }
3033
3034 // Focus LOD with zero running phases: emit a placeholder so
3035 // the canvas isn't empty. Live vs. done is a component-tree
3036 // question (SRD 62 §"Scenario done?"):
3037 // Live → running_phase_count > 0
3038 // Waiting → any pre-mapped Pending phase (component tree
3039 // doesn't know about pre-map; that info lives
3040 // in state.phases from scenario_pre_mapped)
3041 // Done → neither — scenario has nothing left to do.
3042 if self.tree_lod == TreeLod::Focus && !focus_emitted_any {
3043 let live = self.metrics_query.running_phase_count() > 0;
3044 let any_pending = state.phases.iter().any(|p| {
3045 p.kind == crate::state::EntryKind::Phase
3046 && matches!(p.status, crate::state::PhaseStatus::Pending)
3047 });
3048 let (glyph, msg, color) = if live {
3049 // Running phases exist in the component tree but
3050 // haven't appeared in `state.phases` yet — a tiny
3051 // race window during phase start. Show waiting.
3052 ("○", "waiting for phase…", colors::PHASE_PENDING)
3053 } else if any_pending {
3054 ("○", "waiting for phase…", colors::PHASE_PENDING)
3055 } else {
3056 ("✓", "scenario complete", colors::PHASE_DONE)
3057 };
3058 lines.push(Line::from(vec![
3059 Span::raw(" "),
3060 Span::styled(format!("{glyph} "), Style::default().fg(color)),
3061 Span::styled(msg, Style::default().fg(colors::DIM).italic()),
3062 ]));
3063 }
3064
3065 // Pick the visible window. Default to auto-tail; if the user
3066 // has grabbed scroll focus, honor their offset. `tree_display`
3067 // carries the fractional, eased position — advanced in the
3068 // event loop before each draw — so the viewport tweens between
3069 // targets instead of snapping. The clamp deliberately allows
3070 // `start > tail` so a Space-pinned selection sits at the top
3071 // row even when the content is shorter than the panel; the
3072 // renderer's `skip` past the end yields fewer than `visible`
3073 // lines and Paragraph leaves the trailing rows blank.
3074 let visible = inner.height as usize;
3075 let total = lines.len();
3076 let start = self.tree_display.round().max(0.0) as usize;
3077 let start = start.min(total);
3078 let visible_lines: Vec<Line> = lines.into_iter().skip(start).collect();
3079
3080 frame.render_widget(Paragraph::new(visible_lines), inner);
3081
3082 // Scrollbar on the right edge of the block, drawn only when the
3083 // content overflows. Gives the user a visual sense of where
3084 // they are in the list and how much is off-screen.
3085 if total > visible {
3086 let mut sb_state = ScrollbarState::new(total)
3087 .position(start)
3088 .viewport_content_length(visible);
3089 let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight)
3090 .begin_symbol(None)
3091 .end_symbol(None)
3092 .style(Style::default().fg(colors::BORDER))
3093 .thumb_style(Style::default().fg(colors::EMPHASIS));
3094 frame.render_stateful_widget(scrollbar, area, &mut sb_state);
3095 }
3096 }
3097
3098 /// Advance the scroll animation toward the current target. Called
3099 /// once per frame while `draw_tree` runs, so the render reflects the
3100 /// tween's current intermediate position. If the target changed out
3101 /// from under the anim (e.g. auto-tail shifted because a new phase
3102 /// was added), re-aim without resetting time.
3103 fn advance_scroll_anim(&mut self, target: f32) {
3104 match self.tree_anim {
3105 None => {
3106 // No anim — just sync the display to the target.
3107 self.tree_display = target;
3108 }
3109 Some((from, to, started, duration)) => {
3110 // If the live target drifted away from the anim's `to`,
3111 // rewrite `to`. Don't restart the clock; the motion just
3112 // glides to the new endpoint.
3113 let to = if (to - target).abs() > 0.01 {
3114 target
3115 } else {
3116 to
3117 };
3118 let t = (started.elapsed().as_secs_f32() / duration.as_secs_f32()).clamp(0.0, 1.0);
3119 let eased = Self::smoothstep(t);
3120 self.tree_display = from + (to - from) * eased;
3121 if t >= 1.0 {
3122 self.tree_display = to;
3123 self.tree_anim = None;
3124 } else {
3125 self.tree_anim = Some((from, to, started, duration));
3126 }
3127 }
3128 }
3129 }
3130
3131 /// ActivePhase LOD renderer — a chromeless dashboard showing
3132 /// only the currently running phase(s)'s detail block(s).
3133 /// Replaces the scenario-tree panel for this LOD.
3134 ///
3135 /// Title is repurposed:
3136 /// - one running phase → " Phase: <name> (<labels>) "
3137 /// - N running phases → " Phases: <N> running "
3138 /// - zero running → placeholder banner inside the panel
3139 ///
3140 /// Detail rows come from the same `format_phase_detail_with_live`
3141 /// used by every other LOD, so the shape and contents match —
3142 /// just stripped of phase-header rows and tree-indent pipes.
3143 fn draw_active_phase_panel(&self, frame: &mut Frame, area: Rect, state: &RunState) {
3144 // Collect running phase entries in declaration order so the
3145 // panel reads top-to-bottom matching the tree in other LODs.
3146 let running: Vec<&crate::state::PhaseEntry> = state
3147 .phases
3148 .iter()
3149 .filter(|p| {
3150 p.kind == crate::state::EntryKind::Phase
3151 && matches!(p.status, crate::state::PhaseStatus::Running)
3152 })
3153 .collect();
3154
3155 let has_focus = self.focused == Some(FocusedPane::Tree);
3156 let title_style = if has_focus {
3157 Style::default().fg(colors::EMPHASIS).bold()
3158 } else {
3159 Style::default().fg(colors::TEXT)
3160 };
3161 let lod_tag = format!(" [LOD:{}] ", self.tree_lod.label());
3162 let total = state.total_phases();
3163 let title_text = match running.len() {
3164 0 => " Phase ".to_string(),
3165 1 => {
3166 let p = running[0];
3167 let seq_prefix = match (p.seq, total) {
3168 (Some(s), t) if t > 0 => format!("[{s}/{t}] ",),
3169 _ => String::new(),
3170 };
3171 // Phase name + coordinates appear on the per-phase
3172 // header line in the body (`[name] (coords)` in
3173 // blue + yellow). The title carries only the
3174 // optional seq counter so it stays narrow.
3175 format!(" Phase {seq_prefix}")
3176 }
3177 n => format!(" Phases: {n} running "),
3178 };
3179 let block = Block::default()
3180 .borders(Borders::ALL)
3181 .border_style(Style::default().fg(if has_focus {
3182 colors::EMPHASIS
3183 } else {
3184 colors::BORDER
3185 }))
3186 .title(Line::from(vec![
3187 Span::styled(title_text, title_style),
3188 Span::styled(lod_tag, Style::default().fg(colors::DIM)),
3189 ]));
3190 let inner = block.inner(area);
3191 frame.render_widget(block, area);
3192
3193 // Build the content as a flat list of Lines. Each running
3194 // phase contributes its full detail block. Separator lines
3195 // appear between multiple phases; with one phase the detail
3196 // flows straight from the top of the panel.
3197 let mut lines: Vec<Line<'static>> = Vec::new();
3198 if running.is_empty() {
3199 // Empty state — same live/waiting/done logic as Focus.
3200 let live_count = self.metrics_query.running_phase_count();
3201 let any_pending = state.phases.iter().any(|p| {
3202 p.kind == crate::state::EntryKind::Phase
3203 && matches!(p.status, crate::state::PhaseStatus::Pending)
3204 });
3205 let (glyph, msg, color) = if live_count > 0 || any_pending {
3206 ("○", "waiting for phase…", colors::PHASE_PENDING)
3207 } else {
3208 ("✓", "scenario complete", colors::PHASE_DONE)
3209 };
3210 lines.push(Line::from(vec![
3211 Span::raw(" "),
3212 Span::styled(format!("{glyph} "), Style::default().fg(color)),
3213 Span::styled(msg, Style::default().fg(colors::DIM).italic()),
3214 ]));
3215 } else {
3216 for (i, phase) in running.iter().enumerate() {
3217 // Blank-line separator between multiple running
3218 // phases — the per-phase header line below carries
3219 // the name (in blue) and coords (in yellow) so the
3220 // separator-with-name dash row is no longer needed.
3221 if i > 0 {
3222 lines.push(Line::from(""));
3223 }
3224 // `[name] (root-first coords)` header line — phase
3225 // name in blue, coordinate tuple stack in yellow,
3226 // coordinates reordered root-first so outer scopes
3227 // lead. Combines the previous separate name-title
3228 // row and standalone-coords row into a single
3229 // scannable line that mirrors the terminal-mode
3230 // observer's phase row.
3231 let seq_prefix = match (phase.seq, total) {
3232 (Some(s), t) if t > 0 => format!("[{s}/{t}] "),
3233 _ => String::new(),
3234 };
3235 let mut header_spans = vec![
3236 Span::raw(" "),
3237 Span::styled(seq_prefix, Style::default().fg(colors::DIM)),
3238 Span::styled(
3239 format!("[{}]", phase.name),
3240 Style::default().fg(colors::LOG_INFO).bold(),
3241 ),
3242 ];
3243 if !phase.labels.is_empty() {
3244 let root_first = crate::widgets::coords_root_first(&phase.labels);
3245 header_spans.push(Span::raw(" "));
3246 header_spans.push(Span::styled(
3247 root_first,
3248 Style::default().fg(colors::PHASE_RUNNING_TINT).bold(),
3249 ));
3250 }
3251 lines.push(Line::from(header_spans));
3252 let live = state.active_phase(&phase.name, &phase.labels);
3253 for detail_line in self.format_phase_detail_with_live(phase, live) {
3254 lines.push(detail_line);
3255 }
3256 }
3257 }
3258
3259 // Clip to the visible rows. No scroll tween in this LOD —
3260 // detail blocks are sized to fit typical phases at 120
3261 // cols, and a single phase rarely overflows the available
3262 // space. Wider scroll behavior is a Focus-LOD concern.
3263 let visible = inner.height as usize;
3264 let clipped: Vec<Line> = lines.into_iter().take(visible).collect();
3265 frame.render_widget(Paragraph::new(clipped), inner);
3266 }
3267
3268 fn draw_log(&self, frame: &mut Frame, area: Rect, state: &RunState) {
3269 // Title carries the current min-level filter so the
3270 // operator never has to wonder why a Debug entry didn't
3271 // appear; the `D` keybinding cycles the level.
3272 let level_label = match self.log_level_filter {
3273 crate::state::LogSeverity::Debug => "≥DBG",
3274 crate::state::LogSeverity::Info => "≥INF",
3275 crate::state::LogSeverity::Warn => "≥WRN",
3276 crate::state::LogSeverity::Error => "≥ERR",
3277 };
3278 let mut title: Vec<Span> = vec![
3279 Span::styled(" Log ", Style::default().fg(colors::LOG_INFO)),
3280 Span::styled(
3281 format!("[{level_label}] "),
3282 Style::default().fg(colors::DIM),
3283 ),
3284 ];
3285 if self.tree_lod == TreeLod::Hidden {
3286 // Tree-hidden hint: pinned to the right of the level
3287 // tag so the operator sees both pieces of context.
3288 title.extend([
3289 Span::styled("— tree hidden: ", Style::default().fg(colors::DIM)),
3290 Span::styled("→", Style::default().fg(colors::EMPHASIS).bold()),
3291 Span::styled(" to restore, ", Style::default().fg(colors::DIM)),
3292 Span::styled("?", Style::default().fg(colors::EMPHASIS).bold()),
3293 Span::styled(" for help ", Style::default().fg(colors::DIM)),
3294 ]);
3295 }
3296 let block = Block::default()
3297 .borders(Borders::ALL)
3298 .border_style(Style::default().fg(colors::BORDER))
3299 .title(Line::from(title));
3300
3301 let inner = block.inner(area);
3302 frame.render_widget(block, area);
3303
3304 // Filter first, then take the tail. Filtering after
3305 // tail-slicing would erase entries that would otherwise
3306 // be visible whenever the buffer happens to end in
3307 // below-threshold severities.
3308 //
3309 // SRD-81: the log panel is **diagnostics-only**. Phase
3310 // lifecycle / outcome renders are display projections that
3311 // belong in the tree / active-phase panel (rendered natively
3312 // via `TuiReadoutSink`), not here — a multi-line ANSI outcome
3313 // render would otherwise garble as a single un-split `Span`.
3314 let filtered: Vec<&crate::state::LogEntry> = state
3315 .log_messages
3316 .iter()
3317 .filter(|e| e.tag.attached.is_none())
3318 .filter(|e| e.severity >= self.log_level_filter)
3319 .collect();
3320 let visible = inner.height as usize;
3321 let start = filtered.len().saturating_sub(visible);
3322 let lines: Vec<Line> = filtered[start..]
3323 .iter()
3324 .map(|entry| {
3325 let (prefix, color) = match entry.severity {
3326 crate::state::LogSeverity::Debug => ("DBG", colors::LOG_DEBUG),
3327 crate::state::LogSeverity::Info => ("INF", colors::LOG_INFO),
3328 crate::state::LogSeverity::Warn => ("WRN", colors::LOG_WARN),
3329 crate::state::LogSeverity::Error => ("ERR", colors::LOG_ERROR),
3330 };
3331 Line::from(vec![
3332 Span::styled(format!(" {prefix} "), Style::default().fg(color).bold()),
3333 Span::styled(&entry.message, Style::default().fg(colors::TEXT)),
3334 ])
3335 })
3336 .collect();
3337
3338 frame.render_widget(Paragraph::new(lines), inner);
3339 }
3340
3341 /// Cycle the log panel's min-severity filter. Order:
3342 /// `Info → Debug → Warn → Error → Info`. Default is `Info`
3343 /// so high-cadence Debug entries stay hidden unless the
3344 /// operator opts in via the `D` keybinding.
3345 fn cycle_log_level_filter(&mut self) {
3346 use crate::state::LogSeverity::*;
3347 self.log_level_filter = match self.log_level_filter {
3348 Info => Debug,
3349 Debug => Warn,
3350 Warn => Error,
3351 Error => Info,
3352 };
3353 }
3354
3355 // ── SRD-63 Push 5b/7b: readout-binder navigation ──────
3356
3357 /// Cycle focus forward through the readouts bound to
3358 /// the most-recently-fired event slot. Public for the
3359 /// `Tab` keybind. No-op when the binder hasn't fired
3360 /// yet (no slot context).
3361 pub fn cycle_readout_focus_next(&mut self) {
3362 use nmbrs_runtime::readouts::{BinderKey, ReadoutBinder};
3363 self.readout_binder
3364 .borrow_mut()
3365 .on_key(BinderKey::CycleFocusNext);
3366 }
3367
3368 /// Cycle focus backward through the most-recent slot's
3369 /// readouts. Bound to Shift-Tab.
3370 pub fn cycle_readout_focus_prev(&mut self) {
3371 use nmbrs_runtime::readouts::{BinderKey, ReadoutBinder};
3372 self.readout_binder
3373 .borrow_mut()
3374 .on_key(BinderKey::CycleFocusPrev);
3375 }
3376
3377 /// Cycle the focused readout's LOD up
3378 /// (compact → labeled → expanded → compact). Bound to
3379 /// `+`. No-op when no readout is focused.
3380 pub fn cycle_readout_lod_up(&mut self) {
3381 use nmbrs_runtime::readouts::{BinderKey, ReadoutBinder};
3382 self.readout_binder
3383 .borrow_mut()
3384 .on_key(BinderKey::CycleLodUp);
3385 }
3386
3387 /// Cycle the focused readout's LOD down. Bound to `-`.
3388 pub fn cycle_readout_lod_down(&mut self) {
3389 use nmbrs_runtime::readouts::{BinderKey, ReadoutBinder};
3390 self.readout_binder
3391 .borrow_mut()
3392 .on_key(BinderKey::CycleLodDown);
3393 }
3394
3395 /// Toggle the explanation-overlay flag. While set, every
3396 /// readout fire emits `ContentMode::Explanation` instead
3397 /// of `Value`. Bound to `\`. The held-key semantics from
3398 /// SRD-63 are approximated as a press-toggle because
3399 /// crossterm's standard polling doesn't surface key-
3400 /// release reliably.
3401 pub fn toggle_readout_overlay(&mut self) {
3402 use nmbrs_runtime::readouts::{BinderKey, ReadoutBinder};
3403 let mut b = self.readout_binder.borrow_mut();
3404 let now = !b.overlay_held();
3405 b.on_key(BinderKey::OverlayHeld(now));
3406 }
3407
3408 /// Whether the explanation overlay is currently active.
3409 /// Surface code (footer, panel render path) reads this
3410 /// to render an indicator and to pass the right
3411 /// `ContentMode` when firing the binder.
3412 pub fn readout_overlay_active(&self) -> bool {
3413 self.readout_binder.borrow().overlay_held()
3414 }
3415
3416 fn draw_footer(&self, frame: &mut Frame, area: Rect) {
3417 let overlay = if self.readout_overlay_active() {
3418 " 📖 explain"
3419 } else {
3420 ""
3421 };
3422 let line = Line::from(vec![
3423 Span::styled(" q", Style::default().fg(colors::EMPHASIS).bold()),
3424 Span::styled(": quit ", Style::default().fg(colors::DIM)),
3425 Span::styled("↑↓", Style::default().fg(colors::EMPHASIS).bold()),
3426 Span::styled(": select ", Style::default().fg(colors::DIM)),
3427 Span::styled("←→", Style::default().fg(colors::EMPHASIS).bold()),
3428 Span::styled(": LOD ", Style::default().fg(colors::DIM)),
3429 Span::styled("⏎", Style::default().fg(colors::EMPHASIS).bold()),
3430 Span::styled(": expand ", Style::default().fg(colors::DIM)),
3431 Span::styled("␣", Style::default().fg(colors::EMPHASIS).bold()),
3432 Span::styled(": track active ", Style::default().fg(colors::DIM)),
3433 // SRD-63 Push 5b/7b readout-binder navigation:
3434 Span::styled("⇥", Style::default().fg(colors::EMPHASIS).bold()),
3435 Span::styled(": readout focus ", Style::default().fg(colors::DIM)),
3436 Span::styled("+/-", Style::default().fg(colors::EMPHASIS).bold()),
3437 Span::styled(": readout LOD ", Style::default().fg(colors::DIM)),
3438 Span::styled("\\", Style::default().fg(colors::EMPHASIS).bold()),
3439 Span::styled(": explain ", Style::default().fg(colors::DIM)),
3440 Span::styled("?", Style::default().fg(colors::EMPHASIS).bold()),
3441 Span::styled(": help ", Style::default().fg(colors::DIM)),
3442 Span::styled("esc", Style::default().fg(colors::EMPHASIS).bold()),
3443 Span::styled(": collapse/unfocus ", Style::default().fg(colors::DIM)),
3444 Span::styled("l", Style::default().fg(colors::EMPHASIS).bold()),
3445 Span::styled(": log ", Style::default().fg(colors::DIM)),
3446 Span::styled("p", Style::default().fg(colors::EMPHASIS).bold()),
3447 Span::styled(": pause ", Style::default().fg(colors::DIM)),
3448 Span::styled("P", Style::default().fg(colors::EMPHASIS).bold()),
3449 Span::styled(": dump", Style::default().fg(colors::DIM)),
3450 Span::styled(overlay, Style::default().fg(colors::EMPHASIS).bold()),
3451 ]);
3452 frame.render_widget(Paragraph::new(line), area);
3453 }
3454}
3455
3456/// Pull the cycles-servicetime percentiles out of a base-cadence
3457/// frame. Used to update live display fields and history rings —
3458/// per-cadence percentile data is served from `MetricsQuery`, not
3459/// this path.
3460struct LiveLatency {
3461 min: u64,
3462 p50: u64,
3463 p90: u64,
3464 p99: u64,
3465 p999: u64,
3466 max: u64,
3467}
3468
3469fn extract_latency_from_frame(snapshot: &MetricSet) -> Option<LiveLatency> {
3470 use nmbrs_metrics::snapshot::MetricValue;
3471 let family = snapshot.family("cycles_servicetime")?;
3472 for metric in family.metrics() {
3473 if let Some(point) = metric.point()
3474 && let MetricValue::Histogram(h) = point.value()
3475 {
3476 let r = &h.reservoir;
3477 return Some(LiveLatency {
3478 min: r.min(),
3479 p50: r.value_at_quantile(0.50),
3480 p90: r.value_at_quantile(0.90),
3481 p99: r.value_at_quantile(0.99),
3482 p999: r.value_at_quantile(0.999),
3483 max: r.max(),
3484 });
3485 }
3486 }
3487 None
3488}
3489
3490// =========================================================================
3491// Terminal teardown failsafe
3492// =========================================================================
3493
3494/// RAII guard for the TUI's terminal mode changes. Enabling raw
3495/// mode, entering the alternate screen, and turning on mouse
3496/// capture happen in [`Self::enter`]; reversing all three happens
3497/// in `Drop`. This gives every `?` error path, explicit `break`,
3498/// and panic a guaranteed cleanup opportunity — without it, a
3499/// failure mid-run would leave the user's shell in raw mode with
3500/// the alternate screen buffer still active.
3501struct TerminalGuard;
3502
3503impl TerminalGuard {
3504 fn enter() -> io::Result<Self> {
3505 // Capture the pre-raw termios so the signal handler can
3506 // restore it without going through crossterm (which is
3507 // not async-signal-safe). Without this, a SIGINT during
3508 // TUI mode leaves the terminal in raw + mouse-capture
3509 // state and the user's next keystrokes spew escape codes.
3510 save_pretui_termios();
3511 terminal::enable_raw_mode()?;
3512 io::stderr().execute(EnterAlternateScreen)?;
3513 io::stderr().execute(EnableMouseCapture)?;
3514 install_signal_terminal_restore();
3515 Ok(Self)
3516 }
3517}
3518
3519impl Drop for TerminalGuard {
3520 fn drop(&mut self) {
3521 // Best-effort — Drop can't return Result. Order matters:
3522 // mouse capture off first (it piggybacks on raw mode),
3523 // then leave the alternate screen, then raw mode off.
3524 let _ = io::stderr().execute(DisableMouseCapture);
3525 let _ = io::stderr().execute(LeaveAlternateScreen);
3526 let _ = terminal::disable_raw_mode();
3527 }
3528}
3529
3530// =====================================================================
3531// Signal handlers for terminal restoration
3532// =====================================================================
3533//
3534// When the process is killed by a signal we can intercept (SIGINT,
3535// SIGTERM, SIGHUP, SIGQUIT), the normal `Drop` for `TerminalGuard`
3536// never runs — the OS just terminates the process. Without
3537// intervention, the controlling terminal is left in raw mode with
3538// mouse capture and alternate-screen buffers still active. The
3539// shell that regains control then receives mouse-event escape
3540// codes for every cursor move, which is what the user reported.
3541//
3542// The fix is a Unix signal handler that does only async-signal-safe
3543// work (`write` + `tcsetattr`), then re-raises the signal with the
3544// default disposition so the process actually exits with the
3545// expected status. SIGKILL and SIGSTOP can't be intercepted —
3546// nothing to be done about those, but they're rare in practice.
3547
3548/// Non-Unix stub: there is no termios to save — crossterm's
3549/// `disable_raw_mode` restores the Windows console mode, and the
3550/// console host resets state when the process dies, so the
3551/// signal-handler restore dance below has no Windows analogue.
3552#[cfg(not(unix))]
3553pub(crate) fn save_pretui_termios() {}
3554
3555/// Non-Unix stub for the same reason as [`save_pretui_termios`].
3556#[cfg(not(unix))]
3557pub(crate) fn install_signal_terminal_restore() {}
3558
3559/// Original pre-TUI termios, captured before `enable_raw_mode` and
3560/// used by the signal handler to restore cooked-mode line
3561/// discipline. Wrapped in `OnceLock` so the first TUI startup wins.
3562#[cfg(unix)]
3563static PRETUI_TERMIOS: std::sync::OnceLock<libc::termios> = std::sync::OnceLock::new();
3564
3565#[cfg(unix)]
3566pub(crate) fn save_pretui_termios() {
3567 // tcgetattr on stderr (the TUI writes there). If this fails
3568 // (e.g. stderr isn't a tty), we skip — the signal handler will
3569 // still write the cleanup escape codes, which is enough to
3570 // make the user's shell usable even without a full termios
3571 // restore.
3572 let mut t: libc::termios = unsafe { std::mem::zeroed() };
3573 let rc = unsafe { libc::tcgetattr(libc::STDERR_FILENO, &mut t) };
3574 if rc == 0 {
3575 let _ = PRETUI_TERMIOS.set(t);
3576 }
3577}
3578
3579/// Install handlers for SIGINT, SIGTERM, SIGHUP, SIGQUIT that
3580/// restore the terminal and re-raise the signal. Idempotent.
3581///
3582/// Crate-public so the [`crate::key_watcher::KeyWatcher`] can
3583/// install it whenever raw mode is enabled — otherwise a Ctrl-C
3584/// → force-exit in `tui=terminal` mode (where only the watcher
3585/// is up, no `TerminalGuard`) leaves the shell in raw mode with
3586/// the user typing escape codes into their next prompt.
3587#[cfg(unix)]
3588pub(crate) fn install_signal_terminal_restore() {
3589 use std::sync::atomic::{AtomicBool, Ordering};
3590 static INSTALLED: AtomicBool = AtomicBool::new(false);
3591 if INSTALLED.swap(true, Ordering::SeqCst) {
3592 return;
3593 }
3594
3595 // Cast through a typed `extern "C" fn` first so the integer
3596 // cast is unambiguous (lints reject the direct `fn -> usize`).
3597 type SaHandler = extern "C" fn(libc::c_int, *mut libc::siginfo_t, *mut libc::c_void);
3598 let handler: SaHandler = signal_terminal_restore;
3599 let mut act: libc::sigaction = unsafe { std::mem::zeroed() };
3600 act.sa_sigaction = handler as usize;
3601 act.sa_flags = libc::SA_SIGINFO | libc::SA_RESTART;
3602 unsafe {
3603 libc::sigemptyset(&mut act.sa_mask);
3604 for sig in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP, libc::SIGQUIT] {
3605 libc::sigaction(sig, &act, std::ptr::null_mut());
3606 }
3607 }
3608}
3609
3610/// Async-signal-safe terminal-restore handler. The body uses only
3611/// `write`, `tcsetattr`, `signal`, and `raise` — all async-signal-safe.
3612#[cfg(unix)]
3613extern "C" fn signal_terminal_restore(
3614 sig: libc::c_int,
3615 _info: *mut libc::siginfo_t,
3616 _ucontext: *mut libc::c_void,
3617) {
3618 // Best-effort cleanup sequence. Order matches `TerminalGuard::drop`:
3619 // 1. disable mouse capture (all four reporting modes);
3620 // 2. leave the alternate screen;
3621 // 3. re-show the cursor (paranoid — TUIs sometimes hide it);
3622 // 4. reset SGR attributes (paranoid);
3623 // 5. restore the saved termios (cooked mode + signals).
3624 //
3625 // Each escape-sequence write goes via raw `write` to stderr,
3626 // which is async-signal-safe. crossterm's higher-level API
3627 // is not, so we hand-roll the sequences here.
3628 // `\x1b[999;1H` is the "park cursor at bottom-left"
3629 // idiom: terminals clamp the row to the actual last
3630 // visible row, so this lands on the bottom row of the
3631 // viewport regardless of terminal size. Followed by a
3632 // single `\r\n` so the cooked shell's next prompt prints
3633 // on a fresh line below whatever we just rendered (status
3634 // + prompt + log tail), and the user types into a clean
3635 // cell. Replaces the prior INLINE_STATUS_HEIGHT walk loop
3636 // — that approach drifted when scrolls had moved the
3637 // renderer's region around since the last height publish.
3638 const CLEANUP: &[u8] = concat!(
3639 "\x1b[?1000l", // disable basic mouse reporting
3640 "\x1b[?1002l", // disable button-event mouse reporting
3641 "\x1b[?1003l", // disable any-event mouse reporting
3642 "\x1b[?1006l", // disable SGR mouse reporting
3643 "\x1b[?1015l", // disable URXVT mouse reporting
3644 "\x1b[?1049l", // leave alternate screen
3645 "\x1b[?25h", // show cursor
3646 "\x1b[0m", // reset SGR
3647 "\x1b[999;1H", // park at absolute bottom-left (terminal clamps)
3648 "\r\n", // fresh line for the shell prompt
3649 )
3650 .as_bytes();
3651 unsafe {
3652 libc::write(
3653 libc::STDERR_FILENO,
3654 CLEANUP.as_ptr() as *const libc::c_void,
3655 CLEANUP.len(),
3656 );
3657 if let Some(t) = PRETUI_TERMIOS.get() {
3658 libc::tcsetattr(libc::STDERR_FILENO, libc::TCSANOW, t);
3659 }
3660 // Re-raise with default disposition so the process actually
3661 // exits with the signal's standard status. SIG_DFL on the
3662 // signal we just received, then `raise(sig)` lets the
3663 // kernel terminate us as if no handler had been installed.
3664 let mut act: libc::sigaction = std::mem::zeroed();
3665 act.sa_sigaction = libc::SIG_DFL;
3666 libc::sigaction(sig, &act, std::ptr::null_mut());
3667 libc::raise(sig);
3668 }
3669}
3670
3671/// Install a process-global panic hook that restores the terminal
3672/// before the default panic message prints. The previous hook is
3673/// preserved and re-invoked, so crash backtraces (from
3674/// `RUST_BACKTRACE=1` or similar) still render — just onto a
3675/// clean tty instead of on top of the alternate-screen buffer.
3676///
3677/// Idempotent via an atomic flag: the TUI may be started multiple
3678/// times in a single process (e.g. dev reloads), but only the
3679/// first call wraps the panic hook.
3680///
3681/// On panic the hook does three things, in order:
3682/// 1. Restore the terminal so the panic message lands on a normal
3683/// tty rather than on top of the alternate screen.
3684/// 2. Append a structured `PANIC` entry to the session log file (if
3685/// one was set up). This is the *durable* record — it survives
3686/// even when the terminal output is lost to a re-entered alt
3687/// screen, a backgrounded session, or a parent process that
3688/// swallowed stderr.
3689/// 3. Run the previous (default) hook so stack traces still render.
3690pub(crate) fn install_tui_panic_hook() {
3691 use std::sync::atomic::{AtomicBool, Ordering};
3692 static INSTALLED: AtomicBool = AtomicBool::new(false);
3693 if INSTALLED.swap(true, Ordering::SeqCst) {
3694 return;
3695 }
3696 let prev = std::panic::take_hook();
3697 std::panic::set_hook(Box::new(move |info| {
3698 // Same best-effort cleanup sequence as TerminalGuard::drop.
3699 let _ = io::stderr().execute(DisableMouseCapture);
3700 let _ = io::stderr().execute(LeaveAlternateScreen);
3701 let _ = terminal::disable_raw_mode();
3702
3703 // Durable record: route panic into the session log so the
3704 // user can see what happened post-mortem even when the
3705 // terminal was repainted by a worker thread that out-raced
3706 // the cleanup. See SRD 41 §"Diagnostic Log Routing".
3707 let location = info
3708 .location()
3709 .map(|l| format!("{}:{}", l.file(), l.line()))
3710 .unwrap_or_else(|| "<unknown>".into());
3711 let message = info
3712 .payload()
3713 .downcast_ref::<&'static str>()
3714 .map(|s| (*s).to_string())
3715 .or_else(|| info.payload().downcast_ref::<String>().cloned())
3716 .unwrap_or_else(|| "<non-string panic payload>".into());
3717 let thread = std::thread::current()
3718 .name()
3719 .unwrap_or("<unnamed>")
3720 .to_string();
3721 nmbrs_runtime::observer::log(
3722 nmbrs_runtime::observer::LogLevel::Error,
3723 &format!("PANIC at {location} on thread '{thread}': {message}"),
3724 );
3725
3726 // Default hook prints to stderr (now on the normal screen
3727 // since we left the alternate screen above).
3728 prev(info);
3729
3730 // Force-exit to prevent the still-running TUI render thread
3731 // from redrawing over the panic message we just printed.
3732 // Without this, the user sees a flash of the panic followed
3733 // by the TUI redraw clobbering it. The session log entry
3734 // above is the durable record either way.
3735 //
3736 // We exit only when this is a non-main-thread panic (i.e.,
3737 // a worker / render thread). A main-thread panic will
3738 // unwind through `App::run` and the TerminalGuard drops
3739 // cleanly — letting that happen avoids cutting short any
3740 // pending tokio runtime cleanup. Worker panics, though,
3741 // are unrecoverable from the TUI's perspective.
3742 if std::thread::current().name() != Some("main") {
3743 std::process::exit(101);
3744 }
3745 }));
3746}