Files
alkane-os/src/main.rs
T
noahandClaude Opus 4.8 802f254e9a web: make the flare-ui console fully functional with a live sim backend and operator control
The on-box UI shipped as a half-migrated shell: the schema settings rendered
with no submit form, the flare-ui nav tabs shadowed the legacy pages with empty
cards, and --serve stood the UI up with no runtime so every value read "not
identified" and nothing could be controlled. This makes it work end to end,
driven by flare-ui, and fully exercisable on a workstation with no hashboard.

Live backend (alkane-os --serve-sim): run the reference HAL in-process on a
private unix socket, boot the runtime against it, and run a control loop that
applies the operator intent every period and publishes a live snapshot. On this
workstation the console shows the chain frequency climbing toward the target and
the controls taking effect; --serve keeps serving the same console with no
backend for a board whose HAL is not written yet.

Operator control channel (control.rs): the one mutable path into the runtime -
a mode/target and a run switch, plus a per-process CSRF token. ControlMode maps
one-to-one onto the real TuningTarget variants (power / ambient / hashrate /
max-fan), so the UI never offers a behaviour the controller lacks. runtime.rs /
tuning.rs gain set_target/target so a mode change applies in place, keeping the
PID state instead of snapping to the envelope floor.

flare-ui console (console.rs): every nav tab rendered from flare-ui primitives
(shell, render::card, readings, actions, components) with live data - overview
hero + state, mining hashboards/power/fans, a Control page with Start/Stop
action buttons, a working Tuning form that posts to /settings, and the system/
security/logs/files/terminal pages wired to their existing data. The tuning
form submit persists the setting AND switches the live target; Start/Stop and
the form are CSRF-checked. /api/control exposes the operator state as JSON, the
interface of record behind the page.

Wiring: app::start and web::serve_listener/handle/route carry Arc<Control>;
main.rs gains --serve-sim and threads a Control through the existing serve/boot
paths. README updated: the "no web frontend" note is no longer true.

Verified on this workstation: --serve-sim boots (s19jpro-bm1362-pic, 3 chains),
frequency converges toward power:2400, and the flare-ui pages drive stop ->
switch to ambient:18000 -> start, with a stale CSRF token rejected (403).
Tests: 183 lib + integration green; clippy -D warnings clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdKQBPjAXpCwmigUov5eQk
2026-11-10 20:14:10 -06:00

579 lines
21 KiB
Rust

