From eb08a9ef9776f3207652de221c2d062c269993bb Mon Sep 17 00:00:00 2001 From: noah Date: Thu, 17 Sep 2026 11:05:15 -0600 Subject: [PATCH] GUI: per-miner capabilities + live config write path (right-click actions) Completes the right-click config menu (round-2 item 11): the menu now offers real actions computed from the intersection of what every selected miner supports, and applies them to the fleet over the network. - Capability detection: to_row probes each miner's asic-rs supports_* methods (fault light, restart, pause, resume, power limit, tuning) at scan time and stores them in MinerRow.caps -- no extra network round-trip. - Intersection: MinerCaps::intersect_all yields the actions common to the whole selection; the context menu offers only those (a mixed mining + idle selection shows just fault light + restart; an all-mining selection shows everything). - Write path: scan::start_config_action runs on a background thread -- it re-discovers each selected miner with asic-rs scan_miner(ip), applies the setter, and reports per-IP results that drain into the status bar (running progress while applying, a pass/fail summary when done). Cancellable, and a new action cancels any in-flight one so two never overlap. In fake-scan mode it simulates success so the flow is exercisable offline. - Actions: fault light on/off, pause, resume, restart apply immediately; set power limit and set tuning % open a small value-prompt dialog first. Factory reset, change password, and firmware upgrade are deliberately not exposed in a casual right-click. Adds the `measurements` dependency (already in the lock, transitive via asic-rs) for Power::from_watts. Review fixes (one review pass): - Restart / pause / resume now require a confirmation dialog (naming the count) so a misclick can't stop a producing fleet; fault light stays instant, and power/tuning are confirmed by their value entry. - The action result is held on the status bar for a few ticks so a fleet action's outcome (including failures) isn't clobbered by the next timer tick. - The action loop uses a current-thread tokio runtime (it applies to one miner at a time; a worker pool was wasted). - The value prompt validates before closing: a bad value keeps the dialog and the captured selection so it can be corrected. - The menu's "(N)" counts use the rows-backed selection, matching what is actually acted on. Verified off-screen: capability intersection (mixed vs all-mining selections), the value-prompt and confirmation nested modals (menu -> dialog) with no crash, the end-to-end apply flow, 46 unit tests (incl. a caps-intersection test), and the headless self-test. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh --- Cargo.lock | 1 + crates/alkane-gui/Cargo.toml | 1 + crates/alkane-gui/src/fixtures.rs | 11 ++ crates/alkane-gui/src/model.rs | 60 ++++++ crates/alkane-gui/src/scan.rs | 143 ++++++++++++++- crates/alkane-gui/src/ui.rs | 294 +++++++++++++++++++++++++++++- 6 files changed, 499 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4fd9b0f5..b11ea438 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -80,6 +80,7 @@ dependencies = [ "alkane-discovery", "asic-rs", "futures-util", + "measurements", "tokio", "wx-rs", ] diff --git a/crates/alkane-gui/Cargo.toml b/crates/alkane-gui/Cargo.toml index c7aa7dfd..4def9690 100644 --- a/crates/alkane-gui/Cargo.toml +++ b/crates/alkane-gui/Cargo.toml @@ -14,5 +14,6 @@ alkane-discovery = { path = "../alkane-discovery" } # vendored + patched wx-rs (see vendor/wx-rs/patches/) wx-rs = { path = "../../thirdparty/wx-rs/wx-rs-0.2.0-patched" } asic-rs = "0.8.1" +measurements = "0.11" tokio = { version = "1", features = ["rt"] } futures-util = "0.3" diff --git a/crates/alkane-gui/src/fixtures.rs b/crates/alkane-gui/src/fixtures.rs index c290c96e..34ab750d 100644 --- a/crates/alkane-gui/src/fixtures.rs +++ b/crates/alkane-gui/src/fixtures.rs @@ -69,6 +69,17 @@ impl Board { ] }, operating_state: if self.mining { "mining".to_string() } else { "idle".to_string() }, + // Synthetic capabilities so the right-click config menu is + // exercisable offline: mining units support everything, idle ones + // only the fault light + restart (to show the capability intersection). + caps: crate::model::MinerCaps { + fault_light: true, + restart: true, + pause: self.mining, + resume: self.mining, + power_limit: self.mining, + tuning: self.mining, + }, ..Default::default() } } diff --git a/crates/alkane-gui/src/model.rs b/crates/alkane-gui/src/model.rs index 01baf55a..5b35a52d 100644 --- a/crates/alkane-gui/src/model.rs +++ b/crates/alkane-gui/src/model.rs @@ -78,6 +78,48 @@ fn ip_to_u32(s: &str) -> u32 { acc } +/// What a miner supports being told to do, probed from asic-rs' `supports_*` +/// capability methods at scan time. The right-click menu offers an action only +/// when every selected miner supports it (the intersection of capabilities). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct MinerCaps { + pub fault_light: bool, + pub restart: bool, + pub pause: bool, + pub resume: bool, + pub power_limit: bool, + pub tuning: bool, +} + +impl MinerCaps { + /// The capabilities common to `self` and `other` (logical AND per action). + pub fn intersect(self, other: MinerCaps) -> MinerCaps { + MinerCaps { + fault_light: self.fault_light && other.fault_light, + restart: self.restart && other.restart, + pause: self.pause && other.pause, + resume: self.resume && other.resume, + power_limit: self.power_limit && other.power_limit, + tuning: self.tuning && other.tuning, + } + } + + /// The capabilities common to every miner in `caps` (all-true identity when + /// empty is intentionally avoided: an empty selection has no common caps). + pub fn intersect_all(caps: impl IntoIterator) -> MinerCaps { + let mut it = caps.into_iter(); + match it.next() { + Some(first) => it.fold(first, MinerCaps::intersect), + None => MinerCaps::default(), + } + } + + /// True when no action is supported (nothing to offer in the menu). + pub fn is_empty(self) -> bool { + self == MinerCaps::default() + } +} + /// One miner's telemetry snapshot, flattened from asic-rs `MinerData` into the /// scalar fields the table can display. Absent metrics are `None` / empty / /// 0.0 and render as a blank cell. @@ -85,6 +127,8 @@ fn ip_to_u32(s: &str) -> u32 { pub struct MinerRow { pub ip: String, pub selected: bool, + /// What this miner supports being told to do (for the right-click menu). + pub caps: MinerCaps, // identity pub model: String, pub mac: String, @@ -1181,6 +1225,22 @@ mod tests { assert_eq!(Column::Hashrate.num_value(&r2), Some(42.0)); } + #[test] + fn caps_intersection_is_the_common_actions() { + let full = MinerCaps { fault_light: true, restart: true, pause: true, resume: true, power_limit: true, tuning: true }; + let idle = MinerCaps { fault_light: true, restart: true, ..Default::default() }; + // Two full miners keep every action. + assert_eq!(MinerCaps::intersect_all([full, full]), full); + // A full + idle mix keeps only what both support. + assert_eq!(MinerCaps::intersect_all([full, idle]), idle); + // A single miner's caps are its own. + assert_eq!(MinerCaps::intersect_all([full]), full); + // Empty selection -> nothing common. + assert_eq!(MinerCaps::intersect_all([]), MinerCaps::default()); + assert!(MinerCaps::default().is_empty()); + assert!(!full.is_empty()); + } + #[test] fn numeric_filter_excludes_blank_cells() { // A blank-displaying value-type cell (absent reading stored as 0.0) must diff --git a/crates/alkane-gui/src/scan.rs b/crates/alkane-gui/src/scan.rs index 31b5a0e1..45b8be83 100644 --- a/crates/alkane-gui/src/scan.rs +++ b/crates/alkane-gui/src/scan.rs @@ -1,10 +1,11 @@ //! Scan engine: drives vendored asic-rs over the configured subnets and //! streams MinerRow snapshots to the UI thread via a std channel. -use crate::model::MinerRow; +use crate::model::{MinerCaps, MinerRow}; use asic_rs::MinerFactory; use asic_rs::core::traits::miner::Miner; use futures_util::StreamExt; +use measurements::Power; use std::collections::HashSet; use std::net::Ipv4Addr; use std::path::PathBuf; @@ -419,9 +420,19 @@ async fn to_row(miner: &dyn Miner) -> MinerRow { .fold(0.0f64, f64::max); let is_mining = data.is_mining; let slow = crate::model::is_slow(is_mining, hashrate_ths, expected_ths); + // Probe what this miner supports being told to do (sync, no extra I/O). + let caps = MinerCaps { + fault_light: miner.supports_set_fault_light(), + restart: miner.supports_restart(), + pause: miner.supports_pause(), + resume: miner.supports_resume(), + power_limit: miner.supports_set_power_limit(), + tuning: miner.supports_set_tuning_percent(), + }; MinerRow { ip: data.ip.to_string(), selected: false, + caps, model, mac: data.mac.map(|m| m.to_string()).unwrap_or_default(), hostname: data.hostname.clone().unwrap_or_default(), @@ -458,6 +469,136 @@ async fn to_row(miner: &dyn Miner) -> MinerRow { } } +/// A one-shot configuration action applied to a set of miners from the +/// right-click menu. +#[derive(Debug, Clone)] +pub enum ConfigAction { + FaultLight(bool), + Restart, + Pause, + Resume, + PowerLimit(f64), // watts + TuningPercent(u8), +} + +impl ConfigAction { + /// Short label for status text and summaries. + pub fn label(&self) -> String { + match self { + ConfigAction::FaultLight(true) => "fault light on".into(), + ConfigAction::FaultLight(false) => "fault light off".into(), + ConfigAction::Restart => "restart".into(), + ConfigAction::Pause => "pause".into(), + ConfigAction::Resume => "resume".into(), + ConfigAction::PowerLimit(w) => format!("power limit {w:.0} W"), + ConfigAction::TuningPercent(p) => format!("tuning {p}%"), + } + } +} + +/// Progress/results from a running config action. +pub enum ActionMsg { + Started { total: usize }, + Result { ip: String, ok: bool, detail: String }, + Done { ok: usize, total: usize }, +} + +/// A running config action; `stop` cancels the remaining miners. +pub struct ActionHandle { + pub rx: Receiver, + cancel: Arc, +} + +impl ActionHandle { + pub fn stop(&self) { + self.cancel.store(true, Ordering::Relaxed); + } +} + +async fn apply_action(miner: &dyn Miner, action: &ConfigAction) -> Result { + let result = match action { + ConfigAction::FaultLight(on) => miner.set_fault_light(*on).await, + ConfigAction::Restart => miner.restart().await, + ConfigAction::Pause => miner.pause(None).await, + ConfigAction::Resume => miner.resume(None).await, + ConfigAction::PowerLimit(w) => miner.set_power_limit(Power::from_watts(*w)).await, + ConfigAction::TuningPercent(p) => miner.set_tuning_percent(*p).await, + }; + result.map_err(|e| e.to_string()) +} + +/// Apply `action` to each miner in `ips` on a background thread: re-discover the +/// miner (asic-rs `scan_miner`), run the setter, and report per-IP results. In +/// fake-scan mode it reports simulated successes so the flow works offline. +pub fn start_config_action(ips: Vec, action: ConfigAction) -> ActionHandle { + let (tx, rx) = channel(); + let cancel = Arc::new(AtomicBool::new(false)); + let total = ips.len(); + let _ = tx.send(ActionMsg::Started { total }); + + if fake_scan_enabled() { + let err_tx = tx.clone(); + let res = std::thread::Builder::new().name("fake-action".into()).spawn(move || { + let mut ok = 0usize; + for ip in ips { + let _ = tx.send(ActionMsg::Result { ip, ok: true, detail: "simulated".into() }); + ok += 1; + } + let _ = tx.send(ActionMsg::Done { ok, total }); + }); + if res.is_err() { + let _ = err_tx.send(ActionMsg::Done { ok: 0, total }); + } + return ActionHandle { rx, cancel }; + } + + let thread_cancel = cancel.clone(); + let err_tx = tx.clone(); + let res = std::thread::Builder::new().name("config-action".into()).spawn(move || { + // A single-threaded runtime: the loop applies to one miner at a time, so + // a worker-per-CPU pool would be wasted. + let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() { + Ok(rt) => rt, + Err(_) => { + let _ = tx.send(ActionMsg::Done { ok: 0, total }); + return; + } + }; + rt.block_on(async move { + let factory = MinerFactory::new(); + let mut ok = 0usize; + for ip_s in ips { + if thread_cancel.load(Ordering::Relaxed) { + break; + } + let (success, detail) = match ip_s.parse::() { + Err(_) => (false, "bad IP".to_string()), + Ok(ip) => match factory.scan_miner(ip).await { + Ok(Some(miner)) => match apply_action(&*miner, &action).await { + Ok(true) => (true, "ok".to_string()), + Ok(false) => (false, "refused".to_string()), + Err(e) => (false, format!("{e}")), + }, + Ok(None) => (false, "no miner at IP".to_string()), + Err(e) => (false, format!("{e}")), + }, + }; + if success { + ok += 1; + } + if tx.send(ActionMsg::Result { ip: ip_s, ok: success, detail }).is_err() { + return; // UI gone + } + } + let _ = tx.send(ActionMsg::Done { ok, total }); + }); + }); + if res.is_err() { + let _ = err_tx.send(ActionMsg::Done { ok: 0, total }); + } + ActionHandle { rx, cancel } +} + #[cfg(test)] diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index ee3f6322..39807069 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -28,6 +28,23 @@ const ID_FILTER_NONE_BASE: i32 = 500; const ID_CTX_OPEN: i32 = 720; const ID_CTX_SELALL: i32 = 721; const ID_CTX_CLEAR: i32 = 722; +// Config actions on the selection (capability intersection). +const ID_CTX_LIGHT_ON: i32 = 723; +const ID_CTX_LIGHT_OFF: i32 = 724; +const ID_CTX_PAUSE: i32 = 725; +const ID_CTX_RESUME: i32 = 726; +const ID_CTX_TUNING: i32 = 727; +const ID_CTX_POWER: i32 = 728; +const ID_CTX_RESTART: i32 = 729; +// Value-prompt dialog for power-limit / tuning-percent actions. +const ID_ACTION_OK: i32 = 740; +const ID_ACTION_CANCEL: i32 = 741; +// Confirmation dialog for disruptive actions (restart / pause / resume). +const ID_CONFIRM_OK: i32 = 742; +const ID_CONFIRM_CANCEL: i32 = 743; +// Ticks (~seconds) to keep an action's result on the status bar before the +// idle/countdown status takes over again. +const ACTION_RESULT_TICKS: u8 = 8; // Filter dialog: the column-selector dropdown + the comparator dropdown. const ID_FILTER_COL: i32 = 730; const ID_FILTER_OP: i32 = 731; @@ -160,6 +177,21 @@ pub struct App { kpi_cards: Vec<(Widget, Widget, Widget, ColorKind)>, // A context menu built on right-click, popped up outside the App borrow. pending_popup: Option<(Widget, Widget)>, + // A running config action (fault light / restart / pause / power / tuning) + // applied to the selection, plus the value-prompt dialog for power/tuning. + action: Option, + action_ips: Vec, + action_prompt: Widget, + action_input: Widget, + action_is_power: bool, + action_total: usize, + action_done: usize, + // A confirmation dialog for disruptive actions, plus its pending target. + confirm_dialog: Widget, + pending_confirm: Option<(Vec, scan::ConfigAction)>, + // The last action's result, kept on the status bar for a few ticks. + action_result: Option, + action_result_ticks: u8, ranges_dialog: Widget, ranges_edit: Widget, ranges_auto: Widget, @@ -290,6 +322,17 @@ pub fn build(frame: Widget) -> App { pal, kpi_cards, pending_popup: None, + action: None, + action_ips: Vec::new(), + action_prompt: frame, + action_input: frame, + action_is_power: false, + action_total: 0, + action_done: 0, + confirm_dialog: frame, + pending_confirm: None, + action_result: None, + action_result_ticks: 0, ranges_dialog: frame, ranges_edit: frame, ranges_auto: frame, @@ -408,11 +451,44 @@ impl App { /// `popup_menu` runs a nested event loop that re-enters us. fn show_context_menu(&mut self) { let Some(t) = self.table else { return }; - let n = self.selected_ips.len(); + // Count and act on the same set: only selected IPs still backed by a row. + let n = self.selected_ip_list().len(); let menu = Widget::menu_new(); if n >= 1 { let open = if n == 1 { "Open in browser".to_string() } else { format!("Open {n} miners in browser") }; menu.menu_append(ID_CTX_OPEN, &open); + // Config actions common to the whole selection (capability + // intersection): an action is offered only if every selected miner + // supports it. + let caps = MinerCaps::intersect_all( + self.rows + .iter() + .filter(|r| self.selected_ips.contains(&r.ip)) + .map(|r| r.caps), + ); + if !caps.is_empty() { + let sfx = if n == 1 { String::new() } else { format!(" ({n})") }; + menu.menu_append_separator(); + if caps.fault_light { + menu.menu_append(ID_CTX_LIGHT_ON, &format!("Fault light on{sfx}")); + menu.menu_append(ID_CTX_LIGHT_OFF, &format!("Fault light off{sfx}")); + } + if caps.pause { + menu.menu_append(ID_CTX_PAUSE, &format!("Pause mining{sfx}")); + } + if caps.resume { + menu.menu_append(ID_CTX_RESUME, &format!("Resume mining{sfx}")); + } + if caps.tuning { + menu.menu_append(ID_CTX_TUNING, &format!("Set tuning %...{sfx}")); + } + if caps.power_limit { + menu.menu_append(ID_CTX_POWER, &format!("Set power limit...{sfx}")); + } + if caps.restart { + menu.menu_append(ID_CTX_RESTART, &format!("Restart{sfx}")); + } + } menu.menu_append_separator(); } menu.menu_append(ID_CTX_SELALL, "Select all"); @@ -426,16 +502,35 @@ impl App { self.pending_popup.take() } - fn on_menu_item(&mut self, id: i32) { + /// The IPs of the currently-selected miners. + fn selected_ip_list(&self) -> Vec { + self.rows + .iter() + .filter(|r| !r.ip.is_empty() && self.selected_ips.contains(&r.ip)) + .map(|r| r.ip.clone()) + .collect() + } + + /// Start a config action against `ips` on a background thread, cancelling any + /// action already in flight so two never run at once. + fn start_action(&mut self, ips: Vec, action: scan::ConfigAction) { + if ips.is_empty() { + return; + } + if let Some(old) = self.action.take() { + old.stop(); + } + let msg = format!("applying {} to {} miner(s)...", action.label(), ips.len()); + self.action = Some(scan::start_config_action(ips, action)); + wx_rs::set_status_text(&msg); + } + + /// A menu item was chosen. Direct actions start immediately; the value-input + /// actions (power limit / tuning %) return a prompt dialog to show modally. + fn on_menu_item(&mut self, id: i32) -> Option { match id { ID_CTX_OPEN => { - let ips: Vec = self - .rows - .iter() - .filter(|r| !r.ip.is_empty() && self.selected_ips.contains(&r.ip)) - .map(|r| r.ip.clone()) - .collect(); - for ip in ips { + for ip in self.selected_ip_list() { wx_rs::launch_browser(&format!("http://{ip}")); } } @@ -455,8 +550,163 @@ impl App { t.dvlc_select_rows(&[]); } } + // Fault light is harmless -> apply immediately. + ID_CTX_LIGHT_ON => self.start_action(self.selected_ip_list(), scan::ConfigAction::FaultLight(true)), + ID_CTX_LIGHT_OFF => self.start_action(self.selected_ip_list(), scan::ConfigAction::FaultLight(false)), + // Disruptive to running hardware -> confirm first. + ID_CTX_PAUSE => return Some(self.build_confirm_dialog(scan::ConfigAction::Pause)), + ID_CTX_RESUME => return Some(self.build_confirm_dialog(scan::ConfigAction::Resume)), + ID_CTX_RESTART => return Some(self.build_confirm_dialog(scan::ConfigAction::Restart)), + // Value entry is itself the confirmation. + ID_CTX_POWER => return Some(self.build_action_prompt(true)), + ID_CTX_TUNING => return Some(self.build_action_prompt(false)), _ => {} } + None + } + + /// Confirm a disruptive action (restart / pause / resume) before applying it + /// to the selection, so a misclick can't stop a producing fleet. + fn build_confirm_dialog(&mut self, action: scan::ConfigAction) -> Widget { + let ips = self.selected_ip_list(); + let n = ips.len(); + let (verb, btn) = match &action { + scan::ConfigAction::Restart => ("Restart", "Restart"), + scan::ConfigAction::Pause => ("Pause mining on", "Pause"), + scan::ConfigAction::Resume => ("Resume mining on", "Resume"), + _ => ("Apply to", "Confirm"), + }; + let msg = format!("{verb} {n} selected miner(s)? This affects running hardware."); + self.pending_confirm = Some((ips, action)); + let frame = Widget::main_frame(); + let dlg = Widget::dialog(frame, "Confirm action"); + let root = Widget::box_sizer(true); + root.add(Widget::static_text(dlg, &msg), 0, sf::BORDER_ALL, 12); + let btns = Widget::box_sizer(false); + btns.add_stretch(1); + btns.add(Widget::button(dlg, btn, ID_CONFIRM_OK), 0, sf::BORDER_ALL, 6); + btns.add(Widget::button(dlg, "Cancel", ID_CONFIRM_CANCEL), 0, sf::BORDER_ALL, 6); + root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6); + root.set_sizer_on(dlg); + dlg.set_min_size(360, 120); + dlg.fit(dlg); + self.confirm_dialog = dlg; + dlg + } + + /// A small modal to enter a power limit (watts) or tuning percent for the + /// selection. Built here, shown modally by `dispatch` outside the App borrow. + fn build_action_prompt(&mut self, is_power: bool) -> Widget { + self.action_ips = self.selected_ip_list(); + self.action_is_power = is_power; + let n = self.action_ips.len(); + let frame = Widget::main_frame(); + let dlg = Widget::dialog(frame, if is_power { "Set power limit" } else { "Set tuning percent" }); + let root = Widget::box_sizer(true); + let lbl = if is_power { + format!("Power limit in watts for {n} miner(s):") + } else { + format!("Tuning percent (0-100) for {n} miner(s):") + }; + root.add(Widget::static_text(dlg, &lbl), 0, sf::BORDER_ALL, 8); + let input = Widget::text_ctrl(dlg, false); + input.set_min_size(200, -1); + root.add(input, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 8); + let btns = Widget::box_sizer(false); + btns.add_stretch(1); + btns.add(Widget::button(dlg, "Apply", ID_ACTION_OK), 0, sf::BORDER_ALL, 6); + btns.add(Widget::button(dlg, "Cancel", ID_ACTION_CANCEL), 0, sf::BORDER_ALL, 6); + root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6); + root.set_sizer_on(dlg); + dlg.set_min_size(320, 140); + dlg.fit(dlg); + self.action_prompt = dlg; + self.action_input = input; + dlg + } + + /// Apply the value-prompt: parse the input, and only on a valid value close + /// the dialog and start the action. A bad value keeps the dialog (and the + /// captured selection) so the operator can correct it. + fn apply_action_prompt(&mut self) { + let val = self.action_input.get_value(); + let action = if self.action_is_power { + match val.trim().parse::() { + Ok(w) if w > 0.0 && w.is_finite() => Some(scan::ConfigAction::PowerLimit(w)), + _ => None, + } + } else { + match val.trim().parse::() { + Ok(p) if p <= 100 => Some(scan::ConfigAction::TuningPercent(p)), + _ => None, + } + }; + match action { + Some(a) => { + let ips = std::mem::take(&mut self.action_ips); + self.action_prompt.close(1); + self.start_action(ips, a); + } + None => { + let hint = if self.action_is_power { + "enter a positive number of watts" + } else { + "enter a percent from 0 to 100" + }; + wx_rs::set_status_text(&format!("invalid value - {hint}")); + } + } + } + + /// Drain a running config action's results into the status bar (per-miner + /// progress while running, a summary when done). + fn drain_action(&mut self) { + let Some(h) = &self.action else { return }; + let mut status: Option = None; + let mut finished = false; + loop { + match h.rx.try_recv() { + Ok(scan::ActionMsg::Started { total }) => { + self.action_total = total; + self.action_done = 0; + status = Some(format!("applying to 0/{total} miner(s)...")); + } + Ok(scan::ActionMsg::Result { ip, ok, detail }) => { + self.action_done += 1; + let (d, t) = (self.action_done, self.action_total); + status = Some(if ok { + format!("applying... {d}/{t} ({ip} ok)") + } else { + format!("applying... {d}/{t} ({ip}: {detail})") + }); + } + Ok(scan::ActionMsg::Done { ok, total }) => { + status = Some(if ok == total { + format!("applied to {ok}/{total} miner(s)") + } else { + format!("applied to {ok}/{total} miner(s), {} failed", total - ok) + }); + finished = true; + break; + } + Err(std::sync::mpsc::TryRecvError::Empty) => break, + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + status = Some("action ended".into()); + finished = true; + break; + } + } + } + if finished { + self.action = None; + // Keep the summary on the status bar for a few ticks so a fleet + // action's outcome (incl. failures) isn't clobbered by the next tick. + self.action_result = status.clone(); + self.action_result_ticks = ACTION_RESULT_TICKS; + } + if let Some(s) = status { + wx_rs::set_status_text(&s); + } } pub fn drain_scan(&mut self) { @@ -537,9 +787,21 @@ impl App { /// scan-loop scheduler (countdown to the next automatic rescan, or idle). fn tick(&mut self) { self.drain_scan(); + self.drain_action(); if self.scanning { return; // status already shows scan progress } + if self.action.is_some() { + return; // a config action is in flight; keep its status + } + if self.action_result_ticks > 0 { + // Hold the last action's result on the status bar briefly. + self.action_result_ticks -= 1; + if let Some(m) = &self.action_result { + wx_rs::set_status_text(m); + } + return; + } if self.playing && self.auto_secs > 0 { if self.countdown > 1 { self.countdown -= 1; @@ -1116,6 +1378,18 @@ impl App { ID_FILTER_OK => self.apply_filter(), ID_FILTER_CANCEL => self.filter_dialog.close(0), ID_FILTER_RESET => self.reset_filters(), + ID_ACTION_OK => self.apply_action_prompt(), + ID_ACTION_CANCEL => self.action_prompt.close(0), + ID_CONFIRM_OK => { + if let Some((ips, action)) = self.pending_confirm.take() { + self.confirm_dialog.close(1); + self.start_action(ips, action); + } + } + ID_CONFIRM_CANCEL => { + self.pending_confirm = None; + self.confirm_dialog.close(0); + } ID_PLAY => { // Resume/start the scan loop: scan now (unless one is // already running) + auto-rescan on. @@ -1152,7 +1426,7 @@ impl App { WxEventKind::DvlcActivated => self.activate_row(ev.p1 as usize), WxEventKind::DvlcReordered => self.column_reordered(), WxEventKind::DvlcContextMenu => self.show_context_menu(), - WxEventKind::MenuItem => self.on_menu_item(ev.p1 as i32), + WxEventKind::MenuItem => return self.on_menu_item(ev.p1 as i32), WxEventKind::ChoiceChanged => self.on_choice_changed(ev.p1 as i32, ev.p2 as i32), WxEventKind::SysColour => self.repaint_theme(), WxEventKind::Deferred => self.on_deferred(ev.p1 as i32),