tui: wallet selection screen (F6 -> w) with create as the last row

Screen::WalletSelect: a table of saved wallets — name, identity prefix,
locator prefix, creation day — the selected row's full identity and locator
under it, and a `+ create new wallet` row as the last item. j/k or arrows
move, Enter takes the choice, Esc back. Empty, failed and in-flight reads
each get their own copy; a wallet with a NULL label, no published locator or
no usable timestamp reads `(unlabelled)` / `-` / `unknown` rather than blank.

Presentation only. Rows are plain display data (WalletRow) built by the
caller; the render path never reads the store, and the selection is by row
index because two records may share an identity key. Loading a chosen record
into the session is the wallet-store integration step, so the F6 `w` entry
opens the screen on its unavailable state until that accessor lands, and the
create row works today either way.

Evidence: tests/tui_select.rs (16 tests) drives the real draw path through
TestBackend at 80x24, 120x40 and 200x60, pins the dumped frame's footer to
status_footer_phased(..., wallet_select_footer_hint()), asserts exactly one
focus marker, a cell-width line budget from 20 to 200 columns, the window
disclosure with the create row always visible, hostile labels (ESC/BEL/C1/
bidi/newline/tab) and the crate-local UTC date formatter.

(cherry picked from commit 99a4ab640e)
This commit is contained in:
agent 2026-09-21 10:41:53 -04:00
commit d96de1d7f0
No known key found for this signature in database
3 changed files with 1095 additions and 2 deletions

View file

