From 2fa34660195ced87dd82115bf9b0583da9ef004e Mon Sep 17 00:00:00 2001 From: Lance Walters Date: Fri, 18 Sep 2026 23:53:10 -0400 Subject: [PATCH] tui: peer payment history behind the F9 `payments` row (key p) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The F9 / `/settings` menu's only payment row showed the wallet's own transfer list (`Node::wallet_recent_transfers`, F6). The signed `/pay` invoices and `/tip` receipts a peer sent live in the `payments` table and had no path from the TUI, so they were invisible. `Node::list_payments` (PR #119) closes that gap; this wires it into a screen. - `Screen::PeerPayments { state }` + `PeerPaymentsState` / `PeerPaymentRow`, built by `PeerPaymentsState::from_payments` from `Node::list_payments`' rows (newest first: the store returns `payments.id` ascending, the screen windows the vector). - Key handler: `p` on the F9 screen opens it (`open_peer_payments`); `up`/`down` (or `k`/`j`) move the selection, `Esc` goes back, `F9` reopens the menu. - Rows carry direction, kind, amount (`pay::atomic_to_xmr_str`, the same piconero formatter the chat lines use), memo (sanitized at draw time) and the receipt's `verified` / `unverified` word; the focused row is marked with `>` and bold. The selected row's txid and address sit under the rows — the address wrapped over two lines rather than clipped. - States: populated, `no payments with {peer}`, `could not read payments`, and a menu row that refuses when no friend is selected. An empty history is a state, never an error. - Menu: the wallet's own list is retitled `transfers` (F6, unchanged), and the new `payments` row (key `p`) names the peer and the count. Two histories, two rows, no ambiguity. - Widths are measured in cells (`Span::width`); trailing columns are dropped before they can wrap, so the body fits 80x24 (20 inner rows of 21) as well as 120x40 and 200x60. Tests: new `tests/tui_payments.rs` (11 tests) dumps and asserts the screen at 80x24, 120x40 and 200x60 including the empty history, asserts a memo carrying ESC/BEL/C1/bidi/newline bytes never reaches the frame buffer, and asserts the window/column invariants for every width from 20 to 200. Also relaxes one width assertion in `tests/tui_spec.rs`: `fit_cells` was asserted to start with `"abcdef"`, which only holds when another test's in-flight `ONIONWIRE_ASCII` mutation is not visible — the suite mutates env vars without a global lock, so that test flaked (it also fails on an unmodified tree, 1 run in 2). It now accepts either chrome's cut point, which is what the comment already claimed. Docs: `docs/TUI.md` gains the screen's section, the retitled/replaced rows and the updated row count; the "peer payment history" gap entry is closed. --- docs/TUI.md | 84 ++++++- src/tui.rs | 550 +++++++++++++++++++++++++++++++++++++++++- tests/tui_payments.rs | 420 ++++++++++++++++++++++++++++++++ tests/tui_spec.rs | 67 +++-- 4 files changed, 1095 insertions(+), 26 deletions(-) create mode 100644 tests/tui_payments.rs diff --git a/docs/TUI.md b/docs/TUI.md index e83efa3..943512d 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -653,7 +653,8 @@ fires it, including the F6 wallet screen's own keys (`F6 c`, `F6 i`, `F6 r`, | WALLET | sync | chain readiness word (`chain at tip · wallet answering`, `wallet answering · chain not at tip`, `wallet RPC not answering yet`, `child exited`, `not probing · no chain source`) | `F6 p` | | WALLET | receive | the receive address (truncated) or `no address yet · wallet unreachable` | `c copy` / `F6 r` | | WALLET | balance | `{xmr}` / `off` / `err` | `F6` | -| WALLET | payments | `{n} recent` / `no transfers yet` | `F6` | +| WALLET | transfers | `{n} recent` / `no transfers yet` — the wallet's **own** transfer list | `F6` | +| WALLET | payments | `{n} with {peer}` / `no history with {peer}` / `no friend selected` / `history unreadable · {peer}` — the **peer's** payment rows | `p` | | WALLET | create | `/wallet create · seed shown once` | `F6 c` | | WALLET | import | `/wallet import · 25-word seed` | `F6 i` | | SETTINGS | nickname | the self-profile name, or `(none)` | `/profile` | @@ -665,7 +666,13 @@ fires it, including the F6 wallet screen's own keys (`F6 c`, `F6 i`, `F6 r`, | SETTINGS | wipe | `messages · identity and friends stay` | `/wipe` | | SETTINGS | wipe-all | `deletes your identity key · new person` | `/wipe-all` | -19 rows at 80x24 against 21 available inner rows: nothing clips or scrolls. +20 rows at 80x24 against 21 available inner rows: nothing clips or scrolls. + +`transfers` and `payments` are deliberately two rows: `transfers` is the +wallet's own list (`Node::wallet_recent_transfers`, F6), `payments` is the +peer-scoped history (`Node::list_payments`, `p`). Signed `/pay` invoices and +`/tip` receipts a peer sent never appear in the wallet's own transfers, so the +two histories are not interchangeable and the menu names both. ### Guarantees @@ -699,8 +706,77 @@ sibling-card work, not presentation: `Node::wallet_test_connection(..)` — the endpoint config screen is F7 on `feat/wallet-create-import`; the menu shows the endpoint's *state* and leaves the key free. -- Peer payment history — `store.list_payments(..)` has no `Node` accessor, so - the menu can only offer the wallet's own transfer list (F6). +- Peer payment history — **closed by this screen.** `Node::list_payments` exists + on `main`; the `payments` row (key `p`) opens the peer-scoped history, and the + row is distinct from the wallet's own transfer list (`transfers`, F6). - `Node::set_wallet_child_config(cfg)` — the child can be started/stopped and probed, not edited. - `Node::set_petname(..)` — no petname editor exists. + +## Peer payment history (F9 → `payments`, key `p`) + +A screen, not a popup, and peer-scoped: it renders what +`Node::list_payments(&friend_pk)` returns for the chat's selected friend, so the +signed `/pay` invoices and `/tip` receipts a peer sent are visible even though +they never appear in the wallet's own transfer list (F6). The call takes the +store lock only — no Tor dial, no wallet RPC — so it is safe while offline or +while Arti is still bootstrapping, and an empty result (`Ok(vec![])`) is the +**no history** state, never an error. + +``` +cargo test --locked --test tui_payments -- --nocapture peer_payments_frame_dumps +``` + +dumps the screen at 80x24, 120x40 and 200x60, populated and empty. + +### Layout + +``` + dir kind amount XMR receipt memo +> in receipt 0.025 verified lunch money + out tip 0.005 coffee + out invoice 0.1 rent + + tx 3f2a91c0d9e4b7a2c1f0e8d7b6a5948372615041324758697a8b9c0d1e2f3041 + addr 4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYJKUGVktfzxayGbMW + aC8iqPUE9XUBFGrLyDz4DpEBM +``` + +- Rows are **newest first**: `payments.id` ascending is oldest first, so + `PeerPaymentsState::from_payments` reverses it and the render path windows the + result. Rows outside the window are counted in an explicit `… N older` / + `… N newer` line — nothing is dropped silently. +- The focused row is marked with `>` **and** bold, so focus survives a + monochrome terminal. `up`/`down` (or `k`/`j`) move it, `Esc` returns to the + main screen, `F9` reopens the menu. +- The selected row's `tx` and `addr` are spelled out under the rows: a 64-hex + txid is unusable truncated, and a 95-character base58 address is **wrapped** + over two lines rather than clipped to a prefix. +- Amounts use `pay::atomic_to_xmr_str`, the same piconero formatter the chat + lines use; the XMR unit is stated once, in the column header. +- Columns are dropped from the right when the pane is narrower than they need, + so no row can wrap or overrun at any width — not just at 80. + +### States + +| State | Frame | +|---|---| +| populated | the rows, plus the selected row's `tx` / `addr` | +| empty | `no payments with {peer}` and `invoices, receipts and tips from this peer land here` | +| read failed | `could not read payments` plus the sanitized reason — never a blank pane | +| no friend selected | the menu row refuses before the screen opens (`no friend selected` in the status line) | + +### Guarantees + +- **Memo is peer-signed text, sanitized at draw time.** `Node::list_payments` + returns `memo` as stored; the row goes through the same + `menu_cell_text`-then-`fit_cells` path the F9 menu uses, so C0/C1 controls, + ESC, bidi marks and newlines cannot reach the frame buffer or split a row. + `tests/tui_payments.rs` asserts a hostile memo (ESC, BEL, C1, bidi, newline) + never appears in a rendered frame. +- **Only receipts carry `verified`.** The flag column prints `verified` / + `unverified` for receipts and stays blank for invoices and tips, which have no + signature to check; `unverified` also takes the warn tone, so colour is never + the only signal. +- **Read-only.** The screen reads one getter and draws; it cannot send, sign or + dial. diff --git a/src/tui.rs b/src/tui.rs index 10761d8..38f868a 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -16,7 +16,7 @@ use crate::node::Node; use crate::outbox::DEFAULT_MAX_ATTEMPTS; use crate::qr::{self, QrPayload}; use crate::sanitize; -use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus}; +use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus, Payment}; use crate::wallet::{self, ChainSource}; const C_ACCENT: Color = Color::Rgb(232, 165, 75); @@ -1238,6 +1238,12 @@ enum Screen { WalletsSettings { state: WalletMenuState, }, + /// F9 → `payments`: the peer-scoped history from `Node::list_payments`. + /// Holds the same kind of snapshot as the menu (a resize re-fits it), so a + /// repaint never re-reads the store mid-frame. + PeerPayments { + state: PeerPaymentsState, + }, Quit { prompt: QuitPrompt, }, @@ -1334,11 +1340,17 @@ impl App { let mut file_cmd = None; let mut chat_send = None; let mut pass_submit = None; + let mut open_payments = false; + let mut payments_back = false; + let mut payments_move = 0i32; // The function-key shortcuts stay live on the WALLETS & SETTINGS screen // too: that screen's whole point is naming the key that fires each row, // so a key it names has to work while it is open. - if matches!(self.screen, Screen::Main | Screen::WalletsSettings { .. }) { + if matches!( + self.screen, + Screen::Main | Screen::WalletsSettings { .. } | Screen::PeerPayments { .. } + ) { match key.code { KeyCode::F(2) => { self.open_share()?; @@ -1603,6 +1615,14 @@ impl App { Screen::WalletsSettings { .. } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Char('c') => copy_addr = true, + // `p` is the key the menu's `payments` row prints. + KeyCode::Char('p') => open_payments = true, + _ => {} + }, + Screen::PeerPayments { .. } => match key.code { + KeyCode::Esc => payments_back = true, + KeyCode::Up | KeyCode::Char('k') => payments_move = -1, + KeyCode::Down | KeyCode::Char('j') => payments_move = 1, _ => {} }, Screen::Quit { prompt } => match key.code { @@ -1624,6 +1644,21 @@ impl App { if let Some(kind) = wipe_confirm { return self.confirm_wipe(kind); } + if payments_move != 0 + && let Screen::PeerPayments { state } = &mut self.screen + { + if payments_move < 0 { + state.select_prev(); + } else { + state.select_next(); + } + } + if payments_back { + self.screen = Screen::Main; + } + if open_payments { + self.open_peer_payments()?; + } if copy_addr { self.copy_receive_address(); } @@ -1870,6 +1905,19 @@ impl App { .and_then(|p| (!p.display_name.is_empty()).then(|| p.display_name.clone())); let bio_set = profile.as_ref().is_some_and(|p| !p.bio.is_empty()); let xmr_set = profile.as_ref().is_some_and(|p| !p.xmr_addr.is_empty()); + // The friend the rest of the TUI acts on is the chat's selected friend. + // `list_payments` is a lock-only read: no dial, no RPC, so this snapshot + // stays cheap and works while Tor is still bootstrapping. + let friend = self.friends.get(self.selected); + let peer = friend + .map(|f| f.petname.clone().unwrap_or_else(|| f.fingerprint.clone())) + .unwrap_or_default(); + let peer_payments = friend.and_then(|f| { + self.node + .list_payments(&f.pubkey) + .ok() + .map(|rows| rows.len()) + }); self.screen = Screen::WalletsSettings { state: WalletMenuState { configured: wstat.configured, @@ -1885,11 +1933,37 @@ impl App { bio_set, xmr_set, me_fp: self.me_fp.clone(), + peer, + peer_payments, }, }; Ok(()) } + /// The F9 menu's `payments` row: the selected friend's payment history from + /// `Node::list_payments`. + /// + /// Read-only and fail-closed: the call takes the store lock and nothing + /// else, so it never dials and is safe while offline. A friend with no rows + /// is `Ok(vec![])` — an empty history, not an error. + fn open_peer_payments(&mut self) -> Result<(), String> { + let Some(friend) = self.friends.get(self.selected) else { + self.status_note = Some("no friend selected".into()); + return Ok(()); + }; + let peer = friend + .petname + .clone() + .unwrap_or_else(|| friend.fingerprint.clone()); + let pk = friend.pubkey.clone(); + let state = match self.node.list_payments(&pk) { + Ok(rows) => PeerPaymentsState::from_payments(peer, &rows), + Err(e) => PeerPaymentsState::error(peer, e), + }; + self.screen = Screen::PeerPayments { state }; + Ok(()) + } + /// `c` on the WALLETS & SETTINGS menu: copy the receive address through the /// terminal's own clipboard (OSC 52 — no crate, and it survives SSH). The /// address never touches a file. @@ -2390,6 +2464,16 @@ impl App { ); draw_wallets_settings(f, state, &footer) } + Screen::PeerPayments { state } => { + let footer = status_footer( + f.area().width, + &self.me_fp, + &self.me_onion, + self.status_note.as_deref(), + footer_hints(&self.screen), + ); + draw_peer_payments(f, state, &footer) + } } if self.help_open { draw_text_overlay(f, "? help", help_overlay_text()); @@ -2719,6 +2803,7 @@ match screen { Screen::WalletSetup(WalletSetup::CreateSeed { .. }) => "type SEEN Esc cancel ? help", Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help", Screen::WalletsSettings { .. } => "Esc back c copy ? help", + Screen::PeerPayments { .. } => "Esc back up/down select F9 menu ? help", Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help", } } @@ -2983,6 +3068,12 @@ pub struct WalletMenuState { pub xmr_set: bool, /// Our own fingerprint (identity = pubkey), full hex. pub me_fp: String, + /// Display name of the friend the F9 screen's friend-scoped rows act on (the + /// chat's selected friend), or empty when there is none. + pub peer: String, + /// `Some(rows)` when `Node::list_payments` answered for that friend; + /// `None` when the read itself failed (which is not "no history"). + pub peer_payments: Option, } /// Width of `s` in terminal **cells**, measured by ratatui's own text type. @@ -3063,9 +3154,9 @@ impl MenuRow { /// The two groups, in the order the card fixes: WALLET, then SETTINGS. /// -/// Payment history here is the wallet's own transfer list (F6), which is the -/// only history `Node` exposes to the TUI. The peer `payments` table has no -/// `Node` accessor (see the card's gap list). +/// Two payment-ish rows, and they are not the same thing: `transfers` is the +/// wallet's own list (F6, `wallet_recent_transfers`), `payments` is the +/// peer-scoped history (`Node::list_payments`) opened by `p`. fn menu_groups(s: &WalletMenuState) -> (Vec, Vec) { let endpoint_word = if !s.configured { "not configured · receive-only" @@ -3136,7 +3227,7 @@ fn menu_groups(s: &WalletMenuState) -> (Vec, Vec) { }, ), MenuRow::new( - "payments", + "transfers", if s.transfers == 0 { "no transfers yet".to_string() } else { @@ -3149,6 +3240,29 @@ fn menu_groups(s: &WalletMenuState) -> (Vec, Vec) { MenuTone::Normal }, ), + // The peer-scoped history: signed `/pay` invoices and `/tip` receipts + // that peer sent. Distinct from the wallet's own transfer list above, + // and labelled so — `Payments` here means `payments` rows, not the + // wallet's `transfers`. + MenuRow::new( + "payments", + if s.peer.is_empty() { + "no friend selected".to_string() + } else { + let peer = menu_cell_text(&s.peer); + match s.peer_payments { + None => format!("history unreadable {}{peer}", "\u{b7} "), + Some(0) => format!("no history with {peer}"), + Some(n) => format!("{n} with {peer}"), + } + }, + if s.peer.is_empty() { "" } else { "p" }, + if s.peer.is_empty() || s.peer_payments == Some(0) { + MenuTone::Dim + } else { + MenuTone::Normal + }, + ), MenuRow::new( "create", "/wallet create · seed shown once".to_string(), @@ -3334,6 +3448,430 @@ pub fn draw_wallets_settings(f: &mut Frame, state: &WalletMenuState, footer: &st ); } +// --------------------------------------------------------------------------- +// Peer payment history: the F9 menu's `payments` row. +// +// This is the *other* history. The F6 screen shows the wallet's own transfer +// list (`Node::wallet_recent_transfers`); this one shows the peer-scoped rows +// `Node::list_payments` returns — the signed `/pay` invoices and `/tip` +// receipts that peer sent, which never appear in the wallet's own transfers. +// +// Everything here is display data: `memo` is peer-signed text returned as +// stored, so it goes through `menu_cell_text` (control + bidi stripped, no +// newlines) and `fit_cells` (truncated in cells) before it can reach a frame. +// --------------------------------------------------------------------------- + +/// Direction column in cells: `in` / `out`. +const PAY_DIR_W: usize = 3; +/// Kind column in cells: `invoice` / `receipt` / `tip`. +const PAY_KIND_W: usize = 7; +/// Amount column in cells, right-aligned: `0.025000000000` is 14, so 15 holds +/// every XMR string `pay::atomic_to_xmr_str` can produce from a u128 piconero. +const PAY_AMOUNT_W: usize = 15; +/// Receipt flag column in cells: `unverified` is the widest word. +const PAY_FLAG_W: usize = 10; + +/// One payment row, display-ready except for `memo`/`txid`/`address`, which the +/// render path sanitizes. +#[derive(Clone, Debug, Default)] +pub struct PeerPaymentRow { + /// `"in"` or `"out"` — the peer's direction, not ours. + pub dir: String, + /// `"invoice"`, `"receipt"` or `"tip"`. + pub kind: String, + /// `pay::atomic_to_xmr_str(amount_atomic)` — the same formatter the chat + /// lines use, not a second piconero formatter. + pub amount_xmr: String, + /// Peer-signed memo, as stored. Sanitized at draw time. + pub memo: String, + /// Chain txid, when the payment has one. + pub txid: Option, + /// Destination address. + pub address: String, + /// Receipt signature check. Only receipts carry a meaningful flag. + pub verified: bool, +} + +/// What the peer payment screen draws. Rows are **newest first** — the store +/// returns `payments.id` ascending, so `from_payments` reverses them here and +/// the render path windows the result. `error` is display-ready and only set +/// when the store read itself failed; an empty history is not an error. +#[derive(Clone, Debug, Default)] +pub struct PeerPaymentsState { + /// Display name of the peer this history belongs to. + pub peer: String, + pub rows: Vec, + pub error: Option, + /// Index into `rows` (display order, 0 = newest). + pub selected: usize, +} + +impl PeerPaymentsState { + /// Build the screen state from `Node::list_payments`' rows. + pub fn from_payments(peer: String, rows: &[Payment]) -> Self { + let mut out: Vec = rows + .iter() + .map(|p| PeerPaymentRow { + dir: p.dir.clone(), + kind: p.kind.clone(), + amount_xmr: crate::pay::atomic_to_xmr_str(&p.amount_atomic), + memo: p.memo.clone(), + txid: p.txid.clone(), + address: p.address.clone(), + verified: p.verified, + }) + .collect(); + // `payments.id` ascending is oldest first; a history reads newest first. + out.reverse(); + Self { + peer, + rows: out, + error: None, + selected: 0, + } + } + + /// The read failed. The screen says so instead of pretending "no history". + pub fn error(peer: String, why: String) -> Self { + Self { + peer, + rows: Vec::new(), + error: Some(why), + selected: 0, + } + } + + pub fn select_next(&mut self) { + if !self.rows.is_empty() { + self.selected = (self.selected + 1).min(self.rows.len() - 1); + } + } + + pub fn select_prev(&mut self) { + self.selected = self.selected.saturating_sub(1); + } +} + +/// Pad `s` out to `cells` terminal cells on the right. +fn pad_right(s: &str, cells: usize) -> String { + let mut out = s.to_string(); + let w = cell_width(&out); + if w < cells { + out.push_str(&" ".repeat(cells - w)); + } + out +} + +/// Pad `s` out to `cells` terminal cells on the left (numbers line up). +fn pad_left(s: &str, cells: usize) -> String { + let w = cell_width(s); + if w >= cells { + return s.to_string(); + } + let mut out = " ".repeat(cells - w); + out.push_str(s); + out +} + +/// Split `s` into a prefix of at most `max` cells and the (possibly empty) +/// remainder, so a long display value can be wrapped instead of clipped. +fn split_cells(s: &str, max: usize) -> (String, String) { + let mut head = String::new(); + let mut used = 0; + for (i, ch) in s.char_indices() { + let w = cell_width(&ch.to_string()); + if used + w > max { + return (head, s[i..].to_string()); + } + used += w; + head.push(ch); + } + (head, String::new()) +} + +/// Which style a laid-out span carries. +#[derive(Clone, Copy, PartialEq, Eq)] +enum PaySlot { + Head, + Amount, + Flag, + Memo, +} + +/// Lay out one payment line for `w` cells: `head`, then the amount, the receipt +/// flag and a flexible memo. Trailing columns are **dropped** when the pane is +/// too narrow, so no row can ever wrap or overrun — the 80-column floor holds +/// even if a terminal is smaller than the floor. +fn pay_columns( + w: usize, + head: &str, + amount: &str, + flag: &str, + memo: &str, +) -> Vec<(PaySlot, String)> { + let mut out: Vec<(PaySlot, String)> = Vec::new(); + let head = if cell_width(head) > w { + fit_cells(head, w) + } else { + head.to_string() + }; + let mut used = cell_width(&head); + out.push((PaySlot::Head, head)); + + if !amount.is_empty() && w >= used + 2 + PAY_AMOUNT_W { + let amount = fit_cells(amount, PAY_AMOUNT_W); + out.push((PaySlot::Head, " ".to_string())); + out.push((PaySlot::Amount, pad_left(&amount, PAY_AMOUNT_W))); + used += 2 + PAY_AMOUNT_W; + } + if !flag.is_empty() && w >= used + 2 + PAY_FLAG_W { + let flag = fit_cells(flag, PAY_FLAG_W); + out.push((PaySlot::Head, " ".to_string())); + out.push((PaySlot::Flag, pad_right(&flag, PAY_FLAG_W))); + used += 2 + PAY_FLAG_W; + } + if w > used + 2 { + let memo = fit_cells(memo, w - used - 2); + if !memo.is_empty() { + out.push((PaySlot::Head, " ".to_string())); + out.push((PaySlot::Memo, memo)); + } + } + out +} + +/// The column header, so an `in`/`out` and a `receipt`/`invoice` need no legend +/// and the XMR unit is stated once instead of on every row. +fn payment_header_line(w: usize) -> Line<'static> { + let head = format!( + "{} {}", + pad_right("dir", PAY_DIR_W), + pad_right("kind", PAY_KIND_W) + ); + let mut spans = vec![Span::raw(" ".to_string())]; + spans.extend( + pay_columns(w.saturating_sub(2), &head, "amount XMR", "receipt", "memo") + .into_iter() + .map(|(_, text)| Span::styled(text, style_dim())), + ); + Line::from(spans) +} + +/// One payment row. The focused row is marked with `>` **and** bold, so focus +/// survives a monochrome terminal; an unverified receipt says `unverified` as +/// well as taking the warn tone, so the state is never colour-only. +fn payment_row_line(w: usize, row: &PeerPaymentRow, selected: bool) -> Line<'static> { + let dir = fit_cells(&menu_cell_text(&row.dir), PAY_DIR_W); + let kind = fit_cells(&menu_cell_text(&row.kind), PAY_KIND_W); + let head = format!( + "{} {}", + pad_right(&dir, PAY_DIR_W), + pad_right(&kind, PAY_KIND_W) + ); + let amount = menu_cell_text(&row.amount_xmr); + let (flag, flag_tone) = if row.kind == "receipt" { + if row.verified { + ("verified".to_string(), style_text()) + } else { + ("unverified".to_string(), style_stale()) + } + } else { + // A blank flag column, not an absent one: the memo column has to line + // up down the pane or the rows read as ragged. + (" ".repeat(PAY_FLAG_W), style_text()) + }; + let memo = menu_cell_text(&row.memo); + + let mark_style = if selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + style_dim() + }; + let mut spans = vec![Span::styled( + if selected { "> " } else { " " }.to_string(), + mark_style, + )]; + for (slot, text) in pay_columns(w.saturating_sub(2), &head, &amount, &flag, &memo) { + let style = match slot { + PaySlot::Head => style_dim(), + PaySlot::Amount => style_text(), + PaySlot::Flag => flag_tone, + PaySlot::Memo => { + if selected { + style_text() + } else { + style_dim() + } + } + }; + let style = if selected { + style.add_modifier(Modifier::BOLD) + } else { + style + }; + spans.push(Span::styled(text, style)); + } + Line::from(spans) +} + +/// The peer payment body as styled lines for a `width` × `height` **inner** +/// pane. `height` matters: the window is sized so the selected row and the tx / +/// address strip always fit, and the rows that fall outside it are counted in +/// an explicit `… N older` / `… N newer` line rather than silently dropped. +pub fn peer_payments_lines(width: u16, height: u16, s: &PeerPaymentsState) -> Vec> { + let w = width as usize; + let h = height as usize; + if let Some(err) = &s.error { + return vec![ + Line::from(vec![Span::styled( + " could not read payments", + style_alert(), + )]), + Line::from(vec![Span::styled( + fit_cells(&format!(" {}", menu_cell_text(err)), w.max(1)), + style_dim(), + )]), + ]; + } + let peer = menu_cell_text(&s.peer); + if s.rows.is_empty() { + return vec![ + Line::from(vec![Span::styled( + fit_cells(&format!(" no payments with {peer}"), w.max(1)), + style_dim(), + )]), + Line::from(vec![Span::styled( + fit_cells( + " invoices, receipts and tips from this peer land here", + w.max(1), + ), + style_dim(), + )]), + ]; + } + if h < 3 { + // Degenerate pane: the header alone is still an honest frame. + return vec![payment_header_line(w)]; + } + + let total = s.rows.len(); + let selected = s.selected.min(total - 1); + // The selected row's detail: the txid, and the address wrapped over at most + // two lines so a 95-character base58 address is readable at 80 columns + // instead of clipped to a prefix. + let txid = s.rows[selected] + .txid + .as_deref() + .map(menu_cell_text) + .unwrap_or_else(|| "(no txid yet)".to_string()); + let addr = menu_cell_text(&s.rows[selected].address); + let (addr_head, addr_rest) = { + let budget = w.saturating_sub(8).max(1); + if cell_width(&addr) > budget { + let (head, rest) = split_cells(&addr, budget); + (head, fit_cells(&rest, budget)) + } else { + (addr, String::new()) + } + }; + let detail = w >= 40 && h >= 8; + let detail_h = if detail { + 3 + usize::from(!addr_rest.is_empty()) + } else { + 0 + }; + let budget0 = h - (1 + detail_h); + let windowed = total > budget0 && budget0 >= 3; + let budget = if windowed { budget0 - 2 } else { budget0 }; + let visible = budget.max(1).min(total); + let start = if total <= visible { + 0 + } else { + selected.saturating_sub(visible - 1).min(total - visible) + }; + let end = (start + visible).min(total); + + let mut out: Vec> = vec![payment_header_line(w)]; + if windowed && start > 0 { + out.push(Line::from(vec![Span::styled( + fit_cells(&format!(" {} {start} newer", ellipsis()), w.max(1)), + style_dim(), + )])); + } + for (i, row) in s.rows.iter().enumerate().take(end).skip(start) { + out.push(payment_row_line(w, row, i == selected)); + } + if windowed && end < total { + out.push(Line::from(vec![Span::styled( + fit_cells(&format!(" {} {} older", ellipsis(), total - end), w.max(1)), + style_dim(), + )])); + } + if detail { + out.push(Line::default()); + out.push(Line::from(vec![Span::styled( + fit_cells(&format!(" tx {txid}"), w.max(1)), + style_dim(), + )])); + out.push(Line::from(vec![Span::styled( + fit_cells(&format!(" addr {addr_head}"), w.max(1)), + style_dim(), + )])); + if !addr_rest.is_empty() { + out.push(Line::from(vec![Span::styled( + fit_cells(&format!(" {addr_rest}"), w.max(1)), + style_dim(), + )])); + } + } + out +} + +/// The body as plain text, for width/needle assertions. +pub fn peer_payments_text(width: u16, height: u16, s: &PeerPaymentsState) -> String { + peer_payments_lines(width, height, s) + .iter() + .map(|line| { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect::() + }) + .collect::>() + .join("\n") +} + +/// Block title: the screen is peer-scoped, so the peer is named in the frame +/// itself and not only in the rows. +pub fn peer_payments_title(s: &PeerPaymentsState) -> String { + let peer = menu_cell_text(&s.peer); + if peer.is_empty() { + "(o) payments".to_string() + } else { + format!("(o) payments {}{peer}", "\u{b7} ") + } +} + +/// Peer payment history: a full screen like the F9 menu, with the same single +/// status line. `footer` is an already-built `status_footer` row. +pub fn draw_peer_payments(f: &mut Frame, state: &PeerPaymentsState, footer: &str) { + let area = f.area(); + let rows = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area); + f.render_widget( + Paragraph::new(peer_payments_lines( + rows[0].width.saturating_sub(2), + rows[0].height.saturating_sub(2), + state, + )) + .block(themed_block(&peer_payments_title(state))), + rows[0], + ); + f.render_widget( + Paragraph::new(fit_cells(footer, area.width as usize)).style(style_dim()), + rows[1], + ); +} + /// OSC 52 clipboard write for `text`: the terminal copies it, so no crate and /// no clipboard daemon are involved and it still works over SSH. A terminal /// that does not implement OSC 52 ignores the sequence. diff --git a/tests/tui_payments.rs b/tests/tui_payments.rs new file mode 100644 index 0000000..c0e43ef --- /dev/null +++ b/tests/tui_payments.rs @@ -0,0 +1,420 @@ +//! Peer payment history screen (F9 → `payments` row). +//! +//! The screen renders what `Node::list_payments` returns for the friend the rest +//! of the TUI acts on: signed `/pay` invoices, `/tip` receipts and tips, with +//! direction, kind, amount, memo, txid and the receipt's verified flag. +//! +//! Assertions measure in terminal **cells** (`cell_width`, which goes through +//! `Span::width`) and accept either ellipsis form / rule glyph, because +//! `ascii_chrome()` follows `NO_COLOR` / `ONIONWIRE_ASCII` and the two TUI test +//! binaries run in parallel. + +use onionwire::Payment; +use onionwire::tui::{ + PeerPaymentRow, PeerPaymentsState, WalletMenuState, cell_width, draw_peer_payments, + peer_payments_lines, peer_payments_text, status_footer, wallets_settings_menu_text, +}; +use ratatui::Terminal; +use ratatui::backend::TestBackend; + +const FP: &str = "abcdef0123456789deadbeefcafebabe"; +const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; +const TXID: &str = "3f2a91c0d9e4b7a2c1f0e8d7b6a5948372615041324758697a8b9c0d1e2f3041"; +const ADDR: &str = "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYJKUGVktfzxayGbMWaC8iqPUE9XUBFGrLyDz4DpEBM"; + +fn row( + dir: &str, + kind: &str, + xmr: &str, + memo: &str, + txid: Option<&str>, + verified: bool, +) -> PeerPaymentRow { + PeerPaymentRow { + dir: dir.into(), + kind: kind.into(), + amount_xmr: xmr.into(), + memo: memo.into(), + txid: txid.map(str::to_string), + address: ADDR.into(), + verified, + } +} + +/// A peer with three rows: a receipt for a signed invoice, a tip, and the +/// invoice itself. Newest first, the way the card orders the window. +fn peer_state() -> PeerPaymentsState { + PeerPaymentsState { + peer: "lance".into(), + rows: vec![ + row("in", "receipt", "0.025", "lunch money", Some(TXID), true), + row("out", "tip", "0.005", "coffee", None, false), + row("out", "invoice", "0.1", "rent", None, false), + ], + error: None, + selected: 0, + } +} + +fn render(w: u16, h: u16, st: &PeerPaymentsState) -> String { + let backend = TestBackend::new(w, h); + let mut terminal = Terminal::new(backend).expect("terminal"); + let footer = status_footer(w, FP, ONION, None, "Esc back up/down select ? help"); + terminal + .draw(|f| draw_peer_payments(f, st, &footer)) + .expect("draw"); + let buf = terminal.backend().buffer(); + 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 +} + +#[test] +fn peer_payments_lists_every_required_field() { + let body = peer_payments_text(78, 21, &peer_state()); + for needle in [ + "dir", + "kind", + "amount", + "receipt", + "memo", // column header + "in", + "out", // direction + "invoice", + "receipt", + "tip", // kind + "0.025", + "0.1", + "0.005", // amount + "lunch money", + "rent", + "coffee", // memo + "verified", // receipt flag + "tx", + TXID, // txid when present + "addr", + // destination address of the selected row (see the wrap assertions below) + ] { + assert!(body.contains(needle), "missing {needle:?}:\n{body}"); + } + // The address is wrapped over two lines at 80 columns, not clipped: the head + // starts on the `addr` row and the tail survives on the continuation line. + assert!(body.contains(&ADDR[..40]), "\n{body}"); + assert!( + body.contains(&ADDR[ADDR.len() - 20..]), + "the address tail was clipped, not wrapped:\n{body}" + ); + // Amounts carry the shared piconero formatter's units once, in the header. + assert!(body.contains("amount XMR"), "\n{body}"); +} + +#[test] +fn peer_payments_amount_is_the_shared_formatter_not_a_second_one() { + let rows = vec![Payment { + id: 1, + dir: "in".into(), + kind: "receipt".into(), + amount_atomic: "25000000000".into(), + address: ADDR.into(), + memo: "lunch".into(), + txid: Some(TXID.into()), + verified: true, + created_at: 0, + }]; + let st = PeerPaymentsState::from_payments("lance".into(), &rows); + assert_eq!(st.rows[0].amount_xmr, "0.025", "piconero -> XMR"); + assert!( + peer_payments_text(78, 21, &st).contains("0.025"), + "{}", + peer_payments_text(78, 21, &st) + ); +} + +#[test] +fn peer_payments_empty_history_is_an_explicit_line() { + let st = PeerPaymentsState { + peer: "lance".into(), + rows: Vec::new(), + error: None, + selected: 0, + }; + let body = peer_payments_text(78, 21, &st); + assert!( + body.contains("no payments"), + "empty state not named:\n{body}" + ); + assert!(body.contains("lance"), "\n{body}"); + // Empty is a state, never an error. + assert!(!body.to_lowercase().contains("error"), "\n{body}"); + assert!(!body.to_lowercase().contains("failed"), "\n{body}"); + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + let screen = render(w, h, &st); + assert!( + screen.contains("no payments"), + "{w}x{h} blank panel:\n{screen}" + ); + } +} + +#[test] +fn peer_payments_error_is_named_not_blank() { + let st = PeerPaymentsState::error("lance".into(), "store lock poisoned".into()); + let body = peer_payments_text(78, 21, &st); + assert!(body.contains("could not read payments"), "\n{body}"); + assert!(body.contains("store lock poisoned"), "\n{body}"); +} + +#[test] +fn peer_payments_selection_uses_a_marker_not_colour_alone() { + let mut st = peer_state(); + let first = peer_payments_text(78, 21, &st); + let marked = first + .lines() + .find(|l| l.starts_with('>')) + .expect("a selection marker"); + assert!(marked.contains("0.025"), "{marked:?}"); + st.select_next(); + let second = peer_payments_text(78, 21, &st); + let now = second + .lines() + .find(|l| l.starts_with('>')) + .expect("a selection marker"); + assert!(now.contains("0.005"), "{now:?}"); + assert_eq!( + second.lines().filter(|l| l.starts_with('>')).count(), + 1, + "exactly one row is focused:\n{second}" + ); +} + +#[test] +fn peer_payments_windows_a_long_history_and_says_so() { + let rows: Vec = (0..40) + .map(|i| { + row( + "in", + "receipt", + "0.001", + &format!("row {i}"), + Some(TXID), + true, + ) + }) + .collect(); + let st = PeerPaymentsState { + peer: "lance".into(), + rows, + error: None, + selected: 0, + }; + let lines = peer_payments_lines(78, 21, &st); + assert!( + lines.len() <= 21, + "body needs {} rows for a 21-row pane", + lines.len() + ); + let body = peer_payments_text(78, 21, &st); + assert!(body.contains("older"), "window not disclosed:\n{body}"); + // The newest row is the one on screen, not the oldest. + assert!(body.contains("row 0"), "\n{body}"); + assert!(!body.contains("row 39"), "\n{body}"); + // Scrolling to the end brings the oldest row into view. + let mut st = st; + for _ in 0..39 { + st.select_next(); + } + let body = peer_payments_text(78, 21, &st); + assert!(body.contains("row 39"), "\n{body}"); + assert!(body.contains("newer"), "window not disclosed:\n{body}"); +} + +#[test] +fn peer_payments_hostile_memo_cannot_reach_the_terminal() { + // A peer-signed memo is untrusted display data: ESC/BEL/C1 controls, bidi + // overrides and newlines must not survive into the frame buffer. + let hostile = "safe\u{1b}[31mred\u{7}\u{202e}\u{2066}\u{9b}\nrow"; + let st = PeerPaymentsState { + peer: "lance".into(), + rows: vec![row("in", "receipt", "0.025", hostile, Some(hostile), true)], + error: None, + selected: 0, + }; + for (w, h) in [(80u16, 24u16), (120, 40)] { + let screen = render(w, h, &st); + assert!(!screen.contains('\u{1b}'), "{w}x{h} ESC reached the frame"); + assert!(!screen.contains('\u{7}'), "{w}x{h} BEL reached the frame"); + assert!(!screen.contains('\u{9b}'), "{w}x{h} C1 reached the frame"); + assert!( + !screen.contains('\u{202e}') && !screen.contains('\u{2066}'), + "{w}x{h} bidi reached the frame" + ); + assert!(screen.contains("safe"), "{w}x{h}:\n{screen}"); + } + // The control byte itself is dropped, so the rest is inert text: `[31m` can + // only ever be printed, never interpreted. + let body = peer_payments_text(78, 21, &st); + assert!(body.contains("safe[31mred"), "\n{body}"); + assert!(!body.contains('\u{1b}'), "\n{body}"); +} + +#[test] +fn peer_payments_frames_fit_at_the_three_sizes() { + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + let screen = render(w, h, &peer_state()); + assert!(screen.contains("payments"), "{w}x{h}:\n{screen}"); + assert!(screen.contains("lance"), "{w}x{h}:\n{screen}"); + assert!(screen.contains("? help"), "footer clipped:\n{screen}"); + assert!( + screen.contains("lunch money"), + "memo clipped at {w}x{h}:\n{screen}" + ); + for line in screen.lines() { + assert!( + cell_width(line) <= w as usize, + "line wider than {w} at {w}x{h}: {line:?}" + ); + } + let lines = peer_payments_lines(w - 2, h - 3, &peer_state()); + assert!( + lines.len() <= (h - 3) as usize, + "body needs {} rows, {w}x{h} shows {}", + lines.len(), + h - 3 + ); + } + // 200x60 has room for the whole txid and address, untruncated. + let wide = render(200, 60, &peer_state()); + assert!(wide.contains(TXID), "200x60 truncated the txid:\n{wide}"); + assert!(wide.contains(ADDR), "200x60 truncated the address:\n{wide}"); +} + +#[test] +fn peer_payments_columns_drop_before_they_wrap() { + // 80 columns is the floor, but a narrow terminal must still produce rows + // that never overrun the pane: trailing columns are dropped, not wrapped. + for w in 20u16..=200 { + for line in peer_payments_lines(w, 21, &peer_state()) { + let width: usize = line + .spans + .iter() + .map(|s| cell_width(s.content.as_ref())) + .sum(); + assert!(width <= w as usize, "width {w}: {width} cells: {line:?}"); + } + for line in peer_payments_lines( + w, + 21, + &PeerPaymentsState { + peer: "lance".into(), + rows: Vec::new(), + error: None, + selected: 0, + }, + ) { + let width: usize = line + .spans + .iter() + .map(|s| cell_width(s.content.as_ref())) + .sum(); + assert!(width <= w as usize, "empty state width {w}: {line:?}"); + } + } +} + +#[test] +fn wallets_settings_menu_offers_the_peer_payments_row() { + let st = WalletMenuState { + transfers: 3, + peer: "lance".into(), + peer_payments: Some(3), + ..menu_state_defaults() + }; + let body = wallets_settings_menu_text(78, &st); + let row = body + .lines() + .find(|l| l.contains("payments")) + .expect("payments row"); + assert!(row.contains("lance"), "row does not name the peer: {row:?}"); + assert!(row.contains('p'), "row does not name its key: {row:?}"); + // The wallet's own transfer list keeps its F6 row; it is retitled so the + // two histories cannot be mistaken for each other. + assert!( + body.lines().any(|l| l.contains("transfers")), + "wallet transfer row lost:\n{body}" + ); + + // No friend selected: the row is dim and offers no key that would do + // nothing. + let st = WalletMenuState { + peer: String::new(), + peer_payments: None, + ..menu_state_defaults() + }; + let body = wallets_settings_menu_text(78, &st); + let row = body + .lines() + .find(|l| l.contains("payments")) + .expect("payments row"); + assert!(row.contains("no friend"), "{row:?}"); + + // A friend with no payment rows is the empty state, not an error. + let st = WalletMenuState { + peer: "lance".into(), + peer_payments: Some(0), + ..menu_state_defaults() + }; + let body = wallets_settings_menu_text(78, &st); + let row = body + .lines() + .find(|l| l.contains("payments")) + .expect("payments row"); + assert!(row.contains("no history"), "{row:?}"); +} + +/// The F9 menu state with a healthy wallet, as `tests/tui_spec.rs` builds it. +fn menu_state_defaults() -> WalletMenuState { + WalletMenuState { + configured: true, + connected: true, + wallet_error: None, + receive_addr: ADDR.into(), + balance: "0.250000000000".into(), + transfers: 3, + child_state: "ready".into(), + child_source: "local node".into(), + child_error: None, + nickname: Some("lance".into()), + bio_set: true, + xmr_set: true, + me_fp: FP.into(), + peer: String::new(), + peer_payments: None, + } +} + +#[test] +fn peer_payments_frame_dumps() { + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + println!("===== PEER PAYMENTS {w}x{h} ====="); + print!("{}", render(w, h, &peer_state())); + println!("===== PEER PAYMENTS (empty) {w}x{h} ====="); + print!( + "{}", + render( + w, + h, + &PeerPaymentsState { + peer: "lance".into(), + rows: Vec::new(), + error: None, + selected: 0, + } + ) + ); + } +} diff --git a/tests/tui_spec.rs b/tests/tui_spec.rs index 9672138..05cc668 100644 --- a/tests/tui_spec.rs +++ b/tests/tui_spec.rs @@ -6,11 +6,11 @@ use onionwire::outbox::{OutboxEntry, OutboxStatus}; use onionwire::qr; use onionwire::tui::{ OutboxSummary, SlashCmd, WalletMenuState, alert_line, ascii_chrome, cell_width, - chat_with_delivery, delivery_tag, draw_chat, draw_share, draw_text_overlay, draw_wallets_settings, - empty_friend_chat_text, fit_cells, help_overlay_text, main_footer_hints, main_header_line, - osc52_copy_sequence, parse_cmd, paste_screen_text, retry_in_text, roster_col_width, - short_send_reason, status_footer, wallets_settings_menu_lines, wallets_settings_menu_text, - wrap_invite, + chat_with_delivery, delivery_tag, draw_chat, draw_share, draw_text_overlay, + draw_wallets_settings, empty_friend_chat_text, fit_cells, help_overlay_text, main_footer_hints, + main_header_line, osc52_copy_sequence, parse_cmd, paste_screen_text, retry_in_text, + roster_col_width, short_send_reason, status_footer, wallets_settings_menu_lines, + wallets_settings_menu_text, wrap_invite, }; use ratatui::Frame; use ratatui::Terminal; @@ -429,7 +429,14 @@ fn pending_row( } fn queued_row(message_id: i64, body: &str, attempts: u32, next_in: i64, now: i64) -> OutboxEntry { - pending_row(message_id, body, OutboxStatus::Queued, attempts, next_in, now) + pending_row( + message_id, + body, + OutboxStatus::Queued, + attempts, + next_in, + now, + ) } fn sending_row(message_id: i64, body: &str, now: i64) -> OutboxEntry { @@ -555,7 +562,12 @@ fn delivery_markers_have_exercised_ascii_fallbacks() { in_msg(5, "epsilon"), ]; let pending = vec![ - failed_row(1, "alpha", "connect peer.onion:80: connection timed out", now), + failed_row( + 1, + "alpha", + "connect peer.onion:80: connection timed out", + now, + ), queued_row(2, "beta", 1, 30, now), sending_row(3, "gamma", now), ]; @@ -841,9 +853,7 @@ fn rgb_tokens_resolve_to_palette_fg() { assert_eq!(t.highlight.fg, Some(Color::Rgb(232, 165, 75))); assert_eq!(t.highlight.bg, Some(Color::Rgb(48, 42, 28))); assert!( - t.highlight - .add_modifier - .contains(Modifier::BOLD), + t.highlight.add_modifier.contains(Modifier::BOLD), "RGB highlight must be bold" ); } @@ -906,7 +916,10 @@ fn alert_line_prefixes_when_no_color() { let _guard = std::env::var_os("NO_COLOR"); unsafe { std::env::set_var("NO_COLOR", "1") }; let line = alert_line("peer down", 80); - assert!(line.starts_with("! "), "expected '! ' prefix in None mode: {line:?}"); + assert!( + line.starts_with("! "), + "expected '! ' prefix in None mode: {line:?}" + ); unsafe { match _guard { Some(v) => std::env::set_var("NO_COLOR", v), @@ -938,6 +951,8 @@ fn menu_state() -> WalletMenuState { bio_set: true, xmr_set: true, me_fp: FP.into(), + peer: "lance".into(), + peer_payments: Some(3), } } @@ -978,8 +993,18 @@ fn wallets_settings_menu_lists_both_groups_and_every_key() { // F6 wallet screen's own keys, so the menu teaches the shortcuts it sits // beside instead of hiding them. for key in [ - "F6 s/x", "F6 p", "c copy F6 r", "F6 c", "F6 i", "F6 r", "F2", "/profile", "/backup", - "/restore", "/wipe", "/wipe-all", + "F6 s/x", + "F6 p", + "c copy F6 r", + "F6 c", + "F6 i", + "F6 r", + "F2", + "/profile", + "/backup", + "/restore", + "/wipe", + "/wipe-all", ] { assert!( body.contains(key), @@ -1072,7 +1097,10 @@ fn wallets_settings_menu_words_every_state() { }; let body = wallets_settings_menu_text(78, &stale); assert!(body.contains("configured · not connected"), "\n{body}"); - assert!(body.contains("wallet answering · chain not at tip"), "\n{body}"); + assert!( + body.contains("wallet answering · chain not at tip"), + "\n{body}" + ); let exited = WalletMenuState { child_state: "exited".into(), @@ -1136,7 +1164,11 @@ fn wallets_settings_menu_truncates_wide_values_in_cells() { // contract. let ascii = fit_cells("abcdefghij", 8); assert!(cell_width(&ascii) <= 8, "{ascii:?}"); - assert!(ascii.starts_with("abcdef"), "{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_eq!(cell_width("名"), 2); assert_eq!(cell_width("abc"), 3); } @@ -1255,6 +1287,9 @@ fn osc52_copy_sequence_is_a_base64_clipboard_write() { #[test] fn slash_settings_is_the_menu() { assert!(matches!(parse_cmd("/settings"), Some(SlashCmd::Settings))); - assert!(matches!(parse_cmd(" /settings "), Some(SlashCmd::Settings))); + assert!(matches!( + parse_cmd(" /settings "), + Some(SlashCmd::Settings) + )); assert!(parse_cmd("/settings now").is_none()); }