Compare commits

..
Author SHA1 Message Date
apk-dev
b053bed702
feat(android): stop the node when the UI goes away
All checks were successful
ci / test (pull_request) Successful in 3m15s
`WireViewModel.lock()` set `wire = null` and `onCleared()` did not exist at all,
so neither the user pressing Lock nor the Activity finishing stopped anything:
Arti kept its client and the hosted onion service, the outbox worker kept
dialing, and the sqlite connection stayed open behind the JNI handle.

Both paths now go through `stopNode(Wire)`:

1. `flush()` — one last bounded drain, so a queued message gets its chance
   before the process may lose its socket.
2. `shutdown()` — drain again with a shorter budget, stop the onion service,
   abort the retry worker, checkpoint the WAL, and take the node handle out of
   the `Wire` (which is what releases the last Arc to the Tor client and the
   store).

Both run on a process-scoped `TEARDOWN` scope (`SupervisorJob` + `Dispatchers.IO`)
because `onCleared()` runs *after* `viewModelScope` is already cancelled. Errors
are deliberately swallowed there: the UI is gone, and the SDK reports a second
teardown as the typed `WireException.Stopped` rather than a panic.

`unlock()` joins any in-flight teardown before opening again. The old node holds
the sqlite file and Arti's state lock until its teardown returns, and racing it
makes the next `openWire` fail.

A process killed outright (Doze, background-process killer, force-stop) still
never runs any of this — that is what the sqlite outbox and the new `flush()`
are for. The foreground-service card (`t_5bf32cd3`) moves this ownership from
the ViewModel to the service.
2026-09-12 14:37:43 -04:00
apk-dev
6e0226e386
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state
A node had no way to stop. `Wire` was a bare handle over a `Node`: dropping the
Kotlin reference left Arti's client, the hosted v3 onion service, the outbox
retry worker and the sqlite connection alive, and there was no way to ask where
the onion service was. On Android the process is killed without warning by Doze
and the background-process killer, so "drop everything when the process dies" is
not a lifecycle.

Core (`src/node.rs`, `src/hs.rs`):

* `Node::shutdown()` — bounded outbox drain (10s), stop the onion service (the
  rendezvous task is aborted and the RunningOnionService dropped), abort the
  retry worker, checkpoint the sqlite WAL. Idempotent at this level: the flag is
  swapped first, so a racing second call is a no-op.
* `Node::flush() -> FlushOutcome { attempted, delivered, remaining }` — one
  delivery attempt for every queued outbox row, ignoring backoff, then a WAL
  checkpoint. Bounded by 30s because a dead peer's onion holds a dial for ~20s
  and the caller is a UI thread. A timeout leaves rows in `sending`;
  `Outbox::reset_stale` requeues them on the next unlock, same as a process that
  died mid-attempt.
* `Node::tor_state() -> TorState` (`Bootstrapping` / `Published` /
  `DegradedReachable` / `Stopped`) and `hs::tor_state_of(state, stopped,
  reachable)`, which mirrors `hs_is_ready` exactly instead of re-deriving
  readiness.
* Every network entry point (`send`, `send_once`, `connect_onion`, `rotate`,
  `flush`) fails with a typed error after the node stops, rather than dialing a
  dead client.
* `checkpoint_wal` reaches the database through a short-lived second connection:
  `Store` owns the write connection and does not lend it out, and a checkpoint is
  a property of the database, not of one connection. Best effort — WAL replay on
  open recovers anything committed.

The `WorkerHandle` moved into a `Mutex<Option<...>>` so the teardown can *abort*
the retry worker instead of only dropping it when the whole `Node` dies.

SDK (`crates/onionwire-sdk/src/lib.rs`):

* `Wire.shutdown()`, `Wire.flush(): FlushOutcome`, `Wire.torState(): TorState`.
  `Wire` now holds `Mutex<Option<Arc<Node>>>`, so teardown drops the last
  reference to the Tor client and the store instead of keeping them alive behind
  a JNI handle.
* `WireError::Stopped` — a second flat variant, so "you must unlock again" is a
  typed `WireException.Stopped` in Kotlin, not a string match on `Failed`.
* No `unwrap()` on a poisoned mutex anywhere: a poisoned handle reports
  `Stopped`, which is the correct recovery (unlock again).