// SPDX-License-Identifier: MIT
use alkane_os::app;
use alkane_os::control::Control;
use alkane_os::detect::{
ChipModel as DetectedChip, DetectionBackend, EepromState, Envelope, ProbeBudget, ProbeOutcome,
PsuCapability, SensorTopology,
};
use alkane_os::hal_wire::HalClient;
use alkane_os::management::MiningStatus;
use alkane_os::miner::{Bm1366Miner, ChipModel};
use alkane_os::runtime::{Tick, TickOutcome};
use alkane_os::stratum_client::{PoolConnection, PoolEvent};
use alkane_os::target_matrix;
use alkane_os::tuning::{PidConfig, TuningTarget};
use alkane_os::HardwareBackend;
use std::error::Error;
use std::io;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
fn sim_mine(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
let socket = args.next().ok_or("missing HAL socket")?;
let address: SocketAddr = args.next().ok_or("missing pool address")?.parse()?;
let worker = args.next().ok_or("missing pool worker")?;
let chip = match args.next().as_deref() {
Some("BM1362") => ChipModel::Bm1362,
Some("BM1366") => ChipModel::Bm1366,
_ => return Err("select BM1362 or BM1366".into()),
};
let max_accepts: Option<u64> = args.next().map(|value| value.parse()).transpose()?;
if args.next().is_some() || worker.is_empty() || max_accepts == Some(0) {
return Err("invalid simulator mining arguments".into());
}
let password = std::env::var("ALKANE_POOL_PASSWORD")
.map_err(|_| "set ALKANE_POOL_PASSWORD in the environment")?;
let status = Arc::new(MiningStatus::new());
let api = std::env::var("ALKANE_API_LISTEN")
.ok()
.map(|bind| bind.parse())
.transpose()?;
let web = web_listen()?;
let control = Arc::new(Control::default());
let servers = app::start(Arc::clone(&status), api, web, control)?;
let (api_address, web_address) = servers.addresses();
if let Some(address) = api_address {
println!("management API on {address}");
}
if let Some(address) = web_address {
println!("web UI on http://{address}/");
}
// Connect to the pool before enabling power. The SDK HAL server owns the
// power lease and cuts power if this process stalls or disconnects.
let mut pool = PoolConnection::connect(
address,
concat!("alkane-os/", env!("CARGO_PKG_VERSION")),
&worker,
&password,
Duration::from_secs(2),
Duration::from_secs(5),
)
.map_err(|error| io::Error::other(format!("pool handshake: {error:?}")))?;
let mut backend = HalClient::connect(socket)?;
let mut miner = Bm1366Miner::new_for_chip(&mut backend, chip, 0, 0, 0, 100, 80_000)
.ok_or("invalid simulator safety configuration")?;
miner.start()?;
status.set_running(true);
let mut accepted = 0_u64;
loop {
let (event, reports) = pool
.cycle(&mut miner)
.map_err(|error| io::Error::other(format!("mining cycle: {error:?}")))?;
match event {
PoolEvent::ShareAccepted(_) => {
accepted += 1;
status.share_accepted();
if max_accepts == Some(accepted) {
miner.stop()?;
status.set_running(false);
println!("simulator shares accepted: {accepted}");
return Ok(());
}
}
PoolEvent::ShareRejected(id) => {
status.share_rejected();
eprintln!("pool rejected share request {id}");
}
_ => {}
}
if matches!(event, PoolEvent::Idle) && reports.is_empty() {
std::thread::sleep(Duration::from_millis(10));
}
}
}
/// A backend that answers without hardware, so the boot path can be exercised on any machine.
struct SelfCheckBackend;
impl DetectionBackend for SelfCheckBackend {
type Error = ();
fn probe(&mut self, _chain: u8, _attempt: u8) -> Result<ProbeOutcome, ()> {
Ok(ProbeOutcome::Identified {
chip: DetectedChip::Bm1362,
chips: 126,
})
}
fn eeprom(&mut self, _chain: u8) -> Result<EepromState, ()> {
Ok(EepromState::Absent)
}
fn identify_psu(&mut self) -> Result<Option<PsuCapability>, ()> {
Ok(Some(PsuCapability {
name: "APW12".into(),
envelope: Envelope {
v_min_mv: 1200,
v_max_mv: 1600,
f_min_mhz: 0,
f_max_mhz: 1000,
},
max_dc_watts: 3600,
}))
}
}
/// Run detection, the runtime loop and the API document against the self-check backend.
///
/// This is the smoke test an image can run on a bench machine before any hashboard is attached:
/// it proves the profile database parses, detection produces a plan, the tuner moves within the
/// envelope and the published document is well formed.
fn self_check() -> Result<(), Box<dyn Error>> {
let status = MiningStatus::new();
let config = app::BootConfig {
profile_db_json: include_str!("../profiles.example.json").to_owned(),
chain_ports: vec![0, 1, 2],
sensor: SensorTopology::Pic,
budget: ProbeBudget::default(),
fan_zones: Vec::new(),
target: TuningTarget::PowerW(2_400.0),
pid: PidConfig::default(),
ceiling_mc: 95_000,
fault_policy: Default::default(),
};
let mut backend = SelfCheckBackend;
let mut runtime = app::boot(&mut backend, &config, &status)?;
let start = runtime.operating_point().frequency_mhz;
for _ in 0..20 {
let power = 4.0 * f32::from(runtime.operating_point().frequency_mhz);
runtime.tick(&Tick {
power_w: Some(power),
hashrate_ths: None,
hottest_mc: Some(70_000),
ambient_mc: None,
dt_s: 1.0,
});
}
let end = runtime.operating_point().frequency_mhz;
if end <= start {
return Err("self-check: frequency did not move toward the target".into());
}
if runtime.active_chains().len() != 3 {
return Err("self-check: detection did not expose three chains".into());
}
status.set_hardware(app::snapshot(&runtime, &app::target_label(&config.target)));
let document = status.hardware_document();
if document["available"] != true {
return Err("self-check: hardware document is not available".into());
}
println!("{}", serde_json::to_string_pretty(&document)?);
Ok(())
}
fn parse_target(text: &str) -> Result<TuningTarget, Box<dyn Error>> {
let (kind, value) = text
.split_once(':')
.ok_or("target must look like power:2400")?;
let value: f32 = value.parse()?;
Ok(match kind {
"power" => TuningTarget::PowerW(value),
"hashrate" => TuningTarget::HashrateThs(value),
"ambient" => TuningTarget::AmbientC {
margin_mc: value as i32,
},
"fan" => TuningTarget::MaxFan {
max_pwm: value as u8,
},
_ => return Err("target must be power, hashrate, ambient or fan".into()),
})
}
/// Boot a real board through the HAL socket, then run a bounded tuning loop.
fn boot_hal(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
let socket = args.next().ok_or("missing HAL socket")?;
let profiles = args.next().ok_or("missing profile database path")?;
let target = parse_target(&args.next().ok_or("missing target")?)?;
let sensor = match args.next().as_deref() {
Some("nopic") => SensorTopology::NoPic,
Some("pic") | None => SensorTopology::Pic,
Some(_) => return Err("sensor must be pic or nopic".into()),
};
let ticks: usize = args
.next()
.map(|value| value.parse())
.transpose()?
.unwrap_or(30);
let profile_db_json = std::fs::read_to_string(&profiles)?;
let status = Arc::new(MiningStatus::new());
let api = std::env::var("ALKANE_API_LISTEN")
.ok()
.map(|bind| bind.parse())
.transpose()?;
let web = web_listen()?;
let control = Arc::new(Control::default());
let servers = app::start(Arc::clone(&status), api, web, control)?;
let config = app::BootConfig {
profile_db_json,
chain_ports: vec![0, 1, 2],
sensor,
budget: ProbeBudget::default(),
fan_zones: Vec::new(),
target,
pid: PidConfig::default(),
ceiling_mc: 95_000,
fault_policy: Default::default(),
};
let map_path = std::path::PathBuf::from(
std::env::var("ALKANE_FANMAP").unwrap_or_else(|_| "/var/lib/alkane/fanmap.json".into()),
);
// Fan mapping is opt-in: it perturbs the machine and takes minutes, so a plain boot skips it.
let fans: u8 = std::env::var("ALKANE_FAN_FANS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0);
let zones: u8 = std::env::var("ALKANE_FAN_ZONES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0);
let settings = app::HalBoot {
config: &config,
sweep: alkane_os::fanmap::SweepConfig {
fans,
zones,
low_pwm: 40,
high_pwm: 100,
repeats: 1,
settle_ms: std::env::var("ALKANE_FAN_SETTLE_MS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(20_000),
},
thresholds: Default::default(),
map_path: &map_path,
};
let (mut runtime, _map) =
app::boot_from_hal(std::path::Path::new(&socket), &settings, &status)?;
println!(
"detected {} with {} active chains",
runtime.plan().profile,
runtime.active_chains().len()
);
let mut client = HalClient::connect(std::path::Path::new(&socket))?;
let label = app::target_label(&config.target);
for _ in 0..ticks {
let hottest = client.read_temperature_mc(0).ok();
let power_w = client.read_power_w().ok().map(f32::from);
let outcome = runtime.tick(&Tick {
power_w,
hashrate_ths: None,
hottest_mc: hottest,
ambient_mc: None,
dt_s: 1.0,
});
if let TickOutcome::Run(command) = outcome {
for chain in runtime.active_chains() {
client.set_chain_frequency(chain, command.frequency_mhz)?;
}
if let Some(pwm) = command.fan_pwm {
client.set_fan_target(0, pwm)?;
}
}
// Publish every period: a client watching the API must see the live operating point,
// not the boot-time snapshot.
status.set_hardware(app::snapshot(&runtime, &label));
if let Some(reason) = runtime.stop_reason() {
println!("stopped: {reason:?}");
break;
}
std::thread::sleep(Duration::from_millis(50));
}
status.set_hardware(app::snapshot(&runtime, &app::target_label(&config.target)));
println!(
"{}",
serde_json::to_string_pretty(&status.hardware_document())?
);
let _ = servers;
Ok(())
}
/// Where the UI listens. The miner serves it on port 80 of its own address;
/// if that is not permitted (a non-root development run), fall back to 8080
/// rather than refusing to start.
fn web_listen() -> Result<Option<std::net::SocketAddr>, Box<dyn std::error::Error>> {
if let Ok(bind) = std::env::var("ALKANE_WEB_LISTEN") {
return Ok(Some(bind.parse()?));
}
let port = if std::net::TcpListener::bind("0.0.0.0:80").is_ok() {
80
} else {
8080
};
Ok(Some(std::net::SocketAddr::from(([0, 0, 0, 0], port))))
}
/// Serve the full UI and API driven by the reference simulator HAL, in-process.
///
/// This is the "fully functional on a workstation" path: no hashboard is needed.
/// A reference HAL runs on a private unix socket, the runtime boots against it,
/// and a control loop applies the operator intent (mode/target, start/stop) from
/// the web UI every period, publishing a live snapshot. Open the printed URL and
/// the console shows frequency moving toward the target and the controls working.
fn serve_sim() -> Result<(), Box<dyn std::error::Error>> {
use alkane_os::hal_sim::{serve as sim_serve, SimConfig};
let socket = std::env::temp_dir().join(format!("alkane-serve-sim-{}.sock", std::process::id()));
let _ = std::fs::remove_file(&socket);
{
let socket = socket.clone();
std::thread::spawn(move || {
if let Err(error) = sim_serve(&socket, SimConfig::default()) {
eprintln!("reference HAL stopped: {error}");
}
});
}
// Wait for the HAL to bind its socket before the first connection.
for _ in 0..500 {
if socket.exists() {
break;
}
std::thread::sleep(Duration::from_millis(10));
}
let status = Arc::new(MiningStatus::new());
let initial = TuningTarget::PowerW(2_400.0);
// Start hashing immediately so the page is live; the operator can stop it.
let control = Arc::new(Control::new(initial, true));
let config = app::BootConfig {
profile_db_json: include_str!("../profiles.example.json").to_owned(),
chain_ports: vec![0, 1, 2],
sensor: SensorTopology::Pic,
budget: ProbeBudget::default(),
fan_zones: Vec::new(),
target: initial,
pid: PidConfig::default(),
ceiling_mc: 95_000,
fault_policy: Default::default(),
};
let map_path =
std::env::temp_dir().join(format!("alkane-serve-sim-{}.map.json", std::process::id()));
let settings = app::HalBoot {
config: &config,
sweep: alkane_os::fanmap::SweepConfig {
fans: 0,
zones: 0,
low_pwm: 40,
high_pwm: 100,
repeats: 1,
settle_ms: 0,
},
thresholds: Default::default(),
map_path: &map_path,
};
let (mut runtime, _map) = app::boot_from_hal(&socket, &settings, &status)?;
println!(
"detected {} with {} active chains",
runtime.plan().profile,
runtime.active_chains().len()
);
let api = std::env::var("ALKANE_API_LISTEN")
.ok()
.map(|bind| bind.parse())
.transpose()?
.or(Some("127.0.0.1:4028".parse()?));
let servers = app::start(Arc::clone(&status), api, web_listen()?, Arc::clone(&control))?;
let (api_address, web_address) = servers.addresses();
if let Some(address) = api_address {
println!("management API on {address}");
}
if let Some(address) = web_address {
println!("web UI on http://{address}/");
}
// The control loop: its own HAL connection, applying operator intent.
let mut client = HalClient::connect(&socket)?;
let mut last_generation = 0_u64;
loop {
let generation = control.generation();
if generation != last_generation {
runtime.set_target(control.target());
last_generation = generation;
}
let label = app::target_label(&control.target());
if control.running() && runtime.stop_reason().is_none() {
status.set_running(true);
let hottest = client.read_temperature_mc(0).ok();
let power_w = client.read_power_w().ok().map(f32::from);
let outcome = runtime.tick(&Tick {
power_w,
hashrate_ths: None,
hottest_mc: hottest,
// The bench enclosure has no ambient sensor; assume 25 C so the
// ambient-target mode has something to track.
ambient_mc: Some(25_000),
dt_s: 1.0,
});
if let TickOutcome::Run(command) = outcome {
for chain in runtime.active_chains() {
let _ = client.set_chain_frequency(chain, command.frequency_mhz);
}
if let Some(pwm) = command.fan_pwm {
let _ = client.set_fan_target(0, pwm);
}
}
} else {
status.set_running(false);
}
status.set_hardware(app::snapshot(&runtime, &label));
std::thread::sleep(Duration::from_millis(250));
}
}
/// Serve the UI and the API without a mining backend. A board whose HAL
/// backend is not written yet still has to be reachable and observable; every
/// page says "not identified" rather than claiming hardware it cannot see.
fn serve_only() -> Result<(), Box<dyn std::error::Error>> {
let status = Arc::new(MiningStatus::new());
let api = std::env::var("ALKANE_API_LISTEN")
.ok()
.map(|bind| bind.parse())
.transpose()?;
let api = api.or(Some("0.0.0.0:4028".parse()?));
let control = Arc::new(Control::default());
let servers = app::start(Arc::clone(&status), api, web_listen()?, control)?;
let (api_address, web_address) = servers.addresses();
if let Some(address) = api_address {
println!("management API on {address}");
}
if let Some(address) = web_address {
println!("web UI on http://{address}");
}
loop {
std::thread::sleep(Duration::from_secs(3600));
}
}
fn main() {
let mut args = std::env::args().skip(1);
match args.next().as_deref() {
Some("--list-targets") => {
println!("control_board,hash_chip,algorithm");
for target in target_matrix() {
println!(
"{},{},{:?}",
target.control.id, target.chip.id, target.chip.algorithm
);
}
}
Some("--version") => println!("alkane-os {}", env!("CARGO_PKG_VERSION")),
Some("--serve") => {
if let Err(error) = serve_only() {
eprintln!("serve failed: {error}");
std::process::exit(1);
}
}
Some("--serve-sim") => {
if let Err(error) = serve_sim() {
eprintln!("serve-sim failed: {error}");
std::process::exit(1);
}
}
Some("--boot") => {
if let Err(error) = boot_hal(args) {
eprintln!("boot failed: {error}");
std::process::exit(1);
}
}
Some("--sim-hal") => {
let socket = match args.next() {
Some(path) => path,
None => {
eprintln!("usage: alkane-os --sim-hal SOCKET");
std::process::exit(2);
}
};
if let Err(error) = alkane_os::hal_sim::serve(
std::path::Path::new(&socket),
alkane_os::hal_sim::SimConfig::default(),
) {
eprintln!("reference HAL stopped: {error}");
std::process::exit(1);
}
}
Some("--check-profiles") => {
let path = match args.next() {
Some(path) => path,
None => {
eprintln!("usage: alkane-os --check-profiles PATH");
std::process::exit(2);
}
};
let text = match std::fs::read_to_string(&path) {
Ok(text) => text,
Err(error) => {
eprintln!("cannot read {path}: {error}");
std::process::exit(1);
}
};
match alkane_os::profiles::ProfileDb::from_json(&text) {
Ok(db) => {
println!("{} profiles, schema 1, validated", db.len());
}
Err(error) => {
eprintln!("profile database rejected: {error:?}");
std::process::exit(1);
}
}
}
Some("--check-hal") => {
let socket = match args.next() {
Some(path) => path,
None => {
eprintln!("usage: alkane-os --check-hal SOCKET");
std::process::exit(2);
}
};
let checks = alkane_os::hal_conformance::run(std::path::Path::new(&socket));
let mut failed = 0;
for check in &checks {
println!(
"{:<28} {:<4} {}",
check.name,
if check.passed { "PASS" } else { "FAIL" },
check.detail
);
if !check.passed {
failed += 1;
}
}
if failed > 0 {
std::process::exit(1);
}
}
Some("--self-check") => {
if let Err(error) = self_check() {
eprintln!("self-check failed: {error}");
std::process::exit(1);
}
}
Some("--mine-simulator") => {
if let Err(error) = sim_mine(args) {
eprintln!("simulator mining failed: {error}");
std::process::exit(1);
}
}
_ => {
eprintln!("usage: alkane-os --list-targets | --version | --self-check | --serve | --serve-sim | --boot HAL_SOCKET PROFILES.json TARGET [PIC|NOPIC] [TICKS] | --sim-hal SOCKET | --check-hal SOCKET | --check-profiles PATH | --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER BM1362|BM1366 [MAX_ACCEPTS]");
eprintln!(
"env: ALKANE_API_LISTEN=ADDR ALKANE_WEB_LISTEN=ADDR ALKANE_POOL_PASSWORD=..."
);
std::process::exit(2);
}
}
}