Skip to main content

vta_cli_common/
render.rs

1use ratatui::{
2    buffer::{Buffer, CellDiffOption},
3    layout::Rect,
4    style::{Color, Modifier},
5    widgets::Widget,
6};
7use std::sync::OnceLock;
8use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
9
10// ── Bin-name registration ───────────────────────────────────────────
11//
12// pnm-cli and cnm-cli both consume this crate's shared command
13// handlers. When one of those handlers needs to point the operator at a
14// follow-up command (e.g. context-create → "did you mean to run X
15// instead?"), it must use the binary the operator actually invoked,
16// not a hard-coded `pnm`. Each CLI binary calls `set_bin_name("pnm")`
17// or `set_bin_name("cnm")` at startup; handlers read via `bin_name()`
18// and fall back to "vta" if neither was registered (the offline `vta
19// bootstrap …` path also calls into shared modules).
20
21static BIN_NAME: OnceLock<&'static str> = OnceLock::new();
22
23/// Register the binary name used in operator-facing hints. Call once at
24/// CLI startup. Only the first call sticks; later calls are ignored so
25/// that nested invocations (e.g. unit tests) don't clobber it.
26pub fn set_bin_name(name: &'static str) {
27    let _ = BIN_NAME.set(name);
28}
29
30/// The binary name registered via [`set_bin_name`]. Defaults to `"vta"`
31/// (the offline binary's name) when nothing has been registered, so
32/// shared handlers still produce a syntactically valid command string.
33pub fn bin_name() -> &'static str {
34    BIN_NAME.get().copied().unwrap_or("vta")
35}
36
37// ── Full-display toggle ─────────────────────────────────────────────
38//
39// CLI global `--full-display` flag. When enabled, list commands emit
40// every identifier in full (no ratatui-Table truncation) as a sequence
41// of key-value blocks. Default rendering stays as the compact table
42// for a readable overview; full display is the escape hatch for
43// copying complete DIDs, key ids, template names, etc.
44
45static FULL_DISPLAY: AtomicBool = AtomicBool::new(false);
46
47/// Enable or disable full-display output. Called once at CLI startup
48/// from the global flag.
49pub fn set_full_display(enabled: bool) {
50    FULL_DISPLAY.store(enabled, Ordering::Relaxed);
51}
52
53/// Current full-display mode. List commands check this to choose
54/// between table and full-form output.
55pub fn is_full_display() -> bool {
56    FULL_DISPLAY.load(Ordering::Relaxed)
57}
58
59/// Tell the reader that this table shortens identifiers, and how to get them
60/// whole.
61///
62/// The compact table is the right default — it is readable, and most of the
63/// time nobody needs the full value. But a shortened identifier still *looks*
64/// like an identifier, and the obvious thing to do with one is select it and
65/// paste it into the next command. That produces an argument containing a
66/// literal `…` (U+2026), which is not a DID and never was.
67///
68/// `--full-display` already existed. The gap was that you only learned it
69/// existed after being caught by its absence, so the hint goes where the
70/// truncation happens rather than in `--help`.
71pub fn print_truncation_hint() {
72    println!(
73        "  {DIM}Identifiers are shortened to fit. Re-run with `{} --full-display …` \
74         to copy one in full.{RESET}",
75        bin_name()
76    );
77}
78
79/// Emit a list entry as aligned `label: value` lines. Used in
80/// full-display mode where ratatui-Table truncation would hide full
81/// identifiers.
82///
83/// `pairs` is `[(label, value)]`. Labels are padded to the widest so
84/// values line up vertically. A trailing blank line separates entries.
85pub fn print_full_entry(pairs: &[(&str, &str)]) {
86    let widest = pairs.iter().map(|(l, _)| l.len()).max().unwrap_or(0);
87    for (label, value) in pairs {
88        let pad = " ".repeat(widest.saturating_sub(label.len()));
89        println!("  {label}:{pad}  {DIM}{value}{RESET}");
90    }
91    println!();
92}
93
94/// [`print_full_entry`] for owned values. `crate::display::full_display_pairs`
95/// builds `(&'static str, String)` pairs — it has to, since a display name is
96/// computed rather than borrowed from the response — so this saves every call
97/// site the same re-borrowing dance.
98pub fn print_full_entry_owned(pairs: &[(&str, String)]) {
99    let borrowed: Vec<(&str, &str)> = pairs.iter().map(|(l, v)| (*l, v.as_str())).collect();
100    print_full_entry(&borrowed);
101}
102
103/// Print a bold section heading used above a list of full-display
104/// entries. Matches the title style of the table-mode block borders.
105pub fn print_full_list_title(title: &str, count: usize) {
106    println!();
107    println!("{BOLD}{title} ({count}){RESET}");
108    println!();
109}
110
111// ── Output format ───────────────────────────────────────────────────
112//
113// Global `--json` flag. When enabled, list commands emit a single JSON
114// document instead of the ratatui table / full-display rendering. This
115// is the automation entry point — scripts piping `pnm acl list --json`
116// into `jq` get a stable shape, while interactive operators get the
117// human-readable default.
118
119/// Output format selected by the operator.
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum OutputFormat {
122    Human,
123    Json,
124}
125
126static OUTPUT_FORMAT: AtomicU8 = AtomicU8::new(0); // 0 = Human, 1 = Json
127
128/// Register the output format. Called once at CLI startup from the
129/// global `--json` flag.
130pub fn set_output_format(format: OutputFormat) {
131    OUTPUT_FORMAT.store(
132        match format {
133            OutputFormat::Human => 0,
134            OutputFormat::Json => 1,
135        },
136        Ordering::Relaxed,
137    );
138}
139
140/// Current output format. Default `Human`.
141pub fn output_format() -> OutputFormat {
142    if OUTPUT_FORMAT.load(Ordering::Relaxed) == 1 {
143        OutputFormat::Json
144    } else {
145        OutputFormat::Human
146    }
147}
148
149/// Returns true when the operator passed `--json`. List commands check
150/// this and dispatch to a JSON serializer instead of their human-
151/// readable renderer.
152#[must_use]
153pub fn is_json_output() -> bool {
154    output_format() == OutputFormat::Json
155}
156
157/// Pretty-print a serializable value as JSON to stdout. Used by list
158/// commands when [`is_json_output`] is true. Errors here are surfaced
159/// as a CLI error rather than a panic so the caller can render via
160/// `print_cli_error`.
161pub fn print_json<T: serde::Serialize>(value: &T) -> Result<(), serde_json::Error> {
162    let text = serde_json::to_string_pretty(value)?;
163    println!("{text}");
164    Ok(())
165}
166
167// ── ANSI constants ──────────────────────────────────────────────────
168
169pub const BOLD: &str = "\x1b[1m";
170pub const DIM: &str = "\x1b[2m";
171pub const GREEN: &str = "\x1b[32m";
172pub const RED: &str = "\x1b[31m";
173pub const CYAN: &str = "\x1b[36m";
174pub const YELLOW: &str = "\x1b[33m";
175pub const RESET: &str = "\x1b[0m";
176
177// ── Error reporting ─────────────────────────────────────────────────
178
179/// Print a CLI error to stderr in a form an operator can act on.
180///
181/// Downcasts to [`vta_sdk::error::VtaError`] when possible and emits a
182/// tailored remediation hint for the common failure modes (auth, network,
183/// forbidden, validation). Falls back to the raw error message + source
184/// chain for anything else, so unknown failures still get their underlying
185/// cause surfaced.
186///
187/// Call this from the top-level CLI match instead of `eprintln!("Error:
188/// {e}")` — the raw form loses auth/network context that operators need
189/// to fix things themselves.
190pub fn print_cli_error(err: &(dyn std::error::Error + 'static)) {
191    use vta_sdk::error::VtaError;
192    if let Some(vta_err) = err.downcast_ref::<VtaError>() {
193        match vta_err {
194            VtaError::Auth(msg) => {
195                eprintln!("{RED}\u{2717}{RESET} Authentication failed: {msg}");
196                eprintln!(
197                    "  {DIM}Token may be expired. Try `pnm setup` to re-authenticate, or check \
198                     that the VTA's `/auth` endpoint is reachable.{RESET}"
199                );
200            }
201            VtaError::Forbidden(msg) => {
202                eprintln!("{RED}\u{2717}{RESET} Forbidden: {msg}");
203                eprintln!(
204                    "  {DIM}Your role or context access doesn't permit this operation. \
205                     Inspect with `pnm acl get <your-did>`.{RESET}"
206                );
207            }
208            VtaError::NotFound(msg) => {
209                eprintln!("{RED}\u{2717}{RESET} Not found: {msg}");
210            }
211            VtaError::Conflict(msg) => {
212                // The SDK preserves the full 409 JSON body so programmatic
213                // callers can extract structured fields (e.g. `mediator_did`).
214                // For humans, surface the `message` (or `error`) field rather
215                // than dumping the raw JSON; fall back to the raw text for
216                // non-JSON bodies.
217                eprintln!(
218                    "{RED}\u{2717}{RESET} Conflict: {}",
219                    extract_human_message(msg)
220                );
221            }
222            VtaError::Gone(msg) => {
223                // Same treatment as the `Conflict` arm below: the SDK keeps
224                // the full 410 body, so surface the human field rather than
225                // dumping raw JSON at the operator.
226                let human = extract_human_message(msg);
227                eprintln!("{RED}\u{2717}{RESET} Resource is gone: {human}");
228                // 410 has more than one producer — the TEE bootstrap carve-out
229                // and the one-shot backup blob slots — so the carve-out
230                // walkthrough only prints when the refusal is actually about
231                // the carve-out. Unconditionally, it would send a backup
232                // operator down the admin-provisioning path for a bundle that
233                // simply expired. The marker is the server's own wording in
234                // `routes::bootstrap::carve_out_closed_error`; a miss costs
235                // the generic hint, never a wrong one.
236                if human.contains(CARVE_OUT_MARKER) {
237                    let bin = bin_name();
238                    eprintln!(
239                        "  {DIM}This usually means the bootstrap carve-out has already been \
240                         used. For a second admin, run `{bin} bootstrap provision-request` from \
241                         the new operator's host and have an existing admin run \
242                         `{bin} bootstrap provision-integration` against this VTA.{RESET}"
243                    );
244                } else {
245                    eprintln!(
246                        "  {DIM}This resource was single-use or time-limited, and has been \
247                         consumed or has expired. Retrying will not help — restart the \
248                         operation to get a fresh one.{RESET}"
249                    );
250                }
251            }
252            VtaError::Validation(msg) => {
253                eprintln!("{RED}\u{2717}{RESET} Invalid request: {msg}");
254            }
255            VtaError::Network(e) => {
256                eprintln!("{RED}\u{2717}{RESET} Network error: {e}");
257                eprintln!("  {DIM}Is the VTA reachable? Check its URL with `pnm vta info`.{RESET}");
258            }
259            VtaError::Server { status, body } => {
260                eprintln!("{RED}\u{2717}{RESET} Server error (HTTP {status}): {body}");
261                eprintln!(
262                    "  {DIM}This is a VTA-side failure. Check server logs or contact the operator.{RESET}"
263                );
264            }
265            VtaError::UnsupportedTransport(msg) => {
266                eprintln!("{RED}\u{2717}{RESET} Unsupported transport: {msg}");
267                eprintln!(
268                    "  {DIM}This operation requires a specific transport (REST or DIDComm). \
269                     Check which mode your CLI is in and whether the endpoint supports it.{RESET}"
270                );
271            }
272            VtaError::DidcommTransport(msg) => {
273                eprintln!("{RED}\u{2717}{RESET} DIDComm transport error: {msg}");
274                eprintln!(
275                    "  {DIM}Mediator or peer unreachable. Retry after checking mediator \
276                     connectivity.{RESET}"
277                );
278            }
279            VtaError::DidcommRemote { code, comment } => {
280                eprintln!("{RED}\u{2717}{RESET} Remote error ({code}): {comment}");
281            }
282            VtaError::Protocol(msg) => {
283                eprintln!("{RED}\u{2717}{RESET} Protocol error: {msg}");
284            }
285            // ── Runtime service-management variants (T0.2) ────────
286            VtaError::LastServiceRefused => {
287                let bin = bin_name();
288                eprintln!(
289                    "{RED}\u{2717}{RESET} Refused: would leave the VTA with no advertised services."
290                );
291                eprintln!(
292                    "  {DIM}At least one transport (REST or DIDComm) must remain advertised. \
293                     Enable the other transport first via `{bin} services <kind> enable …`, \
294                     then retry.{RESET}"
295                );
296            }
297            VtaError::ServiceNotPresent => {
298                let bin = bin_name();
299                eprintln!("{RED}\u{2717}{RESET} Service is not present.");
300                eprintln!(
301                    "  {DIM}The service kind isn't currently enabled. Use `{bin} services \
302                     <kind> enable …` to bring it online before updating, disabling, or rolling \
303                     it back.{RESET}"
304                );
305            }
306            VtaError::ServiceAlreadyEnabled => {
307                let bin = bin_name();
308                eprintln!("{RED}\u{2717}{RESET} Service is already enabled.");
309                eprintln!(
310                    "  {DIM}Use `{bin} services <kind> update …` to change its configuration, \
311                     or `{bin} services <kind> disable` to remove it.{RESET}"
312                );
313            }
314            VtaError::MediatorHandshakeFailed { reason } => {
315                eprintln!("{RED}\u{2717}{RESET} Mediator handshake failed: {reason}");
316                eprintln!(
317                    "  {DIM}Confirm the mediator DID is correct and the mediator is reachable. \
318                     The reason above is the specific cause from the handshake protocol.{RESET}"
319                );
320            }
321            VtaError::DrainTtlOutOfBounds {
322                min,
323                max,
324                requested,
325            } => {
326                eprintln!(
327                    "{RED}\u{2717}{RESET} Drain TTL {requested}s is outside the allowed range \
328                     [{min}s, {max}s]."
329                );
330                eprintln!(
331                    "  {DIM}Pick a value within those bounds. The minimum applies when the \
332                     command is delivered over DIDComm transport (so the listener stays up long \
333                     enough for the response).{RESET}"
334                );
335            }
336            VtaError::NoPriorMutation => {
337                let bin = bin_name();
338                eprintln!("{RED}\u{2717}{RESET} No prior mutation to roll back.");
339                eprintln!(
340                    "  {DIM}Use `{bin} services <kind> {{enable,update,disable}} …` directly \
341                     instead of rollback.{RESET}"
342                );
343            }
344            other => eprintln!("{RED}\u{2717}{RESET} Error: {other}"),
345        }
346        return;
347    }
348    eprintln!("{RED}\u{2717}{RESET} Error: {err}");
349    let mut source = err.source();
350    while let Some(s) = source {
351        eprintln!("  {DIM}caused by: {s}{RESET}");
352        source = s.source();
353    }
354}
355
356/// Pull a human-readable line out of a (possibly JSON) error body.
357///
358/// The SDK hands `VtaError::Conflict` the *raw* 409 response body so that
359/// programmatic callers can deserialize structured fields. For terminal
360/// output we don't want to dump JSON at the operator, so prefer the body's
361/// `message` field, then its `error` field, and only fall back to the raw
362/// text when the body isn't the expected JSON shape.
363/// Substring that marks a 410 as the TEE first-boot bootstrap carve-out
364/// rather than one of the other single-use resources that now render as
365/// `Gone` (the backup blob slots). Mirrors the server's wording in
366/// `vta_service::routes::bootstrap::carve_out_closed_error`.
367const CARVE_OUT_MARKER: &str = "carve-out";
368
369fn extract_human_message(body: &str) -> String {
370    serde_json::from_str::<serde_json::Value>(body)
371        .ok()
372        .and_then(|v| {
373            v.get("message")
374                .or_else(|| v.get("error"))
375                .and_then(|m| m.as_str())
376                .map(str::to_string)
377        })
378        .unwrap_or_else(|| body.to_string())
379}
380
381// ── Ratatui rendering helpers ───────────────────────────────────────
382
383pub fn print_widget(widget: impl Widget, height: u16) {
384    let width = ratatui::crossterm::terminal::size().map_or(120, |(w, _)| w);
385    let area = Rect::new(0, 0, width, height);
386    let mut buf = Buffer::empty(area);
387    widget.render(area, &mut buf);
388
389    let mut out = String::new();
390    for y in 0..height {
391        let mut cur_fg = Color::Reset;
392        let mut cur_bg = Color::Reset;
393        let mut cur_mod = Modifier::empty();
394
395        for x in 0..width {
396            let cell = &buf[(x, y)];
397            if cell.diff_option == CellDiffOption::Skip {
398                continue;
399            }
400
401            if cell.fg != cur_fg || cell.bg != cur_bg || cell.modifier != cur_mod {
402                out.push_str("\x1b[0m");
403                push_ansi_fg(&mut out, cell.fg);
404                push_ansi_bg(&mut out, cell.bg);
405                push_ansi_mod(&mut out, cell.modifier);
406                cur_fg = cell.fg;
407                cur_bg = cell.bg;
408                cur_mod = cell.modifier;
409            }
410
411            out.push_str(cell.symbol());
412        }
413        out.push_str("\x1b[0m\n");
414    }
415
416    print!("{out}");
417}
418
419pub fn push_ansi_fg(out: &mut String, color: Color) {
420    use std::fmt::Write as _;
421    match color {
422        Color::Reset => {}
423        Color::Black => out.push_str("\x1b[30m"),
424        Color::Red => out.push_str("\x1b[31m"),
425        Color::Green => out.push_str("\x1b[32m"),
426        Color::Yellow => out.push_str("\x1b[33m"),
427        Color::Blue => out.push_str("\x1b[34m"),
428        Color::Magenta => out.push_str("\x1b[35m"),
429        Color::Cyan => out.push_str("\x1b[36m"),
430        Color::Gray => out.push_str("\x1b[37m"),
431        Color::DarkGray => out.push_str("\x1b[90m"),
432        Color::LightRed => out.push_str("\x1b[91m"),
433        Color::LightGreen => out.push_str("\x1b[92m"),
434        Color::LightYellow => out.push_str("\x1b[93m"),
435        Color::LightBlue => out.push_str("\x1b[94m"),
436        Color::LightMagenta => out.push_str("\x1b[95m"),
437        Color::LightCyan => out.push_str("\x1b[96m"),
438        Color::White => out.push_str("\x1b[97m"),
439        Color::Rgb(r, g, b) => {
440            let _ = write!(out, "\x1b[38;2;{r};{g};{b}m");
441        }
442        Color::Indexed(i) => {
443            let _ = write!(out, "\x1b[38;5;{i}m");
444        }
445    }
446}
447
448pub fn push_ansi_bg(out: &mut String, color: Color) {
449    use std::fmt::Write as _;
450    match color {
451        Color::Reset => {}
452        Color::Black => out.push_str("\x1b[40m"),
453        Color::Red => out.push_str("\x1b[41m"),
454        Color::Green => out.push_str("\x1b[42m"),
455        Color::Yellow => out.push_str("\x1b[43m"),
456        Color::Blue => out.push_str("\x1b[44m"),
457        Color::Magenta => out.push_str("\x1b[45m"),
458        Color::Cyan => out.push_str("\x1b[46m"),
459        Color::Gray => out.push_str("\x1b[47m"),
460        Color::DarkGray => out.push_str("\x1b[100m"),
461        Color::LightRed => out.push_str("\x1b[101m"),
462        Color::LightGreen => out.push_str("\x1b[102m"),
463        Color::LightYellow => out.push_str("\x1b[103m"),
464        Color::LightBlue => out.push_str("\x1b[104m"),
465        Color::LightMagenta => out.push_str("\x1b[105m"),
466        Color::LightCyan => out.push_str("\x1b[106m"),
467        Color::White => out.push_str("\x1b[107m"),
468        Color::Rgb(r, g, b) => {
469            let _ = write!(out, "\x1b[48;2;{r};{g};{b}m");
470        }
471        Color::Indexed(i) => {
472            let _ = write!(out, "\x1b[48;5;{i}m");
473        }
474    }
475}
476
477pub fn push_ansi_mod(out: &mut String, modifier: Modifier) {
478    if modifier.contains(Modifier::BOLD) {
479        out.push_str("\x1b[1m");
480    }
481    if modifier.contains(Modifier::DIM) {
482        out.push_str("\x1b[2m");
483    }
484    if modifier.contains(Modifier::ITALIC) {
485        out.push_str("\x1b[3m");
486    }
487    if modifier.contains(Modifier::UNDERLINED) {
488        out.push_str("\x1b[4m");
489    }
490    if modifier.contains(Modifier::REVERSED) {
491        out.push_str("\x1b[7m");
492    }
493    if modifier.contains(Modifier::CROSSED_OUT) {
494        out.push_str("\x1b[9m");
495    }
496}
497
498pub fn print_section(title: &str) {
499    let pad = 46usize.saturating_sub(title.len());
500    println!(
501        "\n{DIM}──{RESET} {BOLD}{title}{RESET} {DIM}{}{RESET}",
502        "─".repeat(pad)
503    );
504}
505
506#[cfg(test)]
507mod tests {
508    use super::extract_human_message;
509
510    #[test]
511    fn prefers_message_field() {
512        let body = r#"{"error":"didcomm_already_enabled","message":"DIDComm is already enabled.","mediator_did":"did:peer:2.med"}"#;
513        assert_eq!(extract_human_message(body), "DIDComm is already enabled.");
514    }
515
516    #[test]
517    fn falls_back_to_error_field_when_no_message() {
518        let body = r#"{"error":"duplicate_key"}"#;
519        assert_eq!(extract_human_message(body), "duplicate_key");
520    }
521
522    #[test]
523    fn falls_back_to_raw_text_for_non_json() {
524        let body = "plain conflict text";
525        assert_eq!(extract_human_message(body), "plain conflict text");
526    }
527
528    #[test]
529    fn falls_back_to_raw_text_when_fields_missing() {
530        // Valid JSON but neither `message` nor `error` present → raw text.
531        let body = r#"{"detail":"something"}"#;
532        assert_eq!(extract_human_message(body), body);
533    }
534}