docs(tui): visual audit, before frames, and design spec #23

Merged
sirius merged 1 commit from wt/t_3c2d56df into main 2026-09-12 04:15:38 +00:00
2 changed files with 1056 additions and 0 deletions

512
docs/TUI.md Normal file
View file

@ -0,0 +1,512 @@
# OnionWire TUI — visual audit and design spec
This card does not change `src/`. Frames come from:
```
cargo test --locked --test tui_frames -- --nocapture dump_audit_frames
```
`tests/tui_chrome.rs` still locks helper **names** and **return strings**. Implementation
must keep `wordmark_banner`, `compact_banner`, `banner_for_width`, `onion_glyph`,
`status_footer`, `main_footer_hints`, `help_overlay_text`, `draw_share`, and `Pane`
working. Add helpers; do not rename those.
## Gaps (could not render the live `App` frame)
`App`, `App::draw`, `App::draw_main`, and every overlay except `draw_share` are
private and need `Arc<Node>` (Arti + store). This presentation-only test cannot
construct that.
| Screen / state | What you get | Why |
|---|---|---|
| Main chat (empty, messages, long line, stale roster, alert) | **RECONSTRUCTED** — same `Layout` constraints as `src/tui.rs` `draw_main` (banner height, 36% roster, composer 3, footer 1) plus the real `banner_for_width` / `status_footer` | `App` private |
| Help / `/who` overlay | **RECONSTRUCTED** — Rect math copied from private `draw_text_overlay` | private |
| Share / invite | **REAL** `draw_share` | public |
| Profile, paste, approve, rotate, wipe, quit, backup, restore, passphrase | **RECONSTRUCTED** — public `*_screen_text` / `ProfileEditor` copy inside `Block::bordered`, titles taken from `src/tui.rs` | private `draw_*` |
| Pay / invoice / file transfer | **No screen exists.** Footer `status_note` only (`invoice sent`, `sending`, `sent file {name}`, `send failed: {e}`) | not a gap in the test — a product finding |
| Tor bootstrap / disconnected HS | Not a TUI screen. `hs status: Bootstrapping` is stderr before `ratatui::init` | out of TUI draw |
| Color / `NO_COLOR` | Glyph dumps only. Color findings are from reading `src/tui.rs` | TestBackend prints symbols |
Color, focus-by-border, and RGB-only styling are invisible in these dumps. Treat
the reconstruction as the glyph skeleton, not a screenshot of Color.
## Deliverable 1 — before frames
Trailing spaces in the live buffer are omitted here. Re-run the command for
byte-identical dumps, including 120x40 and 200x60.
### 80x24 — chrome (`banner_for_width` + `status_footer`, real helpers)
```
.-~~-. .-~~-. .-~~-. ONIONWIRE
( o )( o )( o ) identity = pubkey onion = locator
`-..-' `-..-' `-..-' tor messenger no server
TOR me:abcdef01… onion:abcdefgh… Tab F2 F3 F4 F5 Ctrl-Q ? help
```
Same footer with `status_note = "send failed: connection timed out"` — the note
**does not appear**. Ident + hints win. Fail-closed copy is gone at 80 and at
120 (full onion eats the row). It only survives at 200.
### 80x24 — RECONSTRUCTED main, empty
```
.-~~-. .-~~-. .-~~-. ONIONWIRE
( o )( o )( o ) identity = pubkey onion = locator
`-..-' `-..-' `-..-' tor messenger no server
┌roster 0───────────────────┐┌chat─────────────────────────────────────────────┐
│ ││no friends yet │
│ ││F3 paste an invite to add one │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
└───────────────────────────┘└─────────────────────────────────────────────────┘
┌composer──────────────────────────────────────────────────────────────────────┐
│/wipe /wipe-all /profile /who /pay /tip /file │
└──────────────────────────────────────────────────────────────────────────────┘
TOR me:abcdef01… onion:abcdefgh… Tab F2 F3 F4 F5 Ctrl-Q ? help
```
### 80x24 — RECONSTRUCTED main, messages + stale + alert
```
.-~~-. .-~~-. .-~~-. ONIONWIRE
( o )( o )( o ) identity = pubkey onion = locator
`-..-' `-..-' `-..-' tor messenger no server
passphrases do not match
┌roster 2 1 stale──────────┐┌chat alice──────────────────────────────────────┐
│> alice aaaaaaaa… ││you: ping │
│ bob-the-stale-peer bbbbb││them: pong │
│ ││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 │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
└───────────────────────────┘└─────────────────────────────────────────────────┘
┌composer──────────────────────────────────────────────────────────────────────┐
│hello from composer │
└──────────────────────────────────────────────────────────────────────────────┘
sent TOR me:abcdef01… onion:abcdefgh… Tab F2 F3 F4 F5 Ctrl-Q ? help
```
Roster clips `bob-the-stale-peer bbbbb` mid-glyph. Chat wraps (good). Focus on
chat/composer is **not** visible in the glyph dump (color-only in `pane_block`).
### 80x24 — RECONSTRUCTED main, fail-closed send (note dropped)
```
.-~~-. .-~~-. .-~~-. ONIONWIRE
( o )( o )( o ) identity = pubkey onion = locator
`-..-' `-..-' `-..-' tor messenger no server
┌roster 2 1 stale──────────┐┌chat bob-the-stale-peer─────────────────────────┐
│ alice aaaaaaaa… ││no messages │
│> bob-the-stale-peer bbbbb││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
└───────────────────────────┘└─────────────────────────────────────────────────┘
┌composer──────────────────────────────────────────────────────────────────────┐
│/wipe /wipe-all /profile /who /pay /tip /file │
└──────────────────────────────────────────────────────────────────────────────┘
TOR me:abcdef01… onion:abcdefgh… Tab F2 F3 F4 F5 Ctrl-Q ? help
```
`status_note` was `send failed: peer onion down`. It is not on the frame.
`tests/tui_frames.rs` `status_footer_drops_send_failed_when_crowded` locks this
current behavior so the implementation card can flip it.
### 80x24 — `draw_share` (real)
Invite is 346 chars. Inner width 78. Wraps mid-hex. Full v3 onion fits on its
own line. No QR blocks (locked).
```
┌(o) invite────────────────────────────────────────────────────────────────────┐
│give this string to a friend; they F3 paste it │
│ │
│fp ea4a6c63… │
│onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion │
│ │
│onionwire:v1:k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22│
│c:o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion:spk=0101010│
│101010101010101010101010101010101010101010101010101010101:sig=46caf16b6da95e86│
│… │
└──────────────────────────────────────────────────────────────────────────────┘
```
### 80x24 — RECONSTRUCTED help overlay (private `draw_text_overlay` math)
Help is 22 content lines + border. Popup height is `min(lines, height-2)` = 22,
so it covers the banner, punches through roster/composer borders, and **clips**
`Esc closes this overlay`.
```
.-~~-. .-~~-. .-~~-. ONIONWIRE
( o ┌? help─────────────────────────────────────────────────────────┐
`-..-' │OnionWire keys │
┌roster│ │───────┐
│ │Tab / Shift-Tab cycle roster, chat, composer │ │
│ │… │ │
│ │/backup /path encrypted identity export │ │
└──────│/restore /path overwrite self keys │───────┘
┌compos│? this help │───────┐
│/wipe │Ctrl-Q quit; type CLEAR or QUIT │ │
└──────└───────────────────────────────────────────────────────────────┘───────┘
TOR me:abcdef01… onion:abcdefgh… Tab F2 F3 F4 F5 Ctrl-Q ? help
```
### 80x24 — other overlays (copy is real)
- Profile: `> name:` marker (good). Empty xmr is a blank value, not `(none)`.
- Paste: same wrap-mid-hex as share. Error state replaces the hint with the
error string (no "what next").
- Approve / rotate / wipe / quit / backup / passphrase: full-screen bordered
column of copy + typed buffer. Readable. Fine as modal confirmations.
- `/who`: overlay Clear is only the popup rect; chat remnants (`d`, `ff`) show
in the side gutters. Full onion is shown (good).
### 120x40 / 200x60
At 120, `status_footer` shows the **full** 62-char onion and still drops
`send failed: …`. At 200 the note survives in front of `TOR`. Banner stays the
3-line wordmark (width ≥ 63). Chat pane is large; hierarchy problem is worse
(more empty bordered void), not better. Dump: same cargo command.
## Deliverable 2 — findings
Walked in `tui-aesthetics` ladder order.
### 1. Clipping / overlap
| Sev | Where | Wrong | User impact |
|---|---|---|---|
| **blocker** | `src/tui.rs:1505` `status_footer` candidate list | Fail-closed `status_note` (`send failed: …`) is skipped when ident+hints fill the row. Proven at 80 and 120. | Peer down looks like success. The product rule is "send visibly fails". |
| **major** | `src/tui.rs:1702` `draw_text_overlay` | No `Wrap`. Height clipped to `area.height-2`. At 80x24 help overlaps banner/roster/composer and drops the last line. | `?` is unreadable on the floor size. |
| **major** | `src/tui.rs:1355` roster `format!("{name} {fp}")` | No truncate. `bob-the-stale-peer bbbbb` clips inside the 36% pane. | Cannot tell who is selected/stale. |
| **major** | `src/tui.rs:1570` `draw_share` (and paste body) | 346-char invite wraps mid-token at inner width 78. | Mouse-select copy is split; easy to miss a continuation line. |
| **minor** | `src/tui.rs:1334` alert | Alert is one raw line, no wrap/truncate. | Long error will collide with roster on the next row. |
| **nit** | `tests/tui_chrome.rs:15` (and `src/tui.rs:1512`, `1707`) | Width via `chars().count()`. See deliverable 4. | CJK/emoji can wrap in a real terminal while tests stay green. |
### 2. Hierarchy
| Sev | Where | Wrong | User impact |
|---|---|---|---|
| **major** | `src/tui.rs:1314` `draw_main` | Three-line wordmark + two equal bordered panes + bordered composer + footer. Chat is not the primary element. At 80x24, 3 rows of art + 3 composer + 1 footer + 2×2 borders leave the transcript starved. | First glance is ASCII onions, not the conversation. |
| **major** | `src/tui.rs:1340` | Roster is 36% of width on every size. | Chat (the primary pane) is the leftover. |
| **minor** | every `themed_block` / `pane_block` | Border on every pane, including composer and full-screen modals. | Eye cannot find content; "box drawing UI". |
### 3. Spacing
| Sev | Where | Wrong | User impact |
|---|---|---|---|
| **minor** | `src/tui.rs:1328` banner vs `1367` lists | Banner has no inner pad; list/paragraph sit against borders; footer has no pad. Mixed 0 and 1. | Ragged left edge: chat `no friends yet` vs roster empty. |
| **nit** | `src/tui.rs:93` `/file /path` extra space vs other slash rows | Help columns almost align, one extra space. | Looks unfinished. Do **not** change `help_overlay_text` unless `tui_chrome` is updated — the string is locked. Leave the space. |
### 4. States
| Sev | Where | Wrong | User impact |
|---|---|---|---|
| **major** | `src/tui.rs:1349` empty roster | `List` with zero items → blank pane titled `roster 0`. Empty copy lives only in chat. | Looks broken, not empty. |
| **major** | pay / tip / file | No pane. Outcome is a footer note that 80/120 may drop. | `/pay` and `/file` feel like they did nothing. |
| **minor** | `src/tui.rs:1414` empty composer | Placeholder is the slash cheatsheet, dim color only. | Reads as commands already typed. |
| **minor** | `src/tui.rs:1456` `no messages` | One word. No "type below, Enter sends". | Dead pane. |
| **nit** | loading | `sending` in footer, 100 ms poll, no spinner. | Correct. Keep. |
There is no dedicated disconnected screen. Stale friends get a `stale` suffix
(`src/tui.rs:1357`) — keep the word, not color-only.
### 5. Color
| Sev | Where | Wrong | User impact |
|---|---|---|---|
| **major** | `src/tui.rs:15-21` | Seven RGB colors. No 16-color map. No `NO_COLOR`. | 16-color and `NO_COLOR` terminals get garbage or still emit ANSI. |
| **minor** | `src/tui.rs:1359-1372` | Stale is `C_STALE` plus the word `stale` (ok). Selection is bg+fg+bold+`> ` (ok for roster). | Chat/composer focus is color-only (see focus). |
Accent RGB `(232,165,75)` is fine as **the** accent. Do not add more hues.
### 6. Focus
| Sev | Where | Wrong | User impact |
|---|---|---|---|
| **major** | `src/tui.rs:1468` `pane_block` | Focused chat/composer: accent border + bold title. No marker. Roster has `> `. | Monochrome / `NO_COLOR`: cannot see focus unless roster. Typing `j`/`k` feels dead. |
### 7. Motion
| Sev | Where | Wrong | User impact |
|---|---|---|---|
| **nit** | `src/tui.rs:24` `TUI_POLL` 100 ms | Full `terminal.draw` every poll even with no keys, so background send can refresh status. | Acceptable. No decorative spinner. Do not redraw faster. |
### 8. Copy
| Sev | Where | Wrong | User impact |
|---|---|---|---|
| **minor** | `src/tui.rs:1583` paste error | Error replaces the paste hint. No "what next". | User sees `bad invite` and an empty buffer. |
| **minor** | `src/tui.rs:1415` | Composer placeholder is a command dump, not a verb. | Conflicts with `?` help. |
| **nit** | `src/tui.rs:36` | `fingerprint mismatch` is a good short fail-closed string when it actually reaches the footer. | Often dropped (finding 1). |
### Untrusted text
`src/tui.rs:1461` `String::from_utf8_lossy(&m.plaintext)` goes into `Paragraph`
with wrap, **no** control/bidi strip, **no** ellipsis cap. Profile `bio` /
`display_name` and paste buffer are the same class. A separate in-flight PR
owns sanitization — do not duplicate it here. Implementation must call that
helper (or the agreed strip) on every peer-supplied string before draw.
## Deliverable 3 — spec (implement this)
### Pane structure
One primary element per screen.
| Screen | Primary | Secondary | Chrome |
|---|---|---|---|
| Main | Chat transcript | Roster (left, **22 cells** at 80, **28** at 120+, not 36%) | 1-line header, 3-row composer, 1-row status |
| Share / paste / approve | The invite string / typed buffer | fp + onion above it | title `(o) invite` etc. Keep `draw_share` public |
| Profile | The three fields with `>` on the active one | — | title `(o) profile` |
| Rotate / wipe / quit / backup / restore / passphrase | The confirm copy + typed token | — | existing titles |
| Help | The help text, **full screen** when `height < 28`, else a centered overlay that **fits** (wrap, scroll if needed, never clip the last line) | — | title `? help` |
| `/who` | Profile fields | — | same overlay rules as help |
| Pay / file | **None.** Stay on main. Status line carries the result. | — | — |
`draw_main` at `height <= 24` **must not** spend 3 rows on `wordmark_banner()`.
Use a one-line header. Do **not** change `banner_for_width(80)` — chrome tests
lock it to the wordmark. Add `main_header_line(width, fp, onion)` or call
`compact_banner()` plus ident. At `height >= 40`, the 3-line wordmark **may**
sit above the one-line ident; it is optional, not required.
### Spacing unit
**1 cell.** Apply as:
- Header: no box. One space between fields.
- Roster / chat: `Block` with `Borders::ALL` **only on those two** (the primary
split). Inner text starts one cell after the border (ratatui default).
- Composer: **no** outer box. Prefix `> ` when focused, ` ` when not. One
blank row is not required; the 3-row slot stays for wrapped input.
- Footer: no box. One space between clusters, two spaces between clusters if
width ≥ 120.
- Overlays: one box around the popup. No nested padding.
### Palette
One accent. Semantic color only for state. Pair every color with a glyph or
label.
| Role | RGB (keep) | 16-color | `NO_COLOR` |
|---|---|---|---|
| accent | `Rgb(232,165,75)` | `Yellow` | default + bold / reverse |
| text | `Rgb(196,214,176)` | `White` | default |
| dim | `Rgb(98,110,92)` | `DarkGray` | default |
| alert | `Rgb(220,80,70)` | `Red` | default + `! ` prefix |
| stale | `Rgb(210,180,80)` | `Yellow` | default + ` stale` (already) |
| highlight bg | `Rgb(48,42,28)` | `Reverse` | reverse |
| border | `Rgb(72,84,64)` | `DarkGray` | default |
`NO_COLOR` set (empty or any value): no `Style` fg/bg at all. Glyphs and
weight only.
Detection: `std::env::var_os("NO_COLOR")` is Some → no color. Else if the
backend is not a TTY or `TERM=dumb` → 16-color or no color, never RGB.
Else RGB as today.
### Glyphs
| Use | Unicode | ASCII fallback |
|---|---|---|
| onion / share title | `(o)` (already) | `(o)` |
| focus | `> ` | `> ` |
| truncate | `…` (`src/tui.rs:1730`) | `...` (budget 3 cells) |
| box | ratatui `Borders::ALL` (light) | `+` `-` `\|` via `border::Set` |
| alert prefix | `! ` | `! ` |
| stale | word `stale` | `stale` |
No emoji. `onion_glyph()` stays for callers that already use it; do not put it
on the main header.
ASCII chrome when `ONIONWIRE_ASCII` is set **or** when `NO_COLOR` is set (same
switch is enough; do not add a crate).
### Focus
Never color alone.
- Roster: keep `highlight_symbol("> ")` + bold. Unselected rows start with two
spaces so columns align.
- Chat: title becomes `> chat {name}` when focused, ` chat {name}` when not,
plus bold on the `> ` title.
- Composer: `> ` prefix on the input row when focused (see spacing).
- `Tab` cycle unchanged (`Pane` tests lock it).
### `status_footer` priority (must change)
Replace the current "first candidate that fits, dropping the note" list.
Build left-to-right, **never drop** a non-empty `status_note`:
1. `status_note` (truncate with `…`/`...` to a minimum of 12 cells if needed).
2. `TOR me:{8}…` (keep `me:` — chrome tests require it).
3. `onion:` + full onion if it fits, else 8-char truncate (keep today's
`width >= 110` full-onion rule if it still fits **after** the note).
4. Hints from `main_footer_hints()`, dropping from the left of that list.
5. Always end with `? help`.
`? help` and `TOR` and `me:` must still be present at 80 and 120 so
`tests/tui_chrome.rs` stays green.
Fail-closed copy is `send failed: {e}` or `fingerprint mismatch`. Prefix `! `
when color is off.
### Copy — non-happy states
Do not soften fail-closed into a loader.
| State | Copy |
|---|---|
| no friends, roster | list item `no friends` (so the pane is not blank) |
| no friends, chat | `no friends yet` / `F3 paste an invite to add one` (keep) |
| friend, no messages | `no messages` / `type below, Enter sends` |
| nothing selected send | `no friend selected` (keep) |
| sending | `sending` (keep, no spinner) |
| sent | `sent` |
| peer down / send err | `send failed: {e}` (visible) |
| already sending | `already sending` (keep) |
| stale friend | `stale` suffix (keep) |
| empty composer | `message` as dim placeholder (not the slash list). Slash list stays in `?` |
| paste error | `{err}` then `Enter resubmits Esc back` |
| unknown slash | `unknown command {cmd}` (keep) |
| passphrase mismatch | `passphrases do not match` (keep, alert line) |
### Before → after mockup (80x24 main)
**After** (target). Header 1 line. Roster 22-ish. Chat primary. Composer no
box. Fail-closed note kept. Focus marker on composer.
```
onionwire tor me:abcdef01 onion:abcdefgh
┌friends 2 1 stale┐┌chat alice───────────────────────────────────────────────┐
│ alice aaaaaaaa…││you: ping │
│> bob bbbbbbbb… s││them: pong │
│ ││them: this is a very long chat line that should wrap │
│ ││inside the chat pane instead of running off the edge │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
│ ││ │
└──────────────────┘└──────────────────────────────────────────────────────────┘
> hello from composer
! send failed: peer onion down TOR me:abcdef01 ? help
```
Roster names truncate with ellipsis, not mid-letter. `stale` may abbreviate to
`s` only if the word does not fit; prefer keeping `stale`.
### Before → after mockup (80x24 help)
**After:** full-screen, no punch-through. Last line visible. `help_overlay_text()`
body unchanged (chrome tests).
```
┌? help────────────────────────────────────────────────────────────────────────┐
│OnionWire keys │
│ │
│ Tab / Shift-Tab cycle roster, chat, composer │
│ 1 / 2 / 3 focus roster / chat / composer │
│ j k or Up Down move or scroll focused pane │
│ g / G jump to top / bottom │
│ Enter send chat to selected friend, or a /command │
│ Esc close overlay, go back, clear composer │
│ F2 share invite │
│ F3 paste invite │
│ F4 rotate onion locator │
│ F5 selected friend's profile (/who) │
│ /profile edit name, bio, Monero address │
│ /pay <xmr> [memo] invoice to receive │
│ /tip <xmr> [memo] pay selected friend │
│ /file /path send file to selected friend (1 MiB) │
│ /backup /path encrypted identity export │
│ /restore /path overwrite self keys │
│ ? this help │
│ Ctrl-Q quit; type CLEAR or QUIT │
│ │
│Esc closes this overlay │
└──────────────────────────────────────────────────────────────────────────────┘
```
If the body still overflows 24 rows with the border, **scroll** the paragraph;
do not clip. Do not edit the locked help string to shrink it.
### Left alone (on purpose)
- Wire protocol, session, store, send path.
- Peer-text sanitization (other PR). Render must call it once it exists.
- Fail-closed semantics. Only the **visibility** of the error changes.
- Locked helper names and `help_overlay_text` / wordmark strings.
- No QR. Invite stays a string.
- No dedicated pay/invoice/file screens in v1.
- No spinner. `TUI_POLL` 100 ms stays.
- `docs/PROTOCOL.md` unchanged.
- No new crates on the implementation card unless `unicode-width` is approved
(deliverable 4).
## Deliverable 4 — `chars().count()` is not terminal cells
`tests/tui_chrome.rs` asserts `line.chars().count() <= width`. Same metric in
`status_footer` (`src/tui.rs:1512`) and `draw_text_overlay` (`src/tui.rs:1707`).
| Input | `chars().count()` | Terminal cells (East Asian Width; emoji Wide) |
|---|---|---|
| `你好` | 2 | **4** (both Wide) |
| `e\u{0301}` (e + combining acute) | 2 | **1** |
| `🧅` (U+1F9C5) | 1 | **2** |
A line of twenty `你` is 20 chars and 40 cells: the test passes at width 80,
the terminal wraps. A combining-mark string can look "too long" to the test and
still fit.
**Fix (implementation card, approved-then):** measure in cells. `unicode-width`
is already in the lockfile via ratatui but **not** a direct dependency. Do not
add it on this card. Preferred: depend on `unicode-width` explicitly and assert
`UnicodeWidthStr::width(line) <= width as usize`. Until then, keep the existing
`chars().count()` tests green; do not rewrite them to fit a redesign.
`tests/tui_frames.rs` `chars_count_is_not_terminal_cells` documents the three
examples without adding a crate.

544
tests/tui_frames.rs Normal file
View file

@ -0,0 +1,544 @@
//! 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::tui::{
backup_screen_text, banner_for_width, compact_banner, draw_share, fingerprint_mismatch_banner,
help_overlay_text, main_footer_hints, onion_glyph, quit_screen_text, restore_screen_text,
rotate_screen_text, status_footer, who_overlay_text, wipe_screen_text, wordmark_banner,
ProfileEditor, WipeKind,
};
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);
});
}
}
#[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"));
}
/// Current `status_footer` drops fail-closed copy when ident+hints fill the row.
/// Spec: never drop `send failed`. Do not change `src/` on this card.
#[test]
fn status_footer_drops_send_failed_when_crowded() {
let note = "send failed: peer onion down";
let at_80 = status_footer(80, FP, ONION, Some(note), main_footer_hints());
let at_120 = status_footer(120, FP, ONION, Some(note), main_footer_hints());
let at_200 = status_footer(200, FP, ONION, Some(note), main_footer_hints());
assert!(
!at_80.contains("send failed"),
"80 still has room? {at_80:?}"
);
assert!(
!at_120.contains("send failed"),
"120 still has room? {at_120:?}"
);
assert!(
at_200.contains("send failed"),
"200 should keep the note: {at_200:?}"
);
}
#[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);
}