Skip to main content

nmbrs_tui/
inspector_repl.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! `nmbrs --inspector` — interactive REPL TUI for the OOB
5//! introspection endpoint (see [`crate::inspector_server`]).
6//!
7//! Discovers the local socket under
8//! `${XDG_RUNTIME_DIR:-/tmp}/nmbrs-*.sock`, connects to it for
9//! each command (the protocol is stateless — one connection
10//! per request), and renders the responses in a scrollable
11//! ratatui buffer with an input line at the bottom.
12//!
13//! Tab autocompletes against the `commands` list returned by
14//! the server. Up/Down recall input history. `:q` or Ctrl+C
15//! exits.
16//!
17//! ## Pinned-metric pane
18//!
19//! `:pin <selector>` adds a metric selector (same grammar as
20//! the server's `metric` command) to a pin pane that renders
21//! at the top of the screen. The pane refreshes on a periodic
22//! tick (default 1 s, settable via `:watch <secs>`); each tick
23//! issues one `metric <selector>` round-trip per pinned entry.
24//! `:unpin <n>` removes the n-th pin (1-based) and `:unpin all`
25//! clears the pane. `:pins` lists current pins; `:help` lists
26//! every REPL-local meta-command.
27
28use 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/// Discovered nmbrs runtime — pid + its socket path. Returned
45/// by [`discover_sockets`] so the caller can pick which
46/// process to inspect when more than one is running.
47#[derive(Clone, Debug)]
48pub struct DiscoveredSocket {
49    pub pid: u32,
50    pub path: PathBuf,
51}
52
53/// Scan `${XDG_RUNTIME_DIR:-/tmp}` for `nmbrs-<pid>.sock`
54/// entries. Returns each path together with the parsed pid.
55/// Sockets whose corresponding process no longer exists are
56/// filtered out (best effort — `kill -0` style probe).
57pub 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                // Same fallback as the server's `socket_path_for`.
63                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            // Stale socket — owning process is gone. Don't
89            // surface it; the user can clean up by hand if
90            // they care.
91            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    // Best-effort: assume alive on non-Linux. The connect
107    // attempt later will fail cleanly if it's stale.
108    true
109}
110
111/// Send one command to the socket and return the response. A
112/// fresh connection per request keeps the protocol stateless
113/// and trivially robust — the server doesn't carry per-client
114/// state, so an interrupted client never leaves anything
115/// behind.
116pub fn query(path: &Path, command: &str) -> io::Result<String> {
117    // Windows AF_UNIX shows rare transient stalls where a sent
118    // request never reaches the server's serial accept loop —
119    // observed as the read timing out with no response ever
120    // arriving. A fresh connection reliably recovers: dropping
121    // the stalled one delivers EOF to the server's blocked
122    // per-connection read, unsticking the loop. Retry a couple
123    // of times before surfacing the error; on Unix this path is
124    // effectively never taken.
125    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
162/// Top-level entry: run the REPL against an already-resolved
163/// socket path. The caller is responsible for discovery /
164/// disambiguation; this fn just runs the UI loop.
165pub fn run_repl(socket: PathBuf) -> io::Result<()> {
166    // Pull the command list once at startup so tab-completion
167    // works without a round-trip per keystroke.
168    let commands = match query(&socket, "commands") {
169        Ok(s) => s.lines().map(str::to_string).collect::<Vec<_>>(),
170        Err(_) => Vec::new(),
171    };
172
173    // Initial banner so the user sees something useful before
174    // typing anything.
175    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
189/// Restores the terminal on Drop. Mirrors the pattern used by
190/// the main TUI's `TerminalGuard`.
191struct 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// ─── Cached server vocabulary (controls + metrics) ───────────
209
210/// Background-refreshed snapshot of the server's vocabulary
211/// — control names and `(family, labels)` instances. Used by
212/// the REPL's tab-completion logic to autocomplete `set
213/// <name>`, `metric <family>`, label keys, and label values
214/// without a per-keystroke round-trip.
215///
216/// Refreshed every [`VOCAB_REFRESH_INTERVAL`] by a dedicated
217/// background thread. The REPL reads through `Arc<Mutex<...>>`
218/// — a Mutex is fine here because the contention pattern is
219/// "writer once every 5 s vs. reader on Tab keypress."
220#[derive(Default, Clone)]
221struct ServerVocab {
222    /// Sorted, deduplicated list of dynamic controls. We keep
223    /// type and current-value alongside the name so value-position
224    /// Tab can prefill the current value as an editable starting
225    /// point, and so multi-match completions can show type/value
226    /// inline (rather than name-only).
227    controls: Vec<ControlInfo>,
228    /// Sorted, deduplicated list of `(family, labels-as-text)`
229    /// pairs returned by `metrics`. Each entry preserves the
230    /// raw server form (`family{k=v,...}`) so we can split it
231    /// at completion time.
232    metrics: Vec<String>,
233}
234
235/// Per-control metadata extracted from the `controls` server
236/// response. Source columns: `path | name | type | value | …`.
237#[derive(Clone, Default, PartialEq, Eq)]
238struct ControlInfo {
239    name: String,
240    /// Type label as the server reports it (e.g. `u64`, `f64`,
241    /// `bool`, `str`). Used to drive type-aware value completion.
242    value_type: String,
243    /// Current value, formatted as the server returned it. Used
244    /// as the prefilled value-position completion so the user can
245    /// edit-and-submit instead of typing from scratch.
246    value: String,
247}
248
249const VOCAB_REFRESH_INTERVAL: Duration = Duration::from_secs(5);
250
251/// Spawn a background thread that periodically refreshes the
252/// vocabulary cache. Runs forever — its lifetime ties to the
253/// `Arc<Mutex<ServerVocab>>` it writes to. When the REPL drops
254/// the Arc clone the thread sees a stale clone and continues
255/// harmlessly until the process exits.
256fn 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
271/// One-shot refresh of the vocabulary cache. Used both by the
272/// background thread and by the initial seed at REPL start.
273fn 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            // Each row is `path | name | type | value | rev=… | scope=… | final-marker`.
278            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    // Dedup by name — multiple components may declare the same
290    // control name (e.g. the activity-level `rate` plus a
291    // sub-component's `rate`). Keep the first occurrence; for
292    // completion purposes, name uniqueness is what matters.
293    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
309/// Split a cached metrics row `family{k=v,...}` into its
310/// family name and parsed `(key, value)` label pairs.
311fn 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            // Strip surrounding quotes (server uses Prometheus
331            // style: `key="value"`).
332            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// ─── Pinned-metric pane state ────────────────────────────────
340
341/// One pinned selector + its most recent rendered output. The
342/// pin pane's height is derived at draw time from the line
343/// count of every `rendered` field, capped at [`PIN_PANE_MAX_LINES`].
344#[derive(Clone)]
345struct PinnedEntry {
346    selector: String,
347    rendered: String,
348    /// Last refresh instant — used to suppress duplicate
349    /// per-tick refreshes when the user pauses the loop.
350    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
358// ─── REPL state ──────────────────────────────────────────────
359
360/// State for the REPL.
361struct ReplApp {
362    socket: PathBuf,
363    /// Tab-completion source. Populated once at startup from
364    /// the server's `commands` response.
365    commands: Vec<String>,
366    /// Background-refreshed control + metric vocabulary used by
367    /// argument-aware autocompletion.
368    vocab: Arc<Mutex<ServerVocab>>,
369    /// Scrollback buffer — every command and its response is
370    /// appended as one or more `Line`s. Bounded at
371    /// [`SCROLLBACK_LIMIT`] so a long session doesn't eat all
372    /// memory.
373    scrollback: Vec<Line<'static>>,
374    /// Currently-typed input line.
375    input: String,
376    /// Cursor position within `input` (byte index — input is
377    /// ASCII-only in practice, all command names are
378    /// lower-case English).
379    cursor: usize,
380    /// Command history (most recent at end). `history_idx`
381    /// points one past the end while not browsing; Up/Down
382    /// move within bounds.
383    history: Vec<String>,
384    history_idx: usize,
385    /// Vertical scroll offset for the scrollback view. 0 means
386    /// auto-follow the tail.
387    scroll: u16,
388    should_quit: bool,
389    /// Pinned-metric selectors + rendered output.
390    pinned: Vec<PinnedEntry>,
391    pin_refresh_interval: Duration,
392    /// Last instant the pin loop swept all entries — gated
393    /// against `pin_refresh_interval` so the per-frame draw
394    /// doesn't issue a round-trip per keystroke.
395    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        // Seed the vocabulary cache synchronously so the first
414        // Tab press has data even if the background thread
415        // hasn't ticked yet. Then spawn the refresher.
416        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            // Refresh pinned metrics if the interval elapsed.
443            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                // Esc clears the current input. Helpful when
485                // the user is mid-tab-cycle and wants to
486                // restart the line.
487                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        // Walk back one char (UTF-8 boundary).
504        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    /// Replace `self.input` with `new`, leaving the cursor at
513    /// the end. Helper used by every autocomplete branch.
514    fn set_input(&mut self, new: String) {
515        self.input = new;
516        self.cursor = self.input.len();
517    }
518
519    /// Tab-completion entry point. Picks one of four behaviors
520    /// based on the current input shape:
521    ///
522    /// 1. No whitespace → complete the first token from the
523    ///    server's command list.
524    /// 2. `set <prefix>` → complete the control name from the
525    ///    cached vocabulary.
526    /// 3. `metric <family-prefix>` (no `{`) → complete the
527    ///    family name.
528    /// 4. `metric <family>{k1=v1,…,partial-key>` (no `=` in the
529    ///    last token) → complete a label key.
530    /// 5. `metric <family>{…,k=<partial-value>` → complete a
531    ///    value for that key in instances matching the family.
532    /// 6. `readout <prefix>` → complete the readout name from the
533    ///    built-in registry.
534    fn autocomplete(&mut self) {
535        let input = self.input.clone();
536        // Only-first-token case (existing behavior).
537        if !input.contains(char::is_whitespace) {
538            self.complete_command(&input);
539            return;
540        }
541        // Argument completions for `set` and `metric`.
542        if let Some(rest) = input.strip_prefix("set ") {
543            // The grammar after `set` is `<name> <value> [source=...]`.
544            // Position 1 (name) completes from the controls vocab;
545            // position 2 (value) completes type-aware candidates
546            // (bool → true/false; non-bool empty-prefix → current
547            // value prefill; else a hint line).
548            match rest.split_once(char::is_whitespace) {
549                None => {
550                    // Still inside the name token.
551                    self.complete_control_name(rest);
552                }
553                Some((name, after_name)) => {
554                    // Reject `set <name> <value> <extra>` —
555                    // value is one token, anything past it is
556                    // `source=` etc. that isn't completable.
557                    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        // `readout <name>` — complete the readout name against the
571        // built-in registry (the same set `render_readout` validates
572        // against server-side).
573        if let Some(rest) = input.strip_prefix("readout ") {
574            self.complete_readout_arg(rest);
575        }
576    }
577
578    /// Tab in `readout <prefix>` argument position: complete the
579    /// readout name from the built-in registry
580    /// (`nmbrs_runtime::readouts::Registry::all_names()`) — the
581    /// authoritative set the server's `render_readout` accepts. The
582    /// command takes a single name argument, so once the cursor is
583    /// past it (whitespace in `prefix`) there's nothing to complete.
584    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                // Prefill the current value as the value-position
644                // text. This is the "tab my way to setting a
645                // value" experience: a single tab puts the user in
646                // edit-and-submit posture rather than blank-page
647                // posture. To set a brand-new value, the user
648                // backspaces the prefilled value first; to keep
649                // it (no-op submit), they press Enter.
650                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                // Show name + type + current value for each match
667                // so the operator can pick by what the controls
668                // currently hold, not just by name.
669                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    /// Tab in value position: `set <known_name> <prefix>` where
683    /// `prefix` is what's after the second whitespace boundary.
684    /// For boolean controls, complete `true` / `false`. For
685    /// numeric controls there is no fixed vocabulary — but the
686    /// initial completion already prefilled the current value via
687    /// [`complete_control_name`], so a second Tab in value
688    /// position re-prefills (idempotent) and shows the type hint.
689    /// Returns true if a completion was applied.
690    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        // Type-driven candidates. Loose match against the type
699        // label so `bool` and `Bool` both work.
700        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        // Non-bool: when the prefix is empty, prefill the current
730        // value. This catches the "user backspaced the prefilled
731        // value, hit Tab again to recall it" pattern. Otherwise
732        // there's nothing to complete from a fixed vocab.
733        if prefix.is_empty() {
734            self.set_input(format!("set {} {}", info.name, info.value));
735            return true;
736        }
737        // Type hint as a non-completing nudge.
738        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        // Case A: no `{` yet — completing a family name.
755        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                        // Append `{` to invite the next
770                        // completion stage.
771                        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    /// Inside `metric <family>{...|`. Determine whether the
796    /// trailing token is a partial key (no `=`) or a partial
797    /// value (after `=`), and complete from the cached metrics
798    /// instances filtered by family.
799    fn complete_metric_label(&mut self, family: &str, body: &str, metrics: &[String]) {
800        // Find the trailing partial token after the last `,`.
801        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        // Decide between key-completion and value-completion.
812        if let Some((key, partial_val)) = last.split_once('=') {
813            // Value completion.
814            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            // Key completion.
855            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                    // Replace the last token (the partial key)
871                    // with `single=` so the user immediately
872                    // sees the next completion stage.
873                    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        // REPL-local meta-commands take priority over server
932        // dispatch.
933        if let Some(handled) = self.try_handle_meta(trimmed) {
934            // Echo + (optionally) printed feedback.
935            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        // Echo the input, then dispatch and append the
962        // response.
963        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; // jump to tail on submit
987        self.trim_scrollback();
988    }
989
990    /// Interpret REPL-internal meta commands (`:pin`, `:unpin`,
991    /// `:pins`, `:watch`, `:help`, `:q`/`:quit`/`:clear`).
992    /// Returns `Some(feedback)` when the line is a meta command;
993    /// `None` lets the caller fall through to the server.
994    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        // Reject unknown `:` commands explicitly so the user
1041        // doesn't accidentally send a typoed meta-command to
1042        // the server.
1043        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        // Force an immediate refresh so the user sees data
1062        // right away rather than waiting up to a full interval.
1063        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        // Snapshot selectors first so we don't hold a borrow
1129        // while issuing socket queries.
1130        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    /// Compute the height (in terminal lines) the pin pane
1153    /// should occupy at draw time. `0` when there are no pins
1154    /// (the layout slot collapses), otherwise the sum of
1155    /// (1 header line + rendered line count) for every pin,
1156    /// capped at [`PIN_PANE_MAX_LINES`].
1157    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            // 1 header line per pin, plus the lines of the
1164            // rendered output.
1165            total = total.saturating_add(1 + entry.rendered.lines().count());
1166        }
1167        // Cap and add 2 for the surrounding border the pane uses.
1168        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        // Pin pane (only rendered when non-empty so the layout
1199        // hands us a zero-height slot otherwise).
1200        if pin_h > 0 {
1201            let pin_lines = self.pin_pane_lines();
1202            // Trim to the pane's available inner height (border
1203            // already accounted for in pin_pane_height).
1204            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        // Scrollback panel.
1217        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        // Input line.
1236        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        // Cursor: start of inner + "> " (2 cells) + cursor index.
1247        frame.set_cursor_position(Position::new(inner.x + 2 + self.cursor as u16, inner.y));
1248    }
1249}
1250
1251/// Built-in readout names matching `prefix`, for `readout <name>`
1252/// tab-completion. Pure helper over the authoritative registry
1253/// (`nmbrs_runtime::readouts::Registry::all_names()`) so it's
1254/// unit-testable without constructing a `ReplApp`.
1255fn 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// =========================================================================
1284// Tests
1285// =========================================================================
1286
1287#[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        // Some renderers may emit unquoted values; parser
1315        // should tolerate both forms.
1316        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        // Unique prefix.
1324        assert_eq!(readout_name_candidates("error_"), vec!["error_readout"]);
1325        // Ambiguous prefix → all matches (drives the LCP path).
1326        assert_eq!(
1327            readout_name_candidates("phase_st"),
1328            vec!["phase_starting", "phase_status"],
1329        );
1330        // No match.
1331        assert!(readout_name_candidates("zzz").is_empty());
1332        // Wired to the real registry — a known name is in the full set.
1333        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}