diff --git a/docs/TUI.md b/docs/TUI.md index ff571c2..40e82e5 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -351,16 +351,6 @@ Else RGB as today. | box | ratatui `Borders::ALL` (light) | `+` `-` `\|` via `border::Set` | | alert prefix | `! ` | `! ` | | stale | word `stale` | `stale` | -| delivery: delivered | `✓` | `ok` | -| delivery: queued | `◷` | (word) `queued` | -| delivery: sending | `»` | (word) `sending` | -| delivery: failed | `✗` | (word) `failed` | - -`queued` / `sending` / `failed` always carry their state word, so the ASCII -fallback drops the glyph instead of inventing one. Only `✓` is wordless, so it -falls back to `ok`. `delivery_glyph()` / -`tests/tui_spec.rs::delivery_markers_have_exercised_ascii_fallbacks` exercise the -fallback path. No emoji. `onion_glyph()` stays for callers that already use it; do not put it on the main header. @@ -411,9 +401,6 @@ Do not soften fail-closed into a loader. | sending | `sending` (keep, no spinner) | | sent | `sent` | | peer down / send err | `send failed: {e}` (visible) | -| queued (outbox) | `{n} queued` — replaces the flat `sent`/`send failed` while rows are outstanding | -| queued + terminal failure | `{n} queued, send failed: {short}` | -| terminal failure | `send failed: {short}` (`{f} failed` when more than one) | | already sending | `already sending` (keep) | | stale friend | `stale` suffix (keep) | | empty composer | `message` as dim placeholder (not the slash list). Slash list stays in `?` | @@ -583,42 +570,3 @@ cargo test --locked --test tui_spec -- --nocapture dump_spec_frames Copy wired in `src/tui.rs` (not in the reconstructed standin): empty thread is `no messages` / `type below, Enter sends`; paste error is `{err}` then `Enter resubmits Esc back`; alerts truncate to the frame width. - -## Delivery state (outbox) — implemented - -Per-message state, read from the local outbox. The states are the store's own -(`Queued` / `Sending` / `Sent` / `Failed`) — no parallel model, no new wire -prefix, no server. - -| Row | Marker | -|---|---| -| delivered | `you: ping ✓` | -| queued (2nd attempt, 45s out) | `you: pong ◷ queued (try 2/8, retry 45s)` | -| sending | `you: pong » sending` | -| failed | `you: pong ✗ failed: connection timed out` | -| inbound | `them: pong` (no marker) | - -- `try {n}/{8}` is the outbox attempt count; `retry {s}s` / `retry {m}m` / - `retry now` comes from the stored absolute `next_attempt_at`. -- Failed reasons are sanitized, cut to the tail of the `a: b: c` chain and - capped at 24 cells (`short_send_reason`). -- Footer while rows are outstanding: `{n} queued`; any terminal failure keeps a - fail-closed `send failed: {short}` statement (with `! ` when colour is off). -- The tag trails the body and wraps with it, so it is never clipped away. - -Correlation: a delivered row is deleted from the outbox, so an outbound message -with no row is `Sent`; pending rows are matched to messages by body, newest send -first (`chat_with_delivery`). The outbox holds no message id the UI can join on, -so two identical bodies where only the newer one is still queued attach the -marker to the newer send. An id-bearing accessor would remove that last -ambiguity; see the follow-up card noted in the PR. - -### Size floor / target - -- **Floor: 80x24.** Everything above must render there. -- **Target: 120x40.** -- `tests/tui_spec.rs::chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping` - draws the real `draw_chat` + `status_footer` at 80x24 and asserts every chat - and footer row is `<=` the terminal width, that the markers render, and that - an over-long message wraps instead of being clipped. -- Dump frames: `cargo test --locked --test tui_spec -- --nocapture dump_spec_frames`. diff --git a/src/tui.rs b/src/tui.rs index 6e580bb..090e1a7 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1,7 +1,6 @@ -use std::collections::HashMap; use std::io::{self, IsTerminal}; use std::sync::{Arc, mpsc}; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use std::time::Duration; use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; use ratatui::layout::{Constraint, Layout, Rect}; @@ -12,10 +11,9 @@ use ratatui::{DefaultTerminal, Frame}; use zeroize::{Zeroize, Zeroizing}; use crate::node::Node; -use crate::outbox::DEFAULT_MAX_ATTEMPTS; use crate::qr::{self, QrPayload}; use crate::sanitize; -use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus}; +use crate::store::{Friend, FriendProfile}; const C_ACCENT: Color = Color::Rgb(232, 165, 75); const C_TEXT: Color = Color::Rgb(196, 214, 176); @@ -119,202 +117,6 @@ pub fn empty_friend_chat_text() -> &'static str { "no messages\ntype below, Enter sends" } -// --------------------------------------------------------------------------- -// Delivery state (outbox) -// -// The outbox is the only source of per-message state: `Queued` / `Sending` / -// `Failed` rows are what `Node::outbox_pending` still holds, and a row is -// deleted the moment the send crosses the circuit — so an outbound message with -// no row is `Sent`. No parallel state model, no new wire prefix. -// --------------------------------------------------------------------------- - -/// Longest short-form failure reason shown in a chat row. -pub const FAIL_REASON_BUDGET: usize = 24; - -/// Marker glyph for one delivery state. ASCII chrome falls back to `ok` for the -/// wordless delivered state; `queued` / `sending` / `failed` already carry their -/// word, so their glyph is dropped rather than invented. -pub fn delivery_glyph(status: &OutboxStatus) -> &'static str { - let ascii = ascii_chrome(); - match status { - OutboxStatus::Sent => { - if ascii { - "ok" - } else { - "✓" - } - } - OutboxStatus::Queued => { - if ascii { - "" - } else { - "◷" - } - } - OutboxStatus::Sending => { - if ascii { - "" - } else { - "»" - } - } - OutboxStatus::Failed(_) => { - if ascii { - "" - } else { - "✗" - } - } - } -} - -/// Next-attempt age for a queued row, from the absolute `next_attempt_at` the -/// outbox stores. -pub fn retry_in_text(next_in_secs: i64) -> String { - if next_in_secs <= 0 { - "retry now".to_string() - } else if next_in_secs < 60 { - format!("retry {next_in_secs}s") - } else { - format!("retry {}m", (next_in_secs + 59) / 60) - } -} - -/// Transport failure text, short form: sanitized, tail of the `a: b: c` chain, -/// capped at `budget` cells so one peer's error cannot blow out the row. -pub fn short_send_reason(why: &str, budget: usize) -> String { - let clean = sanitize::display_text(why.as_bytes()); - let tail = clean.rsplit(": ").next().unwrap_or("").trim(); - let text = if tail.is_empty() { clean.trim() } else { tail }; - truncate_chars(text, budget) -} - -/// One row's delivery marker, straight from the outbox state. -pub fn delivery_tag(status: &OutboxStatus, attempts: u32, next_in_secs: i64) -> String { - let glyph = delivery_glyph(status); - let body = match status { - OutboxStatus::Sent => String::new(), - OutboxStatus::Queued => format!( - "queued (try {attempts}/{DEFAULT_MAX_ATTEMPTS}, {})", - retry_in_text(next_in_secs) - ), - OutboxStatus::Sending => "sending".to_string(), - OutboxStatus::Failed(why) => { - format!("failed: {}", short_send_reason(why, FAIL_REASON_BUDGET)) - } - }; - match (glyph.is_empty(), body.is_empty()) { - (_, true) => glyph.to_string(), - (true, false) => body, - (false, false) => format!("{glyph} {body}"), - } -} - -/// Footer summary derived from the outbox rows of the selected friend. -#[derive(Debug, Default, Clone, PartialEq, Eq)] -pub struct OutboxSummary { - /// `Queued` + `Sending`: rows the worker may still deliver. - pub queued: usize, - /// Terminal failures — these never retry. - pub failed: usize, - /// First terminal failure, for the fail-closed footer copy. - pub first_error: Option, -} - -impl OutboxSummary { - /// Footer note, or `None` when nothing is outstanding. Any terminal failure - /// keeps a `send failed` statement so the fail-closed copy stays visible. - pub fn note(&self) -> Option { - let reason = || { - short_send_reason( - self.first_error.as_deref().unwrap_or("unknown"), - FAIL_REASON_BUDGET, - ) - }; - match (self.queued, self.failed) { - (0, 0) => None, - (queued, 0) => Some(format!("{queued} queued")), - (0, 1) => Some(format!("send failed: {}", reason())), - (0, failed) => Some(format!("send failed: {} ({failed} failed)", reason())), - (queued, _) => Some(format!("{queued} queued, send failed: {}", reason())), - } - } -} - -/// Chat transcript with per-message delivery state, plus the footer summary. -/// -/// Pending rows are matched to messages by body, newest send first: an -/// outstanding retry is the most recent send of that text, and the outbox holds -/// no message id the UI could join on. -pub fn chat_with_delivery( - msgs: &[Message], - pending: &[OutboxEntry], - now: i64, -) -> (Vec, OutboxSummary) { - let mut summary = OutboxSummary::default(); - for entry in pending { - match &entry.status { - OutboxStatus::Failed(why) => { - summary.failed += 1; - summary.first_error.get_or_insert_with(|| why.clone()); - } - _ => summary.queued += 1, - } - } - if msgs.is_empty() { - return ( - empty_friend_chat_text() - .lines() - .map(str::to_string) - .collect(), - summary, - ); - } - - let mut by_body: HashMap<&[u8], Vec<&OutboxEntry>> = HashMap::new(); - for entry in pending { - by_body - .entry(entry.body.as_slice()) - .or_default() - .push(entry); - } - let mut tags: Vec> = vec![None; msgs.len()]; - for (i, msg) in msgs.iter().enumerate().rev() { - if msg.dir != "out" { - continue; - } - if let Some(rows) = by_body.get_mut(msg.plaintext.as_slice()) - && let Some(entry) = rows.pop() - { - tags[i] = Some(delivery_tag( - &entry.status, - entry.attempts, - entry.next_attempt_at - now, - )); - } - } - - let lines = msgs - .iter() - .enumerate() - .map(|(i, msg)| { - let side = if msg.dir == "out" { "you" } else { "them" }; - let body = sanitize::display_text(&msg.plaintext); - let tag = match tags[i].clone() { - Some(tag) => tag, - None if msg.dir == "out" => delivery_tag(&OutboxStatus::Sent, 0, 0), - None => String::new(), - }; - if tag.is_empty() { - format!("{side}: {body}") - } else { - format!("{side}: {body} {tag}") - } - }) - .collect(); - (lines, summary) -} - /// Paste overlay copy. Error keeps the resubmit hint. pub fn paste_screen_text(buf: &str, err: Option<&str>) -> String { let hint = match err { @@ -1713,13 +1515,11 @@ impl App { let (tx, rx) = mpsc::channel(); self.status_note = Some("sending".into()); std::mem::drop(self.rt.spawn(async move { - // `send()` reports `Sent` when the circuit took it and `Queued` when - // the peer's onion is unreachable. The footer then reads the real - // row count from the outbox, so this note is only the first word. + // send() now reports `Sent`/`Queued`; surfacing `queued` in the + // footer is a follow-up card, so this arm keeps today's wording. let note = match node.send(&pk, &body).await { - Ok(OutboxStatus::Sent) => "sent".to_string(), - Ok(_) => "queued".to_string(), - Err(e) => format!("send failed: {}", short_send_reason(&e, FAIL_REASON_BUDGET)), + Ok(_) => "sent".to_string(), + Err(e) => format!("send failed: {e}"), }; let _ = tx.send(note); })); @@ -1829,22 +1629,38 @@ impl App { } f.render_stateful_widget(roster, panes[0], &mut roster_state); - let (chat_lines, summary) = self.chat_view(); - let chat_name = self.friends.get(self.selected).map(|friend| { - friend - .petname - .as_deref() - .unwrap_or(&friend.fingerprint) - .to_string() - }); - draw_chat( - f, - panes[1], - &chat_lines, - chat_name.as_deref(), - self.focus == Pane::Chat, - self.chat_scroll, - ); + let chat_lines = self.chat_lines(); + let inner_h = panes[1].height.saturating_sub(2); + let nlines = chat_lines.len(); + let max_scroll = nlines.saturating_sub(inner_h as usize) as u16; + let scroll = self.chat_scroll.min(max_scroll); + let overflow = nlines > inner_h as usize && inner_h > 0; + let chat_title = { + let name = self.friends.get(self.selected).map(|friend| { + friend + .petname + .as_deref() + .unwrap_or(&friend.fingerprint) + .to_string() + }); + let mut t = match name { + Some(n) => format!("chat {n}"), + None => "chat".to_string(), + }; + if overflow { + let end = (scroll as usize + inner_h as usize).min(nlines); + t.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1)); + } + let mark = if self.focus == Pane::Chat { "> " } else { " " }; + format!("{mark}{t}") + }; + let chat_text = chat_lines.join("\n"); + let chat = Paragraph::new(chat_text) + .style(style_text()) + .wrap(Wrap { trim: false }) + .scroll((scroll, 0)) + .block(self.pane_block(&chat_title, Pane::Chat)); + f.render_widget(chat, panes[1]); let mark = if self.focus == Pane::Composer { "> " @@ -1868,108 +1684,62 @@ impl App { cols[3], ); - let footer = self.footer_line(area.width, &summary); + let footer = self.footer_line(area.width); f.render_widget(Paragraph::new(footer).style(style_dim()), cols[4]); } - fn footer_line(&self, width: u16, summary: &OutboxSummary) -> String { - // The outbox is the source of truth while anything is outstanding; the - // transient note still covers "sending", "sent file x", "invoice sent". - let note = summary.note().or_else(|| self.status_note.clone()); + fn footer_line(&self, width: u16) -> String { status_footer( width, &self.me_fp, &self.me_onion, - note.as_deref(), + self.status_note.as_deref(), footer_hints(&self.screen), ) } - fn chat_view(&self) -> (Vec, OutboxSummary) { + fn chat_lines(&self) -> Vec { let Some(friend) = self.friends.get(self.selected) else { - return ( - vec![ - "no friends yet".into(), - "F3 paste an invite to add one".into(), - ], - OutboxSummary::default(), - ); + return vec![ + "no friends yet".into(), + "F3 paste an invite to add one".into(), + ]; }; match self.node.list_messages(&friend.pubkey) { - Ok(msgs) => { - let pending = self.node.outbox_pending(&friend.pubkey).unwrap_or_default(); - chat_with_delivery(&msgs, &pending, unix_now_secs()) - } - Err(e) => (vec![e], OutboxSummary::default()), + Ok(msgs) if msgs.is_empty() => empty_friend_chat_text() + .lines() + .map(str::to_string) + .collect(), + Ok(msgs) => msgs + .iter() + .map(|m| { + let side = if m.dir == "out" { "you" } else { "them" }; + format!("{side}: {}", sanitize::display_text(&m.plaintext)) + }) + .collect(), + Err(e) => vec![e], } } fn pane_block<'a>(&self, title: &'a str, pane: Pane) -> Block<'a> { - pane_block_for(title, self.focus == pane) + let focused = self.focus == pane; + let border = if focused { + style_accent() + } else { + style_border() + }; + let title_style = if focused { + style_accent().add_modifier(Modifier::BOLD) + } else { + style_dim() + }; + apply_chrome_borders(Block::default()) + .border_style(border) + .title(title) + .title_style(title_style) } } -/// Pane chrome without an `App`: focus is accent border + bold title, never -/// color alone (the `> ` marks come from the callers). -fn pane_block_for(title: &str, focused: bool) -> Block<'_> { - let border = if focused { - style_accent() - } else { - style_border() - }; - let title_style = if focused { - style_accent().add_modifier(Modifier::BOLD) - } else { - style_dim() - }; - apply_chrome_borders(Block::default()) - .border_style(border) - .title(title) - .title_style(title_style) -} - -fn unix_now_secs() -> i64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_secs() as i64) - .unwrap_or(0) -} - -/// Real chat-pane renderer: `App::draw_main` calls this, so width, wrap and -/// delivery-marker behaviour are testable without constructing a `Node`. -pub fn draw_chat( - f: &mut Frame, - area: Rect, - lines: &[String], - name: Option<&str>, - focused: bool, - scroll: u16, -) { - let inner_h = area.height.saturating_sub(2); - let nlines = lines.len(); - let max_scroll = nlines.saturating_sub(inner_h as usize) as u16; - let scroll = scroll.min(max_scroll); - let overflow = nlines > inner_h as usize && inner_h > 0; - let mut title = match name { - Some(n) => format!("chat {n}"), - None => "chat".to_string(), - }; - if overflow { - let end = (scroll as usize + inner_h as usize).min(nlines); - title.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1)); - } - let mark = if focused { "> " } else { " " }; - let title = format!("{mark}{title}"); - f.render_widget( - Paragraph::new(lines.join("\n")) - .style(style_text()) - .wrap(Wrap { trim: false }) - .scroll((scroll, 0)) - .block(pane_block_for(&title, focused)), - area, - ); -} - /// Status bar: never drop a non-empty `status_note`. Always keep `TOR`, `me:`, `? help`. pub fn status_footer( width: u16, @@ -1985,7 +1755,7 @@ pub fn status_footer( let mut note = status_note.unwrap_or("").trim().to_string(); if !note.is_empty() && color_mode() == ColorMode::None - && (note.contains("send failed") || note == "fingerprint mismatch") + && (note.starts_with("send failed") || note == "fingerprint mismatch") && !note.starts_with("! ") { note = format!("! {note}"); diff --git a/tests/tui_spec.rs b/tests/tui_spec.rs index 5715085..2310487 100644 --- a/tests/tui_spec.rs +++ b/tests/tui_spec.rs @@ -1,13 +1,10 @@ //! 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, 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, paste_screen_text, retry_in_text, roster_col_width, short_send_reason, + alert_line, ascii_chrome, draw_share, draw_text_overlay, empty_friend_chat_text, + help_overlay_text, main_footer_hints, main_header_line, paste_screen_text, roster_col_width, status_footer, wrap_invite, }; use ratatui::Frame; @@ -379,376 +376,3 @@ fn ascii_switch_80x24_frame_is_pure_ascii() { 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(body: &str) -> Message { - Message { - dir: "out".into(), - plaintext: body.as_bytes().to_vec(), - } -} - -fn in_msg(body: &str) -> Message { - Message { - dir: "in".into(), - plaintext: body.as_bytes().to_vec(), - } -} - -fn pending_row( - body: &str, - status: OutboxStatus, - attempts: u32, - next_in: i64, - now: i64, -) -> OutboxEntry { - OutboxEntry { - id: 1, - friend_pk: vec![9u8; 32], - message_id: 1, - body: body.as_bytes().to_vec(), - attempts, - next_attempt_at: now + next_in, - created_at: now, - status, - last_error: None, - } -} - -fn queued_row(body: &str, attempts: u32, next_in: i64, now: i64) -> OutboxEntry { - pending_row(body, OutboxStatus::Queued, attempts, next_in, now) -} - -fn sending_row(body: &str, now: i64) -> OutboxEntry { - pending_row(body, OutboxStatus::Sending, 1, 0, now) -} - -fn failed_row(body: &str, why: &str, now: i64) -> OutboxEntry { - pending_row(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("ping"), out_msg("pong")]; - let pending = vec![queued_row("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); -} - -#[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("alpha"), - out_msg("beta"), - out_msg("gamma"), - out_msg("delta"), - in_msg("epsilon"), - ]; - let pending = vec![ - failed_row("alpha", "connect peer.onion:80: connection timed out", now), - queued_row("beta", 1, 30, now), - sending_row("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, - }; - assert_eq!(queued.note().as_deref(), Some("2 queued")); - - let failed = OutboxSummary { - queued: 0, - failed: 1, - first_error: Some("connect peer.onion:80: connection timed out".into()), - }; - 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()), - }; - let mixed_note = mixed.note().expect("mixed rows must produce a note"); - assert!(mixed_note.contains("3 queued"), "{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(¬e), 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("2 queued"), "{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(¬e), 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("ok"), in_msg("pong"), out_msg(long)]; - let pending = vec![queued_row(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("1 queued"), - "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("1 queued")); - - // 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); -}