use std::io::{self, Write};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc;
use std::thread::JoinHandle;
use std::time::Duration;
use nmbrs_runtime::observer::LogLevel;
use crate::display_sink::{DisplayInputs, DisplaySink, SinkHandle};
use crate::key_watcher::WatcherSignal;
use crate::prompt_state::{PromptAction, PromptState};
use crate::state::LogSeverity;
const POLL_INTERVAL: Duration = Duration::from_millis(50);
pub(crate) const RESUME_FRESH: u64 = u64::MAX;
pub fn fresh_resume_cursor() -> Arc<AtomicU64> {
Arc::new(AtomicU64::new(RESUME_FRESH))
}
pub struct LogOnlySink {
min_level: LogLevel,
sink_active: Arc<AtomicBool>,
key_rx: Option<mpsc::Receiver<WatcherSignal>>,
runtime: Option<tokio::runtime::Handle>,
resume_from: Option<Arc<AtomicU64>>,
}
impl LogOnlySink {
pub fn new(min_level: LogLevel, sink_active: Arc<AtomicBool>) -> Self {
Self {
min_level,
sink_active,
key_rx: None,
runtime: None,
resume_from: None,
}
}
pub fn with_resume(mut self, resume_from: Arc<AtomicU64>) -> Self {
self.resume_from = Some(resume_from);
self
}
pub fn with_keys(
mut self,
key_rx: mpsc::Receiver<WatcherSignal>,
runtime: Option<tokio::runtime::Handle>,
) -> Self {
self.key_rx = Some(key_rx);
self.runtime = runtime;
self
}
}
fn seed_last_seen(resume: Option<u64>, current: u64) -> u64 {
match resume {
Some(v) if v != RESUME_FRESH => v,
_ => current,
}
}
fn severity_to_level(s: LogSeverity) -> LogLevel {
match s {
LogSeverity::Debug => LogLevel::Debug,
LogSeverity::Info => LogLevel::Info,
LogSeverity::Warn => LogLevel::Warn,
LogSeverity::Error => LogLevel::Error,
}
}
impl DisplaySink for LogOnlySink {
fn start(self: Box<Self>, inputs: DisplayInputs) -> Box<dyn SinkHandle> {
let DisplayInputs {
state,
frame_rx,
metrics_query: _,
} = inputs;
let LogOnlySink {
min_level,
sink_active,
key_rx,
runtime,
resume_from,
} = *self;
let scrollback = state.take_log_stream();
let initial_seq = seed_last_seen(
resume_from.as_ref().map(|a| a.load(Ordering::Acquire)),
state.load().log_seq_total,
);
sink_active.store(true, Ordering::Release);
let stop = Arc::new(AtomicBool::new(false));
let stop_for_thread = stop.clone();
let sink_active_for_thread = sink_active.clone();
let state_for_thread = state.clone();
let join = std::thread::Builder::new()
.name("log-only-sink".into())
.spawn(move || {
run_render_loop(
state_for_thread,
frame_rx,
initial_seq,
min_level,
stop_for_thread,
key_rx,
runtime,
resume_from,
scrollback,
);
sink_active_for_thread.store(false, Ordering::Release);
})
.expect("spawn log-only-sink thread");
Box::new(LogOnlySinkHandle {
stop,
join: Some(join),
sink_active,
})
}
}
#[allow(clippy::too_many_arguments)]
fn run_render_loop(
state: crate::run_state_actor::RunStateHandle,
frame_rx: Option<std::sync::mpsc::Receiver<nmbrs_metrics::snapshot::MetricSet>>,
mut last_seen: u64,
min_level: LogLevel,
stop: Arc<AtomicBool>,
key_rx: Option<mpsc::Receiver<WatcherSignal>>,
runtime: Option<tokio::runtime::Handle>,
resume_from: Option<Arc<AtomicU64>>,
scrollback: crate::run_state_actor::ScrollbackReceiver,
) {
let mut stderr = io::stderr();
let mut status_published: Option<String> = None;
let mut first_paint = true;
let mut footer_return_up: u16 = 0;
let mut prompt: Option<PromptState> = key_rx.as_ref().map(|_| PromptState::new());
let mut prompt_dirty = prompt.is_some();
let mut repl_visibility_drawn = crate::repl_state::current();
let mut console_alt = false;
let mut gutter_state = GutterState::default();
let mut repl_alt_dirty = false;
let mut transcript_len_drawn: usize = 0;
while !stop.load(Ordering::Acquire) {
if let Some(rx) = &frame_rx {
loop {
match rx.try_recv() {
Ok(_frame) => {}
Err(std::sync::mpsc::TryRecvError::Empty) => break,
Err(std::sync::mpsc::TryRecvError::Disconnected) => return,
}
}
}
let mut submitted_commands: Vec<String> = Vec::new();
let mut completion_lists: Vec<Vec<String>> = Vec::new();
if let (Some(rx), Some(p)) = (key_rx.as_ref(), prompt.as_mut()) {
loop {
match rx.try_recv() {
Ok(WatcherSignal::Key(ke)) => {
if matches!(
ke.code,
crossterm::event::KeyCode::Char('p')
| crossterm::event::KeyCode::Char('P')
) && ke.modifiers.is_empty()
&& matches!(
crate::repl_state::current(),
crate::repl_state::ReplVisibility::Hidden
)
{
let paused = nmbrs_runtime::observer::toggle_readout_pause();
let _ = write!(
stderr,
"\r\n{}\r\n",
if paused {
"⏸ readout paused for copy — press 'p' to resume"
} else {
"▶ readout resumed"
}
);
let _ = stderr.flush();
continue;
}
match p.handle_key(ke) {
PromptAction::Continue => {}
PromptAction::Submit(line) => submitted_commands.push(line),
PromptAction::ShowCompletions(list) => completion_lists.push(list),
PromptAction::GrowWindow => {
p.grow_window();
}
PromptAction::ShrinkWindow => {
p.shrink_window();
}
PromptAction::ToggleHelp => {
p.toggle_help();
}
PromptAction::Interrupt => {
unsafe {
libc::raise(libc::SIGINT);
}
}
}
prompt_dirty = true;
}
Ok(WatcherSignal::GrowPrompt) => {
p.grow_window();
prompt_dirty = true;
}
Ok(WatcherSignal::ShrinkPrompt) => {
p.shrink_window();
prompt_dirty = true;
}
Ok(WatcherSignal::ToggleHelp) => {
p.toggle_help();
prompt_dirty = true;
}
Ok(_) => { }
Err(mpsc::TryRecvError::Empty) => break,
Err(mpsc::TryRecvError::Disconnected) => {
prompt = None;
prompt_dirty = false;
break;
}
}
}
}
if nmbrs_runtime::observer::readouts_paused() {
std::thread::sleep(POLL_INTERVAL);
continue;
}
let snap = state.load();
let folded = crate::status_fold::render_active_status_with_gutters(&snap);
let next_status: Option<String> = folded.as_ref().map(|(t, _)| t.clone());
let status_gutters: Vec<crate::status_fold::RowGutter> =
folded.map(|(_, g)| g).unwrap_or_default();
let status_changed = next_status != status_published;
let dispatched_lines = !submitted_commands.is_empty() || !completion_lists.is_empty();
for list in &completion_lists {
crate::repl_state::push_transcript_line(&list.join(" "));
}
for line in &submitted_commands {
let response = crate::inspector_server::dispatch(line, &state, runtime.as_ref());
crate::repl_state::push_transcript(line, &response);
}
let repl_now = crate::repl_state::current();
let console_visible = !matches!(repl_now, crate::repl_state::ReplVisibility::Hidden);
if console_visible && !console_alt {
let _ = write!(stderr, "\x1b[?1049h\x1b[2J\x1b[H");
let _ = stderr.flush();
console_alt = true;
repl_alt_dirty = true;
} else if !console_visible && console_alt {
let _ = write!(stderr, "\x1b[?1049l");
let _ = stderr.flush();
repl_visibility_drawn = repl_now;
console_alt = false;
}
if console_alt {
let repl_switch = repl_now != repl_visibility_drawn;
repl_visibility_drawn = repl_now;
let tlen = crate::repl_state::transcript_len();
let transcript_changed = tlen != transcript_len_drawn;
if repl_alt_dirty
|| prompt_dirty
|| dispatched_lines
|| repl_switch
|| transcript_changed
{
let (cols, rows) = terminal_size_via_ioctl().unwrap_or((200, 50));
redraw_console_altscreen(&mut stderr, prompt.as_ref(), cols, rows);
repl_alt_dirty = false;
prompt_dirty = false;
transcript_len_drawn = tlen;
}
status_published = next_status;
std::thread::sleep(POLL_INTERVAL);
continue;
}
let mut new_logs: Vec<(
crate::state::LogEntry,
String,
Option<nmbrs_runtime::wrappers::gutter::GutterSpec>,
)> = Vec::new();
while let Some(line) = scrollback.try_next() {
if line.seq > last_seen {
last_seen = line.seq;
new_logs.push((line.entry, line.margin_body, line.detail_gutter));
}
}
let need_log_emit = !new_logs.is_empty();
let repl_changed = repl_now != repl_visibility_drawn;
repl_visibility_drawn = repl_now;
let must_redraw =
need_log_emit || status_changed || dispatched_lines || prompt_dirty || repl_changed;
if must_redraw {
let (cols, rows) = terminal_size_via_ioctl().unwrap_or((200, 50));
let status_margin = format_margin_prefix(&snap, nmbrs_runtime::observer::use_color());
let margin_visible_width = visible_width(&status_margin) as u16;
let status_cols = (cols as usize).saturating_sub(margin_visible_width as usize);
let window_mode = matches!(repl_now, crate::repl_state::ReplVisibility::Window);
let repl_visible = !matches!(repl_now, crate::repl_state::ReplVisibility::Hidden);
let new_status_text: Option<String> = if window_mode {
let color = nmbrs_runtime::observer::use_color();
let dim = if color { "\x1b[2m" } else { "" };
let reset = if color { "\x1b[0m" } else { "" };
Some(format!("{dim}REPL · ` close · ~ hide{reset}"))
} else {
next_status
.as_ref()
.map(|s| clamp_multiline(s, status_cols.saturating_sub(1)))
};
if window_mode && let Some(p) = prompt.as_mut() {
let target = rows.saturating_sub(2).max(1);
if p.window_rows() != target {
p.set_window_rows(target);
}
}
let prompt_input = if repl_visible {
prompt.as_ref().map(|p| {
let win_rows = p.window_rows() as usize;
let rendered = if win_rows > 1 {
let transcript_rows = win_rows.saturating_sub(1);
let tail = crate::repl_state::transcript_tail(transcript_rows);
let cols_usize = cols as usize;
let mut composed = String::with_capacity(cols_usize * win_rows);
let blanks = transcript_rows.saturating_sub(tail.len());
for _ in 0..blanks {
composed.push_str("\r\n");
}
for line in tail.iter() {
let row = nmbrs_runtime::activity::truncate_to_width(line, cols_usize);
composed.push_str(&row);
composed.push_str("\r\n");
}
let mut input_row = String::with_capacity(128);
p.render(&mut input_row, cols_usize, true);
let last = input_row.split('\n').next_back().unwrap_or("");
composed.push_str(last.strip_suffix('\r').unwrap_or(last));
composed
} else {
let mut f = String::with_capacity(128);
p.render(&mut f, cols as usize, true);
f
};
PromptInput {
rendered,
window_rows: p.window_rows(),
cursor_col: p.cursor_col() as u16,
}
})
} else {
None
};
if !first_paint {
if footer_return_up > 0 {
let _ = write!(stderr, "\x1b[{footer_return_up}A");
}
let _ = write!(stderr, "\r\x1b[J");
}
if need_log_emit {
let color = nmbrs_runtime::observer::use_color();
for (entry, margin_body, detail_gutter) in &new_logs {
let margin = format_margin_from_body(margin_body, color);
let margin = &margin;
let entry_level = severity_to_level(entry.severity);
if entry_level < min_level {
continue;
}
if entry.tag.attached.is_some()
&& entry.tag.category == crate::state::EventCategory::General
{
continue;
}
if entry
.message
.starts_with("session: graceful shutdown requested")
|| entry.message.starts_with("session: force-exit")
{
let _ = write!(stderr, "\r\n");
}
let painted =
nmbrs_runtime::observer::colorize_log_line(entry_level, &entry.message);
let w = visible_width(margin);
let cell_w = w.saturating_sub(2);
let blank_margin = if w == 0 {
String::new()
} else {
format!("\x1b[2m{:<cell_w$}│\x1b[0m ", "")
};
let final_cell: Option<String> =
detail_gutter.as_ref().map(|spec| match spec {
nmbrs_runtime::wrappers::gutter::GutterSpec::Labeled {
name,
value,
} => labeled_gutter(name, value, cell_w, color),
nmbrs_runtime::wrappers::gutter::GutterSpec::Text(t) => {
text_gutter(t, cell_w, color)
}
nmbrs_runtime::wrappers::gutter::GutterSpec::Bar(f) => {
bar_gutter(*f, cell_w, color)
}
nmbrs_runtime::wrappers::gutter::GutterSpec::Spark(v) => {
text_gutter(&format!("{v:.2}"), cell_w, color)
}
});
let headers_only = matches!(
nmbrs_runtime::observer::completed_phase_display(),
nmbrs_runtime::observer::CompletedPhaseDisplay::Headers
);
let is_detail_entry = entry.tag.attached.is_some()
&& entry.tag.category == crate::state::EventCategory::Evaluation;
if headers_only && is_detail_entry {
continue;
}
let rows: Vec<&str> = painted.split('\n').collect();
let roles = crate::status_fold::classify_block(&rows);
for (i, row) in rows.iter().enumerate() {
let role = roles[i];
if headers_only
&& entry.tag.category == crate::state::EventCategory::Outcome
&& role != crate::status_fold::RowRole::Header
{
continue;
}
let row_margin: &str = if is_detail_entry {
final_cell.as_deref().unwrap_or(&blank_margin)
} else {
match role {
crate::status_fold::RowRole::Header => margin,
crate::status_fold::RowRole::Standard => {
final_cell.as_deref().unwrap_or(&blank_margin)
}
_ => &blank_margin,
}
};
let _ = write!(stderr, "{row_margin}{row}\r\n");
}
}
}
let (_drawn_rows, cursor_below_top) = draw_footer_at_cursor(
&mut stderr,
new_status_text.as_deref(),
prompt_input.as_ref(),
cols,
&status_margin,
margin_visible_width,
&status_gutters,
&mut gutter_state,
);
footer_return_up = cursor_below_top;
let _ = _drawn_rows;
first_paint = false;
let _ = stderr.flush();
prompt_dirty = false;
}
status_published = next_status;
std::thread::sleep(POLL_INTERVAL);
}
if console_alt {
let _ = write!(stderr, "\x1b[?1049l");
let _ = stderr.flush();
}
if footer_return_up > 0 {
let _ = write!(stderr, "\x1b[{footer_return_up}A");
}
let _ = write!(stderr, "\r\x1b[J");
let _ = stderr.flush();
if let Some(a) = &resume_from {
a.store(last_seen, Ordering::Release);
}
}
fn format_margin_prefix(snap: &std::sync::Arc<crate::state::RunState>, color: bool) -> String {
format_margin_from_body(&snap.margin_body_stamp(), color)
}
fn format_margin_from_body(body: &str, color: bool) -> String {
let dim = if color { "\x1b[2m" } else { "" };
let reset = if color { "\x1b[0m" } else { "" };
format!("{dim}{body} \u{2502}{reset} ")
}
#[cfg(unix)]
fn terminal_size_via_ioctl() -> Option<(u16, u16)> {
#[repr(C)]
struct WinSize {
ws_row: u16,
ws_col: u16,
ws_xpixel: u16,
ws_ypixel: u16,
}
let mut ws = WinSize {
ws_row: 0,
ws_col: 0,
ws_xpixel: 0,
ws_ypixel: 0,
};
let rc = unsafe { libc::ioctl(2, libc::TIOCGWINSZ, &mut ws as *mut _) };
if rc < 0 || ws.ws_col == 0 || ws.ws_row == 0 {
return None;
}
Some((ws.ws_col, ws.ws_row))
}
#[cfg(not(unix))]
fn terminal_size_via_ioctl() -> Option<(u16, u16)> {
crossterm::terminal::size()
.ok()
.filter(|&(c, r)| c != 0 && r != 0)
}
pub(crate) struct PromptInput {
pub rendered: String,
pub window_rows: u16,
pub cursor_col: u16,
}
pub(crate) fn draw_footer_at_cursor<W: Write>(
out: &mut W,
status_text: Option<&str>,
prompt: Option<&PromptInput>,
term_cols: u16,
status_margin: &str,
margin_width: u16,
gutters: &[crate::status_fold::RowGutter],
gutter_state: &mut GutterState,
) -> (u16, u16) {
let status_lines: Vec<&str> = status_text
.map(|s| s.split('\n').collect())
.unwrap_or_default();
let status_rows_n = status_lines.len() as u16;
let prompt_rows = prompt.map(|p| p.window_rows).unwrap_or(0);
let total = status_rows_n + prompt_rows;
if total == 0 {
return (0, 0);
}
let avail = (term_cols as usize).saturating_sub(margin_width as usize);
let use_color_now = nmbrs_runtime::observer::use_color();
let blank_w = (margin_width as usize).saturating_sub(2);
let blank_margin_owned = if margin_width == 0 {
String::new()
} else {
format!("\x1b[2m{:<blank_w$}│\x1b[0m ", "")
};
let blank_margin: &str = &blank_margin_owned;
let mut first = true;
for (i, row) in status_lines.iter().enumerate() {
if !first {
let _ = write!(out, "\r\n");
}
first = false;
let ctx_margin_owned;
let margin = if margin_width == 0 {
status_margin
} else {
match gutters.get(i) {
Some(crate::status_fold::RowGutter::Header(body)) => {
ctx_margin_owned = format_margin_from_body(body, use_color_now);
&ctx_margin_owned
}
Some(crate::status_fold::RowGutter::Metric { key, name, value }) => {
ctx_margin_owned = metric_gutter(
gutter_state.rings.entry(key.clone()).or_default(),
name,
*value,
blank_w,
use_color_now,
);
&ctx_margin_owned
}
Some(crate::status_fold::RowGutter::Bar(f)) => {
ctx_margin_owned = bar_gutter(*f, blank_w, use_color_now);
&ctx_margin_owned
}
Some(crate::status_fold::RowGutter::Latency {
key,
p50,
p99,
count,
}) => {
let cell = gutter_state.latency.entry(key.clone()).or_default();
if *count != cell.last_count
|| cell.last_w != blank_w
|| cell.last_render.is_empty()
{
cell.last_render =
latency_gutter(&mut cell.ring, *p50, *p99, blank_w, use_color_now);
cell.last_count = *count;
cell.last_w = blank_w;
}
ctx_margin_owned = cell.last_render.clone();
&ctx_margin_owned
}
Some(crate::status_fold::RowGutter::LatencyHist { key, p50, count }) => {
let cell = gutter_state.hists.entry(key.clone()).or_insert_with(|| {
HistCellState {
trend: crate::widgets::DecimatingTrend::new(
blank_w.saturating_sub(12).max(4),
),
last_count: 0,
last_w: 0,
last_render: String::new(),
}
});
if *count != cell.last_count
|| cell.last_w != blank_w
|| cell.last_render.is_empty()
{
cell.last_render =
latency_hist_gutter(&mut cell.trend, *p50, blank_w, use_color_now);
cell.last_count = *count;
cell.last_w = blank_w;
}
ctx_margin_owned = cell.last_render.clone();
&ctx_margin_owned
}
Some(crate::status_fold::RowGutter::Text(t)) => {
ctx_margin_owned = text_gutter(t, blank_w, use_color_now);
&ctx_margin_owned
}
Some(crate::status_fold::RowGutter::Sysmon { items }) => {
ctx_margin_owned = sysmon_gutter(items, blank_w, use_color_now);
&ctx_margin_owned
}
Some(crate::status_fold::RowGutter::Labeled { name, value }) => {
ctx_margin_owned = labeled_gutter(name, value, blank_w, use_color_now);
&ctx_margin_owned
}
Some(crate::status_fold::RowGutter::BarText { frac, text }) => {
ctx_margin_owned = bar_text_gutter(*frac, text, blank_w, use_color_now);
&ctx_margin_owned
}
Some(crate::status_fold::RowGutter::Spark { key, value }) => {
ctx_margin_owned = spark_gutter(
gutter_state.rings.entry(key.clone()).or_default(),
*value,
blank_w,
use_color_now,
);
&ctx_margin_owned
}
_ if i == 0 => status_margin,
_ => blank_margin,
}
};
let fitted = nmbrs_runtime::activity::truncate_to_width(row, avail);
let reset_tail = if fitted.len() != row.len() {
"\x1b[0m"
} else {
""
};
let _ = write!(out, "\r\x1b[K{margin}{fitted}{reset_tail}");
}
if let Some(p) = prompt {
for row in p.rendered.split('\n') {
if !first {
let _ = write!(out, "\r\n");
}
first = false;
let row = row.strip_suffix('\r').unwrap_or(row);
let row = row.strip_prefix('\r').unwrap_or(row);
let _ = write!(out, "\r\x1b[K{status_margin}{row}");
}
let target_col = margin_width + p.cursor_col + 1;
let _ = write!(out, "\x1b[{target_col}G");
}
(total, total.saturating_sub(1))
}
fn redraw_console_altscreen<W: Write>(
out: &mut W,
prompt: Option<&PromptState>,
cols: u16,
rows: u16,
) {
let color = nmbrs_runtime::observer::use_color();
let dim = if color { "\x1b[2m" } else { "" };
let reset = if color { "\x1b[0m" } else { "" };
let cols_usize = cols as usize;
let _ = write!(
out,
"\x1b[1;1H\x1b[K{dim}REPL · ~ or ` to close · ↑↓ history{reset}"
);
let body_rows = (rows as usize).saturating_sub(2);
let tail = crate::repl_state::transcript_tail(body_rows);
let blanks = body_rows.saturating_sub(tail.len());
let mut row: u16 = 2;
for _ in 0..blanks {
let _ = write!(out, "\x1b[{row};1H\x1b[K");
row += 1;
}
for line in &tail {
let painted = nmbrs_runtime::activity::truncate_to_width(line, cols_usize);
let _ = write!(out, "\x1b[{row};1H\x1b[K{painted}");
row += 1;
}
let mut cursor_col: u16 = 0;
if let Some(p) = prompt {
let mut input = String::with_capacity(128);
p.render(&mut input, cols_usize, true);
let last = input.split('\n').next_back().unwrap_or("");
let last = last.strip_suffix('\r').unwrap_or(last);
let _ = write!(out, "\x1b[{rows};1H\x1b[K{last}");
cursor_col = p.cursor_col() as u16;
} else {
let _ = write!(out, "\x1b[{rows};1H\x1b[K");
}
let _ = write!(out, "\x1b[{rows};{}H", cursor_col + 1);
let _ = out.flush();
}
fn bar_gutter(frac: f64, w: usize, color: bool) -> String {
let dim = if color { "\x1b[2m" } else { "" };
let reset = if color { "\x1b[0m" } else { "" };
let bg = if color { "\x1b[48;2;50;50;50m" } else { "" };
let bright = if color { "\x1b[97m" } else { "" };
let bar = nmbrs_runtime::readouts::format::braille_bar(frac * 100.0, w);
format!("{bg}{bright}{bar}{reset}{dim}│{reset} ")
}
fn latency_gutter(
ring: &mut std::collections::VecDeque<f64>,
p50: u64,
p99: u64,
w: usize,
color: bool,
) -> String {
let dim = if color { "\x1b[2m" } else { "" };
let reset = if color { "\x1b[0m" } else { "" };
let cyan = if color { "\x1b[36m" } else { "" };
let fmt = |n: u64| {
let ms = n as f64 / 1e6;
if ms >= 100.0 {
format!("{ms:.0}")
} else if ms >= 10.0 {
format!("{ms:.1}")
} else {
format!("{ms:.2}")
}
};
let text = format!("{}∕{}ms", fmt(p50), fmt(p99));
let spark_w = w.saturating_sub(text.chars().count() + 1).max(4);
ring.push_back(p50 as f64 / 1e6);
while ring.len() > spark_w {
ring.pop_front();
}
let samples: Vec<f64> = ring.iter().copied().collect();
let spark = crate::widgets::sparkline_str(&samples, spark_w);
format!(
"{cyan}{spark}{reset} {dim}{text:>tw$}│{reset} ",
tw = w.saturating_sub(spark_w + 1)
)
}
fn metric_gutter(
ring: &mut std::collections::VecDeque<f64>,
name: &str,
value: f64,
w: usize,
color: bool,
) -> String {
let accent = if color { "\x1b[1;95m" } else { "" };
let dim = if color { "\x1b[2m" } else { "" };
let reset = if color { "\x1b[0m" } else { "" };
let label = nmbrs_runtime::activity::truncate_to_width(name, w.saturating_sub(5).max(4));
let label_w = label.chars().count();
let spark_w = w.saturating_sub(label_w + 1).max(4);
ring.push_back(value);
while ring.len() > spark_w {
ring.pop_front();
}
let samples: Vec<f64> = ring.iter().copied().collect();
let spark = crate::widgets::sparkline_str(&samples, spark_w);
format!(
"{accent}{spark}{reset} {dim}{label:>lw$}│{reset} ",
lw = w.saturating_sub(spark_w + 1)
)
}
fn bar_text_gutter(frac: f64, text: &str, w: usize, color: bool) -> String {
let dim = if color { "\x1b[2m" } else { "" };
let reset = if color { "\x1b[0m" } else { "" };
let bg = if color { "\x1b[48;2;50;50;50m" } else { "" };
let bright = if color { "\x1b[97m" } else { "" };
let bar_w = if w >= 14 { 8 } else { (w / 3).max(3) };
let text_w = w.saturating_sub(bar_w + 1);
let bar = nmbrs_runtime::readouts::format::braille_bar(frac * 100.0, bar_w);
let fitted = nmbrs_runtime::activity::truncate_to_width(text, text_w);
let pad = text_w.saturating_sub(fitted.chars().filter(|c| !c.is_control()).count());
format!("{bg}{bright}{bar}{reset} {dim}{fitted}{:pad$}│{reset} ", "")
}
fn braille_meter(frac: f64) -> [char; 2] {
const COL_BOTTOM_UP: [[u8; 4]; 2] = [
[0x40, 0x04, 0x02, 0x01], [0x80, 0x20, 0x10, 0x08], ];
let dots = (frac.clamp(0.0, 1.0) * 16.0).round() as usize;
let mut cells = [0u8; 2];
for col in 0..4 {
let filled = dots.saturating_sub(col * 4).min(4);
for bit in &COL_BOTTOM_UP[col % 2][..filled] {
cells[col / 2] |= bit;
}
}
[
char::from_u32(0x2800 + cells[0] as u32).expect("braille block"),
char::from_u32(0x2800 + cells[1] as u32).expect("braille block"),
]
}
fn util_color(frac: f64) -> &'static str {
if frac > 0.90 {
"\x1b[1;38;5;208m"
} else if frac > 0.80 {
"\x1b[38;5;166m"
} else if frac > 0.50 {
"\x1b[33m"
} else if frac > 0.25 {
"\x1b[97m"
} else {
""
}
}
fn sysmon_gutter(items: &[(char, f64)], w: usize, color: bool) -> String {
let reset = if color { "\x1b[0m" } else { "" };
let mut body = String::new();
let mut visible = 0usize;
for (i, (glyph, frac)) in items.iter().enumerate() {
if i > 0 {
body.push(' ');
visible += 1;
}
let c = if color { util_color(*frac) } else { "" };
let [m0, m1] = braille_meter(*frac);
if !c.is_empty() {
body.push_str(c);
}
body.push(*glyph);
body.push(m0);
body.push(m1);
if !c.is_empty() {
body.push_str(reset);
}
visible += 3;
}
let inner = w.saturating_sub(1);
let pad = inner.saturating_sub(visible);
format!("{:pad$}{body} │ ", "")
}
fn text_gutter(text: &str, w: usize, color: bool) -> String {
let dim = if color { "\x1b[2m" } else { "" };
let reset = if color { "\x1b[0m" } else { "" };
let inner = w.saturating_sub(1);
let fitted = nmbrs_runtime::activity::truncate_to_width(text, inner);
let pad = inner.saturating_sub(fitted.chars().filter(|c| !c.is_control()).count());
format!("{dim}{:pad$}{fitted} │{reset} ", "")
}
fn labeled_gutter(name: &str, value: &str, w: usize, color: bool) -> String {
let dim = if color { "\x1b[2m" } else { "" };
let accent = if color { "\x1b[1;92m" } else { "" };
let reset = if color { "\x1b[0m" } else { "" };
let inner = w.saturating_sub(1); let text_w = inner.saturating_sub(2); let plain = format!("{name}: {value}");
if text_w < 3 {
let val = nmbrs_runtime::activity::truncate_to_width(value, inner);
let pad = inner.saturating_sub(val.chars().filter(|c| !c.is_control()).count());
return format!("{dim}{:pad$}{reset}{accent}{val}{reset}{dim} │{reset} ", "");
}
let fitted = nmbrs_runtime::activity::truncate_to_width(&plain, text_w);
let fitted_w = fitted.chars().filter(|c| !c.is_control()).count();
let slack = text_w.saturating_sub(fitted_w);
let left = slack / 2;
let right = slack - left;
let (lbl, val) = match fitted.split_once(": ") {
Some((l, v)) => (format!("{l}: "), v.to_string()),
None => (String::new(), fitted.clone()),
};
format!(
"{dim}[{:left$}{lbl}{reset}{accent}{val}{reset}{dim}{:right$}] │{reset} ",
"", ""
)
}
fn spark_gutter(
ring: &mut std::collections::VecDeque<f64>,
value: f64,
w: usize,
color: bool,
) -> String {
let dim = if color { "\x1b[2m" } else { "" };
let reset = if color { "\x1b[0m" } else { "" };
let cyan = if color { "\x1b[36m" } else { "" };
let text = if value.abs() >= 100.0 {
format!("{value:.0}")
} else if value.abs() >= 10.0 {
format!("{value:.1}")
} else {
format!("{value:.2}")
};
let spark_w = w.saturating_sub(text.chars().count() + 1).max(4);
ring.push_back(value);
while ring.len() > spark_w {
ring.pop_front();
}
let samples: Vec<f64> = ring.iter().copied().collect();
let spark = crate::widgets::sparkline_str(&samples, spark_w);
format!(
"{cyan}{spark}{reset} {dim}{text:>tw$}│{reset} ",
tw = w.saturating_sub(spark_w + 1)
)
}
#[derive(Default)]
pub(crate) struct GutterState {
rings: std::collections::HashMap<String, std::collections::VecDeque<f64>>,
latency: std::collections::HashMap<String, LatencyCellState>,
hists: std::collections::HashMap<String, HistCellState>,
}
#[derive(Default)]
struct LatencyCellState {
ring: std::collections::VecDeque<f64>,
last_count: u64,
last_w: usize,
last_render: String,
}
struct HistCellState {
trend: crate::widgets::DecimatingTrend,
last_count: u64,
last_w: usize,
last_render: String,
}
fn latency_hist_gutter(
trend: &mut crate::widgets::DecimatingTrend,
p50: u64,
w: usize,
color: bool,
) -> String {
let dim = if color { "\x1b[2m" } else { "" };
let reset = if color { "\x1b[0m" } else { "" };
let cyan = if color { "\x1b[36m" } else { "" };
let accent = if color { "\x1b[93m" } else { "" };
let fmt = |ms: f64| {
if ms >= 100.0 {
format!("{ms:.0}")
} else if ms >= 10.0 {
format!("{ms:.1}")
} else {
format!("{ms:.2}")
}
};
let text_probe = format!("{}∕{}ms", fmt(trend.min), fmt(trend.max));
let spark_w = w.saturating_sub(text_probe.chars().count() + 1).max(4);
trend.resize(spark_w);
trend.push(p50 as f64 / 1e6);
let text = format!("{}∕{}ms", fmt(trend.min), fmt(trend.max));
let (hist_cells, raw_cells) = trend.split_view();
let mut visible: Vec<f64> = Vec::with_capacity(spark_w);
visible.extend_from_slice(&hist_cells);
visible.extend_from_slice(&raw_cells);
let cut = visible.len().saturating_sub(spark_w);
let visible = &visible[cut..];
let glyphs = crate::widgets::sparkline_str(visible, visible.len().max(1));
let hist_n = hist_cells.len().saturating_sub(cut);
let hist_part: String = glyphs.chars().take(hist_n).collect();
let raw_part: String = glyphs.chars().skip(hist_n).collect();
let pad = spark_w.saturating_sub(visible.len());
format!(
"{cyan}{hist_part}{reset}{accent}{raw_part}{reset}{:pad$} {dim}{text:>tw$}│{reset} ",
"",
tw = w.saturating_sub(spark_w + 1)
)
}
fn visible_width(s: &str) -> usize {
let mut width = 0;
let mut in_escape = false;
for ch in s.chars() {
if in_escape {
if ch.is_ascii_alphabetic() {
in_escape = false;
}
continue;
}
if ch == '\x1b' {
in_escape = true;
continue;
}
if ch.is_control() {
continue;
}
width += 1;
}
width
}
fn clamp_multiline(s: &str, max_cols: usize) -> String {
let mut out = String::with_capacity(s.len());
let mut first = true;
for row in s.split('\n') {
if !first {
out.push('\n');
}
out.push_str(&nmbrs_runtime::activity::truncate_to_width(row, max_cols));
first = false;
}
out
}
struct LogOnlySinkHandle {
stop: Arc<AtomicBool>,
join: Option<JoinHandle<()>>,
sink_active: Arc<AtomicBool>,
}
impl SinkHandle for LogOnlySinkHandle {
fn shutdown(mut self: Box<Self>) {
self.stop.store(true, Ordering::Release);
if let Some(join) = self.join.take() {
let _ = join.join();
}
self.sink_active.store(false, Ordering::Release);
}
fn owns_terminal(&self) -> bool {
false
}
}
#[cfg(test)]
mod redraw_tests {
use super::*;
#[test]
fn braille_meter_fills_column_major() {
assert_eq!(braille_meter(0.0), ['\u{2800}', '\u{2800}']);
assert_eq!(braille_meter(0.25), ['\u{2847}', '\u{2800}']);
assert_eq!(braille_meter(0.5), ['\u{28FF}', '\u{2800}']);
assert_eq!(braille_meter(1.0), ['\u{28FF}', '\u{28FF}']);
assert_eq!(braille_meter(7.0), ['\u{28FF}', '\u{28FF}']);
assert_eq!(braille_meter(-1.0), ['\u{2800}', '\u{2800}']);
}
#[test]
fn util_colors_step_at_the_declared_thresholds() {
assert_eq!(util_color(0.95), "\x1b[1;38;5;208m");
assert_eq!(util_color(0.85), "\x1b[38;5;166m");
assert_eq!(util_color(0.55), "\x1b[33m");
assert_eq!(util_color(0.30), "\x1b[97m");
assert_eq!(util_color(0.10), "");
assert_eq!(util_color(0.90), "\x1b[38;5;166m");
assert_eq!(util_color(0.80), "\x1b[33m");
assert_eq!(util_color(0.50), "\x1b[97m");
assert_eq!(util_color(0.25), "");
}
#[test]
fn sysmon_gutter_is_width_aligned_with_text_gutter() {
let items = vec![('⛃', 0.97), ('⚙', 0.34), ('▤', 0.61)];
let w = 27;
let ours = crate::status_fold::strip_ansi(&sysmon_gutter(&items, w, true));
let reference = crate::status_fold::strip_ansi(&text_gutter("x", w, true));
assert_eq!(
ours.chars().count(),
reference.chars().count(),
"sysmon cell must occupy the same columns as a text cell:\n{ours:?}\n{reference:?}"
);
assert!(ours.contains('⛃') && ours.contains('⚙') && ours.contains('▤'));
}
#[test]
fn blank_gutter_is_width_aligned_divider() {
let row1 = " 12.3s [5/9] 1.2s │ "; let target = super::visible_width(row1);
let mut out: Vec<u8> = Vec::new();
draw_footer_at_cursor(
&mut out,
Some("head\ndetail"),
None,
80,
row1,
target as u16,
&[],
&mut GutterState::default(),
);
let out = String::from_utf8(out).expect("utf-8");
let line1 = out.split("\r\n").nth(1).expect("two rows");
let margin_end = line1.find("detail").expect("detail text present");
let margin = &line1[..margin_end];
assert_eq!(
super::visible_width(margin),
target,
"blank margin must be exactly the row-0 width: {margin:?}"
);
let mut plain = String::new();
let mut in_esc = false;
for c in margin.chars() {
if in_esc {
if c.is_ascii_alphabetic() {
in_esc = false;
}
continue;
}
if c == '\u{1b}' {
in_esc = true;
continue;
}
if !c.is_ascii_control() {
plain.push(c);
}
}
let div = plain.find('│').expect("divider present");
assert!(
plain[..div].chars().all(|c| c == ' '),
"blank margin must be blank before the divider: {plain:?}"
);
}
fn render_tick_with_margin(
status: Option<&str>,
prompt: Option<&PromptInput>,
margin: &str,
) -> String {
let mut out: Vec<u8> = Vec::new();
let width = super::visible_width(margin) as u16;
draw_footer_at_cursor(
&mut out,
status,
prompt,
80,
margin,
width,
&[],
&mut GutterState::default(),
);
String::from_utf8(out).expect("rendered bytes are utf-8")
}
fn one_row_prompt(buf: &str) -> PromptInput {
let rendered = format!("\x1b[36m❯\x1b[0m {buf}");
let cursor_col = (2 + buf.chars().count()) as u16;
PromptInput {
rendered,
window_rows: 1,
cursor_col,
}
}
#[test]
fn footer_rows_home_erase_and_have_no_trailing_newline() {
let mut out: Vec<u8> = Vec::new();
let (rows, below) = draw_footer_at_cursor(
&mut out,
Some("head row\ntail row"),
None,
80,
"",
0,
&[],
&mut GutterState::default(),
);
let s = String::from_utf8(out).expect("utf-8");
assert_eq!((rows, below), (2, 1), "two rows, cursor 1 below the top");
assert!(
s.contains("\r\x1b[Khead row"),
"head row homed + erased: {s:?}"
);
assert!(
s.contains("\r\x1b[Ktail row"),
"tail row homed + erased: {s:?}"
);
assert_eq!(s.matches("\r\n").count(), 1, "one separator only: {s:?}");
assert!(!s.ends_with("\r\n"), "no trailing newline: {s:?}");
}
#[test]
fn empty_footer_draws_nothing() {
let mut out: Vec<u8> = Vec::new();
let (rows, below) = draw_footer_at_cursor(
&mut out,
None,
None,
80,
"",
0,
&[],
&mut GutterState::default(),
);
assert_eq!((rows, below), (0, 0));
assert!(out.is_empty(), "empty footer emits no bytes: {out:?}");
}
#[test]
fn footer_rows_carry_log_margin_for_column_alignment() {
let margin = "12.34s 5/9 │ ";
let status = "running";
let prompt = one_row_prompt("hi");
let out = render_tick_with_margin(Some(status), Some(&prompt), margin);
assert!(
out.contains(&format!("\r\x1b[K{margin}running")),
"status row must carry the margin: {out:?}"
);
assert!(
out.contains(&format!("\r\x1b[K{margin}\x1b[36m❯\x1b[0m hi")),
"prompt row must carry the margin: {out:?}"
);
assert!(
out.contains("\x1b[18G"),
"cursor must skip past the margin width: {out:?}"
);
}
#[test]
fn contextual_gutter_applies_to_detail_row_only() {
let row1 = "12.34s 5/9 │ ";
let status = "running\nstats line";
let mut out: Vec<u8> = Vec::new();
let gutters = vec![
crate::status_fold::RowGutter::Blank,
crate::status_fold::RowGutter::Bar(0.5),
];
draw_footer_at_cursor(
&mut out,
Some(status),
None,
80,
row1,
super::visible_width(row1) as u16,
&gutters,
&mut GutterState::default(),
);
let out = String::from_utf8(out).expect("utf-8");
assert!(
out.contains(&format!("\r\x1b[K{row1}running")),
"line 0 MUST carry the triad margin: {out:?}"
);
assert!(
out.contains('\u{28ff}') && out.contains("stats line"),
"line 1 MUST carry the bar gutter: {out:?}"
);
}
#[test]
fn overwide_status_row_truncates_to_one_physical_row() {
let margin = "12.34s 5/9 │ "; let wide = "x".repeat(200); let status = format!("head\n{wide}");
let mut out: Vec<u8> = Vec::new();
let (rows, below) = draw_footer_at_cursor(
&mut out,
Some(&status),
None,
80,
margin,
super::visible_width(margin) as u16,
&[],
&mut GutterState::default(),
);
assert_eq!((rows, below), (2, 1));
let out = String::from_utf8(out).expect("utf-8");
for line in out.split("\r\n") {
assert!(
super::visible_width(line) <= 80,
"footer row must fit the terminal width ({}): {line:?}",
super::visible_width(line)
);
}
assert!(out.contains('…'), "truncation marker expected: {out:?}");
let colored = format!("\x1b[31m{}\x1b[0m", "y".repeat(200));
let mut out2: Vec<u8> = Vec::new();
draw_footer_at_cursor(
&mut out2,
Some(&colored),
None,
80,
margin,
super::visible_width(margin) as u16,
&[],
&mut GutterState::default(),
);
let out2 = String::from_utf8(out2).expect("utf-8");
assert!(
out2.ends_with("\x1b[0m"),
"truncated colored row must close its SGR: {out2:?}"
);
}
#[test]
fn empty_gutters_fall_back_to_blank_divider() {
let row1 = "12.34s 5/9 │ ";
let status = "first\nsecond";
let mut out: Vec<u8> = Vec::new();
draw_footer_at_cursor(
&mut out,
Some(status),
None,
80,
row1,
super::visible_width(row1) as u16,
&[],
&mut GutterState::default(),
);
let out = String::from_utf8(out).expect("utf-8");
assert!(
out.contains(&format!("\r\x1b[K{row1}first")),
"line 0 MUST carry the triad margin: {out:?}"
);
assert!(
out.contains("│\x1b[0m second"),
"line 1 MUST carry the blank divider margin: {out:?}"
);
assert!(
!out.contains(&format!("{row1}second")),
"line 1 must NOT repeat the triad margin: {out:?}"
);
}
#[test]
fn seed_last_seen_fresh_uses_current() {
assert_eq!(super::seed_last_seen(None, 42), 42);
assert_eq!(super::seed_last_seen(Some(super::RESUME_FRESH), 42), 42);
}
#[test]
fn seed_last_seen_resume_uses_stored_cursor() {
assert_eq!(super::seed_last_seen(Some(10), 42), 10);
assert_eq!(super::seed_last_seen(Some(0), 42), 0);
}
#[test]
fn visible_width_strips_sgr_sequences() {
assert_eq!(super::visible_width(""), 0);
assert_eq!(super::visible_width("plain text"), 10);
assert_eq!(super::visible_width("\x1b[2mdim\x1b[0m text"), 8);
assert_eq!(
super::visible_width("\x1b[1;31mAB\x1b[0m\x1b[32mCD\x1b[0m"),
4
);
}
#[test]
fn phase_time_lands_in_one_column_across_row_kinds() {
let total = 256usize;
let body = crate::widgets::margin_body(total, "[65/256]", Some(45.0), Some(569.0));
let header = super::format_margin_from_body(&body, false);
let blank_w = crate::widgets::margin_body_width(total) + 1;
let leaf = super::text_gutter("0.0s", blank_w, false);
let divider = |cell: &str| cell.chars().position(|c| c == '│').expect("divider");
assert_eq!(
divider(&header),
divider(&leaf),
"divider column differs:\n header |{header}|\n leaf |{leaf}|"
);
let ends_at = |cell: &str, needle: &str| {
cell.find(needle)
.map(|b| cell[..b].chars().count() + needle.chars().count())
.expect("duration present")
};
assert_eq!(
ends_at(&header, "45.0s"),
ends_at(&leaf, "0.0s"),
"durations end in different columns:\n header |{header}|\n leaf |{leaf}|"
);
}
#[test]
fn timing_rows_are_marked_with_a_single_cell_glyph() {
let body = crate::widgets::margin_body(4, "[1/4]", Some(1.0), Some(2.0));
assert!(body.starts_with(crate::widgets::TIMING_MARK), "got: {body}");
assert_eq!(crate::widgets::TIMING_MARK.chars().count(), 1);
for wide in ["\u{23F1}", "\u{231A}", "\u{1F550}"] {
assert_ne!(crate::widgets::TIMING_MARK, wide);
}
}
#[test]
fn key_metric_cell_is_bracketed_and_centred() {
let cell = super::labeled_gutter("recall", "97.88%", 28, false);
let plain: String = cell.chars().filter(|c| *c != '\u{1b}').collect();
assert!(plain.contains("[") && plain.contains("]"), "got: |{cell}|");
assert!(plain.contains("recall: 97.88%"), "got: |{cell}|");
let open = plain.find('[').unwrap();
assert_eq!(open, 0, "bracket must open at the cell edge: |{cell}|");
let close = plain.find(']').unwrap();
let divider = plain.find('│').unwrap();
assert_eq!(
divider - close,
2,
"close bracket sits one space before the divider: |{cell}|"
);
let inner = &plain[open + 1..close];
let lead = inner.len() - inner.trim_start().len();
let trail = inner.len() - inner.trim_end().len();
assert!(lead.abs_diff(trail) <= 1, "not centred: |{inner}|");
}
}