diff --git a/docs/TUI.md b/docs/TUI.md index a763944..9c52c70 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -23,7 +23,6 @@ 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 | @@ -110,13 +109,12 @@ Pane-specific (`pane_footer_hints`): Footer: ``` -c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help +c create i import r qr 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 | @@ -135,39 +133,6 @@ 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 -`Node::list_wallets`; the render path never reads the store. Selection is by -row index, not by identity key (two records may share one). - -The list is read when the screen opens — from the start screen and from -`F6` `w` — so a wallet created or imported in this session is offered the next -time the screen opens, with no restart. Enter on a wallet row re-points the -app-owned wallet child at that row's `wallet_filename` (`Node::open_wallet`, -a read-modify-write of the sealed record, so the generated RPC creds survive); -a running child is restarted onto the new file, and an idle one picks the -change up on its next start. - -**Start screen.** An install with at least one saved wallet opens on -`WalletSelect`; a fresh install (empty catalogue) opens on the create flow -(`WalletSetup::CreateWarn`), so the first run has no dead empty list. The -stored identity and locator are catalogue columns, not session state: a locator -rotates (`F4`) and identity is the roster key the node already holds, so the -live header keeps reading them from the node. - ## Wallets & settings (`F9` / `/settings`) Discovery layer, not a replacement. Function keys stay live on this screen. @@ -215,5 +180,4 @@ 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/node.rs b/src/node.rs index fef5b8f..120696b 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1251,37 +1251,6 @@ impl Node { .map_err(|e| e.to_string()) } - /// Switch the wallet child to a catalogue wallet's file. - /// - /// The catalogue is the only directory this app has, so a file it does not - /// hold is refused instead of pointing a spend-capable child at a path. A - /// running child is restarted onto the new file; an idle one is only - /// re-pointed, and the change applies on the next `start_wallet_child`. The - /// write is a read-modify-write, so the generated RPC creds survive. - pub fn open_wallet(&self, filename: &str) -> Result<(), String> { - if !self - .list_wallets()? - .iter() - .any(|w| w.wallet_filename == filename) - { - return Err(format!("no saved wallet in {filename}")); - } - let running = self - .wallet_child - .lock() - .map_err(|e| e.to_string())? - .as_ref() - .is_some_and(|child| child.wallet_rpc_running()); - if running { - self.stop_wallet_child()?; - } - self.point_child_at(filename)?; - if running { - self.start_wallet_child()?; - } - Ok(()) - } - /// The file name a wallet created now should live in. `wallet_filename` is /// UNIQUE and the catalogue is the only directory the app has, so this is /// `-` for the first `n` the catalogue does not already hold. @@ -2021,42 +1990,7 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool { } #[cfg(test)] -/// A catalogue row written straight into the store, for tests that need a saved -/// wallet without a wallet RPC. -pub(crate) fn test_record_wallet(store: &Store, file: &str, label: &str) { - let identity_pubkey: [u8; 32] = store - .self_identity() - .expect("self identity") - .identity_pk - .try_into() - .expect("32-byte identity"); - store - .create_wallet(&NewWallet { - name: (!label.trim().is_empty()).then(|| label.to_string()), - identity_pubkey, - onion_locator: format!("{file}.onion"), - wallet_filename: file.to_string(), - }) - .expect("create wallet"); -} - -/// A real `Node` with no Tor and a seeded wallet catalogue, for the TUI's own -/// tests: `App` reads the catalogue, and the only public `Node` constructor -/// bootstraps Tor. `wallets` is `(file name, label)` — a blank label is stored -/// as `NULL`, like a wallet created without one. -#[cfg(test)] -pub(crate) fn test_node_with_wallets(home: &Path, wallets: &[(&str, &str)]) -> Arc { - { - let store = Store::open_at_with_passphrase(home, tests::PASS).expect("open store"); - for (file, label) in wallets { - test_record_wallet(&store, file, label); - } - } - Arc::new(tests::offline_node(home, Arc::new(tests::NoDial))) -} - -#[cfg(test)] -pub(crate) mod tests { +mod tests { use super::*; use crate::wallet_child::DEFAULT_MONEROD_RPC_PORT; use std::pin::Pin; @@ -2068,11 +2002,11 @@ pub(crate) mod tests { use tokio::io::AsyncRead as TokioRead; use tokio::io::AsyncWrite as TokioWrite; - pub(crate) const PASS: &str = "node-ratchet-test-pass"; + const PASS: &str = "node-ratchet-test-pass"; /// Never dials: every send queues, which is what leaves the encoded frame /// visible on the outbox row. - pub(crate) struct NoDial; + struct NoDial; impl crate::outbox::Deliverer for NoDial { fn deliver<'a>( @@ -2129,7 +2063,7 @@ pub(crate) mod tests { /// are the only public constructors and both bootstrap Tor and publish an /// onion service, so this is the only way to drive the shipped send and /// receive path offline. - pub(crate) fn offline_node(home: &Path, deliverer: Arc) -> Node { + fn offline_node(home: &Path, deliverer: Arc) -> Node { offline_node_with_wallet(home, deliverer, Wallet::disabled()) } @@ -3270,96 +3204,4 @@ pub(crate) mod tests { .expect_err("no wallet RPC"); assert!(err.contains("ONIONWIRE_WALLET_RPC"), "{err}"); } - - /// Switching wallets is a catalogue read plus a child re-point: the chosen - /// row's file name is what the child opens, and the generated RPC creds in - /// the same sealed record survive the read-modify-write. - #[tokio::test] - async fn open_wallet_points_the_child_at_the_chosen_file_and_keeps_the_creds() { - let dir = tempfile::tempdir().unwrap(); - let home = dir.path().join("bob"); - let node = offline_node(&home, Arc::new(NoDial)); - { - let store = node.store.lock().unwrap(); - store - .save_wallet_child( - r#"{"user":"owuser","pass":"ow-secret-pass-xyz","wallet_filename":"onionwire"}"#, - ) - .unwrap(); - for file in ["onionwire", "onionwire-1"] { - store - .create_wallet(&NewWallet { - name: None, - identity_pubkey: [7u8; 32], - onion_locator: "abcd.onion".into(), - wallet_filename: file.to_string(), - }) - .unwrap(); - } - } - - node.open_wallet("onionwire-1") - .expect("open a saved wallet"); - assert_eq!( - node.wallet_child_config().wallet_filename, - "onionwire-1", - "the child must open the wallet that was chosen" - ); - let sealed = node - .store - .lock() - .unwrap() - .load_wallet_child() - .unwrap() - .expect("sealed record"); - assert!( - sealed.contains("ow-secret-pass-xyz"), - "the re-point dropped the generated creds: {sealed}" - ); - assert!( - sealed.contains("\"user\":\"owuser\""), - "the re-point dropped the generated creds: {sealed}" - ); - - // A restart re-reads the record, so the choice is remembered. - drop(node); - let restarted = offline_node(&home, Arc::new(NoDial)); - assert_eq!( - restarted.wallet_child_config().wallet_filename, - "onionwire-1", - "the chosen wallet must survive a restart" - ); - } - - /// The catalogue is the only directory the app has, so a file it does not - /// hold is refused instead of pointing a spend-capable child at a path. - #[tokio::test] - async fn open_wallet_refuses_a_file_the_catalogue_does_not_hold() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); - { - let store = node.store.lock().unwrap(); - store - .save_wallet_child(r#"{"user":"owuser","pass":"p","wallet_filename":"onionwire"}"#) - .unwrap(); - store - .create_wallet(&NewWallet { - name: None, - identity_pubkey: [7u8; 32], - onion_locator: String::new(), - wallet_filename: "onionwire".to_string(), - }) - .unwrap(); - } - - let err = node - .open_wallet("onionwire-9") - .expect_err("not a saved wallet"); - assert!(err.contains("no saved wallet"), "{err}"); - assert_eq!( - node.wallet_child_config().wallet_filename, - "onionwire", - "a refused switch must leave the child where it was" - ); - } } diff --git a/src/tui.rs b/src/tui.rs index 8251985..b14994c 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -17,9 +17,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, Payment, WalletRecord, -}; +use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus, Payment}; use crate::wallet::{self, ChainNetwork, ChainSource}; const C_ACCENT: Color = Color::Rgb(232, 165, 75); @@ -1290,12 +1288,6 @@ 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, }, @@ -1350,27 +1342,12 @@ fn function_key_for(screen: &Screen, code: KeyCode) -> Option { impl App { fn new(node: Arc, rt: tokio::runtime::Handle) -> Result { let friends = node.list_friends()?; - // First run is the create flow, not an empty list to pick from; an - // install that already has wallets starts on the list, so a restart - // lands on the wallets it remembers. A catalogue that cannot be read is - // the screen's own error state (the create row still works there). - let screen = match node.list_wallets() { - Ok(rows) if rows.is_empty() => Screen::WalletSetup(WalletSetup::CreateWarn { - typed: String::new(), - }), - Ok(rows) => Screen::WalletSelect { - state: WalletSelectState::from_rows(wallet_rows(rows)), - }, - Err(e) => Screen::WalletSelect { - state: WalletSelectState::error(e), - }, - }; Ok(Self { me_fp: to_hex(&node.identity_pk()), me_onion: node.onion(), node, rt, - screen, + screen: Screen::Main, friends, selected: 0, alert: None, @@ -1448,9 +1425,6 @@ 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 @@ -1692,9 +1666,6 @@ 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(), @@ -1727,13 +1698,6 @@ 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') { @@ -1765,22 +1729,6 @@ 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()?; } @@ -2089,73 +2037,6 @@ impl App { Ok(()) } - /// Enter on the wallet selection screen: `create new wallet` starts the - /// existing creation flow, and a wallet row switches the wallet child to - /// that row's file. - /// - /// `WalletChoice::Open` carries a **row index**, so it is resolved against - /// the catalogue as it is now, not against anything the screen cached: two - /// saved wallets may share an identity key, and only the position (then the - /// row's own `wallet_filename`) names one. A list that changed under the - /// screen is reported rather than silently opening the wrong wallet. - 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(index) => { - let opened = self.select_wallet(index); - match opened { - Ok(label) => { - self.status_note = Some(format!("opened wallet {label}")); - self.screen = Screen::Main; - } - Err(e) => self.alert = Some(e), - } - } - } - Ok(()) - } - - /// Load the catalogue row at `index` into the session: point the wallet - /// child at that wallet's file (and restart it if it was running), then read - /// the list back so the screen never shows a stale catalogue. - /// - /// The stored identity and locator are not pushed into the session: they are - /// the identity/locator *at creation* (a locator rotates, and the identity is - /// the roster key this node already holds), so the live values keep coming - /// from the node. Returns the label to report. - fn select_wallet(&mut self, index: usize) -> Result { - let row = self - .node - .list_wallets()? - .into_iter() - .nth(index) - .ok_or_else(|| "the saved wallets changed — reopen the list".to_string())?; - self.node.open_wallet(&row.wallet_filename)?; - Ok(wallet_label(&row)) - } - - /// F6 `w`: the wallet selection screen, read from the catalogue now. - /// - /// The rows come from the wallet store ([`Node::list_wallets`]) at the - /// moment the screen opens — never cached from startup — so a wallet created - /// in this session shows up on the next look. A read that fails is the - /// screen's own error state, which is not the same word as "no saved - /// wallets": the `create new wallet` row stays reachable either way. - fn open_wallet_select(&mut self) { - let state = match self.node.list_wallets() { - Ok(records) => WalletSelectState::from_rows(wallet_rows(records)), - Err(e) => WalletSelectState::error(e), - }; - self.screen = Screen::WalletSelect { state }; - } - /// `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. @@ -2697,17 +2578,6 @@ 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()); @@ -3323,7 +3193,7 @@ match screen { }, Screen::Passphrase { .. } => "Enter submit Esc cancel ? help", Screen::Wallet { .. } => { - "c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help" + "c create i import r qr 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 { .. }) => { @@ -3333,7 +3203,6 @@ 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", } } @@ -4482,523 +4351,6 @@ 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, - } - } -} - -/// Catalogue rows, display-ready and in store order (oldest first). -/// -/// The mapping is the one documented on [`WalletRow`]: a `NULL` label is the -/// empty string (the screen says `(unlabelled)`), the identity column is -/// `[u8; 32]` and is hex-encoded here, the locator passes through (empty until -/// the HS publishes), and `created_at` is unix seconds. `wallet_filename` is -/// not carried: it is not on the screen. The rows stay index-aligned with the -/// catalogue, which is how [`WalletChoice::Open`] resolves. -pub fn wallet_rows(records: Vec) -> Vec { - records - .into_iter() - .map(|r| WalletRow { - name: r.name.unwrap_or_default(), - identity_pubkey: to_hex(&r.identity_pubkey), - onion_locator: r.onion_locator, - created_at: r.created_at, - }) - .collect() -} - -/// What to call a saved wallet in a status line: its label, or the file when it -/// has none (a blank label is stored as `NULL`). -fn wallet_label(r: &WalletRecord) -> String { - r.name - .as_deref() - .map(str::trim) - .filter(|n| !n.is_empty()) - .unwrap_or(&r.wallet_filename) - .to_string() -} - -/// 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"; - /// 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. @@ -5299,26 +4651,6 @@ 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] @@ -5404,169 +4736,3 @@ mod passphrase_buffer_tests { ); } } - -/// The wallet selection screen against a real store-backed node: the rows come -/// from the catalogue, a choice loads that wallet, and the start screen depends -/// on whether any wallet is remembered. -#[cfg(test)] -mod wallet_store_tests { - use super::*; - use crate::node::{test_node_with_wallets, test_record_wallet}; - - const PASS: &str = crate::node::tests::PASS; - - /// A real node (no Tor) over a seeded catalogue, plus the runtime the app - /// holds a handle to. `wallets` is `(file name, label)`; a blank label is a - /// wallet with no name, like one created from the app. - fn app(home: &std::path::Path, wallets: &[(&str, &str)]) -> (App, tokio::runtime::Runtime) { - let rt = tokio::runtime::Runtime::new().expect("tokio runtime"); - // The offline node's unbootstrapped Arti client needs a runtime context - // to be built (the same reason the node tests are `#[tokio::test]`). - let _guard = rt.enter(); - let node = test_node_with_wallets(home, wallets); - let app = App::new(node, rt.handle().clone()).expect("app"); - (app, rt) - } - - fn select_rows(app: &App) -> Vec { - let Screen::WalletSelect { state } = &app.screen else { - panic!("not on the wallet selection screen"); - }; - state - .rows - .iter() - .map(|r| r.name.clone()) - .collect::>() - } - - /// Nothing remembered means there is no list to choose from: the first run - /// goes straight to the existing creation flow. - #[test] - fn an_install_with_no_wallet_starts_on_the_create_flow() { - let dir = tempfile::tempdir().unwrap(); - let (app, _rt) = app(&dir.path().join("home"), &[]); - assert!( - matches!( - app.screen, - Screen::WalletSetup(WalletSetup::CreateWarn { .. }) - ), - "a first run must start on the create flow" - ); - } - - /// A restart lands on the wallets it remembers, and each row carries the - /// catalogue's own fields (label, hex identity, locator, creation time). - #[test] - fn an_install_with_wallets_starts_on_the_list_read_from_the_catalogue() { - let dir = tempfile::tempdir().unwrap(); - let (app, _rt) = app( - &dir.path().join("home"), - &[("onionwire", "lance"), ("onionwire-1", "")], - ); - let Screen::WalletSelect { state } = &app.screen else { - panic!("saved wallets must start on the selection screen"); - }; - assert!(state.error.is_none(), "{:?}", state.error); - assert!(!state.reading); - assert_eq!( - state.rows.len(), - 2, - "two saved wallets, plus the create row" - ); - assert_eq!(state.rows[0].name, "lance"); - assert_eq!(state.rows[1].name, ""); - assert_eq!( - state.rows[0].identity_pubkey, - to_hex(&app.node.identity_pk()) - ); - assert_eq!(state.rows[0].identity_pubkey.len(), 64, "hex, not bytes"); - assert_eq!(state.rows[0].onion_locator, "onionwire.onion"); - assert!(state.rows[0].created_at > 0, "creation time is real"); - assert_eq!(state.choice(), WalletChoice::Open(0)); - } - - /// The choice is a row index into a list whose records may share an - /// identity key, so the second row must open the second wallet's file. - #[test] - fn choosing_a_row_opens_that_wallets_file_not_the_first_identity_match() { - let dir = tempfile::tempdir().unwrap(); - let (mut app, _rt) = app( - &dir.path().join("home"), - &[("onionwire", "lance"), ("onionwire-1", "cold")], - ); - { - let Screen::WalletSelect { state } = &mut app.screen else { - panic!("not on the selection screen"); - }; - state.select_next(); - assert_eq!(state.choice(), WalletChoice::Open(1)); - } - - app.choose_wallet().expect("choosing a saved wallet"); - - assert!( - matches!(app.screen, Screen::Main), - "a loaded wallet returns to the main view" - ); - assert_eq!( - app.node.wallet_child_config().wallet_filename, - "onionwire-1", - "the child must open the wallet under the marker" - ); - assert_eq!(app.status_note.as_deref(), Some("opened wallet cold")); - } - - /// The last item is not a wallet: Enter on it starts the creation flow. - #[test] - fn the_create_row_starts_the_creation_flow() { - let dir = tempfile::tempdir().unwrap(); - let (mut app, _rt) = app(&dir.path().join("home"), &[("onionwire", "lance")]); - { - let Screen::WalletSelect { state } = &mut app.screen else { - panic!("not on the selection screen"); - }; - state.select_next(); - assert_eq!(state.choice(), WalletChoice::Create); - } - app.choose_wallet().expect("choosing create"); - assert!(matches!( - app.screen, - Screen::WalletSetup(WalletSetup::CreateWarn { .. }) - )); - } - - /// The list is read when the screen opens, never cached from startup, so a - /// wallet recorded in this session is offered the next time — that is what - /// makes a create show up without a restart. - #[test] - fn a_wallet_recorded_after_startup_appears_the_next_time_the_list_opens() { - let dir = tempfile::tempdir().unwrap(); - let home = dir.path().join("home"); - let (mut app, _rt) = app(&home, &[]); - assert!(matches!(app.screen, Screen::WalletSetup(_))); - assert!( - app.node.list_wallets().expect("list wallets").is_empty(), - "nothing to list yet" - ); - - { - // The create path writes exactly this row (a `wallets` entry keyed - // on the file it just made). - let store = - crate::store::Store::open_at_with_passphrase(&home, PASS).expect("open store"); - test_record_wallet(&store, "onionwire-1", "fresh"); - } - - // F6 `w`. - app.open_wallet_select(); - assert_eq!(select_rows(&app), vec!["fresh".to_string()]); - - // And switching to it works from the screen the user is looking at. - app.choose_wallet().expect("open the new wallet"); - assert_eq!( - app.node.wallet_child_config().wallet_filename, - "onionwire-1" - ); - assert_eq!(app.status_note.as_deref(), Some("opened wallet fresh")); - } -} diff --git a/tests/tui_select.rs b/tests/tui_select.rs deleted file mode 100644 index 7447ec1..0000000 --- a/tests/tui_select.rs +++ /dev/null @@ -1,475 +0,0 @@ -//! 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()) - ) - ); - } -}