From cdd605c189becf78f155a9b944d70f817e213a1d Mon Sep 17 00:00:00 2001 From: noah Date: Thu, 17 Sep 2026 14:06:03 -0600 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh --- code-review-report.md | 169 ++++------------- crates/alkane-gui/src/credentials.rs | 36 +++- crates/alkane-gui/src/fixtures.rs | 6 +- crates/alkane-gui/src/model.rs | 103 ++++++++--- crates/alkane-gui/src/scan.rs | 138 +++++++++++++- crates/alkane-gui/src/ui.rs | 262 ++++++++++++++++++++++++--- 6 files changed, 519 insertions(+), 195 deletions(-) diff --git a/code-review-report.md b/code-review-report.md index 8b0a6eba..b33dd223 100644 --- a/code-review-report.md +++ b/code-review-report.md @@ -1,147 +1,48 @@ -# Code Review Report - alkane-toolkit +# Code review report -- alkane-gui round 6 -Scope: our own source (`crates/alkane-*/src`, `ci/`, `scripts/`, `.gitea/`). -Vendored `thirdparty/wxwidgets` and `thirdparty/wx-rs` were excluded from -scanning (the repo lives on a CIFS mount that has previously crashed under -recursive scans). Desktop wxWidgets app - no web UI, so Playwright was skipped. +Scope: the round-6 diff of our own source only (`crates/alkane-gui/src/{model,scan,ui,credentials,fixtures,main}.rs`), vs the round-5 release commit `8c3a410`. Vendored `thirdparty/` and `vendor/` trees were excluded (CIFS fd-exhaustion hazard). Desktop wxWidgets app, so no Playwright/web UI. -Driver: the harness was run to develop and harden the test + microbenchmark -suite that gates the new CI pipeline, and to catch correctness/reliability -defects in the round-2 GUI work. +Method: a 6-dimension parallel review (correctness, reliability/concurrency, security, test+microbench coverage, firmware-flash correctness, maintainability) with an adversarial verify pass on every Critical/High finding. 27 raw findings; 11 Critical/High, all confirmed; 16 non-blocking. The verify pass corrected several severities (recorded below). ## Verdict -READY TO SHIP (after CI green). All Critical/High findings are fixed and -validated locally: 41 unit tests pass (0 failed), 9 microbenchmarks pass with -wide margins, and 9 shell tests cover the CI version logic. No Critical findings -were found; the three High findings are resolved. +NOT READY at review time (1 Critical + multiple High). After the remediation in this round, all Critical/High correctness, reliability, security, and firmware findings are fixed and the flagged coverage gaps are closed. Re-ship pending CI (the release build + all unit tests + the headless self-test gate). -## Codebase summary (reviewed surface) +## Blocking findings and remediation -| Metric | Value | -|---|---| -| Language | Rust (edition 2021) + bash + Gitea Actions YAML | -| Reviewed Rust LoC | ~2,400 (GUI crate: ui.rs 915, model.rs 815->1050, scan.rs 521->700) | -| Backend crates | 1-line stubs (core/discovery/access/flash/artifacts/cli) - not yet implemented | -| Unit tests | 24 -> 41 | -| Microbenchmarks (Rust, `#[ignore]`) | 2 -> 9 | -| Shell tests (compute-version.sh) | 0 -> 9 | -| Reviewers | correctness, reliability, performance, test-coverage (parallel, opus/sonnet) | +| # | Sev (verified) | File:line | Finding | Status | +|---|---|---|---|---| +| 1 | Critical | ui.rs:951 | Re-triggering an action did not wait for the previous to stop -> overlapping firmware flashes to one miner (brick risk). | FIXED -- a flash now takes an exclusive `flashing` lock: it will not start while a scan/refresh/action runs, and nothing (scan/refresh/action/another flash) starts while it runs. `begin_scan`, `start_action`, `start_refresh`, `apply_flash_confirm` all gate on it; the context menu hides network actions while flashing. | +| 2 | High | ui.rs:128 | Unknown-actual rendered the "-" placeholder in solid red (idle/paused/booting miners of a known model looked like 0% catastrophic failures). Masked by the all-zero-expected fixtures. | FIXED -- `fill_rows` now gates the ratio on the actual being known (`hashrate_ths > 0` / `hashboards.is_some()` / `total_chips.is_some()`), so an unknown actual falls to the plain, uncoloured segment. Regression-tested (`combined_cell_unknown_actual_is_not_coloured_red`). | +| 3 | High | ui.rs:910 | Batch flash hid the target IPs/models and pushed one image onto a heterogeneous set. | FIXED -- the confirm dialog now lists every target IP + model and warns loudly when the batch spans more than one model. | +| 4 | High | scan.rs:746 | No mutual exclusion between a flash and a concurrent scan/refresh on the same miner. | FIXED -- same exclusive `flashing` lock as #1 (a flash blocks scans/refreshes and vice-versa). | +| 5 | High | scan.rs:650 | `start_refresh` had zero test coverage. | FIXED -- `fake_mode_background_actions` drives it (Row / Failed / Done + cancellation). | +| 6 | High | scan.rs:746 | `start_firmware_flash_action` / `flash_one` had zero coverage. | FIXED -- same test covers the fake-mode success path + cancellation; the typed-FLASH gate is extracted to `model::flash_confirmed` and unit-tested. | +| 7 | High | scan.rs (start_scan) | Offline-row emission (every probed IP yields a row) untested. | FIXED -- the same test asserts the synthetic offline host comes back `offline`. | +| 8 | Critical->Medium | credentials.rs:34 | Credentials file created 0644 then chmod'd 0600 -> brief world-readable window with the plaintext already written. | FIXED -- created via `OpenOptions::mode(0o600)` and re-tightened to 0600 while still empty, before any plaintext is written. Tested (create-mode + pre-existing-0644 cases). | +| 9 | High->Low | ui.rs:1997 | Typed-FLASH gate uncovered. | FIXED -- extracted to `model::flash_confirmed`, unit-tested (exact / case / prefix / whitespace / empty). | +| 10 | High->Medium | ui.rs:1405 | `ratio_color`/`fan_color`/`tint_toward` colour contracts unasserted (the self-test decodes colours away). | FIXED -- new `ui::tests` module asserts the stops, clamping, and blends without a wx display. | +| 11 | High->Medium | scan.rs:554 | Four `start_*` functions duplicate ~60 lines of thread/channel/cancel boilerplate. | DEFERRED -- pure maintainability/DRY; no current defect. Tracked for a follow-up extraction. | -## Iteration history +## Non-blocking findings addressed this round -| Iter | Reviewers | Findings | Changes applied | -|---|---|---|---| -| 1 | 4 parallel | 3 High, 3 Medium, 4 Low + a 55-item test plan | 6 code fixes, +17 unit tests, +7 Rust benches, +9 shell tests | +- Medium (scan.rs:560) fake-scan branches never checked the cancel flag -- FIXED (all three fake branches now honour it; covered by the cancellation test). +- Medium (model.rs:272) `MinerRow.online` defaulted false (footgun) -- FIXED by inverting to `offline: bool` (default false = online); `..Default::default()` now yields a reachable row and only `offline()` marks one unreachable. +- Medium (model.rs:815) `compute_kpis` re-implemented `status()` precedence and ignored `online` -- FIXED (buckets by `status()`; offline folds into not_hashing). Regression-tested. +- Medium (ui.rs:1759) KPI quick-filter toggle untested -- FIXED (self-test toggles "slow" on and off). +- Medium (ui.rs:1868) offline row `.199` had no spot-check -- FIXED (self-test asserts offline + blank hashrate). +- Medium (credentials.rs:60) `configured_factory` untested -- FIXED (smoke test, both branches). +- Low (ui.rs:981) creds dialog showed the saved password in plaintext -- MITIGATED (no longer pre-filled; blank keeps the stored password). +- Low (ui.rs:1980) self-test IP sort was lexical -- FIXED (numeric via `model::ip_to_u32`). -Single iteration: the four reviewers converged on a small, consistent set of -defects (the IP-sort bug was found independently by both correctness and -performance). Fixes were applied and re-validated locally; no finding remained -stuck. +## Deferred (non-blocking, tracked) -## Blocking findings (Critical + High) - all FIXED +- Maintainability: extract the shared `start_*` background-thread skeleton (#11); fold the two `fill_rows` passes / re-parse into a single `Column::cell_parts` data path (ui.rs:550/542); route fixture `paused` through `is_paused()` (fixtures.rs:32); drop the `ColorKind::Blue`==`Accent` duplicate (ui.rs:193); name the colour magic numbers (ui.rs:105). +- Security hardening (design): scope saved credentials to a chosen backend instead of fanning out to every firmware backend during a subnet scan (credentials.rs:58); a true masked password field needs a wx `TE_PASSWORD` binding (bridge work). +- Firmware: per-tick status text should say "flashing" vs a generic action (ui.rs:1031); a real per-model image-compatibility check before batching (beyond the new dialog warning). +- A segment-encode microbench to gate the new per-`fill_rows` cost (ui.rs:1699). -1. High - IP column sorts lexically, not numerically (model.rs:364,471). - `Column::Ip` fell through to the generic `SortKey::Str(...to_lowercase())` - arm while the default view is IP-ascending, so `10.255.1.10` sorted before - `10.255.1.2` on every launch. Found independently by correctness and - performance. FIX: dedicated numeric IP key (`ip_to_u32`, exact in f64) + - decorate-sort-undecorate in `view()` so a key is computed once per row, not - twice per comparison. Test: `ip_column_sorts_numerically`. +## Human-review checklist (advisory) -2. High - No scan cancellation; Stop/Apply/Play can run two scans at once - (ui.rs Stop/apply_ranges/Play, scan.rs). Stop only dropped the receiver; - the background thread kept probing (each dead host waits out an asic-rs - timeout), and Play (guarded only by `!scanning`) could then spawn a second - thread + tokio runtime. FIX: `ScanHandle` carries an `Arc` cancel - flag the scan loop checks each iteration; a `begin_scan()` helper stops the - in-flight scan before starting a new one; Stop signals cancellation. - -3. High - Native column drag never rebuilds the control (ui.rs - `column_reordered`). It mutated `view.order` but skipped `rebuild_table()`, - so the store's creation order diverged from `display_columns()` and cells - rendered under the wrong headers on the next scan tick. FIX: call - `rebuild_table()` after applying the drag reorder. - -## Non-blocking findings - -- Medium (correctness) - `format_si` rounding/prefix boundary: `999.9 W` - rendered as "1000 W" (4 digits, violates the "<=2 digits + 1 decimal" spec). - FIXED: round first, then roll the prefix over; `[99.95,100)` drops its - decimal. Test: `format_si_rolls_over_at_rounding_boundary`. -- Low (reliability) - `start_scan` used `.expect("spawn scan thread")`, which - would panic across the wx FFI boundary if thread creation failed. FIXED: - send `ScanMsg::Failed` and return the handle instead. -- Medium (performance, DEFERRED) - `Column::cell` always returns an owned - `String`; a `Cow` would avoid clones for already-string fields. Deferred: - the decorate-sort fix removed the dominant per-comparison allocations; this is - a smaller, larger-surface refactor. Guarded by `bench_render_cells`. -- Medium (performance, DEFERRED) - `MinerRow::upsert_into` is an O(n) linear - scan, so cold-starting a fleet of N is O(n^2). Deferred: an ip->index map is - a follow-up; added `bench_upsert_cold_start_population` (3000 rows = ~8ms - locally) as a regression guard. -- Low (performance) - `to_row` traverses the pool list twice; `parse_targets` - dedups via `BTreeSet`. Minor; not on a per-render path. Deferred. -- Low (reliability) - the scan thread is detached (no join on window close). - The cancel flag now lets Stop/close signal it; abrupt teardown on window - close remains, which is acceptable for a desktop app. - -## Test + benchmark plan (delivered) - -New unit tests (17): format_si zero/negative/non-finite + rollover boundary, -format_uptime boundary matrix, numeric IP sort, upsert-new-IP, Light three-state -cell, pool-slot out-of-range cell, filter AND-across / OR-within columns, -apply_visible_reorder non-permutation guard. - -New scan tests: parse_cidr bare/rejections, prefix_mask boundaries, single-host -/32, empty/whitespace lines, short-range single/reversed, parse_targets -aggregate cap + error propagation + empty, validate_ranges, targets_to_cidrs -non-contiguous split, auto-rescan-secs round-trip (temp HOME). - -New Rust microbenchmarks (7, `#[ignore]`, run in CI): view default-sort, -sort-by-each-column, filtered view, upsert cold-start, parse_line near -MAX_ADDRS, parse_targets many ranges, targets_to_cidrs large range. Floors are -5-10x above local numbers to catch regressions without flaking on slower CI. - -New shell tests (9): `ci/test-compute-version.sh` exercises the X.Y.Z logic - -first release, pre-bumped X, backend bump, UI bump, docs-only (no release), -manual-major-wins-over-UI, backend-wins-over-UI, nested ci/ (backend), nested -thirdparty/wx-rs (UI). Wired into the pipeline as a fast-fail step. - -Local results: 41 unit tests ok; 9 benches ok (view default-sort 205us, -sort-by-each-column worst 527us, upsert 3000=7.7ms, parse_line near-cap 797us); -9 shell tests ok. - -## Changes applied during review - -- `crates/alkane-gui/src/model.rs` - format_si rollover, `ip_to_u32`, numeric IP - sort key, decorate-sort-undecorate `view()`, +17 tests, +4 benches. -- `crates/alkane-gui/src/scan.rs` - `ScanHandle` + cancel flag, graceful - spawn-failure, +11 tests, +3 benches. -- `crates/alkane-gui/src/ui.rs` - `begin_scan()` (cancel-before-start), Stop - cancels, `drain_scan` uses the handle, `column_reordered` rebuilds. -- `ci/test-compute-version.sh` - new shell test suite (+ workflow step). -- `.gitea/workflows/release.yml` - install libssl-dev/pkg-config, version-logic - test step (earlier commits: `bash` script invocation, exec bits). - -## Human review checklist (advisory) - -- Confirm the deferred perf items (Cow cells, upsert index map) are acceptable - to ship now; benches guard against regressions until then. -- The headless UI self-test is a hard CI gate (confirmed passing in-container - once `xauth` was added: "SELFTEST PASS" in run 529). -- Backend crates are stubs; when implemented they will need their own tests. - -## Automated actions taken - -- 4 parallel review subagents (best model, isolated scope, guardrailed against - CIFS/vendored recursion). -- 6 code fixes applied and re-validated; 33 tests + 7 benches added. -- Cross-session memory updated at `.claude/code-review-memory.md`. - -## Tooling gaps - -- `cargo clippy` / coverage not run in this pass (CIFS build cost); `cargo fmt` - showed minor drift in fixtures.rs (nit, not applied to keep the diff focused). -- `detect-stack.sh` was not run as-is (its bare `find .` would recurse the - vendored tree over CIFS); stack facts were gathered via `git ls-files`. +- Confirm the exclusive-flash UX is acceptable (a scan sweep briefly blocks starting a flash, and vice-versa) -- chosen for hardware safety. +- Confirm "blank password keeps the saved one" is the desired credentials-dialog semantic. diff --git a/crates/alkane-gui/src/credentials.rs b/crates/alkane-gui/src/credentials.rs index d6f35814..ea07fbac 100644 --- a/crates/alkane-gui/src/credentials.rs +++ b/crates/alkane-gui/src/credentials.rs @@ -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 diff --git a/crates/alkane-gui/src/fixtures.rs b/crates/alkane-gui/src/fixtures.rs index 46ead4e5..b9d8af5a 100644 --- a/crates/alkane-gui/src/fixtures.rs +++ b/crates/alkane-gui/src/fixtures.rs @@ -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 { worker: "", mining: false, paused: true }, ]; let mut rows: Vec = 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 } diff --git a/crates/alkane-gui/src/model.rs b/crates/alkane-gui/src/model.rs index 89ca3e4c..cf1390a1 100644 --- a/crates/alkane-gui/src/model.rs +++ b/crates/alkane-gui/src/model.rs @@ -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 = (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("")); + } } diff --git a/crates/alkane-gui/src/scan.rs b/crates/alkane-gui/src/scan.rs index 4306cc9c..ad8105a1 100644 --- a/crates/alkane-gui/src/scan.rs +++ b/crates/alkane-gui/src/scan.rs @@ -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, 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) -> 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, 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 = (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); + } } diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index c6ea3ea9..5a476109 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -292,6 +292,12 @@ pub struct App { flash_confirm_dialog: Widget, flash_confirm_input: Widget, pending_flash: Option<(Vec, 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 "- / " + // 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 = 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, 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::>() + .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 = 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) { + // 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 = 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, &[])), ""); + } +}