diff --git a/docs/TUI.md b/docs/TUI.md index 9c52c70..7b64afd 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -23,6 +23,7 @@ ASCII chrome. | `Profile` | `/profile` | Edit name, bio, optional Monero address | | `ConfirmKeys` / `Passphrase` | `/backup`, `/restore` | Type `BACKUP`/`RESTORE`, then passphrase | | `Wallet` | `F6` | Receive QR, balance, transfers, child, chain source | +| `WalletSelect` | `F6` `w` | Saved wallets, pick one or create one | | `WalletSetup` | `F6` `c` / `i`, or `/wallet create` / `import` | Spend warning, seed, import | | `WalletsSettings` | `F9` or `/settings` | Discovery menu (does not replace F-keys) | | `PeerPayments` | F9 then `p` | Peer-scoped `/pay` / `/tip` history | @@ -109,12 +110,13 @@ Pane-specific (`pane_footer_hints`): Footer: ``` -c create i import r qr s/x child 1 pruned 2 full 3 testnet Esc back ? help +c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help ``` | Key | Effect | |---|---| | `r` or Enter | Toggle receive-address QR | +| `w` | Saved wallets (`WalletSelect`) | | `c` | Create wallet (`SPEND` then seed once, type `SEEN`) | | `i` | Import 25-word seed | | `s` | Start app-owned wallet child | @@ -133,6 +135,24 @@ feature name. Create/import require the wallet RPC started with `--wallet-dir`. Filename: `onionwire`. Seed is never collected on the composer. +## Saved wallets (`F6` then `w`) + +`WalletSelect`. One row per persisted wallet — name, identity prefix, locator +prefix, creation day — plus the selected row's full identity and locator under +the table. `j`/`k` or arrows select, Enter opens the selection, Esc back to +Main. Footer: `Esc back j k select Enter open ? help`. + +The last item is **not** a wallet: `+ create new wallet` starts the same create +flow as `F6` `c`, so an empty list still has a way forward. An unlabelled wallet +(`NULL` in the store) reads `(unlabelled)`; a wallet whose onion service is not +published yet reads `-`; an unknown creation time reads `unknown`. A read that +failed is named on the screen — that is a different state from `no saved wallets +yet`, and the two never share copy. + +Rows are plain display data (`WalletRow`), built by the caller from +`Store::list_wallets`; the render path never reads the store. Selection is by +row index, not by identity key (two records may share one). + ## Wallets & settings (`F9` / `/settings`) Discovery layer, not a replacement. Function keys stay live on this screen. @@ -180,4 +200,5 @@ Floor **80×24**. Target **120×40**. Frame dumps: ``` cargo test --locked --test tui_spec -- --nocapture dump_spec_frames cargo test --locked --test tui_spec -- --nocapture wallets_settings_menu_frame_dumps +cargo test --locked --test tui_select -- --nocapture wallet_select_frame_dumps ``` diff --git a/src/tui.rs b/src/tui.rs index a72d071..7e7b9eb 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1288,6 +1288,12 @@ enum Screen { PeerPayments { state: PeerPaymentsState, }, + /// F6 → `w`: pick a saved wallet, or create one. The rows are a snapshot + /// like the other two, and the `create new wallet` row is part of the list + /// rather than a separate key. + WalletSelect { + state: WalletSelectState, + }, Quit { prompt: QuitPrompt, }, @@ -1425,6 +1431,9 @@ impl App { let mut open_payments = false; let mut payments_back = false; let mut payments_move = 0i32; + let mut select_back = false; + let mut select_move = 0i32; + let mut select_enter = false; // The function-key shortcuts stay live on the WALLETS & SETTINGS screen // and the peer history too: the settings screen's whole point is naming @@ -1666,6 +1675,9 @@ impl App { Screen::Wallet { .. } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Char('r') | KeyCode::Enter => self.wallet_toggle_qr(), + // `w` is the wallet list: the F6 screen is about the wallet you + // are on, and this is how you get off it. + KeyCode::Char('w') => self.open_wallet_select(), KeyCode::Char('s') => self.wallet_child_start(), KeyCode::Char('x') => self.wallet_child_stop(), KeyCode::Char('p') => self.wallet_child_probe(), @@ -1698,6 +1710,13 @@ impl App { KeyCode::Down | KeyCode::Char('j') => payments_move = 1, _ => {} }, + Screen::WalletSelect { .. } => match key.code { + KeyCode::Esc => select_back = true, + KeyCode::Up | KeyCode::Char('k') => select_move = -1, + KeyCode::Down | KeyCode::Char('j') => select_move = 1, + KeyCode::Enter => select_enter = true, + _ => {} + }, Screen::Quit { prompt } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Enter => match prompt.on_char('\n') { @@ -1729,6 +1748,22 @@ impl App { if payments_back { self.screen = Screen::Main; } + if select_move != 0 + && let Screen::WalletSelect { state } = &mut self.screen + { + if select_move < 0 { + state.select_prev(); + } else { + state.select_next(); + } + } + if select_back { + // A full surface like the F9 menu: Esc leaves it for the main view. + self.screen = Screen::Main; + } + if select_enter { + self.choose_wallet()?; + } if open_payments { self.open_peer_payments()?; } @@ -2037,6 +2072,45 @@ impl App { Ok(()) } + /// Enter on the wallet selection screen: `create new wallet` starts the + /// existing creation flow, and a wallet row is a choice the app has to + /// resolve. + /// + /// Resolving a row into the session is the wallet-store integration step: + /// the record's identity and locator have to be read back and loaded, and + /// `Node` has no wallet-record accessor yet. Until that lands the choice is + /// reported instead of silently dropped — an Enter that does nothing is + /// worse than one that says what is missing. + fn choose_wallet(&mut self) -> Result<(), String> { + let Screen::WalletSelect { state } = &self.screen else { + return Ok(()); + }; + match state.choice() { + WalletChoice::Create => { + self.screen = Screen::WalletSetup(WalletSetup::CreateWarn { + typed: String::new(), + }); + } + WalletChoice::Open(_) => { + self.status_note = Some("wallet switching is not wired up yet".into()); + } + } + Ok(()) + } + + /// F6 `w`: the wallet selection screen. + /// + /// The rows come from the wallet store; reading them is the integration + /// card's step (`Store::list_wallets`), and the render path never touches + /// the store. Until that accessor exists the screen opens on its + /// unavailable state, which says so — the `create new wallet` row at the + /// bottom works either way. + fn open_wallet_select(&mut self) { + self.screen = Screen::WalletSelect { + state: WalletSelectState::error(SELECT_UNAVAILABLE.to_string()), + }; + } + /// `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. @@ -2578,6 +2652,17 @@ impl App { ); draw_peer_payments(f, state, &footer) } + Screen::WalletSelect { state } => { + 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), + ); + draw_wallet_select(f, state, &footer) + } } if self.help_open { draw_text_overlay(f, "? help", help_overlay_text()); @@ -3193,7 +3278,7 @@ match screen { }, Screen::Passphrase { .. } => "Enter submit Esc cancel ? help", Screen::Wallet { .. } => { - "c create i import r qr s/x child 1 pruned 2 full 3 testnet Esc back ? help" + "c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help" } Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help", Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => { @@ -3203,6 +3288,7 @@ match screen { Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help", Screen::WalletsSettings { .. } => wallets_settings_footer_hint(), Screen::PeerPayments { .. } => peer_payments_footer_hint(), + Screen::WalletSelect { .. } => wallet_select_footer_hint(), Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help", } } @@ -4351,6 +4437,497 @@ pub fn draw_peer_payments(f: &mut Frame, state: &PeerPaymentsState, footer: &str ); } +/// One persisted wallet, display-ready. +/// +/// Plain data on purpose: the render path never reads the store, so the screen +/// takes rows the caller built. `name`, `identity_pubkey` and `onion_locator` +/// are untrusted display data (a label the user typed), sanitized at draw time. +/// +/// The store's `WalletRecord` maps onto this like so — +/// `name: r.name.unwrap_or_default()` (a blank label is the placeholder +/// `(unlabelled)` on screen), `identity_pubkey: hex(r.identity_pubkey)` (the +/// column is `[u8; 32]`, so it is encoded here as text), `onion_locator: +/// r.onion_locator` (empty until the HS is published — that renders as `-`), +/// `created_at: r.created_at`. `wallet_filename` is deliberately not carried: +/// it is not on the screen, and the render path has no business with a path. +/// +/// Selection is by **row index**, never by identity: two records may share an +/// identity key, so `WalletChoice::Open` names a position, not a wallet. +#[derive(Clone, Debug, Default)] +pub struct WalletRow { + /// User-given label. Empty means unlabelled (`NULL` in the store) and the + /// row says so rather than leaving the primary cell blank. + pub name: String, + /// The wallet's identity public key, hex. + pub identity_pubkey: String, + /// The wallet's v3 onion locator, without the `.onion` suffix. Empty until + /// the service is published. + pub onion_locator: String, + /// Creation time, unix seconds UTC. `0` (or negative) means unknown. + pub created_at: i64, +} + +/// What Enter does on the selection screen. +/// +/// The index is into the state's `rows` (display order), never into the store's +/// ids: the render path does not know them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WalletChoice { + /// Open the wallet at this index. + Open(usize), + /// The `create new wallet` row — the last item in the list. + Create, +} + +/// What the wallet selection screen draws. +/// +/// One item in the list is not a wallet: the `create new wallet` row, always +/// last, so Enter on it can start the creation flow instead of loading a +/// record. `selected` indexes rows **plus** that trailing row, which is why +/// `rows.len()` is a legal index and `choice()` reads it as `Create`. +/// +/// `error` is display-ready and only set when the read itself failed — an +/// account with no saved wallets is an empty list, not an error. +#[derive(Clone, Debug, Default)] +pub struct WalletSelectState { + pub rows: Vec, + pub selected: usize, + /// The read is in flight. The create row is still listed: it does not + /// depend on the store, so Enter stays live while the list loads. + pub reading: bool, + /// Why the list could not be read, display-ready. + pub error: Option, +} + +impl WalletSelectState { + /// The list a read returned. An empty list is the first-run state. + pub fn from_rows(rows: Vec) -> Self { + Self { + rows, + selected: 0, + reading: false, + error: None, + } + } + + /// The read is in flight. Nothing is listed yet, so the selection sits on + /// the create row. + pub fn reading() -> Self { + Self { + rows: Vec::new(), + selected: 0, + reading: true, + error: None, + } + } + + /// The read failed. This is not "no wallets": the screen says so. + pub fn error(why: String) -> Self { + Self { + rows: Vec::new(), + selected: 0, + reading: false, + error: Some(why), + } + } + + /// Move down one item. The bottom is the create row and is sticky. + pub fn select_next(&mut self) { + self.selected = (self.selected + 1).min(self.rows.len()); + } + + /// Move up one item. The top is the first wallet (or create) and is sticky. + pub fn select_prev(&mut self) { + self.selected = self.selected.saturating_sub(1); + } + + /// The row under the marker, `None` on the create row. + pub fn selected_row(&self) -> Option<&WalletRow> { + self.rows.get(self.selected) + } + + /// What Enter means right now. One past the last wallet — and the only + /// item of an empty or failed list — is `Create`. + pub fn choice(&self) -> WalletChoice { + match self.rows.get(self.selected) { + Some(_) => WalletChoice::Open(self.selected), + None => WalletChoice::Create, + } + } +} + +/// Marker column in cells: `> ` when focused, ` ` otherwise. +const WALLET_MARK_W: usize = 2; +/// Identity column in cells: an 8-character prefix plus the ellipsis — 11 +/// cells under `ONIONWIRE_ASCII`, where the ellipsis is three dots, so that is +/// the width every column is padded to whatever the chrome is doing. +const WALLET_ID_W: usize = 11; +/// Locator column in cells, measured the same way as the identity column. +const WALLET_LOC_W: usize = 11; +/// Creation-day column in cells: `2026-09-21` is 10, and `unknown` is 7. +const WALLET_SINCE_W: usize = 10; +/// Gap between two columns. +const WALLET_GAP: usize = 2; +/// Widest name column. The name is the flexible column and it is capped so the +/// trailing columns stay a table and not a 150-cell walk: every row pads to the +/// same column starts, which is what makes the rows scan as a grid. +const WALLET_NAME_W: usize = 28; +/// Cells the trailing columns need, marker included. +const WALLET_FIXED_W: usize = WALLET_MARK_W + + (WALLET_GAP + WALLET_ID_W) + + (WALLET_GAP + WALLET_LOC_W) + + (WALLET_GAP + WALLET_SINCE_W); + +/// `2026-09-21` for a unix second (UTC), or `unknown` when there is no usable +/// timestamp. Hand-rolled: this crate has no date dependency, and the screen +/// needs exactly one calendar date. +/// +/// Days-to-civil (Howard Hinnant's algorithm) — no leap-year table, no crate. +pub fn format_day_utc(secs: i64) -> String { + if secs <= 0 { + return "unknown".to_string(); + } + let z = secs.div_euclid(86_400) + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!("{year:04}-{month:02}-{day:02}") +} + +/// An identifying prefix of untrusted text: the first `keep` characters, closed +/// with the chrome's ellipsis, fitted into `cells`. +fn wallet_prefix(raw: &str, keep: usize, cells: usize) -> String { + let clean = menu_cell_text(raw); + let head: String = clean.chars().take(keep).collect(); + fit_cells(&format!("{head}{}", ellipsis()), cells) +} + +/// One laid-out grid line: marker, name, then whichever of the three trailing +/// columns fit. +/// +/// Trailing columns are **dropped** when the pane is too narrow, never wrapped, +/// so no row can overrun the pane — the same discipline as the payments grid, +/// and it holds below the 80-column floor too. +#[allow(clippy::too_many_arguments)] +fn wallet_grid_line( + w: usize, + marker: &str, + name: &str, + id: &str, + loc: &str, + since: &str, + marker_style: Style, + name_style: Style, + col_style: Style, +) -> Line<'static> { + let mut spans = vec![Span::styled(marker.to_string(), marker_style)]; + let inner = w.saturating_sub(cell_width(marker)); + let name_w = inner.saturating_sub(WALLET_FIXED_W).min(WALLET_NAME_W); + if name_w == 0 { + // Not even a name fits: the identity is the most identifying thing left. + spans.push(Span::styled( + fit_cells(&menu_cell_text(id), inner.max(1)), + col_style, + )); + return Line::from(spans); + } + spans.push(Span::styled( + pad_right(&fit_cells(name, name_w), name_w), + name_style, + )); + let mut used = name_w; + for (col_w, text) in [ + (WALLET_ID_W, id), + (WALLET_LOC_W, loc), + (WALLET_SINCE_W, since), + ] { + // An empty tail means the row has no more columns to give (the create + // row), and a column that does not fit takes the rest of them with it. + if text.is_empty() || inner < used + WALLET_GAP + col_w { + break; + } + spans.push(Span::raw(" ".repeat(WALLET_GAP))); + spans.push(Span::styled( + pad_right(&fit_cells(text, col_w), col_w), + col_style, + )); + used += WALLET_GAP + col_w; + } + Line::from(spans) +} + +/// The selected row's full identity and locator. The rows carry prefixes, which +/// is what makes the list scannable; the full values are what a user actually +/// verifies, so the strip under the table spells them out. +fn wallet_detail_lines(w: usize, row: &WalletRow) -> Vec> { + let mut out = vec![Line::default()]; + for (label, value) in [ + ("id", menu_cell_text(&row.identity_pubkey)), + ("onion", menu_cell_text(&row.onion_locator)), + ] { + let text = if value.trim().is_empty() { + "(none)".to_string() + } else { + value + }; + out.push(Line::from(vec![ + Span::styled(format!(" {label:<5} "), style_dim()), + Span::styled(fit_cells(&text, w.saturating_sub(9).max(1)), style_text()), + ])); + } + out +} + +/// The wallet selection body as styled lines for a `width` × `height` **inner** +/// pane. +/// +/// Fixed shape at the bottom: a blank, then the `create new wallet` row — the +/// one item that is not a wallet, always last, so the eye always knows where the +/// way out of an empty list is. The table above it windows and says how many +/// rows are out of view rather than dropping them silently. +pub fn wallet_select_lines(width: u16, height: u16, s: &WalletSelectState) -> Vec> { + let w = width as usize; + let h = height as usize; + let mut out: Vec> = Vec::new(); + + // The table is drawn only when there is a table to draw; empty, failed and + // in-flight reads say what they are instead of showing bare column heads. + let table = !s.rows.is_empty(); + if table { + out.push(wallet_grid_line( + w, + " ", + "name", + "identity", + "locator", + "since", + Style::default(), + style_dim(), + style_dim(), + )); + } else { + let (head, head_style, sub) = if let Some(err) = &s.error { + ( + "could not read saved wallets", + style_alert(), + menu_cell_text(err), + ) + } else if s.reading { + ( + "reading saved wallets", + style_dim(), + "one moment".to_string(), + ) + } else { + ( + "no saved wallets yet", + style_dim(), + "create one to get an identity and an onion address".to_string(), + ) + }; + out.push(Line::from(Span::styled( + fit_cells(&format!(" {head}"), w.max(1)), + head_style, + ))); + out.push(Line::from(Span::styled( + fit_cells(&format!(" {sub}"), w.max(1)), + style_dim(), + ))); + } + + // The full-value strip only where it cannot wrap, and its three cells are + // reserved whether or not the selection is a wallet, so the marker moving + // down to the create row never shifts the rows above it. + let strip = w >= 75 && h >= 14; + let strip_h = if strip { 3 } else { 0 }; + // One blank + the create row at the bottom. + let tail_h = 2; + let budget = h.saturating_sub(out.len() + strip_h + tail_h); + + if table { + let total = s.rows.len(); + let selected = s.selected.min(total - 1); + let windowed = total > budget && budget >= 5; + let visible = if windowed { + budget - 2 + } else { + 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); + if windowed && start > 0 { + out.push(Line::from(Span::styled( + fit_cells(&format!(" {} {start} above", ellipsis()), w.max(1)), + style_dim(), + ))); + } + for (i, row) in s.rows.iter().enumerate().take(end).skip(start) { + // No row carries the marker when the selection has walked past the + // last wallet onto the create row. + let selected = s.selected < total && i == s.selected; + // A NULL label reads as a placeholder, and a wallet whose onion + // service is not published yet has no locator at all — both are + // states the row names, not blanks. + let name = { + let clean = menu_cell_text(&row.name); + if clean.trim().is_empty() { + "(unlabelled)".to_string() + } else { + clean + } + }; + let id = { + let clean = menu_cell_text(&row.identity_pubkey); + if clean.trim().is_empty() { + "-".to_string() + } else { + wallet_prefix(&clean, 8, WALLET_ID_W) + } + }; + let loc = { + let clean = menu_cell_text(&row.onion_locator); + if clean.trim().is_empty() { + "-".to_string() + } else { + wallet_prefix(&clean, 8, WALLET_LOC_W) + } + }; + out.push(wallet_grid_line( + w, + if selected { "> " } else { " " }, + &name, + &id, + &loc, + &format_day_utc(row.created_at), + if selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + Style::default() + }, + if selected { + style_text().add_modifier(Modifier::BOLD) + } else { + style_text() + }, + style_dim(), + )); + } + if windowed && end < total { + out.push(Line::from(Span::styled( + fit_cells(&format!(" {} {} below", ellipsis(), total - end), w.max(1)), + style_dim(), + ))); + } + } + + if strip { + let detail = if !table { + Vec::new() + } else { + s.selected_row() + .map(|row| wallet_detail_lines(w, row)) + .unwrap_or_default() + }; + // Reserved either way: the block is the same height whichever item the + // marker is on. + for i in 0..strip_h { + out.push(detail.get(i).cloned().unwrap_or_default()); + } + } + + // The create row closes the list, one blank line under the table, and the + // panel below it stays empty — the same top-packed shape as the F9 menu, so + // the eye finds the table at the top of every full-screen panel. + out.push(Line::default()); + let create_selected = s.rows.get(s.selected).is_none(); + out.push(wallet_grid_line( + w, + if create_selected { "> " } else { " " }, + "+ create new wallet", + "", + "", + "", + if create_selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + Style::default() + }, + if create_selected { + style_accent().add_modifier(Modifier::BOLD) + } else { + style_text() + }, + style_dim(), + )); + out +} + +/// The body as plain text, for width/needle assertions. +pub fn wallet_select_text(width: u16, height: u16, s: &WalletSelectState) -> String { + wallet_select_lines(width, height, s) + .iter() + .map(|line| { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect::() + }) + .collect::>() + .join("\n") +} + +/// Block title: the count is the reason the screen exists, so it is stated. +pub fn wallet_select_title(s: &WalletSelectState) -> String { + if s.rows.is_empty() { + "(o) wallets".to_string() + } else { + format!("(o) wallets {} {} saved", "\u{b7}", s.rows.len()) + } +} + +/// Wallet selection: a full screen like the F9 menu, with the same single +/// status line. `footer` is an already-built `status_footer` row. +pub fn draw_wallet_select(f: &mut Frame, s: &WalletSelectState, footer: &str) { + let area = f.area(); + let rows = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area); + f.render_widget( + Paragraph::new(wallet_select_lines( + rows[0].width.saturating_sub(2), + rows[0].height.saturating_sub(2), + s, + )) + .block(themed_block(&wallet_select_title(s))), + rows[0], + ); + f.render_widget( + Paragraph::new(fit_cells(footer, area.width as usize)).style(style_dim()), + rows[1], + ); +} + +/// The hint line the wallet selection screen prints, single-sourced for the +/// same reason as [`peer_payments_footer_hint`]: a frame-dump fixture must not +/// hand-copy it, or the dump shows a footer the app never renders. +pub fn wallet_select_footer_hint() -> &'static str { + WALLET_SELECT_FOOTER_HINT +} + +const WALLET_SELECT_FOOTER_HINT: &str = "Esc back j k select Enter open ? help"; + +/// The sub-line the screen prints when the wallet store has not been wired into +/// the app yet (see [`WalletRow`]): the list is genuinely unreadable, which is +/// not the same state as "no saved wallets". +pub const SELECT_UNAVAILABLE: &str = "the wallet store is not wired up yet"; + /// 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. @@ -4651,6 +5228,26 @@ mod function_key_tests { } } + /// The wallet list names `Esc`, `j k` and `Enter`, no function key — so it + /// must not quietly answer one. Copy and behaviour have to agree in both + /// directions, or a key that works on every other screen becomes a surprise + /// here. + #[test] + fn the_wallet_select_screen_answers_no_function_key_it_does_not_name() { + let screen = Screen::WalletSelect { + state: WalletSelectState::default(), + }; + let hint = wallet_select_footer_hint(); + for number in [2u8, 3, 4, 5, 6, 8, 9] { + let named = hint.contains(&format!("F{number}")); + assert_eq!( + function_key_for(&screen, KeyCode::F(number)).is_some(), + named, + "F{number} and the hint disagree: {hint:?}" + ); + } + } + /// A screen that names no function key keeps the key to itself: the /// composer's `F`-less screens must not steal F-keys they never advertise. #[test] diff --git a/tests/tui_select.rs b/tests/tui_select.rs new file mode 100644 index 0000000..7447ec1 --- /dev/null +++ b/tests/tui_select.rs @@ -0,0 +1,475 @@ +//! Wallet selection screen (`F6` → `w`). +//! +//! The screen lists the persisted wallets and, last, the `create new wallet` +//! row. Assertions measure in terminal **cells** (`cell_width`, which goes +//! through `Span::width`) and accept either ellipsis form because +//! `ascii_chrome()` follows `NO_COLOR` / `ONIONWIRE_ASCII` and the TUI test +//! binaries run in parallel. + +use onionwire::tui::{ + TorPhase, WalletChoice, WalletRow, WalletSelectState, cell_width, draw_wallet_select, + format_day_utc, status_footer_phased, wallet_select_footer_hint, wallet_select_lines, + wallet_select_text, +}; +use ratatui::Terminal; +use ratatui::backend::TestBackend; + +const FP: &str = "abcdef0123456789deadbeefcafebabe"; +const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; +const ID_A: &str = "ab12cd34ef5678901234567890abcdef1234567890abcdef1234567890abcd"; +const ID_B: &str = "ff00aa11bb22cc33dd44ee55ff6677889900aabbccddeeff0011223344556677"; +const ONION_A: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx"; +const ONION_B: &str = "zyxwvutsrqponmlkjihgfedcba765432zyxwvutsrqponmlkjihgfedcba"; + +fn row(name: &str, id: &str, onion: &str, created_at: i64) -> WalletRow { + WalletRow { + name: name.into(), + identity_pubkey: id.into(), + onion_locator: onion.into(), + created_at, + } +} + +/// Two saved wallets plus the create row: the shape the screen opens on. +fn two_wallets() -> WalletSelectState { + WalletSelectState::from_rows(vec![ + row("lance", ID_A, ONION_A, 1_789_963_705), + row("cold", ID_B, ONION_B, 1_756_320_000), + ]) +} + +/// The row count is the wallet count **plus the create row**, which is always +/// the last item: Enter on it starts the creation flow, not a wallet load. +#[test] +fn selection_walks_every_row_and_ends_on_create() { + let mut st = two_wallets(); + assert_eq!( + st.choice(), + WalletChoice::Open(0), + "opens on the first wallet" + ); + + st.select_next(); + assert_eq!(st.choice(), WalletChoice::Open(1)); + st.select_next(); + assert_eq!( + st.choice(), + WalletChoice::Create, + "the create row is the last item in the list" + ); + + // Past the end is a no-op, not a panic: the bottom of the list is Create. + st.select_next(); + assert_eq!(st.choice(), WalletChoice::Create); + + st.select_prev(); + assert_eq!(st.choice(), WalletChoice::Open(1)); + st.select_prev(); + st.select_prev(); + assert_eq!( + st.choice(), + WalletChoice::Open(0), + "top of the list is sticky" + ); +} + +/// With no saved wallets the screen still has exactly one item — Create — so +/// Enter can never be a dead key on a first run. +#[test] +fn empty_state_still_offers_create() { + let st = WalletSelectState::default(); + assert_eq!(st.choice(), WalletChoice::Create); + assert!(st.selected_row().is_none()); +} + +/// A read that failed is not an empty list: the state says so. +#[test] +fn error_state_is_not_an_empty_list() { + let st = WalletSelectState::error("store lock poisoned".into()); + assert!(st.error.is_some()); + assert_eq!(st.choice(), WalletChoice::Create); +} + +/// The card's four fields, plus the create row, on the body at the 80-column +/// floor: name, identity prefix, locator prefix, creation date. +#[test] +fn wallet_select_lists_every_required_field() { + let body = wallet_select_text(78, 21, &two_wallets()); + for needle in [ + "name", // column header + "identity", // column header + "locator", // column header + "since", // column header + "lance", + "cold", // names + "ab12cd34", // identity prefix + "ff00aa11", // identity prefix of the second wallet + "abcdefgh", // locator prefix + "zyxwvuts", // locator prefix of the second wallet + "2026-09-21", // creation date + "2025-08-27", // creation date of the second wallet + "create new wallet", // the always-last row + ] { + assert!(body.contains(needle), "missing {needle:?}:\n{body}"); + } + // A prefix is a prefix: the row prints an identifying start, not the whole + // key (the full value belongs to the detail strip under the table). + let lance_row = body + .lines() + .find(|l| l.contains("lance")) + .expect("lance row"); + assert!( + !lance_row.contains(ID_A), + "a row printed the whole identity: {lance_row:?}" + ); + // Truncation is disclosed with the chrome's ellipsis (… or ...). + assert!( + body.contains('…') || body.contains("..."), + "no truncation marker on a prefix:\n{body}" + ); +} + +/// The create row is last, and the marker is on the selection — one marker +/// only, whichever row is focused. +#[test] +fn wallet_select_marks_exactly_one_row_and_puts_create_last() { + let mut st = two_wallets(); + let body = wallet_select_text(78, 21, &st); + let marked: Vec<&str> = body.lines().filter(|l| l.starts_with('>')).collect(); + assert_eq!(marked.len(), 1, "exactly one row is focused:\n{body}"); + assert!(marked[0].contains("lance"), "{:?}", marked[0]); + assert!( + body.lines().last().unwrap_or_default().contains("create"), + "the create row is not last:\n{body}" + ); + + st.select_next(); + let body = wallet_select_text(78, 21, &st); + let marked: Vec<&str> = body.lines().filter(|l| l.starts_with('>')).collect(); + assert_eq!(marked.len(), 1, "exactly one row is focused:\n{body}"); + assert!(marked[0].contains("cold"), "{:?}", marked[0]); + + // The bottom of the list is the create row and it takes the marker too. + st.select_next(); + let body = wallet_select_text(78, 21, &st); + let marked: Vec<&str> = body.lines().filter(|l| l.starts_with('>')).collect(); + assert_eq!(marked.len(), 1, "exactly one row is focused:\n{body}"); + assert!( + marked[0].contains("create new wallet"), + "the marker never reached the create row: {:?}", + marked[0] + ); +} + +/// A wallet with no label still identifies itself: the primary cell is a +/// placeholder, the row keeps its identity, and an unknown creation time is a +/// word, not a blank or a zero. +#[test] +fn wallet_select_names_an_unlabelled_wallet_and_an_unknown_date() { + let st = WalletSelectState::from_rows(vec![row("", ID_B, ONION_B, 0)]); + let body = wallet_select_text(78, 21, &st); + assert!( + body.contains("(unlabelled)"), + "a NULL label left the primary cell empty:\n{body}" + ); + assert!( + body.contains("ff00aa11"), + "an unlabelled wallet lost its identity:\n{body}" + ); + assert!( + body.contains("unknown"), + "an unknown creation date is blank:\n{body}" + ); + assert!( + !body.contains("1970-01-01"), + "epoch rendered as a date:\n{body}" + ); +} + +/// A wallet whose onion service has not been published yet has no locator. That +/// is a state, not an error: the cell says so and the row stays readable. +#[test] +fn wallet_select_renders_an_unpublished_locator_as_a_placeholder() { + let st = WalletSelectState::from_rows(vec![row("fresh", ID_A, "", 1_789_963_705)]); + let body = wallet_select_text(78, 21, &st); + let row_line = body + .lines() + .find(|l| l.contains("fresh")) + .expect("wallet row"); + assert!( + row_line.contains("2026-09-21"), + "an empty locator pushed the row out of shape: {row_line:?}" + ); + assert!( + row_line.contains(" - "), + "an unpublished locator has no placeholder: {row_line:?}" + ); + assert!( + !body.to_lowercase().contains("error") && !body.to_lowercase().contains("failed"), + "an unpublished locator read as a failure:\n{body}" + ); +} + +/// Empty, failed and in-flight reads are three different states, and none of +/// them is a blank pane. All three still offer the create row. +#[test] +fn wallet_select_words_the_empty_error_and_reading_states() { + let empty = wallet_select_text(78, 21, &WalletSelectState::default()); + assert!(empty.contains("no saved wallets"), "\n{empty}"); + assert!(empty.contains("create new wallet"), "\n{empty}"); + + let failed = wallet_select_text( + 78, + 21, + &WalletSelectState::error("store lock poisoned".into()), + ); + assert!(failed.contains("could not read"), "\n{failed}"); + assert!(failed.contains("store lock poisoned"), "\n{failed}"); + assert!(failed.contains("create new wallet"), "\n{failed}"); + // A failed read must not read as "you have no wallets". + assert!(!failed.contains("no saved wallets"), "\n{failed}"); + + let reading = wallet_select_text(78, 21, &WalletSelectState::reading()); + assert!(reading.contains("reading"), "\n{reading}"); + assert!(reading.contains("create new wallet"), "\n{reading}"); +} + +/// The whole point of a prefix is that the row cannot outgrow the pane: a row +/// with a name wide enough to swallow the table still truncates in cells. +#[test] +fn wallet_select_truncates_a_wide_name_in_cells() { + let st = WalletSelectState::from_rows(vec![row( + "私のウォレットはとても長い名前を持っています", + ID_A, + ONION_A, + 1_789_963_705, + )]); + let body = wallet_select_text(78, 21, &st); + assert!( + body.contains("私の"), + "a CJK name was dropped entirely:\n{body}" + ); + assert!( + body.contains('…') || body.contains("..."), + "a long name was clipped without an ellipsis:\n{body}" + ); + for line in body.lines() { + assert!( + cell_width(line) <= 78, + "line wider than the pane: {} cells: {line:?}", + cell_width(line) + ); + } +} + +/// Every body line fits the pane it was laid out for, from well under the +/// 80-column floor to 200 — trailing columns drop, nothing wraps. +#[test] +fn wallet_select_columns_drop_before_they_wrap() { + for w in 20u16..=200 { + for state in [ + two_wallets(), + WalletSelectState::default(), + WalletSelectState::error("store lock poisoned".into()), + WalletSelectState::reading(), + ] { + for line in wallet_select_lines(w, 21, &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:?}"); + } + } + } +} + +/// A long list windows and says how many rows are out of view; the create row +/// is never the row that falls off. +#[test] +fn wallet_select_windows_a_long_list_and_keeps_create_visible() { + let rows: Vec = (0..40) + .map(|i| row(&format!("w{i:02}"), ID_A, ONION_A, 1_789_963_705)) + .collect(); + let mut st = WalletSelectState::from_rows(rows); + let body = wallet_select_text(78, 21, &st); + assert!(body.contains("below"), "window not disclosed:\n{body}"); + assert!( + body.contains("w00"), + "the first row is not on screen:\n{body}" + ); + assert!(!body.contains("w39"), "\n{body}"); + assert!( + body.lines().last().unwrap_or_default().contains("create"), + "the create row was pushed off the pane:\n{body}" + ); + + for _ in 0..39 { + st.select_next(); + } + let body = wallet_select_text(78, 21, &st); + assert!( + body.contains("w39"), + "the last row never came into view:\n{body}" + ); + assert!(body.contains("above"), "window not disclosed:\n{body}"); + assert!( + body.lines().last().unwrap_or_default().contains("create"), + "the create row was pushed off the pane:\n{body}" + ); + assert_eq!(st.choice(), WalletChoice::Open(39)); +} + +/// The screen is not a sink for peer bytes: a label is untrusted display data. +#[test] +fn wallet_select_hostile_label_cannot_reach_the_terminal() { + let hostile = "safe\u{1b}[31mred\u{7}\u{202e}\u{2066}\u{9b}\nrow\ttab"; + let st = WalletSelectState::from_rows(vec![row(hostile, ID_A, ONION_A, 1_789_963_705)]); + for (w, h) in [(80u16, 24u16), (120, 40)] { + let screen = render(w, h, &st); + for (what, ch) in [ + ("ESC", '\u{1b}'), + ("BEL", '\u{7}'), + ("C1", '\u{9b}'), + ("bidi", '\u{202e}'), + ("bidi isolate", '\u{2066}'), + ] { + assert!(!screen.contains(ch), "{w}x{h}: {what} reached the frame"); + } + assert!(screen.contains("safe"), "{w}x{h}:\n{screen}"); + } + let body = wallet_select_text(78, 21, &st); + assert!(body.contains("safe[31mred"), "\n{body}"); + assert_eq!( + body.lines().filter(|l| l.contains("safe[31mred")).count(), + 1, + "the hostile label split or duplicated a row:\n{body}" + ); +} + +/// Days from unix seconds, UTC, without a date crate — including a leap day and +/// the epoch, which reads as "unknown" rather than 1970-01-01. +#[test] +fn format_day_utc_covers_the_calendar_edges() { + for (secs, want) in [ + (0i64, "unknown"), + (-1, "unknown"), + (1, "1970-01-01"), + (86_400, "1970-01-02"), + (951_782_400, "2000-02-29"), + (1_700_000_000, "2023-11-14"), + (1_789_963_705, "2026-09-21"), + ] { + assert_eq!(format_day_utc(secs), want, "{secs}"); + } +} + +/// The app renders this screen's one status line with `status_footer_phased` +/// and `footer_hints`; the fixture does the same, so a dumped frame can never +/// show a footer the app does not draw. +fn render(w: u16, h: u16, st: &WalletSelectState) -> String { + let backend = TestBackend::new(w, h); + let mut terminal = Terminal::new(backend).expect("terminal"); + let footer = status_footer_phased( + w, + FP, + ONION, + Some(TorPhase::Ready), + None, + wallet_select_footer_hint(), + ); + terminal + .draw(|f| draw_wallet_select(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 wallet_select_frame_shows_the_shipped_footer() { + let shipped = status_footer_phased( + 80, + FP, + ONION, + Some(TorPhase::Ready), + None, + wallet_select_footer_hint(), + ); + let frame = render(80, 24, &two_wallets()); + let last = frame.lines().nth(23).unwrap_or_default(); + assert_eq!( + last.trim_end(), + shipped.trim_end(), + "the dumped frame's footer is not the one the app renders" + ); +} + +#[test] +fn wallet_select_frames_fit_at_the_three_sizes() { + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + let screen = render(w, h, &two_wallets()); + for needle in [ + "(o) wallets", + "2 saved", + "lance", + "2026-09-21", + "create new wallet", + "? help", + ] { + assert!( + screen.contains(needle), + "{w}x{h} missing {needle:?}:\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 = wallet_select_lines(w - 2, h - 3, &two_wallets()); + assert!( + lines.len() <= (h - 3) as usize, + "body needs {} rows, {w}x{h} shows {}", + lines.len(), + h - 3 + ); + } + // 200x60 fits the whole identity and locator in the detail strip. + let wide = render(200, 60, &two_wallets()); + assert!( + wide.contains(ID_A), + "200x60 truncated the identity:\n{wide}" + ); + assert!( + wide.contains(ONION_A), + "200x60 truncated the locator:\n{wide}" + ); +} + +#[test] +fn wallet_select_frame_dumps() { + for (w, h) in [(80u16, 24u16), (120, 40), (200, 60)] { + println!("===== WALLETS {w}x{h} ====="); + print!("{}", render(w, h, &two_wallets())); + println!("===== WALLETS (empty) {w}x{h} ====="); + print!("{}", render(w, h, &WalletSelectState::default())); + println!("===== WALLETS (failed read) {w}x{h} ====="); + print!( + "{}", + render( + w, + h, + &WalletSelectState::error("store lock poisoned".into()) + ) + ); + } +}