1use std::collections::HashSet;
29use std::io::{self, BufRead, BufReader, Write};
30#[cfg(unix)]
31use std::os::unix::net::UnixStream;
32use std::path::{Path, PathBuf};
33use std::sync::{Arc, Mutex};
34use std::time::{Duration, Instant};
35#[cfg(windows)]
36use uds_windows::UnixStream;
37
38use crossterm::ExecutableCommand;
39use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
40use crossterm::terminal::{self, EnterAlternateScreen, LeaveAlternateScreen};
41use ratatui::prelude::*;
42use ratatui::widgets::*;
43
44#[derive(Clone, Debug)]
48pub struct DiscoveredSocket {
49 pub pid: u32,
50 pub path: PathBuf,
51}
52
53pub fn discover_sockets() -> Vec<DiscoveredSocket> {
58 let dir = std::env::var_os("XDG_RUNTIME_DIR")
59 .map(PathBuf::from)
60 .unwrap_or_else(|| {
61 if cfg!(windows) {
62 std::env::temp_dir()
64 } else {
65 PathBuf::from("/tmp")
66 }
67 });
68 let read_dir = match std::fs::read_dir(&dir) {
69 Ok(rd) => rd,
70 Err(_) => return Vec::new(),
71 };
72 let mut out = Vec::new();
73 for entry in read_dir.flatten() {
74 let path = entry.path();
75 let Some(name) = path.file_name().and_then(|s| s.to_str()) else {
76 continue;
77 };
78 let Some(rest) = name.strip_prefix("nmbrs-") else {
79 continue;
80 };
81 let Some(pid_str) = rest.strip_suffix(".sock") else {
82 continue;
83 };
84 let Ok(pid) = pid_str.parse::<u32>() else {
85 continue;
86 };
87 if !pid_alive(pid) {
88 continue;
92 }
93 out.push(DiscoveredSocket { pid, path });
94 }
95 out.sort_by_key(|s| s.pid);
96 out
97}
98
99#[cfg(target_os = "linux")]
100fn pid_alive(pid: u32) -> bool {
101 Path::new(&format!("/proc/{pid}")).exists()
102}
103
104#[cfg(not(target_os = "linux"))]
105fn pid_alive(_pid: u32) -> bool {
106 true
109}
110
111pub fn query(path: &Path, command: &str) -> io::Result<String> {
117 let mut last_err = None;
126 for _ in 0..3 {
127 match query_once(path, command) {
128 Ok(s) => return Ok(s),
129 Err(e)
130 if matches!(
131 e.kind(),
132 io::ErrorKind::TimedOut
133 | io::ErrorKind::WouldBlock
134 | io::ErrorKind::ConnectionReset
135 | io::ErrorKind::Interrupted
136 ) =>
137 {
138 last_err = Some(e)
139 }
140 Err(e) => return Err(e),
141 }
142 }
143 Err(last_err.expect("loop ran at least once"))
144}
145
146fn query_once(path: &Path, command: &str) -> io::Result<String> {
147 let mut stream = UnixStream::connect(path)?;
148 stream.set_read_timeout(Some(Duration::from_secs(5)))?;
149 stream.set_write_timeout(Some(Duration::from_secs(2)))?;
150 writeln!(stream, "{}", command.trim_end())?;
151 stream.flush()?;
152 let mut reader = BufReader::new(stream);
153 let mut response = String::new();
154 let mut line = String::new();
155 while reader.read_line(&mut line)? > 0 {
156 response.push_str(&line);
157 line.clear();
158 }
159 Ok(response)
160}
161
162pub fn run_repl(socket: PathBuf) -> io::Result<()> {
166 let commands = match query(&socket, "commands") {
169 Ok(s) => s.lines().map(str::to_string).collect::<Vec<_>>(),
170 Err(_) => Vec::new(),
171 };
172
173 let banner = match query(&socket, "meta") {
176 Ok(s) => format!("connected to {}\n\n{s}", socket.display()),
177 Err(e) => format!("connected to {} (meta failed: {e})", socket.display()),
178 };
179
180 let _guard = TerminalGuard::enter()?;
181 let backend = CrosstermBackend::new(io::stderr());
182 let mut terminal = Terminal::new(backend)?;
183 let mut app = ReplApp::new(socket, commands, banner);
184 let result = app.event_loop(&mut terminal);
185 drop(_guard);
186 result
187}
188
189struct TerminalGuard;
192
193impl TerminalGuard {
194 fn enter() -> io::Result<Self> {
195 terminal::enable_raw_mode()?;
196 io::stderr().execute(EnterAlternateScreen)?;
197 Ok(Self)
198 }
199}
200
201impl Drop for TerminalGuard {
202 fn drop(&mut self) {
203 let _ = io::stderr().execute(LeaveAlternateScreen);
204 let _ = terminal::disable_raw_mode();
205 }
206}
207
208#[derive(Default, Clone)]
221struct ServerVocab {
222 controls: Vec<ControlInfo>,
228 metrics: Vec<String>,
233}
234
235#[derive(Clone, Default, PartialEq, Eq)]
238struct ControlInfo {
239 name: String,
240 value_type: String,
243 value: String,
247}
248
249const VOCAB_REFRESH_INTERVAL: Duration = Duration::from_secs(5);
250
251fn spawn_vocab_refresh(socket: PathBuf, vocab: Arc<Mutex<ServerVocab>>) {
257 std::thread::Builder::new()
258 .name("inspector-vocab".into())
259 .spawn(move || {
260 loop {
261 let next = refresh_vocab_once(&socket);
262 if let Ok(mut guard) = vocab.lock() {
263 *guard = next;
264 }
265 std::thread::sleep(VOCAB_REFRESH_INTERVAL);
266 }
267 })
268 .ok();
269}
270
271fn refresh_vocab_once(socket: &Path) -> ServerVocab {
274 let mut vocab = ServerVocab::default();
275 if let Ok(resp) = query(socket, "controls") {
276 for line in resp.lines() {
277 let parts: Vec<&str> = line.splitn(7, '|').map(str::trim).collect();
279 if parts.len() >= 4 {
280 vocab.controls.push(ControlInfo {
281 name: parts[1].to_string(),
282 value_type: parts[2].to_string(),
283 value: parts[3].to_string(),
284 });
285 }
286 }
287 }
288 vocab.controls.sort_by(|a, b| a.name.cmp(&b.name));
289 vocab.controls.dedup_by(|a, b| a.name == b.name);
294
295 if let Ok(resp) = query(socket, "metrics") {
296 for line in resp.lines() {
297 let trimmed = line.trim();
298 if trimmed.is_empty() || trimmed.starts_with('(') {
299 continue;
300 }
301 vocab.metrics.push(trimmed.to_string());
302 }
303 }
304 vocab.metrics.sort();
305 vocab.metrics.dedup();
306 vocab
307}
308
309fn split_metric_row(row: &str) -> Option<(String, Vec<(String, String)>)> {
312 let row = row.trim();
313 let (family, body) = match row.find('{') {
314 Some(idx) => {
315 let (f, rest) = row.split_at(idx);
316 if !rest.ends_with('}') {
317 return None;
318 }
319 (f.to_string(), &rest[1..rest.len() - 1])
320 }
321 None => (row.to_string(), ""),
322 };
323 let mut pairs: Vec<(String, String)> = Vec::new();
324 for piece in body.split(',') {
325 let p = piece.trim();
326 if p.is_empty() {
327 continue;
328 }
329 if let Some((k, v)) = p.split_once('=') {
330 let v = v.trim().trim_matches('"');
333 pairs.push((k.trim().to_string(), v.to_string()));
334 }
335 }
336 Some((family, pairs))
337}
338
339#[derive(Clone)]
345struct PinnedEntry {
346 selector: String,
347 rendered: String,
348 last_refresh: Option<Instant>,
351}
352
353const PIN_PANE_MAX_LINES: usize = 12;
354const DEFAULT_PIN_REFRESH: Duration = Duration::from_secs(1);
355const MIN_PIN_REFRESH: Duration = Duration::from_millis(500);
356const MAX_PIN_REFRESH: Duration = Duration::from_secs(60);
357
358struct ReplApp {
362 socket: PathBuf,
363 commands: Vec<String>,
366 vocab: Arc<Mutex<ServerVocab>>,
369 scrollback: Vec<Line<'static>>,
374 input: String,
376 cursor: usize,
380 history: Vec<String>,
384 history_idx: usize,
385 scroll: u16,
388 should_quit: bool,
389 pinned: Vec<PinnedEntry>,
391 pin_refresh_interval: Duration,
392 last_pin_sweep: Option<Instant>,
396}
397
398const SCROLLBACK_LIMIT: usize = 5000;
399
400impl ReplApp {
401 fn new(socket: PathBuf, commands: Vec<String>, banner: String) -> Self {
402 let mut scrollback = Vec::new();
403 for line in banner.lines() {
404 scrollback.push(Line::from(line.to_string()));
405 }
406 scrollback.push(Line::from(""));
407 scrollback.push(Line::from(Span::styled(
408 "type a command and press Enter — Tab autocompletes, :help shows pin commands, :q quits",
409 Style::default().fg(Color::DarkGray),
410 )));
411 scrollback.push(Line::from(""));
412
413 let initial_vocab = refresh_vocab_once(&socket);
417 let vocab = Arc::new(Mutex::new(initial_vocab));
418 spawn_vocab_refresh(socket.clone(), vocab.clone());
419
420 Self {
421 socket,
422 commands,
423 vocab,
424 scrollback,
425 input: String::new(),
426 cursor: 0,
427 history: Vec::new(),
428 history_idx: 0,
429 scroll: 0,
430 should_quit: false,
431 pinned: Vec::new(),
432 pin_refresh_interval: DEFAULT_PIN_REFRESH,
433 last_pin_sweep: None,
434 }
435 }
436
437 fn event_loop(
438 &mut self,
439 terminal: &mut Terminal<CrosstermBackend<io::Stderr>>,
440 ) -> io::Result<()> {
441 while !self.should_quit {
442 self.maybe_refresh_pins();
444 terminal.draw(|frame| self.draw(frame))?;
445 if event::poll(Duration::from_millis(100))?
446 && let Event::Key(k) = event::read()?
447 {
448 if k.kind != KeyEventKind::Press {
449 continue;
450 }
451 self.handle_key(k.code, k.modifiers);
452 }
453 }
454 Ok(())
455 }
456
457 fn handle_key(&mut self, code: KeyCode, mods: KeyModifiers) {
458 if mods.contains(KeyModifiers::CONTROL) && code == KeyCode::Char('c') {
459 self.should_quit = true;
460 return;
461 }
462 match code {
463 KeyCode::Enter => self.submit(),
464 KeyCode::Char(c) => self.insert_char(c),
465 KeyCode::Backspace => self.delete_back(),
466 KeyCode::Tab => self.autocomplete(),
467 KeyCode::Up => self.history_prev(),
468 KeyCode::Down => self.history_next(),
469 KeyCode::Left => {
470 if self.cursor > 0 {
471 self.cursor -= 1;
472 }
473 }
474 KeyCode::Right => {
475 if self.cursor < self.input.len() {
476 self.cursor += 1;
477 }
478 }
479 KeyCode::Home => self.cursor = 0,
480 KeyCode::End => self.cursor = self.input.len(),
481 KeyCode::PageUp => self.scroll = self.scroll.saturating_add(8),
482 KeyCode::PageDown => self.scroll = self.scroll.saturating_sub(8),
483 KeyCode::Esc => {
484 self.input.clear();
488 self.cursor = 0;
489 }
490 _ => {}
491 }
492 }
493
494 fn insert_char(&mut self, c: char) {
495 self.input.insert(self.cursor, c);
496 self.cursor += c.len_utf8();
497 }
498
499 fn delete_back(&mut self) {
500 if self.cursor == 0 {
501 return;
502 }
503 let mut new_cursor = self.cursor - 1;
505 while !self.input.is_char_boundary(new_cursor) && new_cursor > 0 {
506 new_cursor -= 1;
507 }
508 self.input.replace_range(new_cursor..self.cursor, "");
509 self.cursor = new_cursor;
510 }
511
512 fn set_input(&mut self, new: String) {
515 self.input = new;
516 self.cursor = self.input.len();
517 }
518
519 fn autocomplete(&mut self) {
535 let input = self.input.clone();
536 if !input.contains(char::is_whitespace) {
538 self.complete_command(&input);
539 return;
540 }
541 if let Some(rest) = input.strip_prefix("set ") {
543 match rest.split_once(char::is_whitespace) {
549 None => {
550 self.complete_control_name(rest);
552 }
553 Some((name, after_name)) => {
554 let value_prefix = after_name.trim_start();
558 if value_prefix.contains(char::is_whitespace) {
559 return;
560 }
561 self.complete_control_value(name, value_prefix);
562 }
563 }
564 return;
565 }
566 if let Some(rest) = input.strip_prefix("metric ") {
567 self.complete_metric_arg(rest);
568 return;
569 }
570 if let Some(rest) = input.strip_prefix("readout ") {
574 self.complete_readout_arg(rest);
575 }
576 }
577
578 fn complete_readout_arg(&mut self, prefix: &str) {
585 if prefix.contains(char::is_whitespace) {
586 return;
587 }
588 let matches = readout_name_candidates(prefix);
589 match matches.as_slice() {
590 [] => self.note_no_completion(prefix),
591 [single] => self.set_input(format!("readout {single}")),
592 many => {
593 let names: Vec<String> = many.iter().map(|s| s.to_string()).collect();
594 let lcp = longest_common_prefix(&names);
595 if lcp.len() > prefix.len() {
596 self.set_input(format!("readout {lcp}"));
597 }
598 self.scrollback.push(Line::from(Span::styled(
599 names.join(" "),
600 Style::default().fg(Color::DarkGray),
601 )));
602 self.trim_scrollback();
603 }
604 }
605 }
606
607 fn complete_command(&mut self, prefix: &str) {
608 let matches: Vec<&String> = self
609 .commands
610 .iter()
611 .filter(|c| c.starts_with(prefix))
612 .collect();
613 match matches.as_slice() {
614 [] => self.note_no_completion(prefix),
615 [single] => self.set_input((*single).clone()),
616 many => {
617 let names: Vec<String> = many.iter().map(|s| (*s).clone()).collect();
618 let lcp = longest_common_prefix(&names);
619 if lcp.len() > prefix.len() {
620 self.set_input(lcp);
621 }
622 self.scrollback.push(Line::from(Span::styled(
623 names.join(" "),
624 Style::default().fg(Color::DarkGray),
625 )));
626 self.trim_scrollback();
627 }
628 }
629 }
630
631 fn complete_control_name(&mut self, prefix: &str) {
632 let controls = {
633 let v = self.vocab.lock().ok();
634 v.map(|g| g.controls.clone()).unwrap_or_default()
635 };
636 let matches: Vec<&ControlInfo> = controls
637 .iter()
638 .filter(|c| c.name.starts_with(prefix))
639 .collect();
640 match matches.as_slice() {
641 [] => self.note_no_completion(prefix),
642 [single] => {
643 self.set_input(format!("set {} {}", single.name, single.value));
651 self.scrollback.push(Line::from(Span::styled(
652 format!(
653 " ({}: type={}, current={})",
654 single.name, single.value_type, single.value
655 ),
656 Style::default().fg(Color::DarkGray),
657 )));
658 self.trim_scrollback();
659 }
660 many => {
661 let names: Vec<String> = many.iter().map(|c| c.name.clone()).collect();
662 let lcp = longest_common_prefix(&names);
663 if lcp.len() > prefix.len() {
664 self.set_input(format!("set {lcp}"));
665 }
666 let pretty: Vec<String> = many
670 .iter()
671 .map(|c| format!("{} ({}={})", c.name, c.value_type, c.value))
672 .collect();
673 self.scrollback.push(Line::from(Span::styled(
674 pretty.join(" "),
675 Style::default().fg(Color::DarkGray),
676 )));
677 self.trim_scrollback();
678 }
679 }
680 }
681
682 fn complete_control_value(&mut self, name: &str, prefix: &str) -> bool {
691 let controls = {
692 let v = self.vocab.lock().ok();
693 v.map(|g| g.controls.clone()).unwrap_or_default()
694 };
695 let Some(info) = controls.iter().find(|c| c.name == name) else {
696 return false;
697 };
698 let ty = info.value_type.to_lowercase();
701 if ty == "bool" || ty == "boolean" {
702 let candidates: Vec<&'static str> = ["true", "false"]
703 .iter()
704 .copied()
705 .filter(|s| s.starts_with(prefix))
706 .collect();
707 match candidates.as_slice() {
708 [] => return false,
709 [single] => {
710 self.set_input(format!("set {} {}", info.name, single));
711 return true;
712 }
713 many => {
714 let lcp = longest_common_prefix(
715 &many.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
716 );
717 if lcp.len() > prefix.len() {
718 self.set_input(format!("set {} {}", info.name, lcp));
719 }
720 self.scrollback.push(Line::from(Span::styled(
721 many.join(" "),
722 Style::default().fg(Color::DarkGray),
723 )));
724 self.trim_scrollback();
725 return true;
726 }
727 }
728 }
729 if prefix.is_empty() {
734 self.set_input(format!("set {} {}", info.name, info.value));
735 return true;
736 }
737 self.scrollback.push(Line::from(Span::styled(
739 format!(
740 " ({}: type={}, current={})",
741 info.name, info.value_type, info.value
742 ),
743 Style::default().fg(Color::DarkGray),
744 )));
745 self.trim_scrollback();
746 true
747 }
748
749 fn complete_metric_arg(&mut self, rest: &str) {
750 let metrics = {
751 let v = self.vocab.lock().ok();
752 v.map(|g| g.metrics.clone()).unwrap_or_default()
753 };
754 match rest.find('{') {
756 None => {
757 let prefix = rest;
758 let mut families: Vec<String> = metrics
759 .iter()
760 .filter_map(|row| split_metric_row(row).map(|(f, _)| f))
761 .collect();
762 families.sort();
763 families.dedup();
764 let candidates: Vec<&String> =
765 families.iter().filter(|f| f.starts_with(prefix)).collect();
766 match candidates.as_slice() {
767 [] => self.note_no_completion(prefix),
768 [single] => {
769 self.set_input(format!("metric {single}{{"));
772 }
773 many => {
774 let names: Vec<String> = many.iter().map(|s| (*s).clone()).collect();
775 let lcp = longest_common_prefix(&names);
776 if lcp.len() > prefix.len() {
777 self.set_input(format!("metric {lcp}"));
778 }
779 self.scrollback.push(Line::from(Span::styled(
780 names.join(" "),
781 Style::default().fg(Color::DarkGray),
782 )));
783 self.trim_scrollback();
784 }
785 }
786 }
787 Some(brace_idx) => {
788 let family = &rest[..brace_idx];
789 let body = &rest[brace_idx + 1..];
790 self.complete_metric_label(family, body, &metrics);
791 }
792 }
793 }
794
795 fn complete_metric_label(&mut self, family: &str, body: &str, metrics: &[String]) {
800 let last = body.rsplit(',').next().unwrap_or("").trim_start();
802 let mut matching_instances: Vec<Vec<(String, String)>> = Vec::new();
803 for row in metrics {
804 if let Some((f, pairs)) = split_metric_row(row)
805 && (family == "*" || f == family)
806 {
807 matching_instances.push(pairs);
808 }
809 }
810
811 if let Some((key, partial_val)) = last.split_once('=') {
813 let key = key.trim();
815 let partial_val = partial_val.trim();
816 let mut values: HashSet<String> = HashSet::new();
817 for inst in &matching_instances {
818 for (k, v) in inst {
819 if k == key {
820 values.insert(v.clone());
821 }
822 }
823 }
824 let mut sorted: Vec<String> = values
825 .into_iter()
826 .filter(|v| v.starts_with(partial_val))
827 .collect();
828 sorted.sort();
829 let prefix_to_replace = format!("{key}={partial_val}");
830 match sorted.as_slice() {
831 [] => self.note_no_completion(&prefix_to_replace),
832 [single] => {
833 let new_input = self
834 .input
835 .replace(&format!("{key}={partial_val}"), &format!("{key}={single}"));
836 self.set_input(new_input);
837 }
838 many => {
839 let lcp = longest_common_prefix(many);
840 if lcp.len() > partial_val.len() {
841 let new_input = self
842 .input
843 .replace(&format!("{key}={partial_val}"), &format!("{key}={lcp}"));
844 self.set_input(new_input);
845 }
846 self.scrollback.push(Line::from(Span::styled(
847 many.join(" "),
848 Style::default().fg(Color::DarkGray),
849 )));
850 self.trim_scrollback();
851 }
852 }
853 } else {
854 let partial = last.trim_end_matches('=');
856 let mut keys: HashSet<String> = HashSet::new();
857 for inst in &matching_instances {
858 for (k, _) in inst {
859 keys.insert(k.clone());
860 }
861 }
862 let mut sorted: Vec<String> = keys
863 .into_iter()
864 .filter(|k| k.starts_with(partial))
865 .collect();
866 sorted.sort();
867 match sorted.as_slice() {
868 [] => self.note_no_completion(partial),
869 [single] => {
870 let new = self.input.trim_end_matches(partial).to_string() + single + "=";
874 self.set_input(new);
875 }
876 many => {
877 let lcp = longest_common_prefix(many);
878 if lcp.len() > partial.len() {
879 let new = self.input.trim_end_matches(partial).to_string() + &lcp;
880 self.set_input(new);
881 }
882 self.scrollback.push(Line::from(Span::styled(
883 many.join(" "),
884 Style::default().fg(Color::DarkGray),
885 )));
886 self.trim_scrollback();
887 }
888 }
889 }
890 }
891
892 fn note_no_completion(&mut self, prefix: &str) {
893 self.scrollback.push(Line::from(Span::styled(
894 format!("(no completion for '{prefix}')"),
895 Style::default().fg(Color::DarkGray),
896 )));
897 self.trim_scrollback();
898 }
899
900 fn history_prev(&mut self) {
901 if self.history.is_empty() {
902 return;
903 }
904 if self.history_idx > 0 {
905 self.history_idx -= 1;
906 self.input = self.history[self.history_idx].clone();
907 self.cursor = self.input.len();
908 }
909 }
910
911 fn history_next(&mut self) {
912 if self.history_idx + 1 < self.history.len() {
913 self.history_idx += 1;
914 self.input = self.history[self.history_idx].clone();
915 self.cursor = self.input.len();
916 } else {
917 self.history_idx = self.history.len();
918 self.input.clear();
919 self.cursor = 0;
920 }
921 }
922
923 fn submit(&mut self) {
924 let line = std::mem::take(&mut self.input);
925 self.cursor = 0;
926 let trimmed = line.trim();
927 if trimmed.is_empty() {
928 return;
929 }
930
931 if let Some(handled) = self.try_handle_meta(trimmed) {
934 self.scrollback.push(Line::from(vec![
936 Span::styled("> ", Style::default().fg(Color::Cyan)),
937 Span::raw(trimmed.to_string()),
938 ]));
939 for r_line in handled.lines() {
940 self.scrollback.push(Line::from(r_line.to_string()));
941 }
942 self.scrollback.push(Line::from(""));
943 self.history.push(trimmed.to_string());
944 self.history_idx = self.history.len();
945 self.scroll = 0;
946 self.trim_scrollback();
947 return;
948 }
949 match trimmed {
950 "quit" | "exit" => {
951 self.should_quit = true;
952 return;
953 }
954 "clear" => {
955 self.scrollback.clear();
956 return;
957 }
958 _ => {}
959 }
960
961 self.scrollback.push(Line::from(vec![
964 Span::styled("> ", Style::default().fg(Color::Yellow)),
965 Span::raw(trimmed.to_string()),
966 ]));
967 match query(&self.socket, trimmed) {
968 Ok(response) => {
969 for r_line in response.lines() {
970 self.scrollback.push(Line::from(r_line.to_string()));
971 }
972 if !response.ends_with('\n') {
973 self.scrollback.push(Line::from(response.to_string()));
974 }
975 }
976 Err(e) => {
977 self.scrollback.push(Line::from(Span::styled(
978 format!("connection error: {e}"),
979 Style::default().fg(Color::Red),
980 )));
981 }
982 }
983 self.scrollback.push(Line::from(""));
984 self.history.push(trimmed.to_string());
985 self.history_idx = self.history.len();
986 self.scroll = 0; self.trim_scrollback();
988 }
989
990 fn try_handle_meta(&mut self, line: &str) -> Option<String> {
995 if line == ":q" || line == ":quit" {
996 self.should_quit = true;
997 return Some(String::new());
998 }
999 if line == ":clear" {
1000 self.scrollback.clear();
1001 return Some(String::new());
1002 }
1003 if line == ":help" {
1004 return Some(
1005 "REPL meta-commands:\n \
1006 :pin <selector> pin a metric selector to the top pane\n \
1007 :unpin <n|all> remove a pin (1-based) or clear all\n \
1008 :pins list current pins\n \
1009 :watch <secs> set pin-refresh interval (0.5..60)\n \
1010 :clear clear scrollback\n \
1011 :help this list\n \
1012 :q | :quit quit"
1013 .into(),
1014 );
1015 }
1016 if let Some(rest) = line.strip_prefix(":pin ") {
1017 return Some(self.cmd_pin(rest.trim()));
1018 }
1019 if line == ":pin" {
1020 return Some("usage: :pin <selector>".into());
1021 }
1022 if let Some(rest) = line.strip_prefix(":unpin ") {
1023 return Some(self.cmd_unpin(rest.trim()));
1024 }
1025 if line == ":unpin" {
1026 return Some("usage: :unpin <n|all>".into());
1027 }
1028 if line == ":pins" {
1029 return Some(self.cmd_pins());
1030 }
1031 if let Some(rest) = line.strip_prefix(":watch ") {
1032 return Some(self.cmd_watch(rest.trim()));
1033 }
1034 if line == ":watch" {
1035 return Some(format!(
1036 "current refresh interval: {:.2}s — usage: :watch <secs>",
1037 self.pin_refresh_interval.as_secs_f64(),
1038 ));
1039 }
1040 if line.starts_with(':') {
1044 return Some(format!("unknown meta-command '{line}'. Try :help"));
1045 }
1046 None
1047 }
1048
1049 fn cmd_pin(&mut self, selector: &str) -> String {
1050 if selector.is_empty() {
1051 return "usage: :pin <selector>".into();
1052 }
1053 if self.pinned.iter().any(|p| p.selector == selector) {
1054 return format!("ERR already pinned: {selector}");
1055 }
1056 self.pinned.push(PinnedEntry {
1057 selector: selector.to_string(),
1058 rendered: "(pending first refresh…)".to_string(),
1059 last_refresh: None,
1060 });
1061 self.last_pin_sweep = None;
1064 format!("OK pinned: {selector}")
1065 }
1066
1067 fn cmd_unpin(&mut self, arg: &str) -> String {
1068 if arg == "all" {
1069 let n = self.pinned.len();
1070 self.pinned.clear();
1071 return format!("OK unpinned {n}");
1072 }
1073 let Ok(idx_1based): Result<usize, _> = arg.parse() else {
1074 return format!("ERR parse: '{arg}' is not a positive integer or 'all'");
1075 };
1076 if idx_1based == 0 || idx_1based > self.pinned.len() {
1077 return format!(
1078 "ERR out_of_range: have {} pin(s), got {idx_1based}",
1079 self.pinned.len()
1080 );
1081 }
1082 let removed = self.pinned.remove(idx_1based - 1);
1083 format!("OK unpinned: {}", removed.selector)
1084 }
1085
1086 fn cmd_pins(&self) -> String {
1087 if self.pinned.is_empty() {
1088 return "(no pins)".into();
1089 }
1090 let mut s = String::new();
1091 for (i, p) in self.pinned.iter().enumerate() {
1092 s.push_str(&format!(" {}. {}\n", i + 1, p.selector));
1093 }
1094 s.pop();
1095 s
1096 }
1097
1098 fn cmd_watch(&mut self, arg: &str) -> String {
1099 let secs: f64 = match arg.parse() {
1100 Ok(v) => v,
1101 Err(_) => return format!("ERR parse: '{arg}' is not a number"),
1102 };
1103 let dur = Duration::from_secs_f64(secs);
1104 if dur < MIN_PIN_REFRESH || dur > MAX_PIN_REFRESH {
1105 return format!(
1106 "ERR out_of_range: refresh interval must be between {:.1}s and {:.0}s",
1107 MIN_PIN_REFRESH.as_secs_f64(),
1108 MAX_PIN_REFRESH.as_secs_f64(),
1109 );
1110 }
1111 self.pin_refresh_interval = dur;
1112 format!("OK refresh interval = {secs:.2}s")
1113 }
1114
1115 fn maybe_refresh_pins(&mut self) {
1116 if self.pinned.is_empty() {
1117 return;
1118 }
1119 let now = Instant::now();
1120 let due = match self.last_pin_sweep {
1121 None => true,
1122 Some(t) => now.duration_since(t) >= self.pin_refresh_interval,
1123 };
1124 if !due {
1125 return;
1126 }
1127 self.last_pin_sweep = Some(now);
1128 let selectors: Vec<String> = self.pinned.iter().map(|p| p.selector.clone()).collect();
1131 let mut updates: Vec<String> = Vec::with_capacity(selectors.len());
1132 for sel in &selectors {
1133 let resp = match query(&self.socket, &format!("metric {sel}")) {
1134 Ok(s) => s,
1135 Err(e) => format!("connection error: {e}"),
1136 };
1137 updates.push(resp);
1138 }
1139 for (entry, rendered) in self.pinned.iter_mut().zip(updates) {
1140 entry.rendered = rendered;
1141 entry.last_refresh = Some(now);
1142 }
1143 }
1144
1145 fn trim_scrollback(&mut self) {
1146 if self.scrollback.len() > SCROLLBACK_LIMIT {
1147 let drop = self.scrollback.len() - SCROLLBACK_LIMIT;
1148 self.scrollback.drain(0..drop);
1149 }
1150 }
1151
1152 fn pin_pane_height(&self) -> u16 {
1158 if self.pinned.is_empty() {
1159 return 0;
1160 }
1161 let mut total: usize = 0;
1162 for entry in &self.pinned {
1163 total = total.saturating_add(1 + entry.rendered.lines().count());
1166 }
1167 let capped = total.min(PIN_PANE_MAX_LINES);
1169 (capped as u16).saturating_add(2)
1170 }
1171
1172 fn pin_pane_lines(&self) -> Vec<Line<'static>> {
1173 let mut out: Vec<Line<'static>> = Vec::new();
1174 for (i, entry) in self.pinned.iter().enumerate() {
1175 out.push(Line::from(vec![
1176 Span::styled(format!("[{}] ", i + 1), Style::default().fg(Color::Yellow)),
1177 Span::styled(entry.selector.clone(), Style::default().fg(Color::Cyan)),
1178 ]));
1179 for r in entry.rendered.lines() {
1180 out.push(Line::from(r.to_string()));
1181 }
1182 }
1183 out
1184 }
1185
1186 fn draw(&self, frame: &mut Frame) {
1187 let area = frame.area();
1188 let pin_h = self.pin_pane_height();
1189 let chunks = Layout::default()
1190 .direction(Direction::Vertical)
1191 .constraints([
1192 Constraint::Length(pin_h),
1193 Constraint::Min(1),
1194 Constraint::Length(3),
1195 ])
1196 .split(area);
1197
1198 if pin_h > 0 {
1201 let pin_lines = self.pin_pane_lines();
1202 let inner_h = chunks[0].height.saturating_sub(2) as usize;
1205 let visible: Vec<Line<'static>> = pin_lines.into_iter().take(inner_h).collect();
1206 let pinned = Paragraph::new(visible).block(
1207 Block::default().borders(Borders::ALL).title(format!(
1208 " pinned ({} · refresh={:.1}s) ",
1209 self.pinned.len(),
1210 self.pin_refresh_interval.as_secs_f64(),
1211 )),
1212 );
1213 frame.render_widget(pinned, chunks[0]);
1214 }
1215
1216 let visible = chunks[1].height.saturating_sub(2) as usize;
1218 let total = self.scrollback.len();
1219 let tail_offset = total.saturating_sub(visible);
1220 let top = tail_offset.saturating_sub(self.scroll as usize);
1221 let view: Vec<Line<'static>> = self
1222 .scrollback
1223 .iter()
1224 .skip(top)
1225 .take(visible)
1226 .cloned()
1227 .collect();
1228 let scrollback = Paragraph::new(view).block(
1229 Block::default()
1230 .borders(Borders::ALL)
1231 .title(format!(" nmbrs inspector — {} ", self.socket.display())),
1232 );
1233 frame.render_widget(scrollback, chunks[1]);
1234
1235 let input_block = Block::default()
1237 .borders(Borders::ALL)
1238 .title(" input — Tab=complete · ↑/↓=history · PgUp/PgDn=scroll · :help · :q=quit ");
1239 let inner = input_block.inner(chunks[2]);
1240 frame.render_widget(input_block, chunks[2]);
1241 let prompt = Paragraph::new(Line::from(vec![
1242 Span::styled("> ", Style::default().fg(Color::Yellow)),
1243 Span::raw(self.input.clone()),
1244 ]));
1245 frame.render_widget(prompt, inner);
1246 frame.set_cursor_position(Position::new(inner.x + 2 + self.cursor as u16, inner.y));
1248 }
1249}
1250
1251fn readout_name_candidates(prefix: &str) -> Vec<&'static str> {
1256 nmbrs_runtime::readouts::Registry::all_names()
1257 .iter()
1258 .copied()
1259 .filter(|n| n.starts_with(prefix))
1260 .collect()
1261}
1262
1263fn longest_common_prefix(strs: &[String]) -> String {
1264 if strs.is_empty() {
1265 return String::new();
1266 }
1267 let mut prefix: Vec<u8> = strs[0].as_bytes().to_vec();
1268 for s in &strs[1..] {
1269 let bytes = s.as_bytes();
1270 let len = prefix
1271 .iter()
1272 .zip(bytes.iter())
1273 .take_while(|(a, b)| a == b)
1274 .count();
1275 prefix.truncate(len);
1276 if prefix.is_empty() {
1277 break;
1278 }
1279 }
1280 String::from_utf8_lossy(&prefix).into_owned()
1281}
1282
1283#[cfg(test)]
1288mod tests {
1289 use super::*;
1290
1291 #[test]
1292 fn split_metric_row_parses_family_and_labels() {
1293 let (family, pairs) =
1294 split_metric_row("cycles_servicetime{phase=\"pvs_query\",table=\"fknn\"}").unwrap();
1295 assert_eq!(family, "cycles_servicetime");
1296 assert_eq!(
1297 pairs,
1298 vec![
1299 ("phase".to_string(), "pvs_query".to_string()),
1300 ("table".to_string(), "fknn".to_string()),
1301 ]
1302 );
1303 }
1304
1305 #[test]
1306 fn split_metric_row_handles_no_labels() {
1307 let (family, pairs) = split_metric_row("ops").unwrap();
1308 assert_eq!(family, "ops");
1309 assert!(pairs.is_empty());
1310 }
1311
1312 #[test]
1313 fn split_metric_row_handles_no_quotes() {
1314 let (family, pairs) = split_metric_row("ops{phase=load}").unwrap();
1317 assert_eq!(family, "ops");
1318 assert_eq!(pairs, vec![("phase".to_string(), "load".to_string())]);
1319 }
1320
1321 #[test]
1322 fn readout_name_candidates_filters_by_prefix() {
1323 assert_eq!(readout_name_candidates("error_"), vec!["error_readout"]);
1325 assert_eq!(
1327 readout_name_candidates("phase_st"),
1328 vec!["phase_starting", "phase_status"],
1329 );
1330 assert!(readout_name_candidates("zzz").is_empty());
1332 assert!(readout_name_candidates("").contains(&"phase_outcome"));
1334 }
1335
1336 #[test]
1337 fn longest_common_prefix_works() {
1338 assert_eq!(
1339 longest_common_prefix(&["concurrency".to_string(), "concurrent".to_string(),]),
1340 "concurren"
1341 );
1342 assert_eq!(
1343 longest_common_prefix(&["a".to_string(), "b".to_string()]),
1344 ""
1345 );
1346 assert_eq!(longest_common_prefix(&[]), "");
1347 }
1348}