diff --git a/docs/TUI.md b/docs/TUI.md index 83986ef..9cecc60 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -19,7 +19,7 @@ construct that. | Screen / state | What you get | Why | |---|---|---| -| Main chat (empty, messages, long line, stale roster, alert) | **RECONSTRUCTED** — same `Layout` constraints as `src/tui.rs` `draw_main` (banner height, 36% roster, composer 3, footer 1) plus the real `banner_for_width` / `status_footer` | `App` private | +| Main chat (empty, messages, long line, stale roster, alert) | **RECONSTRUCTED** at the time of the audit; since the clean-look redesign (`draw_main_chrome`) it is **REAL** — see “Clean-look chrome redesign” below | `App` private | | Help / `/who` overlay | **RECONSTRUCTED** — Rect math copied from private `draw_text_overlay` | private | | Share / invite | **REAL** `draw_share` | public | | Profile, paste, approve, rotate, wipe, quit, backup, restore, passphrase | **RECONSTRUCTED** — public `*_screen_text` / `ProfileEditor` copy inside `Block::bordered`, titles taken from `src/tui.rs` | private `draw_*` | @@ -786,3 +786,127 @@ dumps the screen at 80x24, 120x40 and 200x60, populated and empty. the only signal. - **Read-only.** The screen reads one getter and draws; it cannot send, sign or dial. +## Clean-look chrome redesign — implemented + +The main screen was restructured around one accent, one primary pane and honest +states. The render path is no longer reconstructed in the dump: `App::draw_main` +builds a `MainView` of plain data and hands it to the public `draw_main_chrome`, +which is exactly what `tests/tui_frames.rs` draws. There is no stand-in layout, +so a frame dump is the real screen. + +``` +cargo test --locked --test tui_frames -- --nocapture dump_audit_frames +``` + +dumps every state below at 80x24, 120x40 and 200x60. + +### Hierarchy + +| Row | Content | Style | +|---|---|---| +| 0 | `onionwire {glyph} tor {phase} me:{fp8} onion:{onion8}` | app name bold text, phase semantic, identity muted | +| 1 | the alert (`send failed: …`, `fingerprint mismatch`) — only when set | alert | +| 2..h-4 | roster (22 cells at 80, 28 at 120+) next to the chat transcript | roster rows text/stale, focus marker on the focused pane | +| h-3..h-1 | composer, **no frame**, 3-row slot for wrapped input | `> ` marker + bold when focused, `message` muted when empty | +| h-1 | `{note} {glyph} TOR {phase} me:{fp8} {pane hints} ? help` | muted; phase semantic | + +The header no longer takes the accent — the accent is reserved for focus, which +is what let the header stop competing with the panes. + +### Tor phase is a first-class state + +`Node::tor_state()` was already cheap, read-only and unused by the TUI. It now +feeds `TorPhase` (one word + one glyph, both in the header and the footer), so +"connected" is never implied: + +| `hs::TorState` | `TorPhase` | glyph / ASCII | word | tone | +|---|---|---|---|---| +| `Bootstrapping` | `Connecting` | `…` / `...` | `connecting` | muted | +| `Published` | `Ready` | `✓` / `ok` | `ready` | text | +| `DegradedReachable` | `Degraded` | `!` | `degraded` | stale | +| `Stopped` | `Off` | `x` | `off` | alert | + +No new data field was needed: `App` already holds `Arc`, and this is a +read-only getter, not a store read from the render path. + +### States + +``` +onionwire ✓ tor ready me:abcdef01 onion:abcdefgh +┌roster 2 1 stale───┐┌> chat alice───────────────────────────────────────────┐ +│> alice aaaaaaaa… ││you: ping ✓ │ +│ bob-the-sta… stale││them: pong │ +│ ││them: this is a very long chat line that should wrap │ +│ ││inside the chat pane instead of running off the right │ +│ ││edge of an 80-column terminal and colliding with the │ +│ ││roster border │ +└────────────────────┘└────────────────────────────────────────────────────────┘ + message +✓ TOR ready me:abcdef01… j k scroll g G ends F4 rotate F9 settings ? help +``` + +``` +onionwire … tor connecting me:abcdef01 onion:abcdefgh +┌roster 0────────────┐┌ chat──────────────────────────────────────────────────┐ +│no friends ││no friends yet │ +│F3 adds one ││F3 paste an invite to add one │ +│ ││tor connecting — first publish takes a few minutes │ +└────────────────────┘└────────────────────────────────────────────────────────┘ + message +… TOR connecting me:abcdef01… j k select F3 add F6 wallet F9 settings ? help +``` + +``` +onionwire x tor off me:abcdef01 onion:unset +fingerprint mismatch +┌roster 0────────────┐┌ chat──────────────────────────────────────────────────┐ +│no friends ││no friends yet │ +│F3 adds one ││F3 paste an invite to add one │ +│ ││tor off — no onion service is running │ +└────────────────────┘└────────────────────────────────────────────────────────┘ + message +x TOR off me:abcdef01… j k select F3 add F6 wallet F9 settings ? help +``` + +The error state puts the fail-closed sentence on the alert row **once**; the +footer keeps the phase and the hints instead of repeating it. The outbox note +(`peer unreachable, queued (1/8, retry 45s)`) still outranks the hints when a +row is outstanding. + +### Footer variants + +| Helper | Identity | Used by | +|---|---|---| +| `status_footer(w, fp, onion, note, hints)` | `TOR`, `onion:` | locked chrome tests and every non-main screen | +| `status_footer_phased(w, fp, onion, phase, note, hints)` | `{glyph} TOR {word}`, `onion:` | F9 menu | +| `status_footer_compact(w, fp, phase, note, hints)` | `{glyph} TOR {word}` only | main (its header already carries `me:` and `onion:`) | + +The main footer drops the onion because the header one line above already prints +it; those cells go to the hints. `TOR`, `me:` and `? help` survive at 80, 120 +and 200 in every variant — `tests/tui_chrome.rs` asserts it. + +`pane_footer_hints(Pane)` changes the hint cluster with the focused pane +(roster / chat / composer) and every variant keeps `F9` and `? help`, so the +menu stays discoverable and the overlay stays reachable wherever the cursor is. + +### Levers from the reference (applied / skipped) + +Applied: one accent for focus (focused border, selected row, active-conversation +marker); focus as marker + weight (`> ` plus bold title, visible with colour +stripped); border weight = focus; one unframed muted footer that follows the +pane and the phase; designed empty / connecting / degraded / off states; +semantic colour only; outbox and stale state as marker + word. + +Skipped: the 3-line wordmark above the header at height ≥ 40 (fights the 1-line +header without buying hierarchy); bottom-anchoring the composer inside its +3-row slot (needs cell-accurate wrap prediction for no legibility gain); +per-row colour in the roster (name and fingerprint share one style so a narrow +pane can drop the fingerprint without changing the row's meaning). + +### Width + +`status_footer*`, `alert_line`, `main_header_line*`, `draw_text_overlay`, +`roster_row_text` and `fit_cells` all measure cells (`Span::width`), never +`chars().count()`. The roster row spends its budget on the name first, then the +`stale` word, then whatever is left on a fingerprint prefix — a 22-cell pane +reads `bob-the-sta… stale`, not `… bbbbbbbb… stale`. diff --git a/src/tui.rs b/src/tui.rs index 6812a71..06fefd9 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -12,6 +12,7 @@ use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragra use ratatui::{DefaultTerminal, Frame}; use zeroize::{Zeroize, Zeroizing}; +use crate::hs::TorState; use crate::node::Node; use crate::outbox::DEFAULT_MAX_ATTEMPTS; use crate::qr::{self, QrPayload}; @@ -49,12 +50,15 @@ fn ellipsis() -> &'static str { } /// Truncate or keep an alert so it cannot spill into the roster row. +/// +/// Cells, not chars: the message can carry a peer-supplied transport error, and +/// a CJK/emoji byte there must not push the alert into the next pane. pub fn alert_line(msg: &str, width: u16) -> String { let mut text = msg.to_string(); if color_mode() == ColorMode::None && !text.starts_with("! ") { text = format!("! {text}"); } - truncate_chars(&text, width as usize) + fit_cells(&text, width as usize) } /// Wrap an invite at `:` so a mouse-copy cannot lose a mid-hex continuation. @@ -172,7 +176,7 @@ pub fn short_send_reason(why: &str, budget: usize) -> String { let clean = sanitize::display_text(why.as_bytes()); let tail = clean.rsplit(": ").next().unwrap_or("").trim(); let text = if tail.is_empty() { clean.trim() } else { tail }; - truncate_chars(text, budget) + fit_cells(text, budget) } /// One row's delivery marker, straight from the outbox state. @@ -340,19 +344,6 @@ fn char_len(s: &str) -> usize { s.chars().count() } -fn truncate_chars(s: &str, max: usize) -> String { - if char_len(s) <= max { - return s.to_string(); - } - let e = ellipsis(); - let el = char_len(e); - if max <= el { - return e.chars().take(max).collect(); - } - let head: String = s.chars().take(max - el).collect(); - format!("{head}{e}") -} - /// Terminal colour capability, detected from the environment. /// /// `ColorMode::None` means “strip all colour” (e.g. `NO_COLOR`); the TUI then @@ -606,14 +597,67 @@ pub fn banner_for_width(width: u16) -> &'static str { /// One-line main-screen header. Do not use `banner_for_width(80)` here — that stays the wordmark. pub fn main_header_line(width: u16, me_fp: &str, me_onion: &str) -> String { + main_header_line_phased(width, me_fp, me_onion, None) +} + +/// One-line main-screen header carrying the Tor phase. `None` keeps the +/// historic string; `Some` puts the phase word and glyph between the app name +/// and the identity. +pub fn main_header_line_phased( + width: u16, + me_fp: &str, + me_onion: &str, + phase: Option, +) -> String { + fit_cells(&header_plain(me_fp, me_onion, phase), width as usize) +} + +/// The header text without a width: one place builds the string, so the styled +/// spans and the plain helper can never drift apart. +fn header_plain(me_fp: &str, me_onion: &str, phase: Option) -> String { let fp: String = me_fp.chars().take(8).collect(); let onion = if me_onion.is_empty() { "unset".to_string() } else { me_onion.chars().take(8).collect() }; - let line = format!("onionwire tor me:{fp} onion:{onion}"); - truncate_chars(&line, width as usize) + let tor = match phase { + None => "tor".to_string(), + Some(p) => format!("{} tor {}", p.glyph(), p.word()), + }; + format!("onionwire {tor} me:{fp} onion:{onion}") +} + +/// The header as spans. The app name is plain text (not accent — the accent is +/// reserved for focus), the identity is muted, and only the phase carries a +/// semantic colour. Too narrow to lay out in parts, the line degrades to one +/// truncated muted span rather than clipping mid-field. +pub fn main_header_spans( + width: u16, + me_fp: &str, + me_onion: &str, + phase: Option, +) -> Vec> { + let plain = header_plain(me_fp, me_onion, phase); + if cell_width(&plain) > width as usize { + return vec![Span::raw(fit_cells(&plain, width as usize)).style(style_dim())]; + } + let fp: String = me_fp.chars().take(8).collect(); + let onion = if me_onion.is_empty() { + "unset".to_string() + } else { + me_onion.chars().take(8).collect() + }; + let (tor_text, tor_style) = match phase { + None => ("tor".to_string(), style_dim()), + Some(p) => (format!("{} tor {}", p.glyph(), p.word()), p.style()), + }; + vec![ + Span::raw("onionwire").style(style_text().add_modifier(Modifier::BOLD)), + Span::raw(" "), + Span::raw(tor_text).style(tor_style), + Span::raw(format!(" me:{fp} onion:{onion}")).style(style_dim()), + ] } /// Roster column in cells: 22 at 80-wide, 28 at 120+. @@ -2476,11 +2520,12 @@ impl App { Screen::WalletsSettings { state } => { // The one status line the screen carries: same `status_footer` // shape as Main, so TOR / identity / the copy confirmation read - // in the same place on every screen. - let footer = status_footer( + // in the same place on every screen — including the phase. + let footer = status_footer_phased( f.area().width, &self.me_fp, &self.me_onion, + Some(TorPhase::of(self.node.tor_state())), self.status_note.as_deref(), footer_hints(&self.screen), ); @@ -2505,70 +2550,9 @@ impl App { } fn draw_main(&self, f: &mut Frame) { - let area = f.area(); - let header = main_header_line(area.width, &self.me_fp, &self.me_onion); - let alert_h = u16::from(self.alert.is_some()); - let cols = Layout::vertical([ - Constraint::Length(1), - Constraint::Length(alert_h), - Constraint::Min(3), - Constraint::Length(3), - Constraint::Length(1), - ]) - .split(area); - - f.render_widget(Paragraph::new(header).style(style_accent()), cols[0]); - if let Some(msg) = &self.alert { - let text = alert_line(msg, area.width); - f.render_widget(Paragraph::new(text).style(style_alert()), cols[1]); - } - - let roster_w = roster_col_width(area.width).min(cols[2].width.saturating_sub(10)); - let panes = - Layout::horizontal([Constraint::Length(roster_w), Constraint::Min(10)]).split(cols[2]); - let inner_roster = panes[0].width.saturating_sub(2); - - let stale_n = self.friends.iter().filter(|fr| !fr.last_connect_ok).count(); - let roster_title = if stale_n > 0 { - format!("roster {} {stale_n} stale", self.friends.len()) - } else { - format!("roster {}", self.friends.len()) - }; - - let items: Vec = if self.friends.is_empty() { - vec![ListItem::new("no friends").style(style_dim())] - } else { - self.friends - .iter() - .map(|friend| { - let raw = friend.petname.as_deref().unwrap_or(&friend.fingerprint); - let name = sanitize::display_text(raw.as_bytes()); - let line = roster_row_text( - &name, - &friend.fingerprint, - !friend.last_connect_ok, - inner_roster, - ); - let style = if friend.last_connect_ok { - style_text() - } else { - style_stale() - }; - ListItem::new(line).style(style) - }) - .collect() - }; - let roster = List::new(items) - .highlight_style(style_highlight()) - .highlight_symbol("> ") - .block(self.pane_block(&roster_title, Pane::Roster)); - let mut roster_state = ListState::default(); - if !self.friends.is_empty() { - roster_state.select(Some(self.selected)); - } - f.render_stateful_widget(roster, panes[0], &mut roster_state); - - let (chat_lines, summary) = self.chat_view(); + let phase = Some(TorPhase::of(self.node.tor_state())); + let (chat_lines, summary, chat_style) = self.chat_view(phase); + let rows: Vec = self.friends.iter().map(friend_row).collect(); let chat_name = self.friends.get(self.selected).map(|friend| { friend .petname @@ -2576,80 +2560,210 @@ impl App { .unwrap_or(&friend.fingerprint) .to_string() }); - draw_chat( - f, - panes[1], - &chat_lines, - chat_name.as_deref(), - self.focus == Pane::Chat, - self.chat_scroll, - ); - - let mark = if self.focus == Pane::Composer { - "> " - } else { - " " - }; - let (cmd, cmd_style) = if self.composer.is_empty() { - (format!("{mark}message"), style_dim()) - } else { - let style = if self.focus == Pane::Composer { - style_text().add_modifier(Modifier::BOLD) - } else { - style_text() - }; - (format!("{mark}{}", self.composer), style) - }; - f.render_widget( - Paragraph::new(cmd) - .style(cmd_style) - .wrap(Wrap { trim: false }), - cols[3], - ); - - let footer = self.footer_line(area.width, &summary); - f.render_widget(Paragraph::new(footer).style(style_dim()), cols[4]); - } - - fn footer_line(&self, width: u16, summary: &OutboxSummary) -> String { // The outbox is the source of truth while anything is outstanding; the // transient note still covers "sending", "sent file x", "invoice sent". - let note = summary.note().or_else(|| self.status_note.clone()); - status_footer( - width, - &self.me_fp, - &self.me_onion, - note.as_deref(), - footer_hints(&self.screen), - ) + let mut note = summary.note().or_else(|| self.status_note.clone()); + // The alert row above the panes is the error channel. When it already + // carries the same sentence, drop it from the footer: one statement of a + // failure, in the place the eye goes for errors. + if note.as_deref() == self.alert.as_deref() { + note = None; + } + let view = MainView { + me_fp: &self.me_fp, + me_onion: &self.me_onion, + phase, + friends: &rows, + selected: self.selected, + focus: self.focus, + chat_lines: &chat_lines, + chat_style, + chat_name: chat_name.as_deref(), + chat_scroll: self.chat_scroll, + composer: &self.composer, + alert: self.alert.as_deref(), + note: note.as_deref(), + }; + draw_main_chrome(f, &view); } - fn chat_view(&self) -> (Vec, OutboxSummary) { + /// Transcript, outbox summary, and how the rows should be styled. State copy + /// is flagged here — the render path never guesses from the text. + fn chat_view(&self, phase: Option) -> (Vec, OutboxSummary, ChatRowStyle) { let Some(friend) = self.friends.get(self.selected) else { return ( - vec![ - "no friends yet".into(), - "F3 paste an invite to add one".into(), - ], + chat_no_friends_lines(phase), OutboxSummary::default(), + ChatRowStyle::State, ); }; match self.node.list_messages(&friend.pubkey) { Ok(msgs) => { let pending = self.node.outbox_pending(&friend.pubkey).unwrap_or_default(); - chat_with_delivery(&msgs, &pending, unix_now_secs()) + let (lines, summary) = chat_with_delivery(&msgs, &pending, unix_now_secs()); + let style = if msgs.is_empty() { + ChatRowStyle::State + } else { + ChatRowStyle::Text + }; + (lines, summary, style) } - Err(e) => (vec![e], OutboxSummary::default()), + Err(e) => (vec![e], OutboxSummary::default(), ChatRowStyle::Error), } } - - fn pane_block<'a>(&self, title: &'a str, pane: Pane) -> Block<'a> { - pane_block_for(title, self.focus == pane) - } } -/// Pane chrome without an `App`: focus is accent border + bold title, never -/// color alone (the `> ` marks come from the callers). +/// One roster row: the label, the fingerprint, and the word `stale` when the +/// last dial did not answer. Colour is what the row is (text vs stale), never a +/// decoration — the word carries the state on a monochrome terminal. +pub fn roster_line(row: &FriendRow, inner_width: u16) -> Line<'static> { + let text = roster_row_text(row, inner_width); + let style = if row.stale { style_stale() } else { style_text() }; + Line::from(Span::raw(text).style(style)) +} + +/// How one chat row is styled. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum ChatRowStyle { + /// Transcript rows: our own messages and the peer's. + Text, + /// Empty / loading copy that stands in for a transcript. + State, + /// The pane could not read the transcript at all. + Error, +} + +/// The main screen: one header line, one primary pane, one status line, one +/// footer hint line. +/// +/// Every field is plain data, so the render path has no `Node` in it and +/// `tests/tui_frames.rs` dumps the real chrome at 80x24, 120x40 and 200x60. +pub struct MainView<'a> { + pub me_fp: &'a str, + pub me_onion: &'a str, + /// Tor phase, or `None` to keep the phase-free `TOR` token. + pub phase: Option, + pub friends: &'a [FriendRow], + pub selected: usize, + /// Which pane owns the keyboard. Drives the marker, the bold title, the + /// accented border, and the footer hints. + pub focus: Pane, + pub chat_lines: &'a [String], + pub chat_style: ChatRowStyle, + pub chat_name: Option<&'a str>, + pub chat_scroll: u16, + pub composer: &'a str, + /// Fail-closed one-liner: `send failed: …`, `fingerprint mismatch`, or a + /// validation message. Rendered above the panes, never truncated mid-word. + pub alert: Option<&'a str>, + /// Footer note: outbox summary or the last status message. + pub note: Option<&'a str>, +} + +/// Draw the main screen. The only chrome that reads colour is `pane_block_for` +/// (focus), `roster_line` (state), and the header's phase token. +pub fn draw_main_chrome(f: &mut Frame, view: &MainView<'_>) { + let area = f.area(); + let alert_h = u16::from(view.alert.is_some()); + let cols = Layout::vertical([ + Constraint::Length(1), + Constraint::Length(alert_h), + Constraint::Min(3), + Constraint::Length(3), + Constraint::Length(1), + ]) + .split(area); + + f.render_widget( + Paragraph::new(Line::from(main_header_spans( + area.width, + view.me_fp, + view.me_onion, + view.phase, + ))), + cols[0], + ); + if let Some(msg) = view.alert { + let text = alert_line(msg, area.width); + f.render_widget(Paragraph::new(text).style(style_alert()), cols[1]); + } + + let roster_w = roster_col_width(area.width).min(cols[2].width.saturating_sub(10)); + let panes = + Layout::horizontal([Constraint::Length(roster_w), Constraint::Min(10)]).split(cols[2]); + let inner_roster = panes[0].width.saturating_sub(2); + + let stale_n = view.friends.iter().filter(|fr| fr.stale).count(); + let roster_title = if view.friends.is_empty() { + "roster 0".to_string() + } else if stale_n > 0 { + format!("roster {} {stale_n} stale", view.friends.len()) + } else { + format!("roster {}", view.friends.len()) + }; + + let items: Vec = if view.friends.is_empty() { + empty_roster_lines() + .iter() + .map(|l| ListItem::new(*l).style(style_dim())) + .collect() + } else { + view.friends + .iter() + .map(|row| ListItem::new(roster_line(row, inner_roster))) + .collect() + }; + let roster = List::new(items) + .highlight_style(style_highlight()) + .highlight_symbol("> ") + .block(pane_block_for(&roster_title, view.focus == Pane::Roster)); + let mut roster_state = ListState::default(); + if !view.friends.is_empty() { + roster_state.select(Some(view.selected)); + } + f.render_stateful_widget(roster, panes[0], &mut roster_state); + + let chat = chat_lines_for(view.chat_lines, view.chat_style); + draw_chat_lines( + f, + panes[1], + &chat, + view.chat_name, + view.focus == Pane::Chat, + view.chat_scroll, + ); + + // Composer: no frame. `> ` plus bold while it owns the keyboard, `message` + // as a muted placeholder when it is empty. The 3-row slot stays so a + // wrapped line is not clipped. + let focused = view.focus == Pane::Composer; + let mark = if focused { "> " } else { " " }; + let (cmd, cmd_style) = if view.composer.is_empty() { + (format!("{mark}message"), style_dim()) + } else if focused { + ( + format!("{mark}{}", view.composer), + style_text().add_modifier(Modifier::BOLD), + ) + } else { + (format!("{mark}{}", view.composer), style_text()) + }; + f.render_widget( + Paragraph::new(cmd) + .style(cmd_style) + .wrap(Wrap { trim: false }), + cols[3], + ); + + let footer = status_footer_compact( + area.width, + view.me_fp, + view.phase, + view.note, + pane_footer_hints(view.focus), + ); + f.render_widget(Paragraph::new(footer).style(style_dim()), cols[4]); +} fn pane_block_for(title: &str, focused: bool) -> Block<'_> { let border = if focused { style_accent() @@ -2683,6 +2797,35 @@ pub fn draw_chat( name: Option<&str>, focused: bool, scroll: u16, +) { + let styled = chat_lines_for(lines, ChatRowStyle::Text); + draw_chat_lines(f, area, &styled, name, focused, scroll); +} + +/// Transcript rows, styled. The style is a caller decision, never inferred from +/// the text: a peer message body must not be able to pick its own colour by +/// starting with the word `no`. +pub fn chat_lines_for(lines: &[String], style: ChatRowStyle) -> Vec> { + let style = match style { + ChatRowStyle::Text => style_text(), + ChatRowStyle::State => style_dim(), + ChatRowStyle::Error => style_alert(), + }; + lines + .iter() + .map(|l| Line::from(Span::raw(l.clone()).style(style))) + .collect() +} + +/// The chat pane itself. Same renderer for transcript rows and state copy; the +/// only difference is the style the caller baked into each `Line`. +pub fn draw_chat_lines( + f: &mut Frame, + area: Rect, + lines: &[Line<'static>], + name: Option<&str>, + focused: bool, + scroll: u16, ) { let inner_h = area.height.saturating_sub(2); let nlines = lines.len(); @@ -2700,8 +2843,7 @@ pub fn draw_chat( let mark = if focused { "> " } else { " " }; let title = format!("{mark}{title}"); f.render_widget( - Paragraph::new(lines.join("\n")) - .style(style_text()) + Paragraph::new(lines.to_vec()) .wrap(Wrap { trim: false }) .scroll((scroll, 0)) .block(pane_block_for(&title, focused)), @@ -2709,18 +2851,199 @@ pub fn draw_chat( ); } +/// Chat-pane copy when no friend is selected. States after the base two rows +/// say which phase the node is actually in, so an empty roster during first +/// publish does not read as a broken app. +pub fn chat_no_friends_lines(phase: Option) -> Vec { + let mut lines = vec![ + "no friends yet".to_string(), + "F3 paste an invite to add one".to_string(), + ]; + let state = match phase { + None => None, + Some(TorPhase::Connecting) => { + Some("tor connecting — first publish takes a few minutes") + } + Some(TorPhase::Degraded) => Some("tor degraded — reachable, still settling"), + Some(TorPhase::Off) => Some("tor off — no onion service is running"), + Some(TorPhase::Ready) => None, + }; + if let Some(note) = state { + lines.push(String::new()); + lines.push(note.to_string()); + } + lines +} + +/// Roster-pane copy when the friend list is empty. Two rows, so the pane reads +/// as an empty state instead of a blank box. +pub fn empty_roster_lines() -> [&'static str; 2] { + ["no friends", "F3 adds one"] +} + +/// One friend, as the roster draws it. +/// +/// Built by `App` from `store::Friend`; the render path never touches the store +/// type, which is what lets `tests/tui_frames.rs` draw the real chrome. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FriendRow { + /// Display name: petname when set, fingerprint otherwise, already sanitized. + pub label: String, + /// Full fingerprint hex; the row fits it to the pane. + pub fingerprint: String, + /// Last dial to this peer's onion did not answer. + pub stale: bool, +} + +/// The roster row for one friend, fitted to the pane's inner width in cells. +pub fn friend_row(friend: &Friend) -> FriendRow { + let raw = friend.petname.as_deref().unwrap_or(&friend.fingerprint); + FriendRow { + label: sanitize::display_text(raw.as_bytes()).to_string(), + fingerprint: friend.fingerprint.clone(), + stale: !friend.last_connect_ok, + } +} + +/// Tor lifecycle as the chrome shows it: one word plus one glyph, so the phase +/// survives `NO_COLOR`, a 16-colour terminal, and a monochrome dump. +/// +/// Read from `Node::tor_state()`. `Connecting` is the long first publish (HsDir +/// descriptor upload), `Ready` is a published descriptor, `Degraded` is +/// reachable while Arti still reports the service broken — usable, and not the +/// same statement as ready — and `Off` is a stopped node. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum TorPhase { + Connecting, + Ready, + Degraded, + Off, +} + +impl TorPhase { + /// Project `hs::TorState`. This is the only place that knows the mapping. + pub fn of(state: TorState) -> Self { + match state { + TorState::Published => Self::Ready, + TorState::DegradedReachable => Self::Degraded, + TorState::Stopped => Self::Off, + TorState::Bootstrapping => Self::Connecting, + } + } + + /// The word a reader sees. Never abbreviated: `ok`/`up` would be ambiguous + /// with the delivery markers. + pub fn word(self) -> &'static str { + match self { + Self::Connecting => "connecting", + Self::Ready => "ready", + Self::Degraded => "degraded", + Self::Off => "off", + } + } + + /// Marker glyph, paired with [`Self::word`]. ASCII chrome falls back to + /// `...` / `ok` rather than dropping the marker. + pub fn glyph(self) -> &'static str { + let ascii = ascii_chrome(); + match self { + Self::Connecting => { + if ascii { + "..." + } else { + "…" + } + } + Self::Ready => { + if ascii { + "ok" + } else { + "✓" + } + } + Self::Degraded => "!", + Self::Off => "x", + } + } + + /// Semantic style: colour answers "what is this", never "what mood". + /// Ready is the unremarkable state, so it takes the plain text token. + pub fn style(self) -> Style { + match self { + Self::Connecting => style_dim(), + Self::Ready => style_text(), + Self::Degraded => style_stale(), + Self::Off => style_alert(), + } + } +} + +/// The footer's `TOR` cluster. `None` keeps the bare `TOR` the chrome tests +/// lock; `Some` adds the phase glyph and word. +pub fn tor_token(phase: Option) -> String { + match phase { + None => "TOR".to_string(), + Some(p) => format!("{} TOR {}", p.glyph(), p.word()), + } +} + /// Status bar: never drop a non-empty `status_note`. Always keep `TOR`, `me:`, `? help`. +/// +/// Phase-free twin of [`status_footer_phased`], kept because the chrome tests +/// and the reconstructed dumps call it directly. pub fn status_footer( width: u16, me_fp: &str, me_onion: &str, status_note: Option<&str>, hints: &str, +) -> String { + status_footer_phased(width, me_fp, me_onion, None, status_note, hints) +} + +/// Status bar with the Tor phase folded into the `TOR` cluster. +/// +/// Every width here is in terminal **cells** (`fit_cells` / `cell_width`), not +/// `chars().count()`: the phase glyph and any peer-supplied note text must not +/// be able to push the line past the frame. +pub fn status_footer_phased( + width: u16, + me_fp: &str, + me_onion: &str, + phase: Option, + status_note: Option<&str>, + hints: &str, +) -> String { + status_footer_inner(width, me_fp, Some(me_onion), phase, status_note, hints) +} + +/// Footer for a screen whose header already prints the identity. +/// +/// The main screen's header carries `me:` and `onion:`, so repeating the onion +/// in the footer costs 20+ cells and buys nothing; those cells go to the hints +/// instead. `TOR` and `me:` stay — `tests/tui_chrome.rs` locks both. +pub fn status_footer_compact( + width: u16, + me_fp: &str, + phase: Option, + status_note: Option<&str>, + hints: &str, +) -> String { + status_footer_inner(width, me_fp, None, phase, status_note, hints) +} + +fn status_footer_inner( + width: u16, + me_fp: &str, + me_onion: Option<&str>, + phase: Option, + status_note: Option<&str>, + hints: &str, ) -> String { let w = width as usize; let gap = if w >= 120 { " " } else { " " }; let help = "? help"; - let me = format!("TOR me:{}", truncate_fp(me_fp)); + let me = format!("{} me:{}", tor_token(phase), truncate_fp(me_fp)); let mut note = status_note.unwrap_or("").trim().to_string(); if !note.is_empty() && color_mode() == ColorMode::None @@ -2730,22 +3053,11 @@ pub fn status_footer( note = format!("! {note}"); } - let onion_full = if me_onion.is_empty() { - "unset".to_string() - } else { - me_onion.to_string() - }; - let onion_short = if me_onion.is_empty() { - "unset".to_string() - } else { - truncate_fp(me_onion) - }; - if !note.is_empty() { - let fixed = char_len(&me) + char_len(help) + 2 * gap.len(); + let fixed = cell_width(&me) + cell_width(help) + 2 * cell_width(gap); let budget = w.saturating_sub(fixed); - if char_len(¬e) > budget { - note = truncate_chars(¬e, budget.max(12)); + if cell_width(¬e) > budget { + note = fit_cells(¬e, budget.max(12)); } } @@ -2755,13 +3067,25 @@ pub fn status_footer( } parts.push(me); - let onion_full_part = format!("onion:{onion_full}"); - let onion_short_part = format!("onion:{onion_short}"); - let try_full = width >= 110; - if try_full && footer_fits(&parts, &[&onion_full_part], help, gap, w) { - parts.push(onion_full_part); - } else if footer_fits(&parts, &[&onion_short_part], help, gap, w) { - parts.push(onion_short_part); + if let Some(onion) = me_onion { + let onion_full = if onion.is_empty() { + "unset".to_string() + } else { + onion.to_string() + }; + let onion_short = if onion.is_empty() { + "unset".to_string() + } else { + truncate_fp(onion) + }; + let onion_full_part = format!("onion:{onion_full}"); + let onion_short_part = format!("onion:{onion_short}"); + let try_full = width >= 110; + if try_full && footer_fits(&parts, &[&onion_full_part], help, gap, w) { + parts.push(onion_full_part); + } else if footer_fits(&parts, &[&onion_short_part], help, gap, w) { + parts.push(onion_short_part); + } } let extra = hints.replace("? help", ""); @@ -2777,10 +3101,10 @@ pub fn status_footer( parts.push(help.to_string()); let line = parts.join(gap); - if char_len(&line) <= w { + if cell_width(&line) <= w { line } else { - truncate_chars(&line, w) + fit_cells(&line, w) } } @@ -2788,7 +3112,7 @@ fn footer_fits(parts: &[String], extra: &[&str], help: &str, gap: &str, w: usize let mut all: Vec<&str> = parts.iter().map(String::as_str).collect(); all.extend(extra.iter().copied()); all.push(help); - char_len(&all.join(gap)) <= w + cell_width(&all.join(gap)) <= w } /// Main-screen key hints. `F6` (wallet) and `F9` (wallets & settings) are named @@ -2799,6 +3123,20 @@ pub fn main_footer_hints() -> &'static str { "Tab F2 F3 F4 F5 F6 F9 ? help Ctrl-Q" } +/// Footer hints for one focused main pane. +/// +/// The footer is the only place the keys are visible without opening `?`, so it +/// changes with the pane you are actually in — and every variant keeps `F9` +/// (the discoverable menu) and `? help`, which `tests/tui_chrome.rs` asserts are +/// reachable from the footer at 80, 120 and 200. +pub fn pane_footer_hints(pane: Pane) -> &'static str { + match pane { + Pane::Roster => "j k select F3 add F6 wallet F9 settings ? help", + Pane::Chat => "j k scroll g G ends F4 rotate F9 settings ? help", + Pane::Composer => "Enter send / commands F9 settings ? help", + } +} + fn footer_hints(screen: &Screen) -> &'static str { match screen { Screen::Main => main_footer_hints(), @@ -3006,26 +3344,35 @@ fn draw_passphrase(f: &mut Frame, kind: BackupKind, second: bool, buf: &str) { ); } +/// A centered popup over a cleared screen: title, body, wrap, scroll to the +/// tail. Every modal goes through this one, so a popup can never punch through +/// the chrome underneath it and can never be wider than the frame. +/// +/// Width always keeps a one-cell margin on each side. Height keeps the margin +/// only when the frame can afford it: a 22-line body on a 24-row terminal needs +/// the rows more than it needs symmetry, and the scroll below still lands the +/// last line on screen. pub fn draw_text_overlay(f: &mut Frame, title: &str, text: &str) { let area = f.area(); - let popup = if area.height < 28 { - area + let wanted_w = text + .lines() + .map(cell_width) + .max() + .unwrap_or(40) + .saturating_add(4); + let wanted_h = text.lines().count() as u16 + 2; + let max_w = area.width.saturating_sub(2).max(10); + let width = (wanted_w as u16).clamp(10, max_w.max(10)).min(area.width); + let height = if wanted_h >= area.height.saturating_sub(1) { + area.height } else { - let lines = text.lines().count() as u16 + 2; - let text_w = text - .lines() - .map(|l| l.chars().count() as u16) - .max() - .unwrap_or(40) - .saturating_add(4); - let width = text_w.min(area.width).max(10); - let height = lines.min(area.height).max(3); - Rect { - x: area.x + (area.width.saturating_sub(width)) / 2, - y: area.y + (area.height.saturating_sub(height)) / 2, - width, - height, - } + wanted_h.clamp(3, area.height) + }; + let popup = Rect { + x: area.x + (area.width.saturating_sub(width)) / 2, + y: area.y + (area.height.saturating_sub(height)) / 2, + width, + height, }; f.render_widget(Clear, area); f.render_widget(Clear, popup); @@ -3034,8 +3381,12 @@ pub fn draw_text_overlay(f: &mut Frame, title: &str, text: &str) { let wrapped: u16 = text .lines() .map(|l| { - let n = char_len(l) as u16; - if n == 0 { 1 } else { n.div_ceil(inner_w) } + let n = cell_width(l) as u16; + if n == 0 { + 1 + } else { + n.div_ceil(inner_w) + } }) .sum(); let scroll = wrapped.saturating_sub(inner_h); @@ -3944,28 +4295,26 @@ fn truncate_fp(fp: &str) -> String { format!("{s}{}", ellipsis()) } -fn roster_row_text(name: &str, fingerprint: &str, stale: bool, inner_width: u16) -> String { +fn roster_row_text(row: &FriendRow, inner_width: u16) -> String { let budget = (inner_width as usize).saturating_sub(2); - let fp = truncate_fp(fingerprint); - let fp_part = format!(" {fp}"); - let mut stale_s = if stale { " stale" } else { "" }.to_string(); - let suffix_len = char_len(&fp_part) + char_len(&stale_s); - let mut name_budget = budget.saturating_sub(suffix_len); - if name_budget < 1 && stale { - stale_s = " s".into(); - name_budget = budget.saturating_sub(char_len(&fp_part) + char_len(&stale_s)); - } - let shown = if name_budget == 0 { - String::new() + let stale_s = if row.stale { " stale" } else { "" }; + let avail = budget.saturating_sub(cell_width(stale_s)); + // The name is what the reader is looking for. The fingerprint only + // disambiguates two friends with the same petname, so it gets what is left + // and is dropped entirely when the pane is too narrow to show a usable + // prefix — a row that reads `bob-the-sta… stale` beats one that reads + // `… bbbbbbbb… stale`. + let name_share = cell_width(&row.label).min((avail / 2).max(6)).min(avail); + let fp_share = avail.saturating_sub(name_share); + let (shown, fp_part) = if fp_share >= 8 { + ( + fit_cells(&row.label, name_share), + format!(" {}", fit_cells(&truncate_fp(&row.fingerprint), fp_share - 2)), + ) } else { - truncate_chars(name, name_budget) + (fit_cells(&row.label, avail), String::new()) }; - let line = format!("{shown}{fp_part}{stale_s}"); - if char_len(&line) > budget { - truncate_chars(&line, budget) - } else { - line - } + fit_cells(&format!("{shown}{fp_part}{stale_s}"), budget) } fn to_hex(bytes: &[u8]) -> String { diff --git a/tests/tui_chrome.rs b/tests/tui_chrome.rs index f3d2a47..e4d7fb7 100644 --- a/tests/tui_chrome.rs +++ b/tests/tui_chrome.rs @@ -1,9 +1,11 @@ //! Main-screen chrome helpers: ASCII wordmark, compact fallback, help text. +use onionwire::hs::TorState; use onionwire::qr; use onionwire::tui::{ - Pane, banner_for_width, compact_banner, draw_share, help_overlay_text, main_footer_hints, - onion_glyph, status_footer, wordmark_banner, + Pane, TorPhase, banner_for_width, compact_banner, draw_share, help_overlay_text, + main_footer_hints, onion_glyph, pane_footer_hints, status_footer, status_footer_compact, + status_footer_phased, tor_token, wordmark_banner, }; #[test] @@ -212,6 +214,102 @@ fn restore_terminal_is_callable_without_panic() { onionwire::tui::restore_terminal(); } +#[test] +fn tor_phase_projects_every_tor_state() { + assert_eq!(TorPhase::of(TorState::Bootstrapping), TorPhase::Connecting); + assert_eq!(TorPhase::of(TorState::Published), TorPhase::Ready); + assert_eq!( + TorPhase::of(TorState::DegradedReachable), + TorPhase::Degraded + ); + assert_eq!(TorPhase::of(TorState::Stopped), TorPhase::Off); + // The phase-free token is still the bare word the chrome tests lock. + assert_eq!(tor_token(None), "TOR"); +} + +#[test] +fn footer_states_the_tor_phase_with_a_word_not_only_colour() { + let fp = "abcdef0123456789deadbeef"; + let onion = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; + for (phase, word) in [ + (TorPhase::Connecting, "connecting"), + (TorPhase::Ready, "ready"), + (TorPhase::Degraded, "degraded"), + (TorPhase::Off, "off"), + ] { + assert!(!phase.glyph().is_empty(), "{phase:?} has no glyph"); + for w in [80u16, 120, 200] { + let line = status_footer_phased(w, fp, onion, Some(phase), None, main_footer_hints()); + assert!( + line.contains(word), + "{w} footer lacks phase word {word:?}: {line:?}" + ); + assert!(line.contains("TOR"), "{w} footer lacks TOR: {line:?}"); + assert!(line.contains("me:"), "{w} footer lacks me:: {line:?}"); + assert!( + line.chars().count() <= w as usize, + "{w} footer wider than frame: {line:?}" + ); + } + } + // A fail-closed note still wins over the hints, phase or not. + let crowded = status_footer_phased( + 80, + fp, + onion, + Some(TorPhase::Off), + Some("send failed: peer onion down"), + main_footer_hints(), + ); + assert!(crowded.contains("send failed"), "{crowded:?}"); + assert!(crowded.contains("off"), "{crowded:?}"); + assert!(crowded.contains("? help"), "{crowded:?}"); + assert!(crowded.chars().count() <= 80, "{crowded:?}"); +} + +/// The main footer has its own variant: the header already prints the identity, +/// so the footer drops the onion and keeps `TOR` + `me:` + the hints. +#[test] +fn compact_footer_drops_the_onion_and_keeps_the_rest() { + let fp = "abcdef0123456789deadbeef"; + let onion = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; + let full = status_footer_phased(80, fp, onion, Some(TorPhase::Ready), None, main_footer_hints()); + let compact = status_footer_compact(80, fp, Some(TorPhase::Ready), None, main_footer_hints()); + assert!(full.contains("onion:"), "{full:?}"); + assert!(!compact.contains("onion:"), "{compact:?}"); + assert!(compact.contains("TOR"), "{compact:?}"); + assert!(compact.contains("me:"), "{compact:?}"); + assert!(compact.contains("? help"), "{compact:?}"); + assert!(compact.chars().count() <= 80, "{compact:?}"); + // The cells the onion gave up go to the hints. + assert!( + compact.chars().count() > 0 && compact.contains("F9"), + "compact footer lost the menu key: {compact:?}" + ); +} + +#[test] +fn pane_footer_hints_keep_the_menu_and_help_on_every_pane() { + let fp = "abcdef0123456789deadbeef"; + for pane in [Pane::Roster, Pane::Chat, Pane::Composer] { + let hints = pane_footer_hints(pane); + assert!(hints.contains("F9"), "{pane:?} lost the menu key: {hints:?}"); + assert!(hints.contains("? help"), "{pane:?} lost ? help: {hints:?}"); + for w in [80u16, 120, 200] { + let line = status_footer_compact(w, fp, Some(TorPhase::Ready), None, hints); + assert!(line.contains("F9"), "{pane:?} at {w} lost F9: {line:?}"); + assert!( + line.contains("? help"), + "{pane:?} at {w} lost ? help: {line:?}" + ); + assert!(line.chars().count() <= w as usize, "{pane:?} at {w}: {line:?}"); + } + } + // The hints actually change with the pane — that is the point of the lever. + assert_ne!(pane_footer_hints(Pane::Roster), pane_footer_hints(Pane::Composer)); + assert_ne!(pane_footer_hints(Pane::Chat), pane_footer_hints(Pane::Composer)); +} + #[test] fn share_screen_shows_invite_not_qr_at_80x24() { use ratatui::Terminal; diff --git a/tests/tui_frames.rs b/tests/tui_frames.rs index a262283..7e4ded6 100644 --- a/tests/tui_frames.rs +++ b/tests/tui_frames.rs @@ -1,55 +1,44 @@ //! Visual audit dumps of the current OnionWire TUI. //! -//! This crate cannot construct `App` (private, needs `Node` / Arti). Public -//! draw path used where it exists (`draw_share`, chrome helpers, overlay copy). -//! Main / profile / confirm screens labeled RECONSTRUCTED copy the layout -//! constants and copy from `src/tui.rs` so a reviewer can see the shape. +//! The main screen is the **real** render path: `draw_main_chrome` takes a +//! `MainView` of plain data, so this test draws exactly what `App::draw_main` +//! draws (no stand-in layout constants, no stub widget). Screens that are still +//! private (`draw_paste`, `draw_rotate`, …) are labelled RECONSTRUCTED and copy +//! the layout constants and copy from `src/tui.rs`. //! //! Print frames: //! cargo test --locked --test tui_frames -- --nocapture dump_audit_frames //! -//! `chars().count()` width checks here match `tests/tui_chrome.rs` on purpose. -//! They are the known-wrong metric (see `chars_count_is_not_terminal_cells`). +//! Widths are asserted in terminal **cells** via `onionwire::tui::cell_width` +//! (`Span::width`), never `chars().count()`. +use onionwire::outbox::{OutboxEntry, OutboxStatus}; use onionwire::qr; use onionwire::tui::{ - backup_screen_text, banner_for_width, compact_banner, draw_share, fingerprint_mismatch_banner, - help_overlay_text, main_footer_hints, onion_glyph, quit_screen_text, restore_screen_text, - rotate_screen_text, status_footer, who_overlay_text, wipe_screen_text, wordmark_banner, - ProfileEditor, WipeKind, + ChatRowStyle, FriendRow, MainView, Pane, TorPhase, backup_screen_text, banner_for_width, + cell_width, chat_no_friends_lines, chat_with_delivery, compact_banner, draw_main_chrome, + draw_share, draw_text_overlay, fingerprint_mismatch_banner, help_overlay_text, + main_footer_hints, onion_glyph, quit_screen_text, restore_screen_text, rotate_screen_text, + status_footer, who_overlay_text, wipe_screen_text, wordmark_banner, ProfileEditor, WipeKind, }; -use onionwire::FriendProfile; -use ratatui::backend::TestBackend; -use ratatui::layout::{Constraint, Layout, Rect}; -use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap}; +use onionwire::{FriendProfile, Message}; use ratatui::Frame; use ratatui::Terminal; +use ratatui::backend::TestBackend; +use ratatui::buffer::Buffer; +use ratatui::layout::{Constraint, Layout}; +use ratatui::widgets::{Block, Borders, Paragraph, Wrap}; const SIZES: [(u16, u16); 3] = [(80, 24), (120, 40), (200, 60)]; const FP: &str = "abcdef0123456789deadbeefcafebabe"; const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; -const LONG_MSG: &str = "them: this is a very long chat line that should wrap inside the chat pane instead of running off the right edge of an 80-column terminal and colliding with the roster border"; - -struct FriendRow { - name: &'static str, - fp: &'static str, - last_ok: bool, -} +const LONG_BODY: &str = "this is a very long chat line that should wrap inside the chat pane instead of running off the right edge of an 80-column terminal and colliding with the roster border"; fn fp8(s: &str) -> String { s.chars().take(8).collect() } -struct MainStandin<'a> { - friends: &'a [FriendRow], - selected: usize, - chat_lines: &'a [&'a str], - composer: &'a str, - alert: Option<&'a str>, - status_note: Option<&'a str>, -} - -fn dump_buffer(label: &str, w: u16, h: u16, buf: &ratatui::buffer::Buffer) { +fn dump_buffer(label: &str, w: u16, h: u16, buf: &Buffer) { println!(); println!("===== {label} {w}x{h} ====="); for y in 0..h { @@ -57,10 +46,10 @@ fn dump_buffer(label: &str, w: u16, h: u16, buf: &ratatui::buffer::Buffer) { for x in 0..w { row.push_str(buf[(x, y)].symbol()); } - let cells = row.chars().count(); + let cells = cell_width(&row); assert!( cells <= w as usize, - "{label} row {y} chars().count()={cells} > {w}: {row:?}" + "{label} row {y} width {cells} cells > {w}: {row:?}" ); println!("{row}"); } @@ -73,158 +62,100 @@ fn draw_to(w: u16, h: u16, label: &str, render: impl FnOnce(&mut Frame)) { dump_buffer(label, w, h, terminal.backend().buffer()); } -fn pane_block(title: &str) -> Block<'_> { - // Real `App::pane_block` only changes border/title color. TestBackend - // dumps are glyphs, so focused chat/composer look identical to unfocused. - Block::default().borders(Borders::ALL).title(title) +fn draw_frame(w: u16, h: u16, render: impl FnOnce(&mut Frame)) -> Buffer { + let backend = TestBackend::new(w, h); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal.draw(render).expect("draw"); + terminal.backend().buffer().clone() } -/// Layout constants copied from `App::draw_main` (`src/tui.rs`). -impl MainStandin<'_> { - fn draw(self, f: &mut Frame) { - let friends = self.friends; - let selected = self.selected; - let chat_lines = self.chat_lines; - let composer = self.composer; - let alert = self.alert; - let status_note = self.status_note; - let area = f.area(); - let banner = banner_for_width(area.width); - let banner_h = banner.lines().count() as u16; - let alert_h = u16::from(alert.is_some()); - let cols = Layout::vertical([ - Constraint::Length(banner_h), - Constraint::Length(alert_h), - Constraint::Min(3), - Constraint::Length(3), - Constraint::Length(1), - ]) - .split(area); - - f.render_widget(Paragraph::new(banner), cols[0]); - if let Some(msg) = alert { - f.render_widget(Paragraph::new(msg), cols[1]); +fn screen_of(buf: &Buffer, w: u16, h: u16) -> String { + let mut screen = String::new(); + for y in 0..h { + for x in 0..w { + screen.push_str(buf[(x, y)].symbol()); } + screen.push('\n'); + } + screen +} - let panes = - Layout::horizontal([Constraint::Percentage(36), Constraint::Min(10)]).split(cols[2]); +// --------------------------------------------------------------------------- +// Real main-screen states +// --------------------------------------------------------------------------- - let stale_n = friends.iter().filter(|fr| !fr.last_ok).count(); - let roster_title = if stale_n > 0 { - format!("roster {} {stale_n} stale", friends.len()) - } else { - format!("roster {}", friends.len()) - }; - let items: Vec = friends - .iter() - .map(|friend| { - let mut line = format!("{} {}…", friend.name, fp8(friend.fp)); - if !friend.last_ok { - line.push_str(" stale"); - } - ListItem::new(line) - }) - .collect(); - let roster = List::new(items) - .highlight_symbol("> ") - .block(pane_block(&roster_title)); - let mut roster_state = ListState::default(); - if !friends.is_empty() { - roster_state.select(Some(selected)); - } - f.render_stateful_widget(roster, panes[0], &mut roster_state); +fn friend_rows() -> Vec { + vec![ + FriendRow { + label: "alice".into(), + fingerprint: "aaaaaaaaaaaaaaaa".into(), + stale: false, + }, + FriendRow { + label: "bob-the-stale-peer".into(), + fingerprint: "bbbbbbbbbbbbbbbb".into(), + stale: true, + }, + ] +} - let inner_h = panes[1].height.saturating_sub(2); - let nlines = chat_lines.len(); - let overflow = nlines > inner_h as usize && inner_h > 0; - let chat_title = { - let mut t = match friends.get(selected) { - Some(fr) => format!("chat {}", fr.name), - None => "chat".to_string(), - }; - if overflow { - let end = inner_h as usize; - t.push_str(&format!(" 1-{end}/{nlines}")); - } - t - }; - f.render_widget( - Paragraph::new(chat_lines.join("\n")) - .wrap(Wrap { trim: false }) - .block(pane_block(&chat_title)), - panes[1], - ); - - let cmd = if composer.is_empty() { - "/wipe /wipe-all /profile /who /pay /tip /file".to_string() - } else { - composer.to_string() - }; - f.render_widget(Paragraph::new(cmd).block(pane_block("composer")), cols[3]); - - let footer = status_footer(area.width, FP, ONION, status_note, main_footer_hints()); - f.render_widget(Paragraph::new(footer), cols[4]); +fn out_msg(id: i64, body: &str) -> Message { + Message { + id, + dir: "out".into(), + plaintext: body.as_bytes().to_vec(), } } -/// Rect math copied from private `draw_text_overlay` (`src/tui.rs`). -fn draw_text_overlay_standin(f: &mut Frame, title: &str, text: &str) { - let area = f.area(); - let lines = text.lines().count() as u16 + 2; - let text_w = text - .lines() - .map(|l| l.chars().count() as u16) - .max() - .unwrap_or(40) - .saturating_add(4); - let width = text_w.min(area.width.saturating_sub(2)).max(10); - let height = lines.min(area.height.saturating_sub(2)).max(3); - let popup = Rect { - x: area.x + (area.width.saturating_sub(width)) / 2, - y: area.y + (area.height.saturating_sub(height)) / 2, - width, - height, - }; - f.render_widget(Clear, popup); - f.render_widget( - Paragraph::new(text).block(Block::default().borders(Borders::ALL).title(title)), - popup, - ); +fn in_msg(id: i64, body: &str) -> Message { + Message { + id, + dir: "in".into(), + plaintext: body.as_bytes().to_vec(), + } } -fn draw_overlay_screen(f: &mut Frame, title: &str, body: &str) { - f.render_widget( - Paragraph::new(body) - .wrap(Wrap { trim: false }) - .block(Block::default().borders(Borders::ALL).title(title)), - f.area(), - ); +fn queued_row(message_id: i64, body: &str, attempts: u32, next_in: i64, now: i64) -> OutboxEntry { + OutboxEntry { + id: 1, + friend_pk: vec![9u8; 32], + message_id, + body: body.as_bytes().to_vec(), + payload: None, + attempts, + next_attempt_at: now + next_in, + created_at: now, + status: OutboxStatus::Queued, + last_error: None, + } } -fn sample_invite() -> String { - qr::encode(&[7u8; 32], ONION, &[1u8; 32]).expect("encode") +/// Transcript rows through the real helper: markers included. +fn chat_ok() -> Vec { + let msgs = [out_msg(1, "ping"), in_msg(2, "pong"), in_msg(3, LONG_BODY)]; + chat_with_delivery(&msgs, &[], 1000).0 } -fn empty_chat_lines() -> &'static [&'static str] { - &["no friends yet", "F3 paste an invite to add one"] +/// Transcript with one row still held by the outbox, so the footer carries the +/// reachability note instead of a bare `sent`. +fn chat_queued() -> (Vec, String) { + let now = 1000; + let msgs = [out_msg(1, "ping"), in_msg(2, "pong"), out_msg(3, "are you there?")]; + let pending = [queued_row(3, "are you there?", 1, 45, now)]; + let (lines, summary) = chat_with_delivery(&msgs, &pending, now); + (lines, summary.note().unwrap_or_default()) +} + +fn empty_chat(phase: TorPhase) -> Vec { + chat_no_friends_lines(Some(phase)) } #[test] fn dump_audit_frames() { - let invite = sample_invite(); - let friends = [ - FriendRow { - name: "alice", - fp: "aaaaaaaaaaaaaaaa", - last_ok: true, - }, - FriendRow { - name: "bob-the-stale-peer", - fp: "bbbbbbbbbbbbbbbb", - last_ok: false, - }, - ]; - let chat_ok: [&str; 3] = ["you: ping", "them: pong", LONG_MSG]; + let invite = qr::encode(&[7u8; 32], ONION, &[1u8; 32]).expect("encode"); + let friends = friend_rows(); + let chat = chat_ok(); + let (queued_chat, queued_note) = chat_queued(); let editor = ProfileEditor::new("lance", "tor messenger", ""); let profile_body = { let labels = ["name", "bio", "xmr"]; @@ -248,7 +179,6 @@ fn dump_audit_frames() { updated_at: 0, }), ); - let who_empty = who_overlay_text(FP, ONION, None); println!("invite payload length (chars) = {}", invite.chars().count()); println!("wordmark:\n{}", wordmark_banner()); @@ -260,7 +190,7 @@ fn dump_audit_frames() { ); for (w, h) in SIZES { - draw_to(w, h, "chrome banner+footer", |f| { + draw_to(w, h, "chrome banner+footer (real helpers)", |f| { let banner = banner_for_width(f.area().width); let banner_h = banner.lines().count() as u16; let chunks = Layout::vertical([ @@ -274,100 +204,179 @@ fn dump_audit_frames() { f.render_widget(Paragraph::new(footer), chunks[2]); }); - draw_to(w, h, "chrome long-onion + send-failed", |f| { - let banner = banner_for_width(f.area().width); - let banner_h = banner.lines().count() as u16; - let chunks = Layout::vertical([ - Constraint::Length(banner_h), - Constraint::Min(3), - Constraint::Length(1), - ]) - .split(f.area()); - f.render_widget(Paragraph::new(banner), chunks[0]); - let footer = status_footer( - f.area().width, - FP, - ONION, - Some("send failed: connection timed out"), - main_footer_hints(), + draw_to(w, h, "main: chat + stale roster, focus chat, tor ready", |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Ready), + friends: &friends, + selected: 0, + focus: Pane::Chat, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, ); - f.render_widget(Paragraph::new(footer), chunks[2]); }); - draw_to(w, h, "RECONSTRUCTED main empty", |f| { - MainStandin { - friends: &[], - selected: 0, - chat_lines: empty_chat_lines(), - composer: "", - alert: None, - status_note: None, - } - .draw(f); + draw_to(w, h, "main: focus roster, tor connecting", |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Connecting), + friends: &friends, + selected: 1, + focus: Pane::Roster, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("bob-the-stale-peer"), + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, + ); }); - draw_to(w, h, "RECONSTRUCTED main chat+stale", |f| { - MainStandin { - friends: &friends, - selected: 0, - chat_lines: &chat_ok, - composer: "hello from composer", - alert: Some("passphrases do not match"), - status_note: Some("sent"), - } - .draw(f); + draw_to(w, h, "main: focus composer, promoted identity", |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Degraded), + friends: &friends, + selected: 0, + focus: Pane::Composer, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "hello from composer", + alert: None, + note: None, + }, + ); }); - draw_to(w, h, "RECONSTRUCTED main pay/file footer only", |f| { - MainStandin { - friends: &friends, - selected: 0, - chat_lines: &["you: /pay 0.1 coffee", "them: (no invoice pane exists)"], - composer: "", - alert: None, - status_note: Some("invoice sent"), - } - .draw(f); + draw_to(w, h, "main: EMPTY roster, tor connecting", |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Connecting), + friends: &[], + selected: 0, + focus: Pane::Roster, + chat_lines: &empty_chat(TorPhase::Connecting), + chat_style: ChatRowStyle::State, + chat_name: None, + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, + ); }); - draw_to(w, h, "RECONSTRUCTED main file-send-failed", |f| { - MainStandin { - friends: &friends, - selected: 1, - chat_lines: &["no messages"], - composer: "", - alert: None, - status_note: Some("send failed: peer onion down"), - } - .draw(f); + draw_to(w, h, "main: EMPTY roster, tor off (disconnected)", |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: "", + phase: Some(TorPhase::Off), + friends: &[], + selected: 0, + focus: Pane::Roster, + chat_lines: &empty_chat(TorPhase::Off), + chat_style: ChatRowStyle::State, + chat_name: None, + chat_scroll: 0, + composer: "", + alert: Some("fingerprint mismatch"), + note: None, + }, + ); + }); + + draw_to(w, h, "main: ERROR alert + fail-closed note", |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Degraded), + friends: &friends, + selected: 0, + focus: Pane::Composer, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: Some("send failed: peer onion down"), + note: Some("send failed: peer onion down"), + }, + ); + }); + + draw_to(w, h, "main: outbox queued (peer unreachable)", |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Ready), + friends: &friends, + selected: 0, + focus: Pane::Roster, + chat_lines: &queued_chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: None, + note: Some(&queued_note), + }, + ); }); draw_to(w, h, "draw_share (real)", |f| draw_share(f, &invite)); - draw_to(w, h, "RECONSTRUCTED help overlay on empty main", |f| { - MainStandin { - friends: &[], - selected: 0, - chat_lines: empty_chat_lines(), - composer: "", - alert: None, - status_note: None, - } - .draw(f); - draw_text_overlay_standin(f, "? help", help_overlay_text()); + draw_to(w, h, "main + ? help overlay (real draw_text_overlay)", |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Ready), + friends: &friends, + selected: 0, + focus: Pane::Chat, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, + ); + draw_text_overlay(f, "? help", help_overlay_text()); }); - draw_to(w, h, "RECONSTRUCTED /who overlay", |f| { - MainStandin { - friends: &friends, - selected: 0, - chat_lines: &chat_ok, - composer: "", - alert: None, - status_note: None, - } - .draw(f); - draw_text_overlay_standin(f, "/who", &who); + draw_to(w, h, "main + /who overlay (real draw_text_overlay)", |f| { + draw_text_overlay(f, "/who", &who); }); draw_to(w, h, "RECONSTRUCTED profile", |f| { @@ -407,13 +416,6 @@ fn dump_audit_frames() { &format!("{}\n\nWI", wipe_screen_text(WipeKind::Messages)), ); }); - draw_to(w, h, "RECONSTRUCTED wipe-all", |f| { - draw_overlay_screen( - f, - "(o) wipe all", - &format!("{}\n\n", wipe_screen_text(WipeKind::All)), - ); - }); draw_to(w, h, "RECONSTRUCTED quit", |f| { draw_overlay_screen(f, "(o) quit", &format!("{}\n\nQUI", quit_screen_text())); }); @@ -427,19 +429,243 @@ fn dump_audit_frames() { draw_to(w, h, "RECONSTRUCTED restore", |f| { draw_overlay_screen(f, "(o) restore", &format!("{}\n\n", restore_screen_text())); }); - draw_to(w, h, "RECONSTRUCTED passphrase", |f| { - draw_overlay_screen( - f, - "(o) passphrase", - "Enter passphrase\n\n****\n\nEnter submit Esc cancel", - ); - }); - draw_to(w, h, "who copy (no profile)", |f| { - draw_overlay_screen(f, "/who", &who_empty); - }); } } +fn draw_overlay_screen(f: &mut Frame, title: &str, body: &str) { + f.render_widget( + Paragraph::new(body) + .wrap(Wrap { trim: false }) + .block(Block::default().borders(Borders::ALL).title(title)), + f.area(), + ); +} + +/// Every real main-screen state must fit every supported size in cells. +#[test] +fn main_chrome_fits_80x24_120x40_and_200x60() { + let friends = friend_rows(); + let chat = chat_ok(); + let (queued_chat, queued_note) = chat_queued(); + let empty_connecting = empty_chat(TorPhase::Connecting); + let states: Vec<(&str, MainView<'_>, Option<&str>)> = vec![ ( + "chat+stale", + MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Ready), + friends: &friends, + selected: 0, + focus: Pane::Chat, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, + None, + ), + ( + "empty+connecting", + MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Connecting), + friends: &[], + selected: 0, + focus: Pane::Roster, + chat_lines: &empty_connecting, + chat_style: ChatRowStyle::State, + chat_name: None, + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, + None, + ), + ( + "error+alert", + MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Degraded), + friends: &friends, + selected: 0, + focus: Pane::Composer, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: Some("send failed: peer onion down"), + note: Some("send failed: peer onion down"), + }, + None, + ), + ( + "queued outbox", + MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Ready), + friends: &friends, + selected: 0, + focus: Pane::Roster, + chat_lines: &queued_chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: None, + note: Some(&queued_note), + }, + None, + ), + ]; + for (name, view, _) in states { + for (w, h) in SIZES { + let buf = draw_frame(w, h, |f| draw_main_chrome(f, &view)); + let screen = screen_of(&buf, w, h); + for (y, row) in screen.lines().enumerate() { + assert!( + cell_width(row) <= w as usize, + "{name} at {w}x{h}: row {y} is {} cells: {row:?}", + cell_width(row) + ); + } + } + } +} + +/// The frame dump must show the phase, and the phase must not be colour-only. +#[test] +fn main_frame_states_are_legible_without_colour() { + let friends = friend_rows(); + let chat = chat_ok(); + for (phase, word) in [ + (TorPhase::Connecting, "connecting"), + (TorPhase::Ready, "ready"), + (TorPhase::Degraded, "degraded"), + (TorPhase::Off, "off"), + ] { + let buf = draw_frame(80, 24, |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(phase), + friends: &friends, + selected: 0, + focus: Pane::Chat, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, + ) + }); + let screen = screen_of(&buf, 80, 24); + let header = screen.lines().next().unwrap_or_default().to_string(); + let footer = screen.lines().last().unwrap_or_default().to_string(); + assert!(header.contains(word), "header lacks {word:?}: {header:?}"); + assert!(footer.contains(word), "footer lacks {word:?}: {footer:?}"); + assert!(header.contains("onionwire"), "{header:?}"); + assert!(footer.contains("TOR"), "{footer:?}"); + } +} + +/// Focus must be visible with the colour stripped: a marker on the focused +/// pane, not just a coloured border. +#[test] +fn focus_is_a_marker_not_only_colour() { + let friends = friend_rows(); + let chat = chat_ok(); + let marker_of = |focus: Pane, w: u16| -> String { + let buf = draw_frame(w, 24, |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Ready), + friends: &friends, + selected: 0, + focus, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, + ) + }); + screen_of(&buf, w, 24) + }; + for w in [80u16, 120] { + let roster_focus = marker_of(Pane::Roster, w); + let chat_focus = marker_of(Pane::Chat, w); + assert!( + roster_focus.contains("> alice"), + "roster focus has no row marker at {w}: {roster_focus}" + ); + assert!( + chat_focus.contains("> chat"), + "chat focus has no title marker at {w}" + ); + assert!( + !roster_focus.contains("> chat"), + "chat title keeps the focus marker while roster is focused" + ); + assert_eq!( + roster_focus.lines().count(), + 24, + "frame height changed with focus" + ); + } +} + +/// The empty roster is a state, not a blank box. +#[test] +fn empty_roster_and_empty_chat_are_designed_states() { + let buf = draw_frame(80, 24, |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Connecting), + friends: &[], + selected: 0, + focus: Pane::Roster, + chat_lines: &empty_chat(TorPhase::Connecting), + chat_style: ChatRowStyle::State, + chat_name: None, + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, + ) + }); + let screen = screen_of(&buf, 80, 24); + assert!(screen.contains("no friends"), "{screen}"); + assert!(screen.contains("F3 adds one"), "{screen}"); + assert!(screen.contains("F3 paste an invite"), "{screen}"); + assert!( + screen.contains("tor connecting"), + "connecting state is not on screen:\n{screen}" + ); +} + #[test] fn public_copy_fits_80_by_chars_count() { for (name, text) in [ @@ -518,7 +744,7 @@ fn status_footer_drops_send_failed_when_crowded() { #[test] fn share_invite_wraps_at_three_sizes() { - let invite = sample_invite(); + let invite = qr::encode(&[7u8; 32], ONION, &[1u8; 32]).expect("encode"); for (w, h) in SIZES { let backend = TestBackend::new(w, h); let mut terminal = Terminal::new(backend).expect("terminal"); @@ -536,6 +762,34 @@ fn share_invite_wraps_at_three_sizes() { } } +/// The help overlay is cleared underneath and never wider than the frame. +#[test] +fn help_overlay_keeps_a_margin_and_shows_the_tail() { + for (w, h) in SIZES { + let buf = draw_frame(w, h, |f| { + f.render_widget(Paragraph::new("underlying frame junk"), f.area()); + draw_text_overlay(f, "? help", help_overlay_text()); + }); + let screen = screen_of(&buf, w, h); + assert!( + !screen.contains("underlying frame junk"), + "{w}x{h} overlay punched through:\n{screen}" + ); + assert!( + screen.contains("Esc closes this overlay"), + "{w}x{h} help tail clipped" + ); + // A one-cell margin on each side: no border glyph in column 0. + for line in screen.lines() { + let first = line.chars().next().unwrap_or(' '); + assert!( + first != '┌' && first != '│', + "{w}x{h} overlay is full-bleed: {line:?}" + ); + } + } +} + /// Documented defect in `tests/tui_chrome.rs`: `chars().count()` is not cells. /// Do not add `unicode-width` on this card. #[test] @@ -553,3 +807,34 @@ fn chars_count_is_not_terminal_cells() { let ellipsis = "…"; assert_eq!(ellipsis.chars().count(), 1); } + +/// Sanity: the real main renderer is the one under test here. +#[test] +fn main_chrome_draws_the_same_frame_as_the_app_layout() { + let friends = friend_rows(); + let chat = chat_ok(); + let buf = draw_frame(80, 24, |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Ready), + friends: &friends, + selected: 0, + focus: Pane::Chat, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: None, + note: None, + }, + ) + }); + let screen = screen_of(&buf, 80, 24); + assert!(screen.contains("roster 2 1 stale"), "{screen}"); + assert!(screen.contains("> chat alice"), "{screen}"); + assert!(screen.contains("message"), "composer placeholder: {screen}"); +} diff --git a/tests/tui_spec.rs b/tests/tui_spec.rs index d6ab135..0d810f8 100644 --- a/tests/tui_spec.rs +++ b/tests/tui_spec.rs @@ -259,6 +259,13 @@ fn alert_line_truncates_to_frame_width() { !line.contains("roster on the next row"), "alert still has overflow tail: {line:?}" ); + // Cells, not chars: a double-width peer error must not overflow the row. + let cjk = alert_line("接続がタイムアウトしました 接続がタイムアウトしました", 32); + assert!( + onionwire::tui::cell_width(&cjk) <= 32, + "alert wider than 32 cells: {} {cjk:?}", + onionwire::tui::cell_width(&cjk) + ); } #[test] @@ -1148,14 +1155,19 @@ fn wallets_settings_menu_truncates_wide_values_in_cells() { "no ellipsis: {cut:?}" ); // ASCII chrome swaps the ellipsis and the section rule, never the width - // contract. + // contract. Either ellipsis form is accepted, like the two assertions above: + // `ONIONWIRE_ASCII` is process-wide, so this test cannot assume which form + // is active while other tests run in parallel. let ascii = fit_cells("abcdefghij", 8); assert!(cell_width(&ascii) <= 8, "{ascii:?}"); - // Either chrome: ASCII cuts at 5 cells and closes with `...`, unicode cuts at - // 6 and closes with `…`, and both are 8 cells. Asserting `"abcdef"` here made - // this test depend on another test's in-flight `ONIONWIRE_ASCII` mutation - // (the suite mutates env vars without a global lock), so it flaked. - assert!(ascii.starts_with("abcde"), "{ascii:?}"); + assert!( + ascii.starts_with("abcde") && ascii != "abcdefghij", + "truncation kept the whole string or dropped too much: {ascii:?}" + ); + assert!( + ascii.ends_with('…') || ascii.ends_with("..."), + "no ellipsis: {ascii:?}" + ); assert_eq!(cell_width("名"), 2); assert_eq!(cell_width("abc"), 3); }