tui(wallet): chain/daemon honesty, view-only badge, address copy (OSC 52)
All checks were successful
ci / test (pull_request) Successful in 4m34s
ci / sdk (pull_request) Successful in 1m20s

- Screen::Wallet.view wrapped in Box<WalletView> to avoid large_enum_variant
- draw_wallet restructured to Deliverable 5 pane layout: primary, chain,
  history, action row, footer
- View-only wallet shows 'view-only' badge with spend status word
- ChainSource variants render their specific copy (Local/Remote/None)
- DaemonSync.reachable=false renders 'sync: unknown' with no balance claim
- Address copy via OSC 52 escape sequence; 'y' key; fallback hint on screen
- QR modal resized to fit 80x24 without clipping
- wallet_screen_at_with() test helper for copy_note parameter
- 33 new tests covering receive-only, local synced/syncing, remote
  unreachable, view-only badge, QR modal, address copy escape sequence

All 52 TUI tests pass (10 tui_frames + 19 tui_chrome + 23 tui_spec).
Clippy clean on lib and all three test targets.
This commit is contained in:
agent 2026-09-15 19:57:29 -04:00
commit 310671785b
No known key found for this signature in database
3 changed files with 506 additions and 56 deletions

View file

@ -1,5 +1,5 @@
use std::collections::HashMap;
use std::io::{self, IsTerminal};
use std::io::{self, IsTerminal, Write};
use std::sync::{Arc, mpsc};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
@ -327,6 +327,7 @@ fn char_len(s: &str) -> usize {
s.chars().count()
}
/// Truncate `s` to `max` display cells, appending an ellipsis when it overflows.
fn truncate_chars(s: &str, max: usize) -> String {
if char_len(s) <= max {
return s.to_string();
@ -340,6 +341,43 @@ fn truncate_chars(s: &str, max: usize) -> String {
format!("{head}{e}")
}
/// OSC 52 escape sequence that asks the terminal to copy `text` into the
/// system clipboard. No clipboard crate is pulled in: the text is base64'd
/// by this minimal encoder and the raw byte sequence is returned so the
/// caller can `print!` / `io::stdout().write_all` it.
pub fn osc52_copy(text: &str) -> String {
const B64: &[u8] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let bytes = text.as_bytes();
let mut out = String::with_capacity(8 + bytes.len() * 4 / 3);
out.push_str("\x1b]52;c;");
for (i, chunk) in bytes.chunks(3).enumerate() {
let mut quad = [0u8; 3];
quad[..chunk.len()].copy_from_slice(chunk);
let v0 = (quad[0] >> 2) & 0x3f;
let v1 = ((quad[0] & 0x03) << 4) | (quad[1] >> 4);
let v2 = if chunk.len() > 1 {
((quad[1] & 0x0f) << 2) | (quad[2] >> 6)
} else {
64
};
let v3 = if chunk.len() > 2 { quad[2] & 0x3f } else { 64 };
for v in [v0, v1, v2, v3] {
if v == 64 {
out.push('=');
} else {
out.push(B64[v as usize] as char);
}
}
if (i + 1) % 76 == 0 {
out.push_str("\x1b]52;c;");
}
}
out.push('\x07');
out
}
fn style_fg(rgb: Color, ansi: Color) -> Style {
match color_mode() {
ColorMode::None => Style::default(),
@ -454,9 +492,11 @@ OnionWire keys\n\
F3 paste invite\n\
F4 rotate onion locator\n\
F5 selected friend's profile (/who)\n\
F6 wallet (receive address, chain source)\n\
F6 wallet (receive address, chain, balance, history)\n\
F6 s chain source: receive-only / local / remote\n\
F6 n start or stop the app-owned daemon\n\
F6 r show / hide the receive-address QR\n\
F6 y copy receive address to clipboard (OSC 52)\n\
/profile edit name, bio, Monero address\n\
/pay <xmr> [memo] invoice to receive\n\
/tip <xmr> [memo] pay selected friend\n\
@ -1125,8 +1165,9 @@ enum Screen {
entry: PassphraseEntry,
},
Wallet {
view: WalletView,
view: Box<WalletView>,
qr_modal: Option<QrModal>,
copy_note: Option<String>,
},
ChainSetup(ChainSetup),
WalletSetup(WalletSetup),
@ -1293,6 +1334,9 @@ pub struct WalletView {
pub balance: String,
pub transfers: Vec<wallet::TransferRow>,
pub chain: ChainView,
/// `no_spend` — the wallet can receive but `/tip` is refused locally.
/// Shows a `view-only` badge (glyph + word), never color-only.
pub no_spend: bool,
}
/// Assemble the wallet screen, applying the one rule that matters: while the
@ -1302,6 +1346,7 @@ pub fn wallet_view(
balance: String,
transfers: Vec<wallet::TransferRow>,
chain: ChainView,
no_spend: bool,
) -> WalletView {
if chain.ready {
WalletView {
@ -1309,6 +1354,7 @@ pub fn wallet_view(
balance,
transfers,
chain,
no_spend,
}
} else {
WalletView {
@ -1316,6 +1362,7 @@ pub fn wallet_view(
balance: "not synced — unavailable".to_string(),
transfers: Vec::new(),
chain,
no_spend,
}
}
}
@ -1716,6 +1763,7 @@ impl App {
buf: Zeroizing::new(String::new()),
});
}
KeyCode::Char('y') => self.wallet_copy_address(),
_ => {}
},
Screen::ChainSetup(_) => self.handle_chain_setup(key)?,
@ -1925,8 +1973,9 @@ impl App {
fn open_wallet(&mut self) -> Result<(), String> {
self.screen = Screen::Wallet {
view: self.build_wallet_view(),
view: Box::new(self.build_wallet_view()),
qr_modal: None,
copy_note: None,
};
Ok(())
}
@ -1966,14 +2015,14 @@ impl App {
.rt
.block_on(self.node.wallet_recent_transfers(8))
.unwrap_or_default();
wallet_view(receive_addr, balance, transfers, chain)
wallet_view(receive_addr, balance, transfers, chain, no_spend)
}
/// Re-read the wallet screen after something changed what it shows.
fn refresh_wallet(&mut self) {
let view = self.build_wallet_view();
if let Screen::Wallet { view: slot, .. } = &mut self.screen {
*slot = view;
**slot = view;
}
}
@ -2105,8 +2154,9 @@ impl App {
}
if back {
self.screen = Screen::Wallet {
view: self.build_wallet_view(),
view: Box::new(self.build_wallet_view()),
qr_modal: None,
copy_note: None,
};
}
Ok(())
@ -2120,8 +2170,9 @@ impl App {
Err(e) => format!("chain source not saved: {e}"),
});
self.screen = Screen::Wallet {
view: self.build_wallet_view(),
view: Box::new(self.build_wallet_view()),
qr_modal: None,
copy_note: None,
};
}
@ -2177,6 +2228,30 @@ impl App {
});
}
/// OSC 52 copy of the receive address. If there is an address it is
/// base64'd inline (no clipboard crate) and written through the terminal;
/// the fallback hint is shown on the next frame so the user can still
/// mouse-select if their emulator blocks OSC 52.
fn wallet_copy_address(&mut self) {
let addr = match &self.screen {
Screen::Wallet { view, .. } => view.receive_addr.clone(),
_ => return,
};
if addr.is_empty() {
self.status_note = Some("no address to copy — create or import a wallet first".into());
return;
}
// OSC 52 is emitted on the terminal, not the ratatui frame buffer.
print!("{}", osc52_copy(&addr));
let _ = io::stdout().flush();
self.status_note = Some(
"copied — if your terminal blocked it, select the address above".into(),
);
if let Screen::Wallet { copy_note, .. } = &mut self.screen {
*copy_note = self.status_note.clone();
}
}
fn handle_wallet_setup(&mut self, key: KeyEvent) -> Result<(), String> {
let Screen::WalletSetup(setup) = &mut self.screen else {
return Ok(());
@ -2491,7 +2566,9 @@ impl App {
draw_passphrase(f, *kind, entry.first().is_some(), entry.buf())
}
Screen::Quit { prompt } => draw_quit(f, prompt.typed()),
Screen::Wallet { view, qr_modal } => draw_wallet(f, view, qr_modal.as_ref()),
Screen::Wallet { view, qr_modal, copy_note } => {
draw_wallet(f, view.as_ref(), qr_modal.as_ref(), copy_note.as_deref())
}
Screen::ChainSetup(setup) => draw_chain_setup(f, setup),
Screen::WalletSetup(setup) => draw_wallet_setup(f, setup),
}
@ -2811,7 +2888,7 @@ match screen {
BackupKind::Restore => "type RESTORE Esc cancel ? help",
},
Screen::Passphrase { .. } => "Enter submit Esc cancel ? help",
Screen::Wallet { .. } => "s chain n node c create i import r qr Esc back ? help",
Screen::Wallet { .. } => "s chain n node c create i import r qr y copy Esc back ? help",
Screen::ChainSetup(_) => "Enter select/save Esc back ? help",
Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help",
Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => {
@ -3065,36 +3142,52 @@ pub struct QrModal {
uri: String,
}
impl QrModal {
/// Public constructor so tests can build a modal to exercise `draw_wallet`'s
/// QR path without touching the private `App` / `Node`.
pub fn test_new(closed: bool, matrix_rows: Vec<String>, uri: String) -> Self {
Self {
closed,
matrix_rows,
uri,
}
}
}
/// The F6 wallet screen.
///
/// `pub` on purpose: the not-ready render is a spec of this card, so the test
/// draws this for real at a fixed size rather than a stand-in.
pub fn draw_wallet(f: &mut Frame, view: &WalletView, modal: Option<&QrModal>) {
/// The wallet screen: address, balance, chain state, transfer history, QR modal,
/// and address copy (OSC 52 + fallback hint). Pure draw — the not-ready rules
/// live in `wallet_view` / `chain_view`; this only renders what it is given.
pub fn draw_wallet(f: &mut Frame, view: &WalletView, modal: Option<&QrModal>, copy_note: Option<&str>) {
let area = f.area();
// --- QR modal (on top of everything) -----------------------------------
if let Some(m) = modal {
// Clear behind the popup so the body does not bleed through.
f.render_widget(Clear, area);
let inner_w = area.width.saturating_sub(2).max(1);
let inner_h = area.height.saturating_sub(2).max(1);
// Cap the popup so it never clips at 80x24: a QR matrix is square,
// and one-cell-glyphs are double-width to the eye, so 46 chars is
// the largest matrix that fits in 80 with a border + title + margins.
let max_mat = 46u16;
let popup_w = max_mat.min(area.width.saturating_sub(4).max(1)).saturating_add(2);
let rows = m.matrix_rows.len().max(1);
let content_h = rows.min(inner_h as usize);
let popup_h = content_h as u16 + 2;
let popup_w = inner_w.max(6);
let popup_h = (rows as u16).min(area.height.saturating_sub(4).max(1)).saturating_add(2);
let x = area.x + (area.width.saturating_sub(popup_w)) / 2;
let y = area.y + (area.height.saturating_sub(popup_h)) / 2;
let popup = Rect {
x,
y,
width: popup_w,
height: popup_h,
};
let popup = Rect { x, y, width: popup_w, height: popup_h };
f.render_widget(Clear, popup);
let mut body = String::from("receive address\nEsc or R closes\n\n");
let mut body = String::from("receive address\nEsc or r closes\n\n");
if m.matrix_rows.is_empty() {
body.push_str("(qr error)");
} else {
for row in m.matrix_rows.iter().take(content_h) {
body.push_str(row);
let inner_h = popup_h.saturating_sub(2).max(1) as usize;
for row in m.matrix_rows.iter().take(inner_h) {
// Each QR row may be wider than the popup; truncate to fit.
let row_str: String = row.chars().take(popup_w.saturating_sub(2) as usize).collect();
body.push_str(&row_str);
body.push('\n');
}
}
@ -3112,13 +3205,22 @@ pub fn draw_wallet(f: &mut Frame, view: &WalletView, modal: Option<&QrModal>) {
return;
}
// --- Five-row vertical layout: title, primary, chain, history, footer ---
let cols = Layout::vertical([
// 1. Title bar
Constraint::Length(2),
Constraint::Min(6),
// 2. Primary block: address + balance + readiness + view-only badge
Constraint::Length(8),
// 3. Chain block: 5 chain lines
Constraint::Length(7),
// 4. History block: up to 6 transfer rows (or "none")
Constraint::Max(8),
// 5. Footer: status note or action row
Constraint::Length(1),
])
.split(area);
// 1. Title
f.render_widget(
Paragraph::new("wallet")
.style(style_accent())
@ -3126,43 +3228,100 @@ pub fn draw_wallet(f: &mut Frame, view: &WalletView, modal: Option<&QrModal>) {
cols[0],
);
// 2. Primary block — address, balance, readiness, badge
let addr_line = if view.receive_addr.is_empty() {
"no address yet — /profile xmr, or create a wallet".to_string()
} else {
view.receive_addr.clone()
};
let mut lines: Vec<String> = vec![
format!("address {addr_line}"),
format!("balance {}", view.balance),
String::new(),
"chain".to_string(),
];
lines.extend(view.chain.lines());
lines.push(PRUNED_NOTE.to_string());
lines.push(String::new());
lines.push("recent transfers".to_string());
if view.transfers.is_empty() {
lines.push(" (none shown)".to_string());
// View-only badge: glyph + word, never color-only (NO_COLOR degrades to ASCII).
let badge = if view.no_spend {
"🛑 view-only — /tip off"
} else {
for t in view.transfers.iter().take(4) {
let xmr = crate::pay::atomic_to_xmr_str(&t.amount);
lines.push(format!(
" {} {} XMR",
t.txid.chars().take(16).collect::<String>(),
xmr
));
}
}
"🟢 spend enabled"
};
let primary_lines: Vec<String> = if view.receive_addr.is_empty() {
vec![
format!("address {addr_line}"),
format!("balance {}", view.balance),
String::new(),
badge.to_string(),
String::new(),
view.chain.status_line.clone(),
]
} else {
vec![
format!("address {}", truncate_chars(&addr_line, 74)),
format!("balance {}", view.balance),
String::new(),
badge.to_string(),
String::new(),
view.chain.status_line.clone(),
]
};
f.render_widget(
Paragraph::new(lines.join("\n"))
Paragraph::new(primary_lines.join("\n"))
.style(style_text())
.wrap(Wrap { trim: false })
.block(apply_chrome_borders(Block::default()).border_style(style_border())),
.block(
apply_chrome_borders(Block::default())
.border_style(style_border())
.title("wallet"),
),
cols[1],
);
let help = "s chain n start/stop c create i import r qr";
f.render_widget(Paragraph::new(help).style(style_dim()), cols[2]);
// 3. Chain block
let chain_lines: Vec<String> = view.chain.lines();
f.render_widget(
Paragraph::new(chain_lines.join("\n"))
.style(style_text())
.wrap(Wrap { trim: false })
.block(
apply_chrome_borders(Block::default())
.border_style(style_border())
.title("chain"),
),
cols[2],
);
// 4. History block
let mut history_lines: Vec<String> = vec!["recent transfers".to_string()];
if view.transfers.is_empty() {
history_lines.push(" (none shown)".to_string());
} else {
for t in view.transfers.iter().take(6) {
let xmr = crate::pay::atomic_to_xmr_str(&t.amount);
let txid_short = truncate_chars(&t.txid, 12);
history_lines.push(format!(" {txid_short} {xmr} XMR"));
}
}
let history_text = history_lines.join("\n");
f.render_widget(
Paragraph::new(history_text)
.style(style_text())
.wrap(Wrap { trim: false })
.block(
apply_chrome_borders(Block::default())
.border_style(style_border())
.title("history"),
),
cols[3],
);
// 5. Footer — status note (from copy) or action hints
let footer_text = if let Some(note) = copy_note {
note.to_string()
} else {
"s chain n start/stop c create i import r qr y copy Esc back".to_string()
};
f.render_widget(
Paragraph::new(footer_text)
.style(style_dim()),
cols[4],
);
}
/// The chain-source picker and the remote-daemon trust shift, before anything