Compare commits

...
1 Commits
Author SHA1 Message Date
noahandClaude Opus 4.8 86e4761316 GUI round 7: code-review remediation (flash safety, unknown-actual colour, credentials, coverage)
Fixes the Critical/High findings from the round-6 review (6 parallel dimension
reviewers + adversarial verify), plus the cheap high-value non-blocking ones.
Full write-up in code-review-report.md.

Firmware-flash safety (the one irreversible, hardware-destroying action):
- Critical: re-triggering an action no longer races the previous one. A flash
  now takes an exclusive lock (new App.flashing): it will not start while any
  scan / refresh / config action is running, and none of those (nor another
  flash) start while it runs. begin_scan, start_action, start_refresh and
  apply_flash_confirm all gate on it, and the context menu offers only the
  read-only "Open in browser" while flashing. This removes the two overlapping-
  network-operation paths that could interrupt/corrupt an upload and brick a
  miner (old.stop() never joined the in-flight upload).
- High: the flash confirm dialog now lists every target IP + model and warns
  loudly when the batch spans more than one model (a single image is rarely
  valid for all), instead of showing only a bare count.

Correctness:
- High: combined columns no longer paint the "-" placeholder solid red when the
  actual is unknown but the expected is known (an idle/paused/booting miner of a
  recognised model looked like a 0% catastrophic failure). fill_rows now gates
  the ratio on the actual being known; unknown-actual falls to the plain,
  uncoloured segment. Was masked by the all-zero-expected fixtures.
- compute_kpis buckets by status() instead of re-deriving the precedence from
  raw flags (KPI header can no longer disagree with a row's status; offline
  folds into not_hashing).

Security:
- credentials file is created at 0600 up front (OpenOptions::mode) and
  re-tightened while still empty, so the plaintext password is never on disk
  under a looser mode (was create-0644 then chmod-0600).
- the "Set scan credentials" dialog no longer pre-fills the saved password in
  plaintext; a blank Password field keeps the stored one.

Robustness / API:
- the fake-scan branches of the config-action / refresh / flash background
  threads now honour the cancel flag (were ignored, so stop() was a no-op).
- MinerRow.online -> offline (default false = online), removing the footgun
  where a struct-update literal that forgot `online: true` read back offline.