@ -1288,6 +1288,12 @@ enum Screen {
PeerPayments {
state: PeerPaymentsState,
},
/// F6 → `w`: pick a saved wallet, or create one. The rows are a snapshot
/// like the other two, and the `create new wallet` row is part of the list
/// rather than a separate key.
WalletSelect {
state: WalletSelectState,
},
Quit {
prompt: QuitPrompt,
},
@ -1425,6 +1431,9 @@ impl App {
let mut open_payments = false;
let mut payments_back = false;
let mut payments_move = 0i32;
let mut select_back = false;
let mut select_move = 0i32;
let mut select_enter = false;
// The function-key shortcuts stay live on the WALLETS & SETTINGS screen
// and the peer history too: the settings screen's whole point is naming
@ -1666,6 +1675,9 @@ impl App {
Screen::Wallet { .. } => match key.code {
KeyCode::Esc => self.screen = Screen::Main,
KeyCode::Char('r') | KeyCode::Enter => self.wallet_toggle_qr(),
// `w` is the wallet list: the F6 screen is about the wallet you
// are on, and this is how you get off it.
KeyCode::Char('w') => self.open_wallet_select(),
KeyCode::Char('s') => self.wallet_child_start(),
KeyCode::Char('x') => self.wallet_child_stop(),
KeyCode::Char('p') => self.wallet_child_probe(),
@ -1698,6 +1710,13 @@ impl App {
KeyCode::Down | KeyCode::Char('j') => payments_move = 1,
_ => {}
},
Screen::WalletSelect { .. } => match key.code {
KeyCode::Esc => select_back = true,
KeyCode::Up | KeyCode::Char('k') => select_move = -1,
KeyCode::Down | KeyCode::Char('j') => select_move = 1,
KeyCode::Enter => select_enter = true,
_ => {}
},
Screen::Quit { prompt } => match key.code {
KeyCode::Esc => self.screen = Screen::Main,
KeyCode::Enter => match prompt.on_char('\n') {
@ -1729,6 +1748,22 @@ impl App {
if payments_back {
self.screen = Screen::Main;
}
if select_move != 0
&& let Screen::WalletSelect { state } = &mut self.screen
{
if select_move < 0 {
state.select_prev();
} else {
state.select_next();
}
}
if select_back {
// A full surface like the F9 menu: Esc leaves it for the main view.
self.screen = Screen::Main;
}
if select_enter {
self.choose_wallet()?;
}
if open_payments {
self.open_peer_payments()?;
}
@ -2037,6 +2072,45 @@ impl App {
Ok(())
}
/// Enter on the wallet selection screen: `create new wallet` starts the
/// existing creation flow, and a wallet row is a choice the app has to
/// resolve.
///
/// Resolving a row into the session is the wallet-store integration step:
/// the record's identity and locator have to be read back and loaded, and
/// `Node` has no wallet-record accessor yet. Until that lands the choice is
/// reported instead of silently dropped — an Enter that does nothing is
/// worse than one that says what is missing.
fn choose_wallet(&mut self) -> Result<(), String> {
let Screen::WalletSelect { state } = &self.screen else {
return Ok(());
};
match state.choice() {
WalletChoice::Create => {
self.screen = Screen::WalletSetup(WalletSetup::CreateWarn {
typed: String::new(),
});
}
WalletChoice::Open(_) => {
self.status_note = Some("wallet switching is not wired up yet".into());
}
}
Ok(())
}
/// F6 `w`: the wallet selection screen.
///
/// The rows come from the wallet store; reading them is the integration
/// card's step (`Store::list_wallets`), and the render path never touches
/// the store. Until that accessor exists the screen opens on its
/// unavailable state, which says so — the `create new wallet` row at the
/// bottom works either way.
fn open_wallet_select(&mut self) {
self.screen = Screen::WalletSelect {
state: WalletSelectState::error(SELECT_UNAVAILABLE.to_string()),
};
}
/// `c` on the WALLETS & SETTINGS menu: copy the receive address through the
/// terminal's own clipboard (OSC 52 — no crate, and it survives SSH). The
/// address never touches a file.
@ -2578,6 +2652,17 @@ impl App {
);
draw_peer_payments(f, state, &footer)
}
Screen::WalletSelect { state } => {
let footer = status_footer_phased(
f.area().width,
&self.me_fp,
&self.me_onion,
Some(TorPhase::of(self.node.tor_state())),
self.status_note.as_deref(),
footer_hints(&self.screen),
);
draw_wallet_select(f, state, &footer)
}
}
if self.help_open {
draw_text_overlay(f, "? help", help_overlay_text());
@ -3193,7 +3278,7 @@ match screen {
},
Screen::Passphrase { .. } => "Enter submit Esc cancel ? help",
Screen::Wallet { .. } => {
"c create i import r qr s/x child 1 pruned 2 full 3 testnet Esc back ? help"
"c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help"
}
Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help",
Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => {
@ -3203,6 +3288,7 @@ match screen {
Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help",
Screen::WalletsSettings { .. } => wallets_settings_footer_hint(),
Screen::PeerPayments { .. } => peer_payments_footer_hint(),
Screen::WalletSelect { .. } => wallet_select_footer_hint(),
Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help",
}
}
@ -4351,6 +4437,497 @@ pub fn draw_peer_payments(f: &mut Frame, state: &PeerPaymentsState, footer: &str
);
}
/// One persisted wallet, display-ready.
///
/// Plain data on purpose: the render path never reads the store, so the screen
/// takes rows the caller built. `name`, `identity_pubkey` and `onion_locator`
/// are untrusted display data (a label the user typed), sanitized at draw time.
///
/// The store's `WalletRecord` maps onto this like so —
/// `name: r.name.unwrap_or_default()` (a blank label is the placeholder
/// `(unlabelled)` on screen), `identity_pubkey: hex(r.identity_pubkey)` (the
/// column is `[u8; 32]`, so it is encoded here as text), `onion_locator:
/// r.onion_locator` (empty until the HS is published — that renders as `-`),
/// `created_at: r.created_at`. `wallet_filename` is deliberately not carried:
/// it is not on the screen, and the render path has no business with a path.
///
/// Selection is by **row index**, never by identity: two records may share an
/// identity key, so `WalletChoice::Open` names a position, not a wallet.
#[derive(Clone, Debug, Default)]
pub struct WalletRow {
/// User-given label. Empty means unlabelled (`NULL` in the store) and the
/// row says so rather than leaving the primary cell blank.
pub name: String,
/// The wallet's identity public key, hex.
pub identity_pubkey: String,
/// The wallet's v3 onion locator, without the `.onion` suffix. Empty until
/// the service is published.
pub onion_locator: String,
/// Creation time, unix seconds UTC. `0` (or negative) means unknown.
pub created_at: i64,
}
/// What Enter does on the selection screen.
///
/// The index is into the state's `rows` (display order), never into the store's
/// ids: the render path does not know them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WalletChoice {
/// Open the wallet at this index.
Open(usize),
/// The `create new wallet` row — the last item in the list.
Create,
}
/// What the wallet selection screen draws.
///
/// One item in the list is not a wallet: the `create new wallet` row, always
/// last, so Enter on it can start the creation flow instead of loading a
/// record. `selected` indexes rows **plus** that trailing row, which is why
/// `rows.len()` is a legal index and `choice()` reads it as `Create`.
///
/// `error` is display-ready and only set when the read itself failed — an
/// account with no saved wallets is an empty list, not an error.
#[derive(Clone, Debug, Default)]
pub struct WalletSelectState {
pub rows: Vec<WalletRow>,
pub selected: usize,
/// The read is in flight. The create row is still listed: it does not
/// depend on the store, so Enter stays live while the list loads.
pub reading: bool,
/// Why the list could not be read, display-ready.
pub error: Option<String>,
}
impl WalletSelectState {
/// The list a read returned. An empty list is the first-run state.
pub fn from_rows(rows: Vec<WalletRow>) -> Self {
Self {
rows,
selected: 0,
reading: false,
error: None,
}
}
/// The read is in flight. Nothing is listed yet, so the selection sits on
/// the create row.
pub fn reading() -> Self {
Self {
rows: Vec::new(),
selected: 0,
reading: true,
error: None,
}
}
/// The read failed. This is not "no wallets": the screen says so.
pub fn error(why: String) -> Self {
Self {
rows: Vec::new(),
selected: 0,
reading: false,
error: Some(why),
}
}
/// Move down one item. The bottom is the create row and is sticky.
pub fn select_next(&mut self) {
self.selected = (self.selected + 1).min(self.rows.len());
}
/// Move up one item. The top is the first wallet (or create) and is sticky.
pub fn select_prev(&mut self) {
self.selected = self.selected.saturating_sub(1);
}
/// The row under the marker, `None` on the create row.
pub fn selected_row(&self) -> Option<&WalletRow> {
self.rows.get(self.selected)
}
/// What Enter means right now. One past the last wallet — and the only
/// item of an empty or failed list — is `Create`.
pub fn choice(&self) -> WalletChoice {
match self.rows.get(self.selected) {
Some(_) => WalletChoice::Open(self.selected),
None => WalletChoice::Create,
}
}
}
/// Marker column in cells: `> ` when focused, ` ` otherwise.
const WALLET_MARK_W: usize = 2;
/// Identity column in cells: an 8-character prefix plus the ellipsis — 11
/// cells under `ONIONWIRE_ASCII`, where the ellipsis is three dots, so that is
/// the width every column is padded to whatever the chrome is doing.
const WALLET_ID_W: usize = 11;
/// Locator column in cells, measured the same way as the identity column.
const WALLET_LOC_W: usize = 11;
/// Creation-day column in cells: `2026-09-21` is 10, and `unknown` is 7.
const WALLET_SINCE_W: usize = 10;
/// Gap between two columns.
const WALLET_GAP: usize = 2;
/// Widest name column. The name is the flexible column and it is capped so the
/// trailing columns stay a table and not a 150-cell walk: every row pads to the
/// same column starts, which is what makes the rows scan as a grid.
const WALLET_NAME_W: usize = 28;
/// Cells the trailing columns need, marker included.
const WALLET_FIXED_W: usize = WALLET_MARK_W
+ (WALLET_GAP + WALLET_ID_W)
+ (WALLET_GAP + WALLET_LOC_W)
+ (WALLET_GAP + WALLET_SINCE_W);
/// `2026-09-21` for a unix second (UTC), or `unknown` when there is no usable
/// timestamp. Hand-rolled: this crate has no date dependency, and the screen
/// needs exactly one calendar date.
///
/// Days-to-civil (Howard Hinnant's algorithm) — no leap-year table, no crate.
pub fn format_day_utc(secs: i64) -> String {
if secs <= 0 {
return "unknown".to_string();
}
let z = secs.div_euclid(86_400) + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i64::from(month <= 2);
format!("{year:04}-{month:02}-{day:02}")
}
/// An identifying prefix of untrusted text: the first `keep` characters, closed
/// with the chrome's ellipsis, fitted into `cells`.
fn wallet_prefix(raw: &str, keep: usize, cells: usize) -> String {
let clean = menu_cell_text(raw);
let head: String = clean.chars().take(keep).collect();
fit_cells(&format!("{head}{}", ellipsis()), cells)
}
/// One laid-out grid line: marker, name, then whichever of the three trailing
/// columns fit.
///
/// Trailing columns are **dropped** when the pane is too narrow, never wrapped,
/// so no row can overrun the pane — the same discipline as the payments grid,
/// and it holds below the 80-column floor too.
#[allow(clippy::too_many_arguments)]
fn wallet_grid_line(
w: usize,
marker: &str,
name: &str,
id: &str,
loc: &str,
since: &str,
marker_style: Style,
name_style: Style,
col_style: Style,
) -> Line<'static> {
let mut spans = vec![Span::styled(marker.to_string(), marker_style)];
let inner = w.saturating_sub(cell_width(marker));
let name_w = inner.saturating_sub(WALLET_FIXED_W).min(WALLET_NAME_W);
if name_w == 0 {
// Not even a name fits: the identity is the most identifying thing left.
spans.push(Span::styled(
fit_cells(&menu_cell_text(id), inner.max(1)),
col_style,
));
return Line::from(spans);
}
spans.push(Span::styled(
pad_right(&fit_cells(name, name_w), name_w),
name_style,
));
let mut used = name_w;
for (col_w, text) in [
(WALLET_ID_W, id),
(WALLET_LOC_W, loc),
(WALLET_SINCE_W, since),
] {
// An empty tail means the row has no more columns to give (the create
// row), and a column that does not fit takes the rest of them with it.
if text.is_empty() || inner < used + WALLET_GAP + col_w {
break;
}
spans.push(Span::raw(" ".repeat(WALLET_GAP)));
spans.push(Span::styled(
pad_right(&fit_cells(text, col_w), col_w),
col_style,
));
used += WALLET_GAP + col_w;
}
Line::from(spans)
}
/// The selected row's full identity and locator. The rows carry prefixes, which
/// is what makes the list scannable; the full values are what a user actually
/// verifies, so the strip under the table spells them out.
fn wallet_detail_lines(w: usize, row: &WalletRow) -> Vec<Line<'static>> {
let mut out = vec![Line::default()];
for (label, value) in [
("id", menu_cell_text(&row.identity_pubkey)),
("onion", menu_cell_text(&row.onion_locator)),
] {
let text = if value.trim().is_empty() {
"(none)".to_string()
} else {
value
};
out.push(Line::from(vec![
Span::styled(format!(" {label:<5} "), style_dim()),
Span::styled(fit_cells(&text, w.saturating_sub(9).max(1)), style_text()),
]));
}
out
}
/// The wallet selection body as styled lines for a `width` × `height` **inner**
/// pane.
///
/// Fixed shape at the bottom: a blank, then the `create new wallet` row — the
/// one item that is not a wallet, always last, so the eye always knows where the
/// way out of an empty list is. The table above it windows and says how many
/// rows are out of view rather than dropping them silently.
pub fn wallet_select_lines(width: u16, height: u16, s: &WalletSelectState) -> Vec<Line<'static>> {
let w = width as usize;
let h = height as usize;
let mut out: Vec<Line<'static>> = Vec::new();
// The table is drawn only when there is a table to draw; empty, failed and
// in-flight reads say what they are instead of showing bare column heads.
let table = !s.rows.is_empty();
if table {
out.push(wallet_grid_line(
w,
" ",
"name",
"identity",
"locator",
"since",
Style::default(),
style_dim(),
style_dim(),
));
} else {
let (head, head_style, sub) = if let Some(err) = &s.error {
(
"could not read saved wallets",
style_alert(),
menu_cell_text(err),
)
} else if s.reading {
(
"reading saved wallets",
style_dim(),
"one moment".to_string(),
)
} else {
(
"no saved wallets yet",
style_dim(),
"create one to get an identity and an onion address".to_string(),
)
};
out.push(Line::from(Span::styled(
fit_cells(&format!(" {head}"), w.max(1)),
head_style,
)));
out.push(Line::from(Span::styled(
fit_cells(&format!(" {sub}"), w.max(1)),
style_dim(),
)));
}
// The full-value strip only where it cannot wrap, and its three cells are
// reserved whether or not the selection is a wallet, so the marker moving
// down to the create row never shifts the rows above it.
let strip = w >= 75 && h >= 14;
let strip_h = if strip { 3 } else { 0 };
// One blank + the create row at the bottom.
let tail_h = 2;
let budget = h.saturating_sub(out.len() + strip_h + tail_h);
if table {
let total = s.rows.len();
let selected = s.selected.min(total - 1);
let windowed = total > budget && budget >= 5;
let visible = if windowed {
budget - 2
} else {
budget.max(1).min(total)
};
let start = if total <= visible {
0
} else {
selected.saturating_sub(visible - 1).min(total - visible)
};
let end = (start + visible).min(total);
if windowed && start > 0 {
out.push(Line::from(Span::styled(
fit_cells(&format!(" {} {start} above", ellipsis()), w.max(1)),
style_dim(),
)));
}
for (i, row) in s.rows.iter().enumerate().take(end).skip(start) {
// No row carries the marker when the selection has walked past the
// last wallet onto the create row.
let selected = s.selected < total && i == s.selected;
// A NULL label reads as a placeholder, and a wallet whose onion
// service is not published yet has no locator at all — both are
// states the row names, not blanks.
let name = {
let clean = menu_cell_text(&row.name);
if clean.trim().is_empty() {
"(unlabelled)".to_string()
} else {
clean
}
};
let id = {
let clean = menu_cell_text(&row.identity_pubkey);
if clean.trim().is_empty() {
"-".to_string()
} else {
wallet_prefix(&clean, 8, WALLET_ID_W)
}
};
let loc = {
let clean = menu_cell_text(&row.onion_locator);
if clean.trim().is_empty() {
"-".to_string()
} else {
wallet_prefix(&clean, 8, WALLET_LOC_W)
}
};
out.push(wallet_grid_line(
w,
if selected { "> " } else { " " },
&name,
&id,
&loc,
&format_day_utc(row.created_at),
if selected {
style_accent().add_modifier(Modifier::BOLD)
} else {
Style::default()
},
if selected {
style_text().add_modifier(Modifier::BOLD)
} else {
style_text()
},
style_dim(),
));
}
if windowed && end < total {
out.push(Line::from(Span::styled(
fit_cells(&format!(" {} {} below", ellipsis(), total - end), w.max(1)),
style_dim(),
)));
}
}
if strip {
let detail = if !table {
Vec::new()
} else {
s.selected_row()
.map(|row| wallet_detail_lines(w, row))
.unwrap_or_default()
};
// Reserved either way: the block is the same height whichever item the
// marker is on.
for i in 0..strip_h {
out.push(detail.get(i).cloned().unwrap_or_default());
}
}
// The create row closes the list, one blank line under the table, and the
// panel below it stays empty — the same top-packed shape as the F9 menu, so
// the eye finds the table at the top of every full-screen panel.
out.push(Line::default());
let create_selected = s.rows.get(s.selected).is_none();
out.push(wallet_grid_line(
w,
if create_selected { "> " } else { " " },
"+ create new wallet",
"",
"",
"",
if create_selected {
style_accent().add_modifier(Modifier::BOLD)
} else {
Style::default()
},
if create_selected {
style_accent().add_modifier(Modifier::BOLD)
} else {
style_text()
},
style_dim(),
));
out
}
/// The body as plain text, for width/needle assertions.
pub fn wallet_select_text(width: u16, height: u16, s: &WalletSelectState) -> String {
wallet_select_lines(width, height, s)
.iter()
.map(|line| {
line.spans
.iter()
.map(|span| span.content.as_ref())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n")
}
/// Block title: the count is the reason the screen exists, so it is stated.
pub fn wallet_select_title(s: &WalletSelectState) -> String {
if s.rows.is_empty() {
"(o) wallets".to_string()
} else {
format!("(o) wallets {} {} saved", "\u{b7}", s.rows.len())
}
}
/// Wallet selection: a full screen like the F9 menu, with the same single
/// status line. `footer` is an already-built `status_footer` row.
pub fn draw_wallet_select(f: &mut Frame, s: &WalletSelectState, footer: &str) {
let area = f.area();
let rows = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area);
f.render_widget(
Paragraph::new(wallet_select_lines(
rows[0].width.saturating_sub(2),
rows[0].height.saturating_sub(2),
s,
))
.block(themed_block(&wallet_select_title(s))),
rows[0],
);
f.render_widget(
Paragraph::new(fit_cells(footer, area.width as usize)).style(style_dim()),
rows[1],
);
}
/// The hint line the wallet selection screen prints, single-sourced for the
/// same reason as [`peer_payments_footer_hint`]: a frame-dump fixture must not
/// hand-copy it, or the dump shows a footer the app never renders.
pub fn wallet_select_footer_hint() -> &'static str {
WALLET_SELECT_FOOTER_HINT
}
const WALLET_SELECT_FOOTER_HINT: &str = "Esc back j k select Enter open ? help";
/// The sub-line the screen prints when the wallet store has not been wired into
/// the app yet (see [`WalletRow`]): the list is genuinely unreadable, which is
/// not the same state as "no saved wallets".
pub const SELECT_UNAVAILABLE: &str = "the wallet store is not wired up yet";
/// OSC 52 clipboard write for `text`: the terminal copies it, so no crate and
/// no clipboard daemon are involved and it still works over SSH. A terminal
/// that does not implement OSC 52 ignores the sequence.
@ -4651,6 +5228,26 @@ mod function_key_tests {
}
}
/// The wallet list names `Esc`, `j k` and `Enter`, no function key — so it
/// must not quietly answer one. Copy and behaviour have to agree in both
/// directions, or a key that works on every other screen becomes a surprise
/// here.
#[test]
fn the_wallet_select_screen_answers_no_function_key_it_does_not_name() {
let screen = Screen::WalletSelect {
state: WalletSelectState::default(),
};
let hint = wallet_select_footer_hint();
for number in [2u8, 3, 4, 5, 6, 8, 9] {
let named = hint.contains(&format!("F{number}"));
assert_eq!(
function_key_for(&screen, KeyCode::F(number)).is_some(),
named,
"F{number} and the hint disagree: {hint:?}"
);
}
}
/// A screen that names no function key keeps the key to itself: the
/// composer's `F`-less screens must not steal F-keys they never advertise.
#[test]