* Fixes the crate not compiling on this base at all: `Node::send` has returned
  `Result<OutboxStatus, String>` since the outbox landed, and the SDK still
  mapped it to `Result<(), String>` (E0308). CI's path allowlist excludes
  `crates/**` from the Rust job, which is why it stayed green.

The live Tor test found a real bug in the first version of `tor_state`: Arti's
combined status is still `Bootstrapping` after a *successful* probe of our own
onion (that mismatch is what the 360s publish wait exists for), and a freshly
launched service reports `Shutdown` before its publish reactor starts — so a
node that was live and reachable reported `Bootstrapping`, and briefly
`Stopped`, right after unlock. `Node` now tracks an `onion_reachable` flag set
when the publish bar is crossed and cleared when `rotate` hard-cuts the service,
and `Shutdown`/`Broken` on a live node read `Bootstrapping` (transient) rather
than terminal.
2026-09-12 14:37:43 -04:00
Sirius DevOps
068b655c19
feat(outbox): local retry queue for chat sends
All checks were successful
ci / test (pull_request) Successful in 3m22s
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.

- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
  is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
  messages row, under that row's existing AEAD + AAD), append_message_id(),
  queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
  Err on transport failure; protocol errors still fail immediately and are
  never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
  was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
  add the seizure/cadence delta to the threat model.

