onionwire/tests/tui_spec.rs
agent 4e13242a44
All checks were successful
ci / test (pull_request) Successful in 7m40s
ci / sdk (pull_request) Successful in 1m42s
tui: drop the F9 menu that restates F6 and F7
The Wallets & Settings screen only named keys that already work. F6 is the
wallet, F7 is the node, and p on the roster or chat opens peer payments.
Profile, backup and wipe stay composer commands, named in help.
2026-10-08 11:03:28 -04:00

1035 lines
36 KiB
Rust

//! Spec implementation tests for docs/TUI.md (this card).
//! Does not own `tests/tui_frames.rs` (PR #23).
use onionwire::Message;
use onionwire::outbox::{OutboxEntry, OutboxStatus};
use onionwire::qr;
use onionwire::tui::{
OutboxSummary, alert_line, ascii_chrome, cell_width, chat_with_delivery, delivery_tag,
draw_chat, draw_share, draw_text_overlay, empty_friend_chat_text,
help_overlay_text, main_footer_hints, main_header_line, osc52_copy_sequence, parse_cmd,
paste_screen_text, retry_in_text, roster_col_width, short_send_reason, status_footer,
wallet_screen_hint, wallet_screen_text, wallet_setup_keys_line, wrap_invite,
};
use ratatui::Frame;
use ratatui::Terminal;
use ratatui::backend::TestBackend;
use ratatui::layout::{Constraint, Layout};
use ratatui::widgets::{Block, Borders, List, ListItem, Paragraph, Wrap};
use std::sync::Mutex;
const FP: &str = "abcdef0123456789deadbeefcafebabe";
static ASCII_ENV: Mutex<()> = Mutex::new(());
const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion";
/// A 94-character base58 receive address. Width, not the exact length, is what matters.
const SAMPLE_ADDR: &str = "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYJKUGVktfzxayGbMWaC8iqPUE9XUBFGrLyDz4DpEBM";
fn screen_from(buf: &ratatui::buffer::Buffer, w: u16, h: u16) -> String {
let mut screen = String::new();
for y in 0..h {
for x in 0..w {
screen.push_str(buf[(x, y)].symbol());
}
screen.push('\n');
}
screen
}
#[test]
fn status_footer_keeps_send_failed_and_chrome() {
let note = "send failed: peer onion down";
for w in [80u16, 120, 200] {
let line = status_footer(w, FP, ONION, Some(note), main_footer_hints());
assert!(
line.chars().count() <= w as usize,
"footer wider than {w}: {} {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 main_header_is_one_line_at_80() {
let line = main_header_line(80, FP, ONION);
assert!(!line.contains('\n'), "header must be one line: {line:?}");
assert!(
line.chars().count() <= 80,
"header wider than 80: {} {line:?}",
line.chars().count()
);
assert!(line.to_ascii_lowercase().contains("onionwire"), "{line:?}");
assert!(line.contains("me:"), "{line:?}");
}
#[test]
fn roster_is_fixed_cells_not_percent() {
assert_eq!(roster_col_width(80), 22);
assert_eq!(roster_col_width(119), 22);
assert_eq!(roster_col_width(120), 28);
assert_eq!(roster_col_width(200), 28);
}
#[test]
fn help_overlay_at_80x24_is_fullscreen_last_line_visible() {
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| {
f.render_widget(
Paragraph::new(" .-~~-. ONIONWIRE\n┌roster junk\n┌composer"),
f.area(),
);
draw_text_overlay(f, "? help", help_overlay_text());
})
.expect("draw");
let buf = terminal.backend().buffer();
let screen = screen_from(buf, 80, 24);
assert!(
screen.contains("Esc closes this overlay"),
"last help line clipped:\n{screen}"
);
assert!(
!screen.contains(".-~~-."),
"help punched through banner:\n{screen}"
);
assert!(
!screen.contains("┌roster"),
"help punched through roster:\n{screen}"
);
assert!(screen.contains("? help"), "help title missing:\n{screen}");
}
fn draw_main_standin(f: &mut Frame, empty_roster: bool, composer: &str, note: Option<&str>) {
let area = f.area();
let header = main_header_line(area.width, FP, ONION);
let cols = Layout::vertical([
Constraint::Length(1),
Constraint::Min(3),
Constraint::Length(3),
Constraint::Length(1),
])
.split(area);
f.render_widget(Paragraph::new(header), cols[0]);
let roster_w = roster_col_width(area.width).min(cols[1].width.saturating_sub(10));
let panes =
Layout::horizontal([Constraint::Length(roster_w), Constraint::Min(10)]).split(cols[1]);
let items = if empty_roster {
vec![ListItem::new("no friends")]
} else {
vec![ListItem::new("alice aaaaaaaa…")]
};
f.render_stateful_widget(
List::new(items)
.highlight_symbol("> ")
.block(Block::default().borders(Borders::ALL).title("roster 0")),
panes[0],
&mut ratatui::widgets::ListState::default(),
);
f.render_widget(
Paragraph::new("no friends yet")
.wrap(Wrap { trim: false })
.block(Block::default().borders(Borders::ALL).title(" chat")),
panes[1],
);
f.render_widget(
Paragraph::new(format!("> {composer}")).wrap(Wrap { trim: false }),
cols[2],
);
let footer = status_footer(area.width, FP, ONION, note, main_footer_hints());
f.render_widget(Paragraph::new(footer), cols[3]);
}
#[test]
fn reconstructed_main_empty_roster_and_composer() {
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| draw_main_standin(f, true, "message", None))
.expect("draw");
let screen = screen_from(terminal.backend().buffer(), 80, 24);
let row0: String = screen.lines().next().unwrap_or("").to_string();
assert!(
!row0.contains(".-~~-."),
"80x24 main still uses 3-line wordmark:\n{screen}"
);
assert!(
screen.contains("no friends"),
"empty roster blank:\n{screen}"
);
assert!(
screen.contains("message"),
"composer missing placeholder:\n{screen}"
);
assert!(
!screen.contains("/wipe"),
"composer still dumps slash list:\n{screen}"
);
}
#[test]
fn reconstructed_main_keeps_send_failed_on_footer() {
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| draw_main_standin(f, false, "hello", Some("send failed: peer onion down")))
.expect("draw");
let screen = screen_from(terminal.backend().buffer(), 80, 24);
assert!(
screen.contains("send failed"),
"fail-closed missing from frame:\n{screen}"
);
}
#[test]
fn dump_spec_frames() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
for (w, h) in [(80u16, 24u16), (120, 40)] {
let backend = TestBackend::new(w, h);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| {
draw_main_standin(
f,
false,
"hello from composer",
Some("send failed: peer onion down"),
)
})
.expect("draw");
println!("===== AFTER main {w}x{h} =====");
print!("{}", screen_from(terminal.backend().buffer(), w, h));
let backend = TestBackend::new(w, h);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| {
draw_main_standin(f, true, "message", None);
draw_text_overlay(f, "? help", help_overlay_text());
})
.expect("draw");
println!("===== AFTER help {w}x{h} =====");
print!("{}", screen_from(terminal.backend().buffer(), w, h));
let invite = sample_invite();
let backend = TestBackend::new(w, h);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal.draw(|f| draw_share(f, &invite)).expect("draw");
println!("===== AFTER share {w}x{h} =====");
print!("{}", screen_from(terminal.backend().buffer(), w, h));
}
}
fn sample_invite() -> String {
let sk = [7u8; 32];
qr::encode(&sk, ONION, &[1u8; 32]).expect("encode")
}
fn invite_line_ok(line: &str) -> bool {
let t = line.trim();
t.is_empty()
|| t.starts_with("onionwire:")
|| t.starts_with("k=")
|| t.starts_with("o=")
|| t.starts_with("spk=")
|| t.starts_with("sig=")
|| t.chars().all(|c| c.is_ascii_hexdigit())
}
#[test]
fn alert_line_truncates_to_frame_width() {
let long = "passphrases do not match and then a lot more context that would collide with the roster on the next row if left unwrapped";
let line = alert_line(long, 80);
assert!(
line.chars().count() <= 80,
"alert wider than 80: {} {line:?}",
line.chars().count()
);
assert!(
line.contains('…') || line.contains("..."),
"long alert was not truncated: {line:?}"
);
assert!(
!line.contains("roster on the next row"),
"alert still has overflow tail: {line:?}"
);
// Cells, not chars: a double-width peer error must not overflow the row.
let cjk = alert_line("接続がタイムアウトしました 接続がタイムアウトしました", 32);
assert!(
onionwire::tui::cell_width(&cjk) <= 32,
"alert wider than 32 cells: {} {cjk:?}",
onionwire::tui::cell_width(&cjk)
);
}
#[test]
fn wrap_invite_breaks_on_field_boundaries() {
let invite = sample_invite();
assert!(invite.len() > 78, "fixture too short to wrap: {invite}");
let wrapped = wrap_invite(&invite, 78);
for line in wrapped.lines() {
assert!(
line.chars().count() <= 78,
"invite line wider than 78: {} {line:?}",
line.chars().count()
);
assert!(
invite_line_ok(line),
"invite wrapped mid-token: {line:?}\n{wrapped}"
);
}
assert!(
wrapped.contains("onionwire:v1:"),
"lost invite prefix:\n{wrapped}"
);
assert!(wrapped.contains("k="), "lost k= field:\n{wrapped}");
assert!(wrapped.contains("spk="), "lost spk= field:\n{wrapped}");
let joined: String = wrapped.lines().map(str::trim).collect();
assert_eq!(
joined, invite,
"wrap must be newline-joinable back to payload"
);
}
#[test]
fn draw_share_invite_does_not_wrap_mid_token() {
let invite = sample_invite();
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal.draw(|f| draw_share(f, &invite)).expect("draw");
let screen = screen_from(terminal.backend().buffer(), 80, 24);
assert!(
screen.contains("onionwire:v1:"),
"missing prefix:\n{screen}"
);
for raw in screen.lines() {
let inner = raw.trim_start_matches(['│', '|', ' ']);
let inner = inner.trim_end_matches(['│', '|', ' ']);
if inner.starts_with("onionwire:")
|| inner.starts_with("k=")
|| inner.starts_with("o=")
|| inner.starts_with("spk=")
|| inner.starts_with("sig=")
|| inner.chars().all(|c| c.is_ascii_hexdigit())
{
assert!(
invite_line_ok(inner),
"share pane mid-token wrap: {inner:?}\n{screen}"
);
}
if inner.starts_with('c') && inner.contains(":o=") {
panic!("share still wraps mid-hex into :o=: {inner:?}\n{screen}");
}
}
}
#[test]
fn empty_friend_chat_has_send_hint() {
let text = empty_friend_chat_text();
assert!(text.contains("no messages"), "{text:?}");
assert!(text.contains("type below, Enter sends"), "{text:?}");
}
#[test]
fn paste_error_keeps_resubmit_hint() {
let body = paste_screen_text("", Some("bad invite"));
assert!(body.contains("bad invite"), "{body:?}");
assert!(body.contains("Enter resubmits"), "{body:?}");
assert!(body.contains("Esc back"), "{body:?}");
let ok = paste_screen_text("onionwire:v1:k=x", None);
assert!(
ok.contains("paste onionwire:v1 payload"),
"happy-path hint lost: {ok:?}"
);
}
#[test]
fn ascii_switch_80x24_frame_is_pure_ascii() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe { std::env::set_var("ONIONWIRE_ASCII", "1") };
assert!(
ascii_chrome(),
"ONIONWIRE_ASCII set but ascii_chrome() is false"
);
let footer = status_footer(80, FP, ONION, None, main_footer_hints());
assert!(
footer.contains("..."),
"ASCII truncation marker missing: {footer:?}"
);
assert!(
!footer.contains('…'),
"unicode ellipsis still in footer: {footer:?}"
);
let invite = sample_invite();
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal.draw(|f| draw_share(f, &invite)).expect("draw");
let screen = screen_from(terminal.backend().buffer(), 80, 24);
let non_ascii: Vec<char> = screen.chars().filter(|c| !c.is_ascii()).collect();
assert!(
non_ascii.is_empty(),
"ASCII switch ignored, non-ASCII in 80x24 frame: {non_ascii:?}\n{screen}"
);
assert!(
screen.contains("..."),
"truncation marker missing from ASCII frame:\n{screen}"
);
assert!(
screen.contains('+') && screen.contains('|') && screen.contains('-'),
"ASCII borders missing:\n{screen}"
);
println!("===== AFTER ascii share 80x24 =====\n{screen}");
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
}
// ---------------------------------------------------------------------------
// Outbox delivery state (card t_d9a5b065)
//
// States come from the outbox API (`Outbox::pending` → `Queued` / `Sending` /
// `Failed`; delivered rows are deleted, so absence means `Sent`). No new wire
// prefix, no parallel state model.
// ---------------------------------------------------------------------------
fn out_msg(id: i64, body: &str) -> Message {
Message {
id,
dir: "out".into(),
plaintext: body.as_bytes().to_vec(),
}
}
fn in_msg(id: i64, body: &str) -> Message {
Message {
id,
dir: "in".into(),
plaintext: body.as_bytes().to_vec(),
}
}
fn pending_row(
message_id: i64,
body: &str,
status: OutboxStatus,
attempts: u32,
next_in: i64,
now: i64,
) -> OutboxEntry {
OutboxEntry {
id: 1,
friend_pk: vec![9u8; 32],
message_id,
body: body.as_bytes().to_vec(),
payload: None,
attempts,
next_attempt_at: now + next_in,
created_at: now,
status,
last_error: None,
}
}
fn queued_row(message_id: i64, body: &str, attempts: u32, next_in: i64, now: i64) -> OutboxEntry {
pending_row(message_id, body, OutboxStatus::Queued, attempts, next_in, now)
}
fn sending_row(message_id: i64, body: &str, now: i64) -> OutboxEntry {
pending_row(message_id, body, OutboxStatus::Sending, 1, 0, now)
}
fn failed_row(message_id: i64, body: &str, why: &str, now: i64) -> OutboxEntry {
pending_row(
message_id,
body,
OutboxStatus::Failed(why.into()),
8,
0,
now,
)
}
/// Marker is everything after the two-space separator the render helper uses.
fn marker_of(line: &str) -> &str {
line.rsplit(" ").next().unwrap_or("")
}
/// Force the non-ASCII (unicode glyph) path. Caller holds `ASCII_ENV`.
fn force_unicode_mode() {
unsafe {
std::env::remove_var("ONIONWIRE_ASCII");
std::env::remove_var("NO_COLOR");
}
}
#[test]
fn queued_and_delivered_messages_render_different_markers() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
let now = 1_700_000_000;
let msgs = vec![out_msg(1, "ping"), out_msg(2, "pong")];
let pending = vec![queued_row(2, "pong", 2, 45, now)];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
assert!(
lines[0].contains('✓'),
"delivered row lost its mark: {:?}",
lines[0]
);
assert!(!lines[0].contains("queued"), "{:?}", lines[0]);
assert!(
lines[1].contains('◷'),
"queued row lost its glyph: {:?}",
lines[1]
);
assert!(lines[1].contains("queued"), "{:?}", lines[1]);
assert!(
lines[1].contains("try 2/8"),
"attempt count missing: {:?}",
lines[1]
);
assert!(
lines[1].contains("retry 45s"),
"retry age missing: {:?}",
lines[1]
);
assert_ne!(
marker_of(&lines[0]),
marker_of(&lines[1]),
"queued and delivered must not share a marker"
);
assert_eq!(summary.queued, 1);
assert_eq!(summary.failed, 0);
}
/// The case the body match got wrong: the same text sent twice, only the
/// *older* send still queued. Joined by body, the (single) pending row lands on
/// the newest send and the actually-queued row shows `✓` — which is exactly
/// false delivery. The join is on `Message::id` / `OutboxEntry::message_id`.
#[test]
fn identical_bodies_join_by_message_id_not_body() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
let now = 1_700_000_000;
let msgs = vec![out_msg(7, "same text"), out_msg(8, "same text")];
let pending = vec![queued_row(7, "same text", 1, 30, now)];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
assert!(
lines[0].contains('◷') && lines[0].contains("queued"),
"queued marker must land on the queued row (id 7): {:?}",
lines[0]
);
assert!(
!lines[0].contains('✓'),
"queued row must not claim delivery: {:?}",
lines[0]
);
assert_eq!(
marker_of(&lines[1]),
"✓",
"delivered row (id 8) must keep its mark: {:?}",
lines[1]
);
assert_eq!(
summary.note().as_deref(),
Some("peer unreachable, queued (1/8, retry 30s)")
);
}
#[test]
fn delivery_markers_have_exercised_ascii_fallbacks() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe {
std::env::set_var("ONIONWIRE_ASCII", "1");
std::env::remove_var("NO_COLOR");
}
let now = 500;
let msgs = vec![
out_msg(1, "alpha"),
out_msg(2, "beta"),
out_msg(3, "gamma"),
out_msg(4, "delta"),
in_msg(5, "epsilon"),
];
let pending = vec![
failed_row(1, "alpha", "connect peer.onion:80: connection timed out", now),
queued_row(2, "beta", 1, 30, now),
sending_row(3, "gamma", now),
];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
for line in &lines {
assert!(
line.is_ascii(),
"ASCII fallback missing, non-ASCII in {line:?}"
);
}
assert_eq!(marker_of(&lines[0]), "failed: connection timed out");
assert_eq!(marker_of(&lines[1]), "queued (try 1/8, retry 30s)");
assert_eq!(marker_of(&lines[2]), "sending");
assert_eq!(marker_of(&lines[3]), "ok", "delivered fallback is `ok`");
assert_eq!(lines[4], "them: epsilon", "inbound rows carry no state");
assert_eq!(summary.queued, 2, "queued + sending are both outstanding");
assert_eq!(summary.failed, 1);
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
}
#[test]
fn retry_age_and_failure_reason_are_short_forms() {
assert_eq!(retry_in_text(45), "retry 45s");
assert_eq!(retry_in_text(59), "retry 59s");
assert_eq!(retry_in_text(60), "retry 1m");
assert_eq!(retry_in_text(720), "retry 12m");
assert_eq!(retry_in_text(0), "retry now");
assert_eq!(retry_in_text(-30), "retry now");
assert_eq!(
short_send_reason("connect abcdef.onion:80: connection timed out", 24),
"connection timed out"
);
let long = short_send_reason("a-really-long-failure-description-here", 12);
assert!(long.chars().count() <= 12, "{long:?}");
assert!(
long.contains('…') || long.contains("..."),
"truncation marker missing: {long:?}"
);
assert_eq!(short_send_reason("nope", 24), "nope");
}
#[test]
fn delivery_tag_reads_the_outbox_status_enum() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
assert_eq!(delivery_tag(&OutboxStatus::Sent, 0, 0), "✓");
assert_eq!(
delivery_tag(&OutboxStatus::Queued, 3, 120),
"◷ queued (try 3/8, retry 2m)"
);
assert_eq!(delivery_tag(&OutboxStatus::Sending, 1, 0), "» sending");
assert_eq!(
delivery_tag(&OutboxStatus::Failed("connect x:80: nope".into()), 8, 0),
"✗ failed: nope"
);
}
#[test]
fn footer_summary_counts_queued_and_keeps_fail_closed() {
let none = OutboxSummary::default();
assert_eq!(none.note(), None);
let queued = OutboxSummary {
queued: 2,
failed: 0,
first_error: None,
attempts: 3,
next_in_secs: Some(45),
};
assert_eq!(
queued.note().as_deref(),
Some("peer unreachable, queued (3/8, retry 45s)")
);
let failed = OutboxSummary {
queued: 0,
failed: 1,
first_error: Some("connect peer.onion:80: connection timed out".into()),
..OutboxSummary::default()
};
let note = failed.note().expect("failed rows must produce a note");
assert!(note.starts_with("send failed:"), "{note:?}");
assert!(note.contains("connection timed out"), "{note:?}");
let mixed = OutboxSummary {
queued: 3,
failed: 1,
first_error: Some("connect peer.onion:80: connection timed out".into()),
attempts: 2,
next_in_secs: Some(60),
};
let mixed_note = mixed.note().expect("mixed rows must produce a note");
assert!(
mixed_note.contains("queued (2/8, retry 1m)"),
"{mixed_note:?}"
);
assert!(mixed_note.starts_with("peer unreachable"), "{mixed_note:?}");
assert!(mixed_note.contains("send failed"), "{mixed_note:?}");
// Fail-closed copy stays visible in the real footer at the 80-col floor.
let line = status_footer(80, FP, ONION, Some(&note), main_footer_hints());
assert!(
line.chars().count() <= 80,
"{} {line:?}",
line.chars().count()
);
assert!(line.contains("send failed"), "footer dropped it: {line:?}");
assert!(line.contains("TOR") && line.contains("? help"), "{line:?}");
let queued_line = status_footer(80, FP, ONION, queued.note().as_deref(), main_footer_hints());
assert!(
queued_line.contains("queued (3/8, retry 45s)"),
"{queued_line:?}"
);
assert!(queued_line.chars().count() <= 80);
// `! ` ornament (colour off) still lands on the derived failing note.
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe { std::env::set_var("NO_COLOR", "1") };
let no_color = status_footer(80, FP, ONION, Some(&note), main_footer_hints());
assert!(no_color.contains("! send failed"), "{no_color:?}");
unsafe { std::env::remove_var("NO_COLOR") };
}
/// The card's width criterion: draw the real helpers at the documented floor
/// (80x24) and prove nothing in the chat/footer region exceeds the width, and
/// that an over-long row wraps in the pane instead of being clipped.
#[test]
fn chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
let now = 1_700_000_000;
let long = "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";
let msgs = vec![out_msg(1, "ok"), in_msg(2, "pong"), out_msg(3, long)];
let pending = vec![queued_row(3, long, 3, 45, now)];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
for line in lines.iter().take(2) {
assert!(
line.chars().count() <= 80,
"short row wider than 80: {} {line:?}",
line.chars().count()
);
}
let footer = status_footer(
80,
FP,
ONION,
summary.note().as_deref(),
main_footer_hints(),
);
assert!(footer.chars().count() <= 80, "{footer:?}");
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| {
let area = f.area();
let cols = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area);
draw_chat(f, cols[0], &lines, Some("alice"), true, 0);
f.render_widget(Paragraph::new(footer.clone()), cols[1]);
})
.expect("draw");
let buf = terminal.backend().buffer();
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');
}
for (y, row) in screen.lines().enumerate() {
assert!(
row.chars().count() <= 80,
"80x24 chat/footer row {y} wider than the terminal: {} {row:?}",
row.chars().count()
);
}
assert!(
screen.contains('◷'),
"queued glyph missing from frame:\n{screen}"
);
assert!(screen.contains("queued"), "queued word missing:\n{screen}");
assert!(screen.contains('✓'), "delivered glyph missing:\n{screen}");
assert!(
screen.contains("with the roster border"),
"long row was clipped, not wrapped:\n{screen}"
);
assert!(
screen.contains("peer unreachable, queued (3/8, retry 45s)"),
"footer summary missing:\n{screen}"
);
println!("===== AFTER outbox 80x24 (real draw_chat + status_footer) =====\n{screen}");
}
/// The renderer consumes the real outbox API, not a hand-written fixture: a
/// genuine unreachable-onion send leaves a `Queued` row, and that row is what
/// the chat line and the footer note are built from.
#[tokio::test]
async fn renders_a_queued_row_from_a_real_outbox_send() {
use onionwire::Store;
use onionwire::outbox::{BoxFut, Deliverer, Outbox};
use std::sync::Arc;
struct Dead;
impl Deliverer for Dead {
fn deliver<'a>(
&'a self,
_onion: &'a str,
_pinned_id: &'a [u8],
_prekey: &'a [u8],
_plaintext: &'a [u8],
) -> BoxFut<'a, Result<(), String>> {
Box::pin(async { Err("connect dead.onion:80: timed out".to_string()) })
}
}
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "tui-spec-pass").expect("open store");
let pk = [1u8; 32];
store
.upsert_friend(&pk, "dead.onion", None)
.expect("friend");
store.set_friend_prekey(&pk, &[7u8; 32]).expect("prekey");
let store = Arc::new(std::sync::Mutex::new(store));
let outbox = Outbox::new(Arc::clone(&store), Arc::new(Dead));
assert_eq!(
outbox.send(&pk, b"queued for a dead peer").await,
Ok(OutboxStatus::Queued)
);
let pending = outbox.pending(&pk).expect("pending rows");
assert_eq!(pending.len(), 1, "one queued row");
let msgs = store
.lock()
.expect("store lock")
.list_messages(&pk)
.expect("messages");
let now = pending[0].next_attempt_at - 45;
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
assert_eq!(lines.len(), 1);
assert!(
lines[0].contains("queued (try 1/8, retry 45s)"),
"real outbox row did not render: {:?}",
lines[0]
);
assert_eq!(
summary.note().as_deref(),
Some("peer unreachable, queued (1/8, retry 45s)")
);
// And once a send crosses the circuit the row is gone, so the same message
// renders as delivered.
let (delivered, summary) = chat_with_delivery(&msgs, &[], now);
assert!(delivered[0].contains('✓'), "{:?}", delivered[0]);
assert_eq!(summary.note(), None);
}
// ---------------------------------------------------------------------------
// Colour token set (card t_49b7c2b1)
// ---------------------------------------------------------------------------
use onionwire::tui::{ColorMode, alert_line_for_mode, tokens_for};
use ratatui::style::{Color, Modifier};
#[test]
fn rgb_tokens_resolve_to_palette_fg() {
let t = tokens_for(ColorMode::Rgb);
assert_eq!(t.text.fg, Some(Color::Rgb(196, 214, 176)));
assert_eq!(t.dim.fg, Some(Color::Rgb(98, 110, 92)));
assert_eq!(t.accent.fg, Some(Color::Rgb(232, 165, 75)));
assert_eq!(t.alert.fg, Some(Color::Rgb(220, 80, 70)));
assert_eq!(t.stale.fg, Some(Color::Rgb(210, 180, 80)));
assert_eq!(t.border.fg, Some(Color::Rgb(72, 84, 64)));
// highlight uses bg + fg + bold in RGB mode
assert_eq!(t.highlight.fg, Some(Color::Rgb(232, 165, 75)));
assert_eq!(t.highlight.bg, Some(Color::Rgb(48, 42, 28)));
assert!(
t.highlight
.add_modifier
.contains(Modifier::BOLD),
"RGB highlight must be bold"
);
}
#[test]
fn none_tokens_strip_colour_fg_and_alert_keeps_bold() {
let t = tokens_for(ColorMode::None);
assert_eq!(t.text.fg, None, "None mode must strip all colour");
assert_eq!(t.dim.fg, None);
assert_eq!(t.alert.fg, None);
assert_eq!(t.border.fg, None);
assert_eq!(t.stale.fg, None);
// accent falls back to bold (no colour) in None mode
assert_eq!(
t.accent.add_modifier,
Modifier::BOLD,
"None accent must be bold-only"
);
// highlight falls back to bold + reversed
assert_eq!(
t.highlight.add_modifier,
Modifier::BOLD | Modifier::REVERSED,
"None highlight must be bold+reversed"
);
assert_eq!(t.highlight.fg, None);
assert_eq!(t.highlight.bg, None);
}
#[test]
fn ansi16_tokens_use_ansi_colours() {
let t = tokens_for(ColorMode::Ansi16);
assert_eq!(t.text.fg, Some(Color::White));
assert_eq!(t.dim.fg, Some(Color::DarkGray));
assert_eq!(t.alert.fg, Some(Color::Red));
assert_eq!(t.border.fg, Some(Color::DarkGray));
assert_eq!(t.stale.fg, Some(Color::Yellow));
assert_eq!(t.accent.fg, Some(Color::Yellow));
// highlight in Ansi16 has no colour, just modifiers
assert_eq!(t.highlight.fg, None);
assert_eq!(t.highlight.bg, None);
assert!(
t.highlight
.add_modifier
.contains(Modifier::REVERSED | Modifier::BOLD)
);
}
#[test]
fn tokens_for_is_deterministic_across_calls() {
let a = tokens_for(ColorMode::Rgb);
let b = tokens_for(ColorMode::Rgb);
assert_eq!(a.text.fg, b.text.fg);
assert_eq!(a.accent.fg, b.accent.fg);
assert_eq!(a.highlight.fg, b.highlight.fg);
}
#[test]
fn alert_line_prefixes_when_no_color() {
// ColorMode::None (NO_COLOR) → alert_line prepends "! ". The mode is
// injected rather than read from the process env: other tests in this
// binary flip NO_COLOR concurrently, which made the env version flaky.
let plain = alert_line_for_mode(ColorMode::None, "peer down", 80);
assert!(
plain.starts_with("! "),
"expected '! ' prefix in None mode: {plain:?}"
);
// The ornament belongs to the None path only; RGB keeps the message verbatim.
assert_eq!(
alert_line_for_mode(ColorMode::Rgb, "peer down", 80),
"peer down"
);
// An alert that already carries the ornament is not double-prefixed.
assert_eq!(
alert_line_for_mode(ColorMode::None, "! peer down", 80),
"! peer down"
);
}
// ---------------------------------------------------------------------------
// One wallet screen (F6) and one node screen (F7). No second menu.
// ---------------------------------------------------------------------------
/// Those labels are not a second menu. F6 still shows the receive address,
/// the balance and create. F7 still names start (`ctrl-s`).
#[test]
fn wallet_and_node_are_the_screens_not_a_second_menu() {
let help = help_overlay_text();
for gone in ["F9", "/settings", "wallets & settings", "F7 ctrl-s/x"] {
assert!(
!help.contains(gone),
"help still restates a menu ({gone:?}):\n{help}"
);
}
// Composer commands that were only named on the menu stay named in help.
for kept in ["/profile", "/backup", "/restore", "/wipe", "/wipe-all"] {
assert!(help.contains(kept), "help dropped {kept:?}:\n{help}");
}
assert!(help.contains("receive"), "F6 help dropped receive:\n{help}");
assert!(help.contains("F6"), "{help}");
assert!(help.contains("F7"), "{help}");
let body = wallet_screen_text(SAMPLE_ADDR, "0.250000000000");
assert!(body.contains("address"), "receive row missing:\n{body}");
assert!(body.contains(SAMPLE_ADDR), "address missing:\n{body}");
assert!(body.contains("balance"), "balance missing:\n{body}");
assert!(body.contains("0.250000000000"), "balance value missing:\n{body}");
let hint = wallet_screen_hint();
assert!(hint.contains("create"), "create missing from the wallet hint: {hint}");
assert!(hint.contains("F7"), "the wallet hint must name the node: {hint}");
let keys = wallet_setup_keys_line();
assert!(keys.contains("ctrl-s"), "F7 no longer names start: {keys}");
assert!(keys.contains("ctrl-x"), "{keys}");
assert!(keys.contains("ctrl-r"), "{keys}");
// The old menu's row labels are not a screen of their own.
let surfaces = format!("{help}\n{body}\n{hint}\n{keys}\n{}", main_footer_hints());
assert!(!surfaces.contains("F9"));
assert!(!main_footer_hints().contains("F9"));
}
/// The wallet hint and the node start line are what those screens print, and
/// both fit the 80-column floor in cells.
#[test]
fn wallet_and_node_copy_fits_the_80_column_floor() {
// The receive address is longer than 80 cells; the screen wraps it. The
// labels and the keys are the lines that must fit unwrapped.
let body = wallet_screen_text("4Ada", "0.250000000000");
for line in body.lines() {
assert!(
cell_width(line) <= 78,
"wallet body wider than the inner 80-column pane: {line:?}"
);
}
assert!(cell_width(wallet_screen_hint()) <= 78);
assert!(cell_width(wallet_setup_keys_line()) <= 78);
for w in [80u16, 120, 200] {
let line = status_footer(w, FP, ONION, None, main_footer_hints());
assert!(cell_width(&line) <= w as usize, "{w}: {line:?}");
assert!(line.contains("F6"), "F6 dropped at {w}: {line:?}");
assert!(line.contains("F7"), "F7 dropped at {w}: {line:?}");
assert!(!line.contains("F9"), "F9 still rendered at {w}: {line:?}");
}
}
#[test]
fn osc52_copy_sequence_is_a_base64_clipboard_write() {
// OSC 52: ESC ] 52 ; c ; <base64> BEL — the terminal owns the clipboard, so
// the address never touches a file and no crate is needed.
assert_eq!(osc52_copy_sequence("4Ada"), "\u{1b}]52;c;NEFkYQ==\u{7}");
let seq = osc52_copy_sequence(SAMPLE_ADDR);
let payload = seq
.strip_prefix("\u{1b}]52;c;")
.and_then(|s| s.strip_suffix('\u{7}'))
.expect("osc52 envelope");
assert_eq!(payload.len(), 128, "94 bytes base64 to 128 characters");
assert!(payload.ends_with("=="), "{payload:?}");
assert!(
payload
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '/' || c == '='),
"{payload:?}"
);
// Junk cannot escape the sequence: bidi/control characters, a newline and a
// stray BEL are stripped before encoding, and surrounding space is trimmed.
let seq = osc52_copy_sequence("4Ada\u{202e}\n\u{7}");
assert_eq!(seq, "\u{1b}]52;c;NEFkYQ==\u{7}");
assert_eq!(osc52_copy_sequence(" 4Ada "), "\u{1b}]52;c;NEFkYQ==\u{7}");
}
#[test]
fn settings_is_not_a_command_and_the_composer_commands_stay() {
assert!(parse_cmd("/settings").is_none(), "/settings must not open a menu");
assert!(parse_cmd(" /settings ").is_none());
assert!(parse_cmd("/profile").is_some());
assert!(parse_cmd("/wipe").is_some());
assert!(parse_cmd("/wipe-all").is_some());
assert!(parse_cmd("/wallet create").is_some());
}