Tests (the review's primary focus -- these paths had zero coverage):
- scan.rs fake_mode_background_actions: start_scan offline-row emission,
  start_refresh (Row/Failed/Done), start_firmware_flash_action, and that a
  cancelled run still terminates with Done rather than hanging.
- model.rs: flash_confirmed (exact/case/prefix/whitespace), compute_kpis vs
  status() consistency, Default-is-online.
- new ui::tests: ratio_color/fan_color/tint_toward stops+clamping+blends, and
  the combined-cell unknown-actual and cooling-cell encodings.
- credentials.rs: configured_factory smoke (both branches) + pre-existing-0644
  re-tighten.
- self-test: offline row (.199) spot-check, KPI quick-filter toggle on/off, and
  a numeric (not lexical) IP-sort assertion via model::ip_to_u32.

Deferred (non-blocking, tracked in code-review-report.md): start_* boilerplate
extraction; per-model firmware image-compatibility check; scoping saved
credentials to a chosen backend; a masked password field (needs a wx-rs
TE_PASSWORD binding); flash-specific status text; a segment-encode microbench.

Verified: cargo check --release --tests is clean; unit tests + benches + the
headless self-test run in CI (local release link is OOM-blocked on this
desktop).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-17 14:06:03 -06:00
5 changed files with 484 additions and 61 deletions
+33 -3
View File
@@ -6,7 +6,7 @@
//! firmware registry, so `scan`'s callers never have to think about it.
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
use asic_rs::MinerFactory;
use asic_rs::core::traits::miner::MinerAuth;
@@ -31,9 +31,19 @@ pub fn save_credentials(user: &str, pass: &str) -> std::io::Result<()> {
if let Some(dir) = p.parent() {
std::fs::create_dir_all(dir)?;
}
let mut f = std::fs::File::create(&p)?;
f.write_all(format!("{user}\n{pass}\n").as_bytes())?;
// Open (and create) with mode 0600 up front so a freshly created file is
// never world/group-readable, even for the instant before the write. For a
// pre-existing file the create mode is ignored, so also tighten it to 0600
// while it is still empty (post-truncate, pre-write) -- the plaintext is
// never on disk under a looser mode.
let mut f = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(&p)?;
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
f.write_all(format!("{user}\n{pass}\n").as_bytes())?;
Ok(())
}
@@ -84,7 +94,27 @@ mod tests {
let meta = std::fs::metadata(config_path(CREDENTIALS_FILE)).unwrap();
assert_eq!(meta.permissions().mode() & 0o777, 0o600, "credentials file must be 0600");
// configured_factory() must construct in both branches without panicking:
// with saved credentials (fans auth across every firmware backend) ...
let _ = configured_factory();
// A pre-existing, world-readable credentials file must be tightened to
// 0600 by save_credentials (the create-mode is ignored for an existing
// file, so the explicit set_permissions is what protects it).
let path = config_path(CREDENTIALS_FILE);
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
save_credentials("admin2", "s3cr3t").unwrap();
let meta = std::fs::metadata(&path).unwrap();
assert_eq!(
meta.permissions().mode() & 0o777,
0o600,
"save over a pre-existing 0644 file must re-tighten to 0600"
);
assert_eq!(load_credentials(), Some(("admin2".to_string(), "s3cr3t".to_string())));
clear_credentials().unwrap();
// ... and with no saved credentials (plain MinerFactory::new()).
let _ = configured_factory();
assert_eq!(load_credentials(), None, "cleared -> None");
clear_credentials().unwrap(); // idempotent: clearing an already-clear store is not an error
+3 -3
View File
@@ -70,7 +70,7 @@ impl Board {
is_mining: self.mining,
slow,
paused: self.paused,
online: true,
// offline defaults to false (online); these bench rows are reachable.
mac: format!("AA:BB:CC:00:{:02X}:{last_octet:02X}", last_octet.wrapping_mul(3)),
hostname: format!("miner-{last_octet}"),
hashboards: boards,
@@ -118,7 +118,7 @@ impl Board {
/// bucket is exercisable offline); one is slow (S21 Pro aml stock at ~30%
/// of expected); the other six hash normally; the last row is an
/// unreachable IP rendered via `MinerRow::offline()` (blank fields,
/// `online: false`).
/// `offline: true`).
///
/// Derived totals (used by the workflow tests):
/// total = 10, hashing = 6, slow = 1, not hashing = 1, paused = 1, offline = 1,
@@ -162,7 +162,7 @@ pub fn bench_fleet() -> Vec<MinerRow> {
worker: "", mining: false, paused: true },
];
let mut rows: Vec<MinerRow> = boards.into_iter().map(Board::into_row).collect();
// Synthetic offline board: unreachable IP, blank/zeroed fields, online: false.
// Synthetic offline board: unreachable IP, blank/zeroed fields, offline: true.
rows.push(MinerRow::offline("10.255.1.199".into()));
rows
}
+75 -28
View File
@@ -152,8 +152,9 @@ pub fn format_uptime(secs: u64) -> String {
/// Pack a dotted-quad IPv4 string into a u32 for numeric ordering, so
/// "10.255.1.9" sorts before "10.255.1.10" (a plain string sort gets this
/// wrong). Anything unparseable sorts first (0).
fn ip_to_u32(s: &str) -> u32 {
/// wrong). Anything unparseable sorts first (0). `pub(crate)` so the headless
/// self-test can build the same numeric order it asserts the view against.
pub(crate) fn ip_to_u32(s: &str) -> u32 {
let mut parts = s.split('.');
let mut acc = 0u32;
for _ in 0..4 {
@@ -265,26 +266,28 @@ pub struct MinerRow {
/// Not-mining because an operator paused it (distinct from simply idle);
/// see `is_paused`.
pub paused: bool,
/// Whether this miner responded to the scan. `Default` gives `false`, so
/// every constructor of a real (non-offline) row -- `scan::to_row`,
/// fixtures -- MUST set this to `true` explicitly; only `MinerRow::offline`
/// is meant to leave it `false`.
pub online: bool,
/// Whether this miner FAILED to respond to the scan. Stored as `offline`
/// (not `online`) so `Default` gives `false` -- i.e. a plain
/// `MinerRow { ..Default::default() }` is a reachable row, and only
/// `MinerRow::offline` deliberately marks a row unreachable. This removes
/// the old footgun where a struct-update literal that forgot `online: true`
/// silently read back as offline.
pub offline: bool,
}
impl MinerRow {
/// A miner that did not respond to this scan attempt: ip only, every
/// other field blank/zero/false, `online: false` so `status()` reports
/// other field blank/zero/false, `offline: true` so `status()` reports
/// "offline".
pub fn offline(ip: String) -> MinerRow {
let mut r = MinerRow::default();
r.ip = ip;
r.online = false;
r.offline = true;
r
}
pub fn status(&self) -> &'static str {
if !self.online {
if self.offline {
"offline"
} else if self.slow {
"slow"
@@ -318,6 +321,14 @@ pub fn is_paused(operating_state: &str, is_mining: bool) -> bool {
!is_mining && operating_state.to_lowercase().contains("pause")
}
/// The typed-confirmation gate for the irreversible firmware-flash action: the
/// operator must type exactly "FLASH" (surrounding whitespace ignored, but not
/// case-folded and not a prefix). Pure so the guard is unit-testable without a
/// live dialog.
pub fn flash_confirmed(input: &str) -> bool {
input.trim() == "FLASH"
}
/// Model columns. Ip is fixed (always shown first); the rest map 1:1 to a
/// scannable metric and can be shown/hidden/reordered. Row selection replaces
/// the old checkbox column.
@@ -814,14 +825,14 @@ pub fn compute_kpis(rows: &[MinerRow], view_idx: &[usize]) -> Kpis {
};
for &i in view_idx {
let r = &rows[i];
if r.slow {
k.slow += 1;
} else if r.paused {
k.paused += 1;
} else if r.is_mining {
k.hashing += 1;
} else {
k.not_hashing += 1;
// Bucket by the same precedence status() uses, so the KPI header can
// never disagree with a row's own status text. There is no separate
// "offline" KPI, so offline folds into not_hashing (the `_` arm).
match r.status() {
"slow" => k.slow += 1,
"paused" => k.paused += 1,
"hashing" => k.hashing += 1,
_ => k.not_hashing += 1,
}
k.total_hashrate_ths += r.hashrate_ths;
k.total_power_w += r.power_w;
@@ -1030,7 +1041,6 @@ mod tests {
chip_temp_c: 55.0 + (i % 25) as f64,
fan_rpms: vec![4000.0 + (i % 900) as f64],
is_mining: i % 7 != 0,
online: true,
model: format!("Model-{}", i % 12),
firmware: format!("fw-{}", i % 6),
worker: format!("blueflare.{i}"),
@@ -1198,9 +1208,9 @@ mod tests {
#[test]
fn passes_filters_ands_across_columns() {
let rows = vec![
MinerRow { ip: "10.0.0.1".into(), online: true, is_mining: true, model: "A".into(), ..Default::default() },
MinerRow { ip: "10.0.0.2".into(), online: true, is_mining: true, model: "B".into(), ..Default::default() },
MinerRow { ip: "10.0.0.3".into(), online: true, is_mining: false, model: "A".into(), ..Default::default() },
MinerRow { ip: "10.0.0.1".into(), is_mining: true, model: "A".into(), ..Default::default() },
MinerRow { ip: "10.0.0.2".into(), is_mining: true, model: "B".into(), ..Default::default() },
MinerRow { ip: "10.0.0.3".into(), is_mining: false, model: "A".into(), ..Default::default() },
];
let mut view = ViewState::default();
view.filters.insert(Column::Status, ColFilter::Values(HashSet::from(["hashing".to_string()])));
@@ -1531,26 +1541,32 @@ mod tests {
fn status_offline_and_paused() {
let offline = MinerRow::offline("10.1.2.3".into());
assert_eq!(offline.status(), "offline");
assert!(!offline.online);
assert!(offline.offline);
assert_eq!(offline.ip, "10.1.2.3");
assert_eq!(offline.hashrate_ths, 0.0, "offline row is otherwise blank");
let paused = MinerRow { online: true, paused: true, ..Default::default() };
// A plain default row is online (offline: false), so a struct-update
// literal that forgets to say so is reachable, not silently offline.
let default_is_online = MinerRow { ..Default::default() };
assert!(!default_is_online.offline, "Default row must be online");
assert_eq!(default_is_online.status(), "not hashing");
let paused = MinerRow { paused: true, ..Default::default() };
assert_eq!(paused.status(), "paused");
let hashing = MinerRow { online: true, is_mining: true, ..Default::default() };
let hashing = MinerRow { is_mining: true, ..Default::default() };
assert_eq!(hashing.status(), "hashing");
let not_hashing = MinerRow { online: true, ..Default::default() };
let not_hashing = MinerRow { ..Default::default() };
assert_eq!(not_hashing.status(), "not hashing");
// offline outranks slow/paused/hashing in the precedence order.
let offline_but_flagged =
MinerRow { online: false, slow: true, paused: true, is_mining: true, ..Default::default() };
MinerRow { offline: true, slow: true, paused: true, is_mining: true, ..Default::default() };
assert_eq!(offline_but_flagged.status(), "offline");
// slow outranks paused (and hashing).
let slow_and_paused = MinerRow { online: true, slow: true, paused: true, ..Default::default() };
let slow_and_paused = MinerRow { slow: true, paused: true, ..Default::default() };
assert_eq!(slow_and_paused.status(), "slow");
}
@@ -1562,4 +1578,35 @@ mod tests {
assert!(!is_paused("Mining", false));
assert!(!is_paused("", false));
}
#[test]
fn kpis_bucket_by_status_not_raw_flags() {
// An offline row that also carries stale slow/paused/mining flags must
// count as not_hashing (matching status() == "offline"), never as slow
// or paused -- i.e. compute_kpis and status() can't diverge.
let rows = vec![
MinerRow { offline: true, slow: true, paused: true, is_mining: true, ..Default::default() },
MinerRow { slow: true, ..Default::default() },
MinerRow { paused: true, ..Default::default() },
MinerRow { is_mining: true, ..Default::default() },
];
let idx: Vec<usize> = (0..rows.len()).collect();
let k = compute_kpis(&rows, &idx);
assert_eq!(k.slow, 1, "only the genuinely-slow row");
assert_eq!(k.paused, 1, "only the genuinely-paused row");
assert_eq!(k.hashing, 1);
assert_eq!(k.not_hashing, 1, "the offline-but-flagged row folds here, not into slow");
assert_eq!(k.total, 4);
}
#[test]
fn flash_confirmed_requires_exact_word() {
assert!(flash_confirmed("FLASH"));
assert!(flash_confirmed(" FLASH "), "surrounding whitespace is trimmed");
assert!(!flash_confirmed("flash"), "case-sensitive");
assert!(!flash_confirmed("Flash"));
assert!(!flash_confirmed("FLASHING"), "not a prefix match");
assert!(!flash_confirmed("FLASH NOW"));
assert!(!flash_confirmed(""));
}
}
+137 -1
View File
@@ -451,7 +451,8 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
MinerRow {
ip: data.ip.to_string(),
selected: false,
online: true,
// A miner that responded to the scan is reachable.
offline: false,
caps,
model,
mac: data.mac.map(|m| m.to_string()).unwrap_or_default(),
@@ -559,9 +560,13 @@ pub fn start_config_action(ips: Vec<String>, action: ConfigAction) -> ActionHand
if fake_scan_enabled() {
let err_tx = tx.clone();
let thread_cancel = cancel.clone();
let res = std::thread::Builder::new().name("fake-action".into()).spawn(move || {
let mut ok = 0usize;
for ip in ips {
if thread_cancel.load(Ordering::Relaxed) {
break;
}
let _ = tx.send(ActionMsg::Result { ip, ok: true, detail: "simulated".into() });
ok += 1;
}
@@ -655,10 +660,14 @@ pub fn start_refresh(ips: Vec<String>) -> RefreshHandle {
if fake_scan_enabled() {
let err_tx = tx.clone();
let thread_cancel = cancel.clone();
let res = std::thread::Builder::new().name("fake-refresh".into()).spawn(move || {
let fleet = crate::fixtures::bench_fleet();
let mut ok = 0usize;
for ip in ips {
if thread_cancel.load(Ordering::Relaxed) {
break;
}
match fleet.iter().find(|r| r.ip == ip) {
Some(row) => {
if tx.send(RefreshMsg::Row(row.clone())).is_err() {
@@ -751,9 +760,13 @@ pub fn start_firmware_flash_action(ips: Vec<String>, image: FirmwareImage) -> Ac
if fake_scan_enabled() {
let err_tx = tx.clone();
let thread_cancel = cancel.clone();
let res = std::thread::Builder::new().name("fake-firmware-flash".into()).spawn(move || {
let mut ok = 0usize;
for ip in ips {
if thread_cancel.load(Ordering::Relaxed) {
break;
}
let _ = tx.send(ActionMsg::Result { ip, ok: true, detail: "simulated".into() });
ok += 1;
}
@@ -1052,4 +1065,127 @@ mod tests {
println!("bench_targets_to_cidrs_large_range: {} addrs -> {sink} cidrs, {:?}/op", ips.len(), per);
assert!(per.as_millis() < 200, "targets_to_cidrs regressed: {per:?}/op");
}
/// Exercise the round-6 background actions through their fake-scan branch:
/// offline-row emission (start_scan), per-IP refresh (start_refresh),
/// firmware flash (start_firmware_flash_action), and that a cancelled run
/// still terminates. ALKANE_FAKE_SCAN is process-global, but no other test
/// calls these functions, so setting it here only affects this one
/// (sequential) test; all fake-mode assertions live in a single #[test] so
/// they never race each other over the env var.
#[test]
fn fake_mode_background_actions() {
use std::sync::mpsc::RecvTimeoutError;
use std::time::Duration;
let deadline = Duration::from_secs(5);
std::env::set_var(FAKE_SCAN_ENV, "1");
// start_scan: every probed IP produces a Row, including a synthetic
// unreachable host that must come back as an offline row.
{
let h = start_scan(vec!["10.255.1.0/30".into()]);
let mut rows = Vec::new();
let mut total = 0usize;
loop {
match h.rx.recv_timeout(deadline) {
Ok(ScanMsg::Started { total: t, .. }) => total = t,
Ok(ScanMsg::Row(r)) => rows.push(r),
Ok(ScanMsg::Done(_)) => break,
Ok(_) => {}
Err(RecvTimeoutError::Timeout) => panic!("fake start_scan hung"),
Err(RecvTimeoutError::Disconnected) => break,
}
}
assert_eq!(rows.len(), total, "one Row per probed target, incl. the offline host");
let offline = rows
.iter()
.find(|r| r.ip == "10.255.1.254")
.expect("synthetic offline row must be emitted");
assert!(offline.offline);
assert_eq!(offline.status(), "offline");
}
// start_refresh: a known fixture IP re-reads as a Row, an unknown IP is
// reported Failed{offline}, and the run ends with Done{ok:1,total:2}.
{
let known = "10.255.1.112".to_string(); // an S17 in bench_fleet
let unknown = "10.0.0.250".to_string();
let h = start_refresh(vec![known.clone(), unknown.clone()]);
let (mut rows, mut failed, mut done) = (0usize, 0usize, None);
loop {
match h.rx.recv_timeout(deadline) {
Ok(RefreshMsg::Started { .. }) => {}
Ok(RefreshMsg::Row(r)) => {
assert_eq!(r.ip, known);
rows += 1;
}
Ok(RefreshMsg::Failed { ip, detail }) => {
assert_eq!(ip, unknown);
assert_eq!(detail, "offline");
failed += 1;
}
Ok(RefreshMsg::Done { ok, total }) => {
done = Some((ok, total));
break;
}
Err(RecvTimeoutError::Timeout) => panic!("fake start_refresh hung"),
Err(RecvTimeoutError::Disconnected) => break,
}
}
assert_eq!(rows, 1);
assert_eq!(failed, 1);
assert_eq!(done, Some((1, 2)));
}
// start_firmware_flash_action: fake mode reports one simulated success
// per IP and a matching Done summary.
{
let image = FirmwareImage::new("fw.bin".to_string(), vec![0u8; 8]);
let h = start_firmware_flash_action(
vec!["10.255.1.166".into(), "10.255.1.149".into()],
image,
);
let (mut results, mut done) = (0usize, None);
loop {
match h.rx.recv_timeout(deadline) {
Ok(ActionMsg::Started { .. }) => {}
Ok(ActionMsg::Result { ok, detail, .. }) => {
assert!(ok);
assert_eq!(detail, "simulated");
results += 1;
}
Ok(ActionMsg::Done { ok, total }) => {
done = Some((ok, total));
break;
}
Err(RecvTimeoutError::Timeout) => panic!("fake flash hung"),
Err(RecvTimeoutError::Disconnected) => break,
}
}
assert_eq!(results, 2);
assert_eq!(done, Some((2, 2)));
}
// Cancellation contract: stopping a run still delivers a terminal Done
// rather than hanging (the fake branches now honour the cancel flag).
{
let big: Vec<String> = (0..200).map(|i| format!("10.9.0.{}", i % 256)).collect();
let h = start_refresh(big);
h.stop();
let mut saw_done = false;
loop {
match h.rx.recv_timeout(deadline) {
Ok(RefreshMsg::Done { .. }) => {
saw_done = true;
break;
}
Ok(_) => {}
Err(_) => break,
}
}
assert!(saw_done, "a cancelled fake refresh must still emit Done, not hang");
}
std::env::remove_var(FAKE_SCAN_ENV);
}
}
+236 -26
View File
@@ -292,6 +292,12 @@ pub struct App {
flash_confirm_dialog: Widget,
flash_confirm_input: Widget,
pending_flash: Option<(Vec<String>, FirmwareImage, String)>,
// True while a firmware flash's ActionHandle is in flight. A flash is the
// one irreversible, hardware-destroying action, so it takes an exclusive
// lock: nothing else (scan / refresh / config action / another flash) may
// start while it runs, and it will not start while anything else is running,
// so no two network operations ever race the same miner mid-upload.
flashing: bool,
// The "Set scan credentials..." dialog.
creds_dialog: Widget,
creds_user_input: Widget,
@@ -462,6 +468,7 @@ pub fn build(frame: Widget) -> App {
flash_confirm_dialog: frame,
flash_confirm_input: frame,
pending_flash: None,
flashing: false,
creds_dialog: frame,
creds_user_input: frame,
creds_pass_input: frame,
@@ -554,19 +561,33 @@ impl App {
let r = &self.rows[ri];
for (ci, c) in cols.iter().enumerate() {
let encoded = match c {
// Gate the ratio on the ACTUAL being known: an unknown actual
// (hashrate 0.0 sentinel / None count) renders as "- / <expected>"
// and must fall through to the plain, uncoloured segment rather
// than paint the "-" solid red as if the miner were at 0%.
Column::Hashrate => {
let ratio = actual_expected_ratio(r.hashrate_ths, r.expected_ths);
let ratio = (r.hashrate_ths > 0.0)
.then(|| actual_expected_ratio(r.hashrate_ths, r.expected_ths))
.flatten();
encode_combined_cell(&self.pal, &c.cell(r), ratio)
}
Column::Hashboards => {
let actual = r.hashboards.map(|v| v as f64).unwrap_or(0.0);
let expected = r.expected_hashboards.map(|v| v as f64).unwrap_or(0.0);
encode_combined_cell(&self.pal, &c.cell(r), actual_expected_ratio(actual, expected))
let ratio = r.hashboards.and_then(|a| {
actual_expected_ratio(
a as f64,
r.expected_hashboards.map(|v| v as f64).unwrap_or(0.0),
)
});
encode_combined_cell(&self.pal, &c.cell(r), ratio)
}
Column::TotalChips => {
let actual = r.total_chips.map(|v| v as f64).unwrap_or(0.0);
let expected = r.expected_chips.map(|v| v as f64).unwrap_or(0.0);
encode_combined_cell(&self.pal, &c.cell(r), actual_expected_ratio(actual, expected))
let ratio = r.total_chips.and_then(|a| {
actual_expected_ratio(
a as f64,
r.expected_chips.map(|v| v as f64).unwrap_or(0.0),
)
});
encode_combined_cell(&self.pal, &c.cell(r), ratio)
}
Column::Cooling => encode_cooling_cell(&self.pal, &r.fan_rpms),
_ => continue,
@@ -672,6 +693,13 @@ impl App {
let menu = Widget::menu_new();
let open = if n == 1 { "Open in browser".to_string() } else { format!("Open {n} miners in browser") };
menu.menu_append(ID_CTX_OPEN, &open);
// While a firmware flash holds the exclusive lock, offer only the
// read-only "Open in browser" action; every network action is refused
// anyway, so don't dangle them in the menu.
if self.flashing {
self.pending_popup = Some((t, menu));
return;
}
menu.menu_append_separator();
// Refresh is always offered for a non-empty selection, independent of
// the capability intersection below.
@@ -740,6 +768,10 @@ impl App {
if ips.is_empty() {
return;
}
if self.flashing {
wx_rs::set_status_text("firmware flash in progress -- wait for it to finish");
return;
}
if let Some(old) = self.action.take() {
old.stop();
}
@@ -755,6 +787,10 @@ impl App {
if ips.is_empty() {
return;
}
if self.flashing {
wx_rs::set_status_text("firmware flash in progress -- wait for it to finish");
return;
}
if let Some(old) = self.refresh.take() {
old.stop();
}
@@ -774,13 +810,19 @@ impl App {
}
ID_CTX_REFRESH => self.start_refresh(self.selected_ip_list()),
ID_CTX_FLASH => {
let supporting: Vec<String> = self
// A flash needs exclusive hardware access; don't even prompt if
// any scan / refresh / action is running (re-checked at confirm).
if self.flashing || self.scanning || self.action.is_some() || self.refresh.is_some() {
wx_rs::set_status_text("busy (scan/action in progress) -- try again once it finishes");
return None;
}
let targets: Vec<(String, String)> = self
.selected_rows()
.iter()
.filter(|r| r.caps.firmware_flash)
.map(|r| r.ip.clone())
.map(|r| (r.ip.clone(), r.model.clone()))
.collect();
if supporting.is_empty() {
if targets.is_empty() {
return None;
}
// wxFileDialog runs its own nested modal loop; that's fine to
@@ -791,7 +833,7 @@ impl App {
return None;
};
match FirmwareImage::from_file(&path) {
Ok(image) => return Some(self.build_flash_confirm_dialog(&path, supporting, image)),
Ok(image) => return Some(self.build_flash_confirm_dialog(&path, targets, image)),
Err(e) => wx_rs::set_status_text(&format!("failed to read firmware image: {e}")),
}
}
@@ -907,18 +949,44 @@ impl App {
/// operator must type FLASH exactly, on top of seeing the image's file
/// name and how many of the selected miners actually support it. Built
/// here, shown modally by `dispatch` outside the App borrow.
fn build_flash_confirm_dialog(&mut self, path: &str, ips: Vec<String>, image: FirmwareImage) -> Widget {
let n = ips.len();
fn build_flash_confirm_dialog(
&mut self,
path: &str,
targets: Vec<(String, String)>,
image: FirmwareImage,
) -> Widget {
let n = targets.len();
let name = std::path::Path::new(path)
.file_name()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| path.to_string());
// List exactly which miners (IP + model) will receive the image, so the
// typed confirmation is informed. Warn loudly if the batch spans more
// than one model, since a single image is rarely valid for all of them.
let mut models: Vec<&str> = targets.iter().map(|(_, m)| m.as_str()).collect();
models.sort_unstable();
models.dedup();
let target_list = targets
.iter()
.map(|(ip, model)| format!(" {ip} ({model})"))
.collect::<Vec<_>>()
.join("\n");
let mixed_warn = if models.len() > 1 {
format!(
"\n\nWARNING: the selection spans {} different models ({}). One image is rarely valid for all of them and a wrong image can brick a miner.",
models.len(),
models.join(", ")
)
} else {
String::new()
};
let ips: Vec<String> = targets.into_iter().map(|(ip, _)| ip).collect();
self.pending_flash = Some((ips, image, name.clone()));
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Flash firmware");
let root = Widget::box_sizer(true);
let msg = format!(
"Flash \"{name}\" to {n} selected miner(s)? This overwrites running firmware and cannot be undone.\n\nType FLASH to confirm:"
"Flash \"{name}\" to these {n} miner(s)? This overwrites running firmware and cannot be undone.\n\n{target_list}{mixed_warn}\n\nType FLASH to confirm:"
);
root.add(Widget::static_text(dlg, &msg), 0, sf::BORDER_ALL, 12);
let input = Widget::text_ctrl(dlg, false);
@@ -941,16 +1009,22 @@ impl App {
/// typed exactly "FLASH"; otherwise keep the dialog open (and the pending
/// target captured) so they can correct it.
fn apply_flash_confirm(&mut self) {
if self.flash_confirm_input.get_value().trim() != "FLASH" {
if !flash_confirmed(&self.flash_confirm_input.get_value()) {
wx_rs::set_status_text("type FLASH exactly to confirm");
return;
}
if let Some((ips, image, _name)) = self.pending_flash.take() {
self.flash_confirm_dialog.close(1);
if let Some(old) = self.action.take() {
old.stop();
// Authoritative exclusivity check: a scan/refresh/action may have
// started while the dialog was open. A flash must never race another
// network operation on the same miner, so refuse rather than run the
// prior handle's `stop()` (which does not join the in-flight upload).
if self.flashing || self.scanning || self.action.is_some() || self.refresh.is_some() {
wx_rs::set_status_text("busy (scan/action started) -- flash cancelled, try again");
return;
}
let msg = format!("flashing firmware to {} miner(s)...", ips.len());
self.flashing = true;
self.action = Some(scan::start_firmware_flash_action(ips, image));
wx_rs::set_status_text(&msg);
}
@@ -963,12 +1037,18 @@ impl App {
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Set scan credentials");
let root = Widget::box_sizer(true);
let hint = Widget::static_text(
dlg,
"HTTP credentials for firmware auto-discovery on password-protected miners.",
);
root.add(hint, 0, sf::BORDER_ALL, 8);
let (saved_user, saved_pass) = credentials::load_credentials().unwrap_or_default();
// Never re-display the saved password in plaintext. Leave the field
// blank; a blank password on Save keeps whatever is already stored (see
// apply_creds_save), so opening this dialog to change only the username
// does not require -- or reveal -- the password.
let pass_hint = if saved_pass.is_empty() {
"HTTP credentials for firmware auto-discovery on password-protected miners."
} else {
"HTTP credentials for firmware auto-discovery. A password is already saved; leave Password blank to keep it, or type a new one to replace it."
};
let hint = Widget::static_text(dlg, pass_hint);
root.add(hint, 0, sf::BORDER_ALL, 8);
let user_row = Widget::box_sizer(false);
user_row.add(Widget::static_text(dlg, "Username:"), 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
let user_input = Widget::text_ctrl(dlg, false);
@@ -979,7 +1059,6 @@ impl App {
let pass_row = Widget::box_sizer(false);
pass_row.add(Widget::static_text(dlg, "Password:"), 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
let pass_input = Widget::text_ctrl(dlg, false);
pass_input.set_value(&saved_pass);
pass_input.set_min_size(200, -1);
pass_row.add(pass_input, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 6);
root.add_sizer(pass_row, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6);
@@ -1000,7 +1079,14 @@ impl App {
fn apply_creds_save(&mut self) {
let user = self.creds_user_input.get_value();
let pass = self.creds_pass_input.get_value();
let mut pass = self.creds_pass_input.get_value();
// A blank password field means "keep the saved password" (the dialog no
// longer pre-fills it in plaintext), so fall back to the stored value.
if pass.is_empty() {
if let Some((_, saved_pass)) = credentials::load_credentials() {
pass = saved_pass;
}
}
match credentials::save_credentials(&user, &pass) {
Ok(()) => {
self.creds_dialog.close(1);
@@ -1061,6 +1147,9 @@ impl App {
}
if finished {
self.action = None;
// Release the firmware-flash exclusive lock (harmless no-op for a
// plain config action, which never set it).
self.flashing = false;
// 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();
@@ -1240,6 +1329,12 @@ impl App {
/// the old scan to stop before replacing it prevents two scan threads (and
/// two tokio runtimes) probing the network at once.
fn begin_scan(&mut self, lines: Vec<String>) {
// Never probe the network while a firmware flash is uploading: a stray
// scan connection to a miner mid-write can interrupt/corrupt the flash.
if self.flashing {
wx_rs::set_status_text("firmware flash in progress -- scan deferred");
return;
}
if let Some(old) = self.scan.take() {
old.stop();
}
@@ -1973,14 +2068,39 @@ impl App {
} else {
check("WardenOS-dev (.115) present", false, "row not found".into());
}
// The synthetic unreachable row must classify as offline with a blank
// hashrate (round-6 offline-recognition path).
if let Some(row) = find("10.255.1.199") {
check("offline row (.199) is offline", cell(row, status_col) == "offline",
format!("status=\"{}\"", cell(row, status_col)));
check("offline row (.199) blank hashrate", cell(row, hr_col).is_empty(),
format!("hashrate=\"{}\"", cell(row, hr_col)));
} else {
check("offline row (.199) present", false, "row not found".into());
}
check("IP is the first column", ip_col == Some(0),
format!("ip col index = {ip_col:?}"));
// default view is IP-ascending
// default view is IP-ascending -- compare against the model's own
// numeric dotted-quad order (not a lexical string sort, which only
// coincidentally matches while every fixture octet is the same width).
let ips: Vec<String> = self.view_idx.iter().map(|&ri| self.rows[ri].ip.clone()).collect();
let mut sorted = ips.clone();
sorted.sort();
sorted.sort_by_key(|ip| ip_to_u32(ip));
check("default sort is IP ascending", ips == sorted, String::new());
// 5. KPI quick-filter: clicking a status card filters the table to that
// status; clicking again clears it back to the full fleet.
let full = self.view_idx.len();
self.toggle_kpi_filter("slow");
let slow_only = self.view_idx.iter().all(|&ri| self.rows[ri].status() == "slow");
check("KPI filter 'slow' shows only slow rows",
self.view_idx.len() == 1 && slow_only && self.active_kpi_filter == Some("slow"),
format!("len={}, active={:?}", self.view_idx.len(), self.active_kpi_filter));
self.toggle_kpi_filter("slow");
check("KPI filter toggled off restores full fleet",
self.view_idx.len() == full && self.active_kpi_filter.is_none(),
format!("len={} (want {full}), active={:?}", self.view_idx.len(), self.active_kpi_filter));
ok
}
}
@@ -2023,3 +2143,93 @@ pub fn dispatch(ev: WxEvent) {
on.popup_menu(menu);
}
}
#[cfg(test)]
mod tests {
//! Pure colour/encoding helpers exercised without any wx display: these are
//! the visual contracts the headless self-test's `decode_segments_plain`
//! cell comparison deliberately strips out, so they need their own coverage.
use super::*;
/// A palette with unambiguous sentinel colours so equality checks are exact.
fn test_pal() -> Palette {
Palette {
card_bg: (1, 1, 1),
label: (10, 20, 30),
neutral: (40, 40, 40),
green: (0, 255, 0),
amber: (255, 128, 0),
red: (255, 0, 0),
accent: (0, 0, 255),
}
}
#[test]
fn tint_toward_endpoints_and_midpoint() {
let a = (10, 20, 30);
let b = (200, 100, 250);
assert_eq!(tint_toward(a, b, 0.0), a);
assert_eq!(tint_toward(a, b, 1.0), b);
assert_eq!(tint_toward(a, a, 0.37), a, "same endpoints -> unchanged at any fraction");
assert_eq!(tint_toward((0, 0, 0), (255, 255, 255), 0.5), (128, 128, 128));
}
#[test]
fn ratio_color_stops_and_clamping() {
let p = test_pal();
assert_eq!(ratio_color(&p, 0.0), p.red, "0% -> red");
assert_eq!(ratio_color(&p, 0.5), p.amber, "50% -> amber");
assert_eq!(ratio_color(&p, 1.0), p.green, "100% -> green");
assert_eq!(ratio_color(&p, -3.0), p.red, "clamped below 0");
assert_eq!(ratio_color(&p, 9.0), p.green, "clamped above 1 (overperforming -> green)");
}
#[test]
fn fan_color_grey_to_blue_scale() {
let p = test_pal();
assert_eq!(fan_color(&p, 0.0), p.label, "stopped fan -> grey label colour");
assert_eq!(fan_color(&p, 6000.0), p.accent, "at/above ceiling -> saturated accent blue");
assert_eq!(fan_color(&p, 12000.0), p.accent, "clamped above the ceiling");
assert_eq!(fan_color(&p, 3000.0), tint_toward(p.label, p.accent, 0.5), "halfway blend");
}
#[test]
fn combined_cell_unknown_actual_is_not_coloured_red() {
let p = test_pal();
// Unknown actual ("-") with no ratio must take the plain, uncoloured
// branch -- not paint the "-" solid red as a 0% miner would be.
let unknown = encode_combined_cell(&p, "- / 200 TH/s", None);
assert_eq!(unknown, encode_segments(&[(None, "- / 200 TH/s".to_string())]));
assert_eq!(decode_segments_plain(&unknown), "- / 200 TH/s");
// A known ratio colours only the actual half; the slash + expected stay
// uncoloured, and it still round-trips to the same plain text.
let known = encode_combined_cell(&p, "60.0 TH/s / 200 TH/s", Some(0.3));
let expected = encode_segments(&[
(Some(ratio_color(&p, 0.3)), "60.0 TH/s".to_string()),
(None, " / ".to_string()),
(None, "200 TH/s".to_string()),
]);
assert_eq!(known, expected);
assert_eq!(decode_segments_plain(&known), "60.0 TH/s / 200 TH/s");
}
#[test]
fn cooling_cell_colours_each_fan_with_black_slashes() {
let p = test_pal();
assert_eq!(
decode_segments_plain(&encode_cooling_cell(&p, &[4800.0, 4600.0])),
"4.8k/4.6k",
);
// Slash segments carry no colour (they render in the default text colour).
let encoded = encode_cooling_cell(&p, &[4800.0, 4600.0]);
let expected = encode_segments(&[
(Some(fan_color(&p, 4800.0)), format_fan_rpm(4800.0)),
(None, "/".to_string()),
(Some(fan_color(&p, 4600.0)), format_fan_rpm(4600.0)),
]);
assert_eq!(encoded, expected);
// No fans -> a single empty segment that decodes to "".
assert_eq!(decode_segments_plain(&encode_cooling_cell(&p, &[])), "");
}
}