From fbf44889eaf0309a377f381d80c28057e46288ca Mon Sep 17 00:00:00 2001 From: Noah <2+noah@noreply.gitea.bluefla.re> Date: Fri, 13 Nov 2026 10:56:04 -0600 Subject: [PATCH] feat(gui): post-install verify, flash-plan checklist; backend helpers Stock->alkane re-scan flicker: after a successful install the just-installed boards are held in a "verifying alkane..." state and a stock re-scan row is suppressed until the board answers as alkane, with a bounded give-up window. Fixes the board re-scanning as stock before finally showing alkane. Flash-plan checklist: picking a local .afw in the install dialog now detects the flash tier and shows a [x]/[ ] checklist of what it overwrites (U-Boot / Kernel / Userspace), read from the bundle manifest. Verified end-to-end under a virtual display: a zynq-7010 .afw shows tier 2, U-Boot preserved, kernel and userspace written. Backend helpers (alkane-artifacts, additive, unit-tested): - AfwManifest::flash_plan() -> FlashPlan { tier, writes_uboot, writes_kernel, writes_userspace }. - ReleaseSource::for_repo(owner, repo) and ReleaseInfo::compatible_boards / is_compatible_with, for the upcoming any-repo picker with board-compat detection. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i --- crates/alkane-artifacts/src/afw.rs | 148 ++++++++++++++++++++++++ crates/alkane-artifacts/src/fetch.rs | 128 +++++++++++++++++++- crates/alkane-gui/src/ui.rs | 167 +++++++++++++++++++++++++-- 3 files changed, 430 insertions(+), 13 deletions(-) diff --git a/crates/alkane-artifacts/src/afw.rs b/crates/alkane-artifacts/src/afw.rs index 1dda0c5d..6f8e824c 100644 --- a/crates/alkane-artifacts/src/afw.rs +++ b/crates/alkane-artifacts/src/afw.rs @@ -155,6 +155,54 @@ pub struct AfwManifest { pub notes: Option, } +/// What an `.afw` bundle overwrites on the target, derived from its manifest. +/// +/// Tiers mirror the flash tiers: 1 = update (userspace / HAL only, no kernel or +/// bootloader write), 2 = kernel (kernel, dtb and boot images; bootloader +/// preserved), 3 = bootloader (U-Boot/SPL is rewritten as well). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct FlashPlan { + pub tier: u8, + pub writes_uboot: bool, + pub writes_kernel: bool, + pub writes_userspace: bool, +} + +impl AfwManifest { + /// Compute the flash tier and the regions this bundle overwrites. Pure + /// computation over the parsed manifest; no device or file access. + /// + /// - `writes_uboot`: `bootloader_policy` is [`BootloaderPolicy::Include`] + /// (anything but `Preserve`), or an image with role `bootloader` exists. + /// - `writes_kernel`: an image with role `kernel`, `dtb` or `boot` exists. + /// - `writes_userspace`: an image with role `rootfs` exists. + /// - `tier`: 3 if `writes_uboot`, else 2 if `writes_kernel`, else 1. + pub fn flash_plan(&self) -> FlashPlan { + let has_role = |roles: &[&str]| { + self.images + .iter() + .any(|image| roles.contains(&image.role.as_str())) + }; + let writes_uboot = + self.bootloader_policy != BootloaderPolicy::Preserve || has_role(&["bootloader"]); + let writes_kernel = has_role(&["kernel", "dtb", "boot"]); + let writes_userspace = has_role(&["rootfs"]); + let tier = if writes_uboot { + 3 + } else if writes_kernel { + 2 + } else { + 1 + }; + FlashPlan { + tier, + writes_uboot, + writes_kernel, + writes_userspace, + } + } +} + #[derive(Clone, Debug, Eq, PartialEq)] pub struct AfwMember { pub name: String, @@ -1080,6 +1128,106 @@ mod tests { )); } + /// Build a parsed manifest with the given bootloader policy and one image + /// per listed role (payload bytes are irrelevant to `flash_plan`). + fn plan_manifest(policy: &str, roles: &[&str]) -> AfwManifest { + let mut value = manifest(&[0_u8; 4]); + value["bootloader_policy"] = json!(policy); + value["images"] = json!(roles + .iter() + .enumerate() + .map(|(i, role)| json!({ + "name": format!("img{i}"), "file": format!("payload/img{i}"), + "role": role, "format": "raw", "size": 4, "sha256": "0".repeat(64), + "partition": null, "install": false + })) + .collect::>()); + serde_json::from_value(value).unwrap() + } + + #[test] + fn flash_plan_tier2_preserve_kernel_and_rootfs() { + let plan = plan_manifest("preserve", &["kernel", "dtb", "rootfs"]).flash_plan(); + assert_eq!(plan.tier, 2); + assert!(plan.writes_kernel); + assert!(plan.writes_userspace); + assert!(!plan.writes_uboot); + } + + #[test] + fn flash_plan_tier3_include_with_bootloader_image() { + let plan = + plan_manifest("include", &["bootloader", "kernel", "dtb", "rootfs"]).flash_plan(); + assert_eq!(plan.tier, 3); + assert!(plan.writes_uboot); + assert!(plan.writes_kernel); + assert!(plan.writes_userspace); + } + + #[test] + fn flash_plan_tier3_from_bootloader_image_alone() { + // A bootloader image forces tier 3 even if the policy says preserve + // (verification rejects that combination, but the plan stays safe). + let plan = plan_manifest("preserve", &["bootloader"]).flash_plan(); + assert_eq!(plan.tier, 3); + assert!(plan.writes_uboot); + assert!(!plan.writes_kernel); + assert!(!plan.writes_userspace); + } + + #[test] + fn flash_plan_tier3_from_include_policy_alone() { + let plan = plan_manifest("include", &["rootfs"]).flash_plan(); + assert_eq!(plan.tier, 3); + assert!(plan.writes_uboot); + assert!(!plan.writes_kernel); + assert!(plan.writes_userspace); + } + + #[test] + fn flash_plan_tier1_rootfs_only() { + let plan = plan_manifest("preserve", &["rootfs"]).flash_plan(); + assert_eq!(plan.tier, 1); + assert!(plan.writes_userspace); + assert!(!plan.writes_kernel); + assert!(!plan.writes_uboot); + } + + #[test] + fn flash_plan_boot_role_counts_as_kernel() { + let plan = plan_manifest("preserve", &["boot"]).flash_plan(); + assert_eq!(plan.tier, 2); + assert!(plan.writes_kernel); + assert!(!plan.writes_userspace); + assert!(!plan.writes_uboot); + // The shared cv1835 fixture is a single "boot" FIT under preserve. + let fixture: AfwManifest = serde_json::from_value(manifest(&[0_u8; 4])).unwrap(); + assert_eq!(fixture.flash_plan().tier, 2); + } + + #[test] + fn flash_plan_component_only_is_tier1_with_no_regions() { + let plan = plan_manifest("preserve", &["component"]).flash_plan(); + assert_eq!(plan.tier, 1); + assert!(!plan.writes_uboot); + assert!(!plan.writes_kernel); + assert!(!plan.writes_userspace); + } + + #[test] + fn flash_plan_empty_images_preserve_is_tier1() { + let plan = plan_manifest("preserve", &[]).flash_plan(); + assert_eq!(plan.tier, 1); + assert!(!plan.writes_uboot && !plan.writes_kernel && !plan.writes_userspace); + } + + #[test] + fn flash_plan_tier3_dominates_kernel() { + let plan = plan_manifest("include", &["bootloader", "kernel"]).flash_plan(); + assert_eq!(plan.tier, 3); + assert!(plan.writes_uboot && plan.writes_kernel); + } + #[test] fn refuses_a_hash_mismatch() { let p1 = p1_image(P1); diff --git a/crates/alkane-artifacts/src/fetch.rs b/crates/alkane-artifacts/src/fetch.rs index aaf43149..3a8c4958 100644 --- a/crates/alkane-artifacts/src/fetch.rs +++ b/crates/alkane-artifacts/src/fetch.rs @@ -60,6 +60,14 @@ impl ReleaseSource { /// The alkane-os release source, honoring `ALKANE_RELEASE_BASE` and a token /// from `ALKANE_RELEASE_TOKEN` or `GITEA_TOKEN`. pub fn alkane_os() -> Self { + Self::for_repo("blueflare", "alkane-os") + } + + /// A release source for an arbitrary Gitea `owner`/`repo`. The base URL + /// (`ALKANE_RELEASE_BASE`, else the self-hosted Gitea) and the token + /// (`ALKANE_RELEASE_TOKEN`, else `GITEA_TOKEN`, else the build-time embedded + /// token) are resolved exactly as for `alkane_os`. + pub fn for_repo(owner: &str, repo: &str) -> Self { let base_url = std::env::var("ALKANE_RELEASE_BASE") .ok() .filter(|s| !s.is_empty()) @@ -71,8 +79,8 @@ impl ReleaseSource { .or_else(|| EMBEDDED_TOKEN.map(str::to_string).filter(|t| !t.is_empty())); Self { base_url, - owner: "blueflare".to_string(), - repo: "alkane-os".to_string(), + owner: owner.to_string(), + repo: repo.to_string(), token, } } @@ -223,6 +231,18 @@ pub fn fetch_latest_afw( Ok(dest) } +/// Board tokens recognised in `.afw` asset names (the `--` filename +/// segment). Used by `ReleaseInfo::compatible_boards`. +pub const KNOWN_BOARDS: &[&str] = &[ + "zynq-7010", + "am335x", + "cv1835", + "a113d", + "allwinner-h3", + "allwinner-h6", + "allwinner-h616", +]; + /// One `.afw` asset in a release. #[derive(Debug, Clone)] pub struct AfwAsset { @@ -249,6 +269,30 @@ impl ReleaseInfo { let needle = format!("-{board}-"); self.afw_assets.iter().find(|a| a.name.contains(&needle)) } + + /// The distinct board tokens (from `KNOWN_BOARDS`) this release carries an + /// `.afw` for, detected from the asset filenames (`--` segment, e.g. + /// `alkane-os-0.1.2-zynq-7010-armv7.afw` -> `zynq-7010`). Ordered by first + /// appearance across the assets; a release with no recognised board yields an + /// empty list. + pub fn compatible_boards(&self) -> Vec { + let mut boards: Vec = Vec::new(); + for asset in &self.afw_assets { + for board in KNOWN_BOARDS { + let needle = format!("-{board}-"); + if asset.name.contains(&needle) && !boards.iter().any(|b| b == board) { + boards.push((*board).to_string()); + } + } + } + boards + } + + /// Whether this release has an `.afw` for `board` (same match as + /// `asset_for_board`). + pub fn is_compatible_with(&self, board: &str) -> bool { + self.asset_for_board(board).is_some() + } } /// Parse a Gitea releases array (newest first) into `ReleaseInfo`s, keeping only @@ -401,4 +445,84 @@ mod tests { ); assert!(parsed[1].asset_for_board("zynq-7010").is_none()); } + + #[test] + fn for_repo_builds_the_api_url_for_a_custom_repo() { + std::env::remove_var("ALKANE_RELEASE_BASE"); + let src = ReleaseSource::for_repo("someorg", "some-firmware"); + assert_eq!(src.owner, "someorg"); + assert_eq!(src.repo, "some-firmware"); + assert_eq!( + src.api_list(), + "https://gitea.bluefla.re/api/v1/repos/someorg/some-firmware/releases?limit=50" + ); + // alkane_os() is for_repo("blueflare", "alkane-os"). + let os = ReleaseSource::alkane_os(); + assert_eq!( + (os.owner.as_str(), os.repo.as_str()), + ("blueflare", "alkane-os") + ); + } + + fn release_with(names: &[&str]) -> ReleaseInfo { + ReleaseInfo { + tag: "v0.1.2".into(), + name: String::new(), + prerelease: false, + draft: false, + published_at: String::new(), + afw_assets: names + .iter() + .map(|n| AfwAsset { + name: (*n).to_string(), + url: format!("https://example.invalid/{n}"), + }) + .collect(), + } + } + + #[test] + fn compatible_boards_extracts_board_tokens_from_asset_names() { + let single = release_with(&["alkane-os-0.1.2-zynq-7010-armv7.afw"]); + assert_eq!(single.compatible_boards(), vec!["zynq-7010"]); + + // Multi-board release: distinct boards in first-appearance order, + // duplicates (a second arch build of one board) collapse. + let multi = release_with(&[ + "alkane-os-0.1.2-am335x-armv7.afw", + "alkane-os-0.1.2-zynq-7010-armv7.afw", + "alkane-os-0.1.2-allwinner-h616-aarch64.afw", + "alkane-os-0.1.2-am335x-arm.afw", + "alkane-os-0.1.2-cv1835-riscv64.afw", + ]); + assert_eq!( + multi.compatible_boards(), + vec!["am335x", "zynq-7010", "allwinner-h616", "cv1835"] + ); + + // allwinner-h6 must not match an allwinner-h616 asset (and vice versa). + let h616 = release_with(&["alkane-os-0.1.2-allwinner-h616-aarch64.afw"]); + assert_eq!(h616.compatible_boards(), vec!["allwinner-h616"]); + let h6 = release_with(&["alkane-os-0.1.2-allwinner-h6-aarch64.afw"]); + assert_eq!(h6.compatible_boards(), vec!["allwinner-h6"]); + + // No .afw assets, or an unrecognised board, yields nothing. + assert!(release_with(&[]).compatible_boards().is_empty()); + assert!(release_with(&["alkane-os-0.1.2-mystery-board-arm.afw"]) + .compatible_boards() + .is_empty()); + } + + #[test] + fn is_compatible_with_matches_asset_for_board() { + let rel = release_with(&[ + "alkane-os-0.1.2-zynq-7010-armv7.afw", + "alkane-os-0.1.2-a113d-aarch64.afw", + ]); + assert!(rel.is_compatible_with("zynq-7010")); + assert!(rel.is_compatible_with("a113d")); + assert!(!rel.is_compatible_with("am335x")); + assert!(!rel.is_compatible_with("allwinner-h6")); + assert!(!release_with(&[]).is_compatible_with("zynq-7010")); + } } diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index 020c8217..8924eb9e 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -512,6 +512,38 @@ fn encode_status_icon(pal: &Palette, status: &str) -> String { encode_segments(&[(Some(status_kind_color(pal, status)), shape.to_string())]) } +/// A read-only flash-plan summary for a local `.afw`: its tier and which regions +/// it overwrites (U-Boot / Kernel / Userspace), from the bundle's own manifest. +/// Shown in the install dialog when a file is picked so the operator sees exactly +/// what the flash touches before starting. +fn afw_plan_text(path: &str) -> String { + use alkane_artifacts::afw::{verify_afw, VerifyOptions}; + let opts = VerifyOptions { + allow_unsigned: true, + expect_board: None, + }; + match verify_afw(std::path::Path::new(path), &opts) { + Ok(v) => { + let p = v.manifest.flash_plan(); + let mark = |b: bool| if b { "[x]" } else { "[ ]" }; + format!( + "Flash plan: tier {} (board {}). Overwrites:\n {} U-Boot{}\n {} Kernel\n {} Userspace (rootfs)", + p.tier, + v.manifest.board, + mark(p.writes_uboot), + if p.writes_uboot { + "" + } else { + " -- preserved" + }, + mark(p.writes_kernel), + mark(p.writes_userspace), + ) + } + Err(e) => format!("Could not read flash plan from this file: {e}"), + } +} + /// The colour a component-health state renders in (round 13 #3): grey = /// unreachable, red = detected but down, yellow = sub-optimal, green = healthy. fn health_color(pal: &Palette, h: crate::model::CompHealth) -> (u8, u8, u8) { @@ -842,6 +874,16 @@ pub struct App { // operation running (refresh, config action, light, firmware, restore, access // check), its Health cell shows this text instead of the component icons. op_status: std::collections::HashMap, + // IPs of the install currently in flight, so a successful install can arm a + // post-install alkane verification for exactly those boards. + install_targets: HashSet, + // After a successful install a board reboots into alkane; the next scan can + // still catch it mid-reboot answering as stock. Each awaited IP maps to the + // number of scan rounds left to confirm alkane before giving up; while an IP + // waits, a non-alkane row for it is suppressed so the table never flickers to + // stock (the operator sees "verifying alkane..." instead). Issue: post-install + // the row re-scanned as stock before finally showing alkane. + installed_awaiting: HashMap, // A confirmation dialog for disruptive actions, plus its pending target. confirm_dialog: Widget, pending_confirm: Option<(Vec, scan::ConfigAction)>, @@ -913,6 +955,9 @@ pub struct App { // release when set; the read-only label beside the button shows it. install_local_path: Option, install_local_label: Widget, + // A read-only flash-plan checklist (tier + which regions are overwritten), + // filled from a picked local .afw's manifest. + install_plan_label: Widget, uninstall_dialog: Widget, uninstall_pass_input: Widget, uninstall_firmware_input: Widget, @@ -1263,6 +1308,8 @@ pub fn build(frame: Widget) -> App { action_targets: Vec::new(), pending_password_update: None, op_status: std::collections::HashMap::new(), + install_targets: HashSet::new(), + installed_awaiting: HashMap::new(), confirm_dialog: frame, pending_confirm: None, flash_confirm_dialog: frame, @@ -1301,6 +1348,7 @@ pub fn build(frame: Widget) -> App { install_board: stock_ops::DEFAULT_BOARD.to_string(), install_local_path: None, install_local_label: frame, + install_plan_label: frame, uninstall_dialog: frame, uninstall_pass_input: frame, uninstall_firmware_input: frame, @@ -2755,6 +2803,15 @@ impl App { 12, ); + // Flash-plan checklist: detects the tier and which regions a picked local + // .afw overwrites (U-Boot / Kernel / Userspace). + let plan = Widget::static_text( + dlg, + "Flash plan: pick a local .afw above to see its tier and what it overwrites.", + ); + root.add(plan, 0, sf::BORDER_ALL, 12); + self.install_plan_label = plan; + root.add( Widget::static_text(dlg, "Board password (optional):"), 0, @@ -2878,6 +2935,9 @@ impl App { ips.len() )); self.set_op_status(&ips, "installing..."); + // Remember these targets so a successful install arms the post-install + // alkane verification (prevents the stock->alkane re-scan flicker). + self.install_targets = ips.iter().cloned().collect(); self.stock_op = Some(stock_ops::start_install( ips, board, @@ -3019,18 +3079,25 @@ impl App { let mut oks = 0usize; let mut fails: Vec = Vec::new(); let mut op_clear: Vec = Vec::new(); + // Successfully-installed IPs whose boards should now come up as alkane. + let mut verify_ips: Vec = Vec::new(); let mut progress: Option = None; loop { match h.rx.try_recv() { Ok(StockMsg::Started) => {} Ok(StockMsg::Progress(s)) => progress = Some(s), Ok(StockMsg::Result { ip, ok, detail }) => { - if !ip.is_empty() { - op_clear.push(ip.clone()); - } if ok { oks += 1; + if !ip.is_empty() && self.install_targets.contains(&ip) { + verify_ips.push(ip.clone()); + } else if !ip.is_empty() { + op_clear.push(ip.clone()); + } } else { + if !ip.is_empty() { + op_clear.push(ip.clone()); + } fails.push(format!("{ip}: {detail}")); } } @@ -3048,17 +3115,31 @@ impl App { for ip in &op_clear { self.op_status.remove(ip); } + // Arm post-install alkane verification for the boards that installed OK: + // keep a "verifying" status on them and suppress stock re-scan rows until + // they answer as alkane (prevents the stock->alkane flicker). + for ip in &verify_ips { + self.installed_awaiting.insert(ip.clone(), 8); + self.op_status + .insert(ip.clone(), "installed; verifying alkane...".into()); + } if let Some(p) = progress { wx_rs::set_status_text(&p); } if done { self.stock_op = None; + self.install_targets.clear(); self.op_status .retain(|_, v| v != "installing..." && v != "restoring..."); } - if !op_clear.is_empty() || done { + if !op_clear.is_empty() || !verify_ips.is_empty() || done { self.fill_rows(); } + // Kick a dedicated re-probe of the just-installed boards; the row + // suppression below only accepts them once they answer as alkane. + if done && !verify_ips.is_empty() && self.refresh.is_none() && !self.scanning { + self.start_refresh(verify_ips.clone()); + } if done { if !fails.is_empty() { // Surface the actual reason, not just a count (issue #38: a bare @@ -4143,9 +4224,19 @@ impl App { status = Some(format!("refreshing 0/{total} miner(s)...")); } Ok(scan::RefreshMsg::Row(row)) => { - op_clear.push(row.ip.clone()); - row.upsert_into(&mut self.rows); - changed = true; + if self.installed_awaiting.contains_key(&row.ip) { + // Accept a just-installed board only once it is alkane. + if crate::alkane_detect::is_alkane(&row) { + self.installed_awaiting.remove(&row.ip); + op_clear.push(row.ip.clone()); + row.upsert_into(&mut self.rows); + changed = true; + } + } else { + op_clear.push(row.ip.clone()); + row.upsert_into(&mut self.rows); + changed = true; + } } Ok(scan::RefreshMsg::Failed { ip, detail }) => { op_clear.push(ip.clone()); @@ -4175,6 +4266,7 @@ impl App { self.refresh = None; // Any stragglers still marked "refreshing..." revert to icons. self.op_status.retain(|_, v| v != "refreshing..."); + Self::tick_installed_awaiting(&mut self.installed_awaiting, &mut self.op_status); } // Refresh progress stays in the Health column, not the scan line (#8). let _ = status; @@ -4183,6 +4275,34 @@ impl App { } } + /// Count down each board awaiting post-install alkane confirmation. When a + /// board's rounds run out, stop suppressing its row and clear the status: the + /// install finished but the board never came up answering as alkane. Takes the + /// two maps directly (not `&mut self`) so it can run while a scan/refresh + /// handle still borrows another field of `self`. + fn tick_installed_awaiting( + awaiting: &mut HashMap, + op_status: &mut HashMap, + ) { + if awaiting.is_empty() { + return; + } + let mut expired = Vec::new(); + for (ip, left) in awaiting.iter_mut() { + *left = left.saturating_sub(1); + if *left == 0 { + expired.push(ip.clone()); + } + } + for ip in expired { + awaiting.remove(&ip); + op_status.remove(&ip); + crate::logs::log(format!( + "{ip}: installed, but did not answer as alkane within the verify window" + )); + } + } + pub fn drain_scan(&mut self) { let Some(handle) = &self.scan else { return }; let mut changed = false; @@ -4221,8 +4341,19 @@ impl App { Ok(ScanMsg::Row(row)) => { // Ignore stray rows outside the current target set. if self.target_ips.is_empty() || self.target_ips.contains(&row.ip) { - row.upsert_into(&mut self.rows); - changed = true; + if self.installed_awaiting.contains_key(&row.ip) { + // Just installed: accept the row only once it answers as + // alkane; a stock mid-reboot answer is suppressed. + if crate::alkane_detect::is_alkane(&row) { + self.installed_awaiting.remove(&row.ip); + self.op_status.remove(&row.ip); + row.upsert_into(&mut self.rows); + changed = true; + } + } else { + row.upsert_into(&mut self.rows); + changed = true; + } } } Ok(ScanMsg::Done(_s)) => { @@ -4231,8 +4362,17 @@ impl App { self.progress.show(false); self.table_parent.layout(); crate::logs::log(format!("scan complete: {} miner(s) found", self.rows.len())); - // Arm the next automatic scan (if the loop is running). - self.countdown = if self.playing { self.auto_secs } else { 0 }; + Self::tick_installed_awaiting(&mut self.installed_awaiting, &mut self.op_status); + // Arm the next automatic scan (if the loop is running). While + // boards are still being verified as alkane, re-probe soon + // instead of waiting the full interval. + self.countdown = if !self.installed_awaiting.is_empty() && self.playing { + self.auto_secs.min(12) + } else if self.playing { + self.auto_secs + } else { + 0 + }; } Ok(ScanMsg::Failed(e)) => { self.scanning = false; @@ -5837,10 +5977,15 @@ impl App { .unwrap_or_else(|| path.clone()); self.install_local_label .set_label(&format!("Using local file: {name}")); + self.install_plan_label.set_label(&afw_plan_text(&path)); self.install_local_path = Some(path); + self.install_dialog.layout(); } else { self.install_local_label .set_label("(none; using the selected release above)"); + self.install_plan_label.set_label( + "Flash plan: pick a local .afw above to see its tier and what it overwrites.", + ); self.install_local_path = None; } }