src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 13:55:07 -04:00
e6e2a158a8 Merge pull request 'feat(tui): ASCII chrome, invite wrap, remaining copy' (#27) from wt/t_b02176dc into main
All checks were successful
ci / test (push) Successful in 3m16s
release / version (push) Successful in 3s
release / x86_64 (push) Successful in 1m53s
release / aarch64 (push) Successful in 2m24s
release / publish (push) Successful in 11s
Reviewed-on: #27
2026-09-12 17:47:52 +00:00
Sirius DevOps
35b8caa716
feat(tui): ASCII chrome, invite wrap, alert truncate, remaining copy
Some checks failed
ci / test (pull_request) Failing after 4m39s
ONIONWIRE_ASCII (and NO_COLOR) switches truncation to ... and ASCII
borders. Share/paste wrap at : so a mouse-copy cannot lose a mid-hex
line. Alerts truncate to the frame; empty threads and paste errors keep
the next-step hint. Skip the optional 40-row wordmark.
2026-09-12 00:54:16 -04:00
4 changed files with 355 additions and 21 deletions

View file

@ -510,3 +510,63 @@ add it on this card. Preferred: depend on `unicode-width` explicitly and assert
`tests/tui_frames.rs` `chars_count_is_not_terminal_cells` documents the three
examples without adding a crate.
## After frames (spacing / ASCII / wrap / copy)
Base: `origin/main` after PR #24 (`33beede`). Hierarchy, fail-closed footer,
1-line header, roster width, help overlay, and `NO_COLOR` palette are unchanged
here. Optional 3-line wordmark at height ≥ 40 was skipped (it fights the 1-line
header without buying hierarchy).
### 80x24 — `draw_share` after (field-boundary wrap)
Invite lines break on `:`. `sig=` hex that does not fit continues as an
all-hex line. Joining those lines (no extra spaces) is the original payload.
```
┌(o) invite────────────────────────────────────────────────────────────────────┐
│give this string to a friend; they F3 paste it │
│ │
│fp ea4a6c63… │
│onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion │
│ │
│onionwire:v1: │
│k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: │
│o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: │
│spk=0101010101010101010101010101010101010101010101010101010101010101: │
│sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e0│
│5401b0af934cefea617f71466f406af4bef956847200a8e915190b │
└──────────────────────────────────────────────────────────────────────────────┘
```
### 80x24 — ASCII switch (`ONIONWIRE_ASCII=1`)
No non-ASCII byte. Truncation marker is `...`. Borders are `+` `-` `|`.
```
+(o) invite--------------------------------------------------------------------+
|give this string to a friend; they F3 paste it |
| |
|fp ea4a6c63... |
|onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion |
| |
|onionwire:v1: |
|k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: |
|o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: |
|spk=0101010101010101010101010101010101010101010101010101010101010101: |
|sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e0|
|5401b0af934cefea617f71466f406af4bef956847200a8e915190b |
+------------------------------------------------------------------------------+
```
### 80x24 / 120x40 — main chrome after
Same 1-line header, unboxed composer, fail-closed footer as PR #24. Dump:
```
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.

View file

@ -1038,8 +1038,15 @@ fn spawn_flush_friend(outbox: Arc<Outbox>, friend_pk: Vec<u8>) {
/// `Store` owns the write connection and deliberately does not lend it out, and
/// a checkpoint is a property of the *database*, not of one connection — so a
/// short-lived second connection to the same file is the least invasive way to
/// reach it from the node without widening `Store`'s API. The checkpoint needs
/// no passphrase: it moves already-committed pages, it does not decrypt them.
/// reach it from the node without widening `Store`'s API.
///
/// That works because the connection needs no passphrase: it moves
/// already-committed pages, it does not decrypt them. It stops working the
/// moment the store is SQLCipher-encrypted (PR #43), because the key lives only
/// inside `Store` and a second connection cannot read the file at all. That case
/// is detected and reported as a skip rather than a failure: nothing is lost
/// (sqlite folds the WAL into the db when the last connection closes) — the
/// explicit truncation just has to move inside `Store` to happen here.
fn checkpoint_wal(home: &Path) -> Result<(), String> {
let db = home.join("onionwire.db");
if !db.exists() {
@ -1050,7 +1057,15 @@ fn checkpoint_wal(home: &Path) -> Result<(), String> {
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
})
.map_err(|e| format!("wal_checkpoint: {e}"))?;
.map_err(|e| {
let msg = e.to_string();
if msg.contains("not a database") {
// SQLCipher store: no key here, so this connection sees noise.
format!("store is SQLCipher-encrypted — skipped ({msg})")
} else {
format!("wal_checkpoint: {msg}")
}
})?;
if busy != 0 {
// Another connection is reading/writing: pages are still safe in the
// WAL, they just were not moved this time.

View file

@ -5,6 +5,7 @@ use std::time::Duration;
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::symbols::border;
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap};
use ratatui::{DefaultTerminal, Frame};
@ -38,8 +39,90 @@ fn color_mode() -> ColorMode {
}
}
/// ASCII chrome when `ONIONWIRE_ASCII` or `NO_COLOR` is set. No extra crate.
pub fn ascii_chrome() -> bool {
std::env::var_os("ONIONWIRE_ASCII").is_some() || std::env::var_os("NO_COLOR").is_some()
}
const ASCII_BORDERS: border::Set = border::Set {
top_left: "+",
top_right: "+",
bottom_left: "+",
bottom_right: "+",
vertical_left: "|",
vertical_right: "|",
horizontal_top: "-",
horizontal_bottom: "-",
};
fn ellipsis() -> &'static str {
"…"
if ascii_chrome() { "..." } else { "…" }
}
/// Truncate or keep an alert so it cannot spill into the roster row.
pub fn alert_line(msg: &str, width: u16) -> String {
let mut text = msg.to_string();
if color_mode() == ColorMode::None && !text.starts_with("! ") {
text = format!("! {text}");
}
truncate_chars(&text, width as usize)
}
/// Wrap an invite at `:` so a mouse-copy cannot lose a mid-hex continuation.
/// Joining the lines (no extra spaces) reconstructs `payload`.
pub fn wrap_invite(payload: &str, width: usize) -> String {
if width == 0 {
return String::new();
}
let mut lines: Vec<String> = Vec::new();
let mut cur = String::new();
let parts: Vec<&str> = payload.split(':').collect();
for (i, part) in parts.iter().enumerate() {
let piece = if i + 1 < parts.len() {
format!("{part}:")
} else {
(*part).to_string()
};
for chunk in char_chunks(&piece, width) {
if cur.is_empty() {
cur = chunk;
} else if char_len(&cur) + char_len(&chunk) <= width {
cur.push_str(&chunk);
} else {
lines.push(std::mem::take(&mut cur));
cur = chunk;
}
}
}
if !cur.is_empty() {
lines.push(cur);
}
lines.join("\n")
}
fn char_chunks(s: &str, width: usize) -> Vec<String> {
if width == 0 {
return Vec::new();
}
if char_len(s) <= width {
return vec![s.to_string()];
}
let chars: Vec<char> = s.chars().collect();
chars.chunks(width).map(|c| c.iter().collect()).collect()
}
/// Friend selected, no messages yet.
pub fn empty_friend_chat_text() -> &'static str {
"no messages\ntype below, Enter sends"
}
/// Paste overlay copy. Error keeps the resubmit hint.
pub fn paste_screen_text(buf: &str, err: Option<&str>) -> String {
let hint = match err {
Some(e) => format!("{e}\nEnter resubmits Esc back"),
None => "paste onionwire:v1 payload, Enter to submit".to_string(),
};
format!("{hint}\n\n{buf}")
}
fn char_len(s: &str) -> usize {
@ -1431,11 +1514,7 @@ impl App {
f.render_widget(Paragraph::new(header).style(style_accent()), cols[0]);
if let Some(msg) = &self.alert {
let text = if color_mode() == ColorMode::None && !msg.starts_with("! ") {
format!("! {msg}")
} else {
msg.clone()
};
let text = alert_line(msg, area.width);
f.render_widget(Paragraph::new(text).style(style_alert()), cols[1]);
}
@ -1561,7 +1640,10 @@ impl App {
];
};
match self.node.list_messages(&friend.pubkey) {
Ok(msgs) if msgs.is_empty() => vec!["no messages".into()],
Ok(msgs) if msgs.is_empty() => empty_friend_chat_text()
.lines()
.map(str::to_string)
.collect(),
Ok(msgs) => msgs
.iter()
.map(|m| {
@ -1585,8 +1667,7 @@ impl App {
} else {
style_dim()
};
Block::default()
.borders(Borders::ALL)
apply_chrome_borders(Block::default())
.border_style(border)
.title(title)
.title_style(title_style)
@ -1701,9 +1782,17 @@ fn footer_hints(screen: &Screen) -> &'static str {
}
}
fn apply_chrome_borders(block: Block<'_>) -> Block<'_> {
let block = block.borders(Borders::ALL);
if ascii_chrome() {
block.border_set(ASCII_BORDERS)
} else {
block
}
}
fn themed_block(title: &str) -> Block<'_> {
Block::default()
.borders(Borders::ALL)
apply_chrome_borders(Block::default())
.border_style(style_accent())
.title(title)
.title_style(style_accent().add_modifier(Modifier::BOLD))
@ -1714,8 +1803,10 @@ pub fn draw_share(f: &mut Frame, payload: &str) {
Ok(p) => (truncate_fp(&to_hex(&p.pubkey)), p.onion),
Err(_) => ("?".into(), "?".into()),
};
let inner = f.area().width.saturating_sub(2) as usize;
let invite = wrap_invite(payload, inner.max(1));
let body = format!(
"give this string to a friend; they F3 paste it\n\nfp {fp}\nonion {onion}\n\n{payload}"
"give this string to a friend; they F3 paste it\n\nfp {fp}\nonion {onion}\n\n{invite}"
);
f.render_widget(
Paragraph::new(body)
@ -1727,10 +1818,9 @@ pub fn draw_share(f: &mut Frame, payload: &str) {
}
fn draw_paste(f: &mut Frame, buf: &str, err: Option<&str>) {
let hint = err
.unwrap_or("paste onionwire:v1 payload, Enter to submit")
.to_string();
let body = format!("{hint}\n\n{buf}");
let inner = f.area().width.saturating_sub(2) as usize;
let shown = wrap_invite(buf, inner.max(1));
let body = paste_screen_text(&shown, err);
let style = if err.is_some() {
style_alert()
} else {

View file

@ -1,17 +1,21 @@
//! Spec implementation tests for docs/TUI.md (this card).
//! Does not own `tests/tui_frames.rs` (PR #23).
use onionwire::qr;
use onionwire::tui::{
draw_text_overlay, help_overlay_text, main_footer_hints, main_header_line, roster_col_width,
status_footer,
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;
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";
fn screen_from(buf: &ratatui::buffer::Buffer, w: u16, h: u16) -> String {
@ -179,6 +183,8 @@ fn reconstructed_main_keeps_send_failed_on_footer() {
#[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");
@ -205,5 +211,168 @@ fn dump_spec_frames() {
.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:?}"
);
}
#[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") };
}