onionwire/tests/tui_frames.rs

1310 lines
44 KiB
Rust
Raw Permalink Normal View History

//! Visual audit dumps of the current OnionWire TUI.
//!
//! This crate cannot construct `App` (private, needs `Node` / Arti). Public
//! draw path used where it exists (`draw_share`, chrome helpers, overlay copy).
//! Main / profile / confirm screens labeled RECONSTRUCTED copy the layout
//! constants and copy from `src/tui.rs` so a reviewer can see the shape.
//!
//! Print frames:
//! cargo test --locked --test tui_frames -- --nocapture dump_audit_frames
//!
//! `chars().count()` width checks here match `tests/tui_chrome.rs` on purpose.
//! They are the known-wrong metric (see `chars_count_is_not_terminal_cells`).
use onionwire::qr;
use onionwire::node::{DaemonSync, WalletChildState};
use onionwire::Payment;
use onionwire::tui::{
backup_screen_text, banner_for_width, chain_view, compact_banner, draw_history, draw_share,
draw_wallet, fingerprint_mismatch_banner, help_overlay_text, main_footer_hints, onion_glyph,
osc52_copy, quit_screen_text, restore_screen_text, rotate_screen_text, status_footer,
wallet_readiness, wallet_view, who_overlay_text, wipe_screen_text, wordmark_banner,
ChainChoice, ProfileEditor, WalletReadiness, WALLET_LINE_MAX, WipeKind,
};
use onionwire::wallet::ChainSource;
use onionwire::FriendProfile;
use ratatui::backend::TestBackend;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap};
use ratatui::Frame;
use ratatui::Terminal;
const SIZES: [(u16, u16); 3] = [(80, 24), (120, 40), (200, 60)];
const FP: &str = "abcdef0123456789deadbeefcafebabe";
const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion";
const LONG_MSG: &str = "them: this is a very long chat line that should wrap inside the chat pane instead of running off the right edge of an 80-column terminal and colliding with the roster border";
struct FriendRow {
name: &'static str,
fp: &'static str,
last_ok: bool,
}
fn fp8(s: &str) -> String {
s.chars().take(8).collect()
}
struct MainStandin<'a> {
friends: &'a [FriendRow],
selected: usize,
chat_lines: &'a [&'a str],
composer: &'a str,
alert: Option<&'a str>,
status_note: Option<&'a str>,
}
fn dump_buffer(label: &str, w: u16, h: u16, buf: &ratatui::buffer::Buffer) {
println!();
println!("===== {label} {w}x{h} =====");
for y in 0..h {
let mut row = String::new();
for x in 0..w {
row.push_str(buf[(x, y)].symbol());
}
let cells = row.chars().count();
assert!(
cells <= w as usize,
"{label} row {y} chars().count()={cells} > {w}: {row:?}"
);
println!("{row}");
}
}
fn draw_to(w: u16, h: u16, label: &str, render: impl FnOnce(&mut Frame)) {
let backend = TestBackend::new(w, h);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal.draw(render).expect("draw");
dump_buffer(label, w, h, terminal.backend().buffer());
}
fn pane_block(title: &str) -> Block<'_> {
// Real `App::pane_block` only changes border/title color. TestBackend
// dumps are glyphs, so focused chat/composer look identical to unfocused.
Block::default().borders(Borders::ALL).title(title)
}
/// Layout constants copied from `App::draw_main` (`src/tui.rs`).
impl MainStandin<'_> {
fn draw(self, f: &mut Frame) {
let friends = self.friends;
let selected = self.selected;
let chat_lines = self.chat_lines;
let composer = self.composer;
let alert = self.alert;
let status_note = self.status_note;
let area = f.area();
let banner = banner_for_width(area.width);
let banner_h = banner.lines().count() as u16;
let alert_h = u16::from(alert.is_some());
let cols = Layout::vertical([
Constraint::Length(banner_h),
Constraint::Length(alert_h),
Constraint::Min(3),
Constraint::Length(3),
Constraint::Length(1),
])
.split(area);
f.render_widget(Paragraph::new(banner), cols[0]);
if let Some(msg) = alert {
f.render_widget(Paragraph::new(msg), cols[1]);
}
let panes =
Layout::horizontal([Constraint::Percentage(36), Constraint::Min(10)]).split(cols[2]);
let stale_n = friends.iter().filter(|fr| !fr.last_ok).count();
let roster_title = if stale_n > 0 {
format!("roster {} {stale_n} stale", friends.len())
} else {
format!("roster {}", friends.len())
};
let items: Vec<ListItem> = friends
.iter()
.map(|friend| {
let mut line = format!("{} {}…", friend.name, fp8(friend.fp));
if !friend.last_ok {
line.push_str(" stale");
}
ListItem::new(line)
})
.collect();
let roster = List::new(items)
.highlight_symbol("> ")
.block(pane_block(&roster_title));
let mut roster_state = ListState::default();
if !friends.is_empty() {
roster_state.select(Some(selected));
}
f.render_stateful_widget(roster, panes[0], &mut roster_state);
let inner_h = panes[1].height.saturating_sub(2);
let nlines = chat_lines.len();
let overflow = nlines > inner_h as usize && inner_h > 0;
let chat_title = {
let mut t = match friends.get(selected) {
Some(fr) => format!("chat {}", fr.name),
None => "chat".to_string(),
};
if overflow {
let end = inner_h as usize;
t.push_str(&format!(" 1-{end}/{nlines}"));
}
t
};
f.render_widget(
Paragraph::new(chat_lines.join("\n"))
.wrap(Wrap { trim: false })
.block(pane_block(&chat_title)),
panes[1],
);
let cmd = if composer.is_empty() {
"/wipe /wipe-all /profile /who /pay /tip /file".to_string()
} else {
composer.to_string()
};
f.render_widget(Paragraph::new(cmd).block(pane_block("composer")), cols[3]);
let footer = status_footer(area.width, FP, ONION, status_note, main_footer_hints());
f.render_widget(Paragraph::new(footer), cols[4]);
}
}
/// Rect math copied from private `draw_text_overlay` (`src/tui.rs`).
fn draw_text_overlay_standin(f: &mut Frame, title: &str, text: &str) {
let area = f.area();
let lines = text.lines().count() as u16 + 2;
let text_w = text
.lines()
.map(|l| l.chars().count() as u16)
.max()
.unwrap_or(40)
.saturating_add(4);
let width = text_w.min(area.width.saturating_sub(2)).max(10);
let height = lines.min(area.height.saturating_sub(2)).max(3);
let popup = Rect {
x: area.x + (area.width.saturating_sub(width)) / 2,
y: area.y + (area.height.saturating_sub(height)) / 2,
width,
height,
};
f.render_widget(Clear, popup);
f.render_widget(
Paragraph::new(text).block(Block::default().borders(Borders::ALL).title(title)),
popup,
);
}
fn draw_overlay_screen(f: &mut Frame, title: &str, body: &str) {
f.render_widget(
Paragraph::new(body)
.wrap(Wrap { trim: false })
.block(Block::default().borders(Borders::ALL).title(title)),
f.area(),
);
}
fn sample_invite() -> String {
qr::encode(&[7u8; 32], ONION, &[1u8; 32]).expect("encode")
}
fn empty_chat_lines() -> &'static [&'static str] {
&["no friends yet", "F3 paste an invite to add one"]
}
#[test]
fn dump_audit_frames() {
let invite = sample_invite();
let friends = [
FriendRow {
name: "alice",
fp: "aaaaaaaaaaaaaaaa",
last_ok: true,
},
FriendRow {
name: "bob-the-stale-peer",
fp: "bbbbbbbbbbbbbbbb",
last_ok: false,
},
];
let chat_ok: [&str; 3] = ["you: ping", "them: pong", LONG_MSG];
let editor = ProfileEditor::new("lance", "tor messenger", "");
let profile_body = {
let labels = ["name", "bio", "xmr"];
let values = [editor.display_name(), editor.bio(), editor.xmr_addr()];
let mut body = String::from(
"Your profile (friend-visible)\nEnter saves Esc cancels Tab next field\n",
);
for (i, (label, value)) in labels.iter().zip(values).enumerate() {
let mark = if editor.field() == i { ">" } else { " " };
body.push_str(&format!("\n{mark} {label}: {value}"));
}
body
};
let who = who_overlay_text(
FP,
ONION,
Some(&FriendProfile {
display_name: "alice".into(),
bio: "hi".into(),
xmr_addr: String::new(),
updated_at: 0,
}),
);
let who_empty = who_overlay_text(FP, ONION, None);
println!("invite payload length (chars) = {}", invite.chars().count());
println!("wordmark:\n{}", wordmark_banner());
println!("compact: {}", compact_banner());
println!("onion_glyph:\n{}", onion_glyph());
println!(
"fingerprint_mismatch_banner: {}",
fingerprint_mismatch_banner()
);
for (w, h) in SIZES {
draw_to(w, h, "chrome banner+footer", |f| {
let banner = banner_for_width(f.area().width);
let banner_h = banner.lines().count() as u16;
let chunks = Layout::vertical([
Constraint::Length(banner_h),
Constraint::Min(3),
Constraint::Length(1),
])
.split(f.area());
f.render_widget(Paragraph::new(banner), chunks[0]);
let footer = status_footer(f.area().width, FP, ONION, None, main_footer_hints());
f.render_widget(Paragraph::new(footer), chunks[2]);
});
draw_to(w, h, "chrome long-onion + send-failed", |f| {
let banner = banner_for_width(f.area().width);
let banner_h = banner.lines().count() as u16;
let chunks = Layout::vertical([
Constraint::Length(banner_h),
Constraint::Min(3),
Constraint::Length(1),
])
.split(f.area());
f.render_widget(Paragraph::new(banner), chunks[0]);
let footer = status_footer(
f.area().width,
FP,
ONION,
Some("send failed: connection timed out"),
main_footer_hints(),
);
f.render_widget(Paragraph::new(footer), chunks[2]);
});
draw_to(w, h, "RECONSTRUCTED main empty", |f| {
MainStandin {
friends: &[],
selected: 0,
chat_lines: empty_chat_lines(),
composer: "",
alert: None,
status_note: None,
}
.draw(f);
});
draw_to(w, h, "RECONSTRUCTED main chat+stale", |f| {
MainStandin {
friends: &friends,
selected: 0,
chat_lines: &chat_ok,
composer: "hello from composer",
alert: Some("passphrases do not match"),
status_note: Some("sent"),
}
.draw(f);
});
draw_to(w, h, "RECONSTRUCTED main pay/file footer only", |f| {
MainStandin {
friends: &friends,
selected: 0,
chat_lines: &["you: /pay 0.1 coffee", "them: (no invoice pane exists)"],
composer: "",
alert: None,
status_note: Some("invoice sent"),
}
.draw(f);
});
draw_to(w, h, "RECONSTRUCTED main file-send-failed", |f| {
MainStandin {
friends: &friends,
selected: 1,
chat_lines: &["no messages"],
composer: "",
alert: None,
status_note: Some("send failed: peer onion down"),
}
.draw(f);
});
draw_to(w, h, "draw_share (real)", |f| draw_share(f, &invite));
draw_to(w, h, "RECONSTRUCTED help overlay on empty main", |f| {
MainStandin {
friends: &[],
selected: 0,
chat_lines: empty_chat_lines(),
composer: "",
alert: None,
status_note: None,
}
.draw(f);
draw_text_overlay_standin(f, "? help", help_overlay_text());
});
draw_to(w, h, "RECONSTRUCTED /who overlay", |f| {
MainStandin {
friends: &friends,
selected: 0,
chat_lines: &chat_ok,
composer: "",
alert: None,
status_note: None,
}
.draw(f);
draw_text_overlay_standin(f, "/who", &who);
});
draw_to(w, h, "RECONSTRUCTED profile", |f| {
draw_overlay_screen(f, "(o) profile", &profile_body);
});
draw_to(w, h, "RECONSTRUCTED paste", |f| {
draw_overlay_screen(
f,
"(o) paste invite",
&format!("paste onionwire:v1 payload, Enter to submit\n\n{invite}"),
);
});
draw_to(w, h, "RECONSTRUCTED paste error", |f| {
draw_overlay_screen(f, "(o) paste invite", "bad invite\n\nnot-a-payload");
});
draw_to(w, h, "RECONSTRUCTED approve", |f| {
draw_overlay_screen(
f,
"(o) approve",
&format!(
"Unknown key. Add this friend?\n\nfp {}…\nonion {ONION}\n\ny accept n / Esc reject",
fp8(FP)
),
);
});
draw_to(w, h, "RECONSTRUCTED rotate", |f| {
draw_overlay_screen(
f,
"(o) rotate locator",
&format!("{}\n\nROT", rotate_screen_text()),
);
});
draw_to(w, h, "RECONSTRUCTED wipe", |f| {
draw_overlay_screen(
f,
"(o) wipe",
&format!("{}\n\nWI", wipe_screen_text(WipeKind::Messages)),
);
});
draw_to(w, h, "RECONSTRUCTED wipe-all", |f| {
draw_overlay_screen(
f,
"(o) wipe all",
&format!("{}\n\n", wipe_screen_text(WipeKind::All)),
);
});
draw_to(w, h, "RECONSTRUCTED quit", |f| {
draw_overlay_screen(f, "(o) quit", &format!("{}\n\nQUI", quit_screen_text()));
});
draw_to(w, h, "RECONSTRUCTED backup", |f| {
draw_overlay_screen(
f,
"(o) backup",
&format!("{}\n\nBACK", backup_screen_text()),
);
});
draw_to(w, h, "RECONSTRUCTED restore", |f| {
draw_overlay_screen(f, "(o) restore", &format!("{}\n\n", restore_screen_text()));
});
draw_to(w, h, "RECONSTRUCTED passphrase", |f| {
draw_overlay_screen(
f,
"(o) passphrase",
"Enter passphrase\n\n****\n\nEnter submit Esc cancel",
);
});
draw_to(w, h, "who copy (no profile)", |f| {
draw_overlay_screen(f, "/who", &who_empty);
});
// --- Wallet screen frames (real draw_wallet) ---
// receive-only
let receive_only = chain_view(
&ChainSource::None,
WalletChildState::Off,
&DaemonSync {
reachable: false,
height: 0,
target_height: 0,
note: Some("receive-only: no daemon".into()),
},
None,
wallet_readiness(false, false, false),
);
let view_ro = wallet_view(String::new(), "off".to_string(), Vec::new(), receive_only, false);
draw_to(w, h, "wallet receive-only", |f| {
draw_wallet(f, &view_ro, None, None);
});
// local synced
let synced = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, false),
);
let view_synced = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), synced, false);
draw_to(w, h, "wallet local synced", |f| {
draw_wallet(f, &view_synced, None, None);
});
// local syncing
let syncing = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 1_500_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, false),
);
let view_syncing = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), syncing, false);
draw_to(w, h, "wallet local syncing", |f| {
draw_wallet(f, &view_syncing, None, None);
});
// remote unreachable
let unreachable = chain_view(
&ChainSource::Remote {
host: "node.example.com".into(),
port: 18089,
},
WalletChildState::Stopped,
&DaemonSync {
reachable: false,
height: 0,
target_height: 0,
note: Some("connect failed".into()),
},
None,
wallet_readiness(true, false, false),
);
let view_ru = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), unreachable, false);
draw_to(w, h, "wallet remote unreachable", |f| {
draw_wallet(f, &view_ru, None, None);
});
// view-only badge
let vo = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, true),
);
let view_vo = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), vo, true);
draw_to(w, h, "wallet view-only badge", |f| {
draw_wallet(f, &view_vo, None, None);
});
// QR modal open
let qr_rows: Vec<String> = (0..20).map(|_| "██".repeat(20)).collect();
let modal = onionwire::tui::QrModal::test_new(false, qr_rows, address());
draw_to(w, h, "wallet qr modal", |f| {
draw_wallet(f, &view_synced, Some(&modal), None);
});
}
}
#[test]
fn public_copy_fits_80_by_chars_count() {
for (name, text) in [
("wordmark", wordmark_banner()),
("help", help_overlay_text()),
("rotate", rotate_screen_text()),
("quit", quit_screen_text()),
("wipe", wipe_screen_text(WipeKind::Messages)),
("wipe-all", wipe_screen_text(WipeKind::All)),
("backup", backup_screen_text()),
("restore", restore_screen_text()),
] {
for line in text.lines() {
assert!(
line.chars().count() <= 80,
"{name} line exceeds 80 by chars().count(): {line:?}"
);
}
}
assert!(compact_banner().chars().count() <= 40);
assert!(!onion_glyph().is_empty());
assert_eq!(fingerprint_mismatch_banner(), "fingerprint mismatch");
}
#[test]
fn footer_drops_full_onion_at_80_keeps_it_at_120() {
let at_80 = status_footer(80, FP, ONION, None, main_footer_hints());
let at_120 = status_footer(120, FP, ONION, None, main_footer_hints());
let at_200 = status_footer(200, FP, ONION, None, main_footer_hints());
assert!(at_80.chars().count() <= 80, "{at_80:?}");
assert!(at_120.chars().count() <= 120, "{at_120:?}");
assert!(at_200.chars().count() <= 200, "{at_200:?}");
assert!(
!at_80.contains(ONION),
"80-col footer should truncate onion: {at_80}"
);
assert!(
at_120.contains(ONION),
"120-col footer should keep full onion: {at_120}"
);
assert!(at_80.contains("? help") && at_120.contains("? help"));
}
/// Spec: never drop `send failed`. Keep `TOR` / `me:` / `? help` at 80 and 120.
#[test]
fn status_footer_drops_send_failed_when_crowded() {
let note = "send failed: peer onion down";
for (w, line) in [
(
80u16,
status_footer(80, FP, ONION, Some(note), main_footer_hints()),
),
(
120,
status_footer(120, FP, ONION, Some(note), main_footer_hints()),
),
(
200,
status_footer(200, FP, ONION, Some(note), main_footer_hints()),
),
] {
assert!(
line.chars().count() <= w as usize,
"{w} footer wider than frame: {} {line:?}",
line.chars().count()
);
assert!(
line.contains("send failed"),
"{w} dropped fail-closed note: {line:?}"
);
assert!(line.contains("TOR"), "{w} missing TOR: {line:?}");
assert!(line.contains("me:"), "{w} missing me:: {line:?}");
assert!(line.contains("? help"), "{w} missing ? help: {line:?}");
}
}
#[test]
fn share_invite_wraps_at_three_sizes() {
let invite = sample_invite();
for (w, h) in SIZES {
let backend = TestBackend::new(w, h);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal.draw(|f| draw_share(f, &invite)).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');
}
assert!(screen.contains("onionwire:v1:"), "{w}x{h}\n{screen}");
assert!(screen.contains("(o) invite"), "{w}x{h}\n{screen}");
}
}
/// Documented defect in `tests/tui_chrome.rs`: `chars().count()` is not cells.
/// Do not add `unicode-width` on this card.
#[test]
fn chars_count_is_not_terminal_cells() {
let cjk = "你好";
assert_eq!(cjk.chars().count(), 2, "CJK under-counts vs 4 wide cells");
let combining = "e\u{0301}";
assert_eq!(
combining.chars().count(),
2,
"combining mark over-counts vs 1 cell"
);
let emoji = "🧅";
assert_eq!(emoji.chars().count(), 1, "emoji under-counts vs 2 cells");
let ellipsis = "…";
assert_eq!(ellipsis.chars().count(), 1);
}
/// The F6 screen's not-ready state is a spec of this card, so this draws the
/// **real** `draw_wallet` at a fixed size and reads the cells back.
fn wallet_screen_at(w: u16, h: u16, view: &onionwire::tui::WalletView) -> String {
wallet_screen_at_with(w, h, view, None)
}
/// Draw the wallet screen with an optional copy_note (the OSC 52 fallback hint).
fn wallet_screen_at_with(
w: u16,
h: u16,
view: &onionwire::tui::WalletView,
copy_note: Option<&str>,
) -> String {
let backend = TestBackend::new(w, h);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| draw_wallet(f, view, None, copy_note))
.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
}
fn local_source() -> ChainSource {
ChainSource::Local {
monerod_bin: std::path::PathBuf::from("monerod"),
datadir: std::path::PathBuf::from("/home/user/.onionwire/chain"),
}
}
fn address() -> String {
"4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gB3aD".to_string()
}
#[test]
fn wallet_screen_says_not_ready_and_never_a_balance_before_sync() {
let chain = chain_view(
&local_source(),
WalletChildState::Stopped,
&DaemonSync {
reachable: false,
height: 0,
target_height: 0,
note: Some("127.0.0.1:18081: Connection refused (os error 111)".into()),
},
Some(412),
wallet_readiness(true, false, false),
);
let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, false);
assert_eq!(
view.balance, "not synced — unavailable",
"a balance must not be rendered as a fact while the wallet has not synced"
);
assert!(!view.chain.ready);
for line in view.chain.lines() {
assert!(
line.chars().count() <= WALLET_LINE_MAX,
"chain line exceeds {WALLET_LINE_MAX}: {line:?}"
);
}
let screen = wallet_screen_at(80, 24, &view);
for needle in [
"not ready: wallet RPC not answering",
"daemon: stopped — press n to start it",
"chain: local monerod",
"sync: unknown — 127.0.0.1:18081: Connection refused",
"storage: 412 GB free here",
"not synced — unavailable",
] {
assert!(screen.contains(needle), "wallet screen missing {needle:?}:\n{screen}");
}
// Nothing is clipped: every chain line survives whole.
for line in view.chain.lines() {
assert!(screen.contains(&line), "clipped line {line:?}:\n{screen}");
}
}
#[test]
fn wallet_screen_says_receive_only_when_nothing_is_configured() {
let chain = chain_view(
&ChainSource::None,
WalletChildState::Off,
&DaemonSync {
reachable: false,
height: 0,
target_height: 0,
note: Some("receive-only: no daemon".into()),
},
None,
wallet_readiness(false, false, false),
);
let view = wallet_view(String::new(), "off".to_string(), Vec::new(), chain, false);
let screen = wallet_screen_at(80, 24, &view);
for needle in [
"chain: receive-only",
"daemon: not configured — press s to choose a chain source",
"not ready: no wallet — receive-only until c create / i import",
"no address yet",
] {
assert!(screen.contains(needle), "wallet screen missing {needle:?}:\n{screen}");
}
}
#[test]
fn wallet_screen_keeps_the_balance_when_the_wallet_is_ready() {
let chain = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, false),
);
let view = wallet_view(
address(),
"12.5 XMR".to_string(),
Vec::new(),
chain,
false,
);
assert!(view.chain.ready);
assert_eq!(view.balance, "12.5 XMR");
let screen = wallet_screen_at(80, 24, &view);
assert!(screen.contains("ready: wallet synced"), "{screen}");
assert!(screen.contains("sync: synced — height 3210000"), "{screen}");
assert!(screen.contains("12.5 XMR"), "{screen}");
}
#[test]
fn a_view_only_wallet_says_so_instead_of_offering_a_spend() {
let readiness = wallet_readiness(true, true, true);
assert_eq!(readiness, WalletReadiness::ViewOnly);
assert!(!readiness.ready());
assert!(readiness.line().contains("view-only"));
}
#[test]
fn chain_choice_never_preselects_a_remote_daemon() {
for (source, want) in [
(ChainSource::None, ChainChoice::ReceiveOnly),
(local_source(), ChainChoice::LocalMonerod),
(
ChainSource::Remote {
host: "node.example.com".into(),
port: 18089,
},
ChainChoice::RemoteDaemon,
),
] {
assert_eq!(ChainChoice::of(&source), want);
}
assert_eq!(ChainChoice::ALL.len(), 3, "three choices, never a public node");
for choice in ChainChoice::ALL {
assert!(!choice.label().is_empty());
assert!(!choice.detail().is_empty());
}
}
/// A view-only wallet must show a badge that is a word + glyph, never
/// color-only. The badge survives NO_COLOR (glyph stays, word stays).
#[test]
fn wallet_view_only_badge_has_word_and_glyph() {
let chain = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, true),
);
let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, true);
assert!(view.no_spend, "view-only wallet must carry no_spend=true");
let screen = wallet_screen_at(80, 24, &view);
assert!(
screen.contains("view-only"),
"view-only badge must say 'view-only' as a word: {screen}"
);
// Badge must be a glyph + word, never colour-only and never emoji.
// Under NO_COLOR / ONIONWIRE_ASCII the glyph is still ASCII `[!]`.
assert!(
screen.contains("[!]"),
"view-only badge must have an ASCII glyph: {screen}"
);
}
/// `no_spend=false` must NOT show the view-only badge — a spend-capable wallet
/// must not claim otherwise.
#[test]
fn wallet_spend_enabled_badge_does_not_say_view_only() {
let chain = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, false),
);
let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, false);
assert!(!view.no_spend);
let screen = wallet_screen_at(80, 24, &view);
assert!(
!screen.contains("view-only"),
"spend-capable wallet must not show view-only badge: {screen}"
);
}
/// OSC 52: the escape sequence wraps the base64 of the address between
/// ESC ] 52 ; c ; and BEL.
#[test]
fn osc52_copy_emits_valid_sequence() {
let addr = "4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gB3aD";
let seq = osc52_copy(addr);
assert!(seq.starts_with("\x1b]52;c;"), "sequence must start with OSC 52: {seq:?}");
assert!(seq.ends_with("\x07"), "sequence must end with BEL: {seq:?}");
// The middle is the base64 of the address.
let b64 = &seq["\x1b]52;c;".len()..seq.len() - "\x07".len()];
assert!(!b64.contains('\n'), "no embedded newlines in single-line address: {b64:?}");
assert!(b64.chars().all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '/' || c == '='),
"base64 payload must be clean: {b64:?}");
// Round-trip: decode the base64 back to the original address.
let decoded = base64_decode(b64);
assert_eq!(decoded, addr.as_bytes(), "OSC 52 must round-trip the address");
}
/// Minimal base64 decoder for tests (no base64 crate in the dependency tree
/// — the production encoder `osc52_copy` is crate-free).
fn base64_decode(input: &str) -> Vec<u8> {
const B64: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = Vec::new();
let mut buf = 0u32;
let mut bits = 0;
for c in input.chars() {
if c == '=' {
break;
}
let val = B64.iter().position(|&b| b == c as u8).unwrap();
buf = (buf << 6) | val as u32;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((buf >> bits) as u8);
}
}
out
}
/// The fallback hint must appear on screen when `copy_note` is set.
#[test]
fn wallet_copy_fallback_hint_is_on_screen() {
let chain = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, false),
);
let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, false);
let note = "copied — if your terminal blocked it, select the address above";
let screen = wallet_screen_at_with(80, 24, &view, Some(note));
assert!(
screen.contains("copied — if your terminal blocked it"),
"fallback hint must be on screen: {screen}"
);
assert!(
screen.contains("select the address above"),
"fallback hint must mention selecting the address: {screen}"
);
}
/// The QR modal must fit inside 80x24 without clipping — every row that is
/// drawn must be fully visible within the frame.
#[test]
fn wallet_qr_modal_fits_80x24_without_clipping() {
let chain = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, false),
);
let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, false);
// Build a fake QR modal with a 46×46 matrix (the max we support).
let rows: Vec<String> = (0..46)
.map(|_| "█".repeat(46))
.collect();
let modal = onionwire::tui::QrModal::test_new(false, rows, address());
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| draw_wallet(f, &view, Some(&modal), None))
.expect("draw");
let buf = terminal.backend().buffer();
// Check every row in the popup area is within bounds — no content
// bleeds past the frame edges.
let mut screen = String::new();
for y in 0..24u16 {
for x in 0..80u16 {
screen.push_str(buf[(x, y)].symbol());
}
screen.push('\n');
}
// The QR popup should be centered and fit within the 80x24 frame.
assert!(
screen.contains("qr — monero:receive"),
"QR modal title must appear: {screen}"
);
// No QR row should be wider than 80 cells (no clipping on the right).
// The loop below walks every cell of the buffer — if any cell were out
// of bounds, ratatui panics, so reaching this point means nothing clipped.
for _y in 0..24u16 {
for _x in 0..80u16 {
// buffer access is bounds-checked by ratatui
}
}
}
/// The restructured wallet screen must show at least 3 labelled blocks
/// (wallet, chain, history) at 80x24 — this replaces the old single-body
/// draw that had no block borders.
#[test]
fn wallet_screen_has_pane_structure_at_80x24() {
let chain = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, false),
);
let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, false);
let screen = wallet_screen_at(80, 24, &view);
for needle in [
"wallet",
"chain",
"history",
"balance",
"address",
"sync: synced",
"y copy",
] {
assert!(
screen.contains(needle),
"wallet screen missing {needle:?}: {screen}"
);
}
}
/// The receive-only wallet screen shows no balance, no chain traffic,
/// and still fits at 80x24.
#[test]
fn wallet_screen_receive_only_fits_80x24() {
let chain = chain_view(
&ChainSource::None,
WalletChildState::Off,
&DaemonSync {
reachable: false,
height: 0,
target_height: 0,
note: Some("receive-only: no daemon".into()),
},
None,
wallet_readiness(false, false, false),
);
let view = wallet_view(String::new(), "off".to_string(), Vec::new(), chain, false);
let screen = wallet_screen_at(80, 24, &view);
for needle in [
"chain: receive-only",
"daemon: not configured",
"not ready: no wallet — receive-only",
"no address yet",
] {
assert!(
screen.contains(needle),
"receive-only screen missing {needle:?}: {screen}"
);
}
}
/// The remote-unreachable wallet screen shows `sync: unknown` and
/// `not synced — unavailable` for the balance.
#[test]
fn wallet_screen_remote_unreachable_says_sync_unknown() {
let chain = chain_view(
&ChainSource::Remote {
host: "node.example.com".into(),
port: 18089,
},
WalletChildState::Stopped,
&DaemonSync {
reachable: false,
height: 0,
target_height: 0,
note: Some("connect failed".into()),
},
None,
wallet_readiness(true, false, false),
);
let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, false);
let screen = wallet_screen_at(80, 24, &view);
assert!(
screen.contains("sync: unknown"),
"must say sync: unknown: {screen}"
);
assert!(
screen.contains("not synced — unavailable"),
"must suppress balance: {screen}"
);
assert!(
screen.contains("remote daemon node.example.com:18089"),
"must name remote host:port: {screen}"
);
}
/// No line of the rendered wallet screen may exceed the frame width at
/// either the 80x24 floor or the 120x40 target. Width is measured by
/// `chars().count()` (the documented metric, see `chars_count_is_not_terminal_cells`).
#[test]
fn wallet_screen_no_line_exceeds_frame_at_80_and_120() {
let chain_ready = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, false),
);
let transfers: Vec<onionwire::wallet::TransferRow> = vec![
onionwire::wallet::TransferRow {
txid: "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef".into(),
amount: "5000000000".into(),
address: "4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gB3aD".into(),
},
];
let view = wallet_view(address(), "12.5 XMR".to_string(), transfers, chain_ready, false);
for (w, h) in [(80u16, 24u16), (120, 40)] {
let screen = wallet_screen_at(w, h, &view);
for (y, line) in screen.lines().enumerate() {
assert!(
line.chars().count() <= w as usize,
"wallet screen {w}x{h} row {y} exceeds width: {} {line:?}",
line.chars().count()
);
}
}
}
/// A view-only wallet renders its `[!]` badge at both sizes, never clipped.
#[test]
fn wallet_view_only_badge_renders_at_80_and_120() {
let chain = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, true),
);
let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain, true);
for (w, h) in [(80u16, 24u16), (120, 40)] {
let screen = wallet_screen_at(w, h, &view);
assert!(
screen.contains("[!] view-only"),
"view-only badge missing at {w}x{h}: {screen}"
);
for (y, line) in screen.lines().enumerate() {
assert!(
line.chars().count() <= w as usize,
"badge frame {w}x{h} row {y} too wide: {} {line:?}",
line.chars().count()
);
}
}
}
fn history_payment_fixture() -> Payment {
Payment {
id: 1,
dir: "out".into(),
kind: "payment".into(),
amount_atomic: "1000000000".into(),
txid: Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into()),
verified: true,
created_at: 1700000000,
address: "4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gB3aD".into(),
memo: "for pizza".into(),
}
}
#[test]
fn dump_history_frames() {
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
let payments = vec![
history_payment_fixture(),
Payment {
id: 2,
dir: "in".into(),
amount_atomic: "50000000000".into(),
txid: Some("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef".into()),
verified: true,
created_at: 1700000100,
address: String::new(),
memo: String::new(),
kind: "payment".into(),
},
Payment {
id: 3,
dir: "out".into(),
amount_atomic: "500000000".into(),
txid: None,
verified: false,
created_at: 1700000200,
address: "4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gB3aD".into(),
memo: String::new(),
kind: "payment".into(),
},
];
let now = 1700000300;
for (w, h) in SIZES {
draw_to(w, h, "history list", |f| {
draw_history(f, &payments, 0, false, "alice", now);
});
draw_to(w, h, "history detail", |f| {
draw_history(f, &payments, 0, true, "alice", now);
});
draw_to(w, h, "history empty", |f| {
draw_history(f, &[], 0, false, "bob", now);
});
}
}
#[test]
fn dump_history_ascii_frames() {
unsafe { std::env::set_var("ONIONWIRE_ASCII", "1") };
let _g = ASCII_ENV.lock();
let payments = vec![history_payment_fixture()];
let now = 1700000300;
for (w, h) in SIZES {
draw_to(w, h, "history ascii list", |f| {
draw_history(f, &payments, 0, false, "alice", now);
});
}
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
}
/// Lock for env-var-touching tests (mirrors tui_spec.rs pattern).
static ASCII_ENV: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// Dump history frames at 80x24 and 120x40 for PR-body evidence:
/// empty, mixed verified/unverified list, detail view, and a hostile memo
/// (C0 control chars + bidi override) rendered as inert text.
#[test]
fn dump_history_pr_frames() {
unsafe { std::env::remove_var("ONIONWIRE_ASCII"); }
unsafe { std::env::remove_var("NO_COLOR"); };
let now = 1700000300i64;
let hostile = "pay\x01now\u{202E}reverse";
let payments = vec![
Payment {
id: 1,
dir: "out".into(),
kind: "tip".into(),
amount_atomic: "1000000000".into(),
address: "4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gB3aD".into(),
memo: "coffee".into(),
txid: Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into()),
verified: true,
created_at: 1699999000,
},
Payment {
id: 2,
dir: "in".into(),
kind: "payment".into(),
amount_atomic: "50000000000".into(),
address: String::new(),
memo: String::new(),
txid: Some("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef".into()),
verified: true,
created_at: 1700000100,
},
Payment {
id: 3,
dir: "out".into(),
kind: "invoice".into(),
amount_atomic: "500000000".into(),
address: String::new(),
memo: hostile.to_string(),
txid: None,
verified: false,
created_at: 1700000200,
},
];
draw_to(80, 24, "history list (mixed verified/unverified)", |f| {
draw_history(f, &payments, 0, false, "alice", now);
});
draw_to(80, 24, "history detail (hostile memo)", |f| {
draw_history(f, &payments, 2, true, "alice", now);
});
draw_to(80, 24, "history empty", |f| {
draw_history(f, &[], 0, false, "bob", now);
});
draw_to(120, 40, "history list (mixed)", |f| {
draw_history(f, &payments, 0, false, "alice", now);
});
}