diff --git a/src/node.rs b/src/node.rs index fd52ab1..b39a4e8 100644 --- a/src/node.rs +++ b/src/node.rs @@ -3195,7 +3195,7 @@ pub(crate) mod tests { /// single-child tests read; a test that spans two children reads the /// pid-named one, because a previous child's write into the shared path is /// unsequenced against the test (see [`wait_for_child_rpc_port`]). - fn fake_child_bin(dir: &Path, name: &str, log: &Path, body: &str) -> PathBuf { + pub(crate) fn fake_child_bin(dir: &Path, name: &str, log: &Path, body: &str) -> PathBuf { fake_child_bin_after(dir, name, log, "", body) } @@ -3294,6 +3294,41 @@ pub(crate) mod tests { Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url") } + /// Point `node`'s wallet client at a mock. The child process stays whatever + /// `start_wallet_child` spawned; only the dial target moves. + pub(crate) fn test_install_wallet(node: &Node, wallet: Wallet) { + *node.wallet.lock().expect("wallet") = wallet; + } + + /// Like [`mock_syncing_wallet`], but `height` is read on every `get_info`, + /// so a later store is a later answer. `synchronized` stays false: the + /// status line is a syncing chain, not a caught-up one. + pub(crate) async fn mock_wallet_at( + height: std::sync::Arc, + target: u64, + ) -> Wallet { + use std::sync::atomic::Ordering; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind mock wallet"); + let port = listener.local_addr().expect("mock wallet addr").port(); + let reply: Arc String + Send + Sync> = Arc::new(move |req: &str| { + if req.contains("get_info") { + let h = height.load(Ordering::Relaxed); + format!( + r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{h},"target_height":{target},"synchronized":false}}}}"# + ) + } else if req.contains("get_address") { + r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4test"}}"#.to_string() + } else { + r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0"}}"#.to_string() + } + }); + tokio::spawn(serve_mock_rpc(listener, reply)); + Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url") + } + /// A loopback daemon that answers `get_info` on the port the child probes /// when its wallet RPC is down. `None` when that port is already held (a real /// `monerod` on this box): that daemon is not ours to replace, and the test diff --git a/src/tui.rs b/src/tui.rs index 5068dac..1cda191 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use std::io::{self, IsTerminal, Write}; use std::path::Path; use std::sync::{Arc, mpsc}; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; use ratatui::layout::{Constraint, Layout, Rect}; @@ -475,6 +475,11 @@ fn style_highlight() -> Style { /// How long the TUI waits for a key before redrawing (so background send can update status). pub const TUI_POLL: Duration = Duration::from_millis(100); +/// How often a screen that shows chain height re-asks the daemon. The NODE row +/// is a snapshot of the last probe; without this it stays on the height from +/// child start while the chain keeps moving. +const CHAIN_STATUS_INTERVAL: Duration = Duration::from_secs(1); + /// Non-blocking read of a background send/job status. Never waits on Tor. pub fn take_job_result(rx: &mpsc::Receiver) -> Option { match rx.try_recv() { @@ -1242,6 +1247,13 @@ struct App { who_open: bool, chat_scroll: u16, job_rx: Option>, + /// In-flight chain-status probe. The draw path only reprints the last + /// answer; this is what asks again. + chain_probe_rx: Option>, + /// When the last probe was started. `None` means one is due now. + chain_probe_at: Option, + /// Tests set this to zero so a second height is asked immediately. + chain_status_every: Duration, } enum Screen { @@ -1431,8 +1443,8 @@ pub struct WalletSetupConfigState { cuprate_network: ChainNetwork, /// The last save / test answer, display-ready, never a secret. note: Option, - /// The live node/child line, refreshed on open and by `Ctrl-R`. This is the - /// answer to "did the node I just configured come up?" — taken from + /// The live node/child line. Filled on open, by `Ctrl-R`, and by the + /// chain-status poll while this screen is showing. Taken from /// `Node::wallet_child_status`, never inferred from the draft above. status: Option, } @@ -1524,8 +1536,8 @@ impl WalletSetupConfigState { state } - /// Read the live node/child line into the screen. Called on open and by - /// `Ctrl-R`, so what the status row shows is what the node answered, never + /// Read the live node/child line into the screen. The poll and `Ctrl-R` + /// call this after a probe, so the row is what the node answered, never /// what the draft above it claims. pub fn refresh_status(&mut self, node: &Node) { let line = node.wallet_child_status().line(); @@ -1844,12 +1856,16 @@ impl App { who_open: false, chat_scroll: 0, job_rx: None, + chain_probe_rx: None, + chain_probe_at: None, + chain_status_every: CHAIN_STATUS_INTERVAL, }) } fn run(&mut self, terminal: &mut DefaultTerminal) -> Result { loop { self.drain_job(); + self.pump_chain_status(); terminal.draw(|f| self.draw(f)).map_err(|e| e.to_string())?; if !event::poll(TUI_POLL).map_err(io_err)? { continue; @@ -2735,6 +2751,8 @@ impl App { return; } if ctrl && key.code == KeyCode::Char('r') { + self.chain_probe_at = None; + self.kick_chain_probe(); self.refresh_setup_status(); return; } @@ -3247,6 +3265,67 @@ impl App { self.job_rx = None; } + /// F7 and the wallet screen are the only places the chain height is drawn. + fn screen_shows_chain_status(&self) -> bool { + matches!( + self.screen, + Screen::WalletSetupConfig { .. } | Screen::Wallet { .. } + ) + } + + /// Ask the daemon again, off the UI thread. A probe already in flight is + /// left alone: the next poll applies it. Does nothing when no child is up, + /// so an unconfigured install never dials. + fn kick_chain_probe(&mut self) { + if self.chain_probe_rx.is_some() { + return; + } + if !self.node.wallet_child_status().running { + return; + } + let node = Arc::clone(&self.node); + let (tx, rx) = mpsc::channel(); + self.chain_probe_rx = Some(rx); + self.chain_probe_at = Some(Instant::now()); + let _j = self.rt.spawn(async move { + let _ = node.wallet_child_refresh().await; + let _ = tx.send(()); + }); + } + + /// Copy a finished probe into the F7 snapshot. The wallet screen reads the + /// same atomics at draw time, so it needs no copy. + fn apply_chain_status(&mut self) { + let done = self.chain_probe_rx.as_ref().is_some_and(|rx| { + matches!( + rx.try_recv(), + Ok(()) | Err(mpsc::TryRecvError::Disconnected) + ) + }); + if !done { + return; + } + self.chain_probe_rx = None; + if let Screen::WalletSetupConfig { state } = &mut self.screen { + state.refresh_status(&self.node); + } + } + + /// One turn of the chain-status poll: apply a finished probe, and start + /// another when the interval has elapsed and a screen is showing the line. + fn pump_chain_status(&mut self) { + self.apply_chain_status(); + if !self.screen_shows_chain_status() { + return; + } + let due = self + .chain_probe_at + .is_none_or(|t| t.elapsed() >= self.chain_status_every); + if due { + self.kick_chain_probe(); + } + } + fn who_body(&self) -> String { let Some(friend) = self.friends.get(self.selected) else { return "no friend selected\n\nEsc closes".into(); @@ -7564,4 +7643,85 @@ mod wallet_setup_config_tests { "F6 must not still advertise the keys it lost: {footer}" ); } + + /// The NODE row is a snapshot. A daemon whose height moves must show up on + /// the next poll, with no keypress — a one-shot probe at start is how the + /// row sat on a stale `sync h/target` while the chain kept moving. + #[test] + fn the_setup_screen_sync_line_follows_a_later_probe() { + use std::sync::Arc; + use std::sync::atomic::{AtomicU64, Ordering}; + + use crate::node::tests::{fake_child_bin, mock_wallet_at, test_install_wallet}; + use crate::wallet_child::ChildConfig; + use crate::wallet_child::test_support::PublishedPortHold; + + let dir = tempfile::tempdir().unwrap(); + let (mut app, rt) = app(&dir.path().join("home")); + // The poll interval is for the event loop. This test asks directly. + app.chain_status_every = Duration::ZERO; + + let log = dir.path().join("argv.log"); + let bin = fake_child_bin( + &dir.path().join("fake-bins"), + "monero-wallet-rpc", + &log, + "sleep 30", + ); + app.node + .set_wallet_child_config(&ChildConfig { + source: ChainSource::Remote { + host: "127.0.0.1".into(), + port: 18089, + }, + wallet_rpc_bin: bin, + arti_bin: std::path::PathBuf::from("arti"), + wallet_filename: "onionwire".into(), + }) + .expect("set config"); + // The start gate dials the port the fake was told to bind. A shell + // fake cannot bind one, so hold it here. Not 18081 — that is the + // user's live daemon when this suite runs beside it. + let _hold = PublishedPortHold::watching(std::slice::from_ref(&log)); + app.node.start_wallet_child().expect("start"); + + let height = Arc::new(AtomicU64::new(1111)); + let wallet = rt.block_on(mock_wallet_at(Arc::clone(&height), 9000)); + test_install_wallet(&app.node, wallet); + app.handle_key(key(KeyCode::F(7))).expect("F7"); + + wait_for_sync_line(&mut app, &rt, "sync 1111/9000"); + // A redraw alone must not invent a new probe. The number moves only + // when the poll asks again. + height.store(2222, Ordering::Relaxed); + let stale = wallet_setup_config_text(120, state_of(&app)); + assert!( + stale.contains("sync 1111/9000"), + "a redraw must not skip the probe:\n{stale}" + ); + assert!( + !stale.contains("sync 2222/9000"), + "the row moved without a probe:\n{stale}" + ); + wait_for_sync_line(&mut app, &rt, "sync 2222/9000"); + + app.node.stop_wallet_child().expect("stop"); + } + + fn wait_for_sync_line(app: &mut App, rt: &tokio::runtime::Runtime, needle: &str) { + let deadline = std::time::Instant::now() + Duration::from_secs(3); + loop { + app.pump_chain_status(); + let body = wallet_setup_config_text(120, state_of(app)); + if body.contains(needle) { + return; + } + if std::time::Instant::now() > deadline { + panic!("NODE row never showed {needle}:\n{body}"); + } + rt.block_on(async { + tokio::time::sleep(Duration::from_millis(20)).await; + }); + } + } }