Make the main dashboard an editable deck, like wardenOS's dashboard, and split the remaining settings into their own tabs. - console.rs: dashboard/overview is now an editable deck - a .wdash-style document stored on the box (bus dashboard/* verbs behind /api/dashboard) whose blocks draw live values from the open miner-state API. A self-contained island (CSS + JS in the flare-ui shell) renders the grid and, in edit mode, adds, removes, reorders and saves blocks; Reset restores the template. Drivers, Services and Monitor are now distinct settings tabs rather than bundled into System/Security. - schema/alkane-bb.json: add the settings/drivers, settings/services and settings/monitor menus so the nav shows them (settings now has 11 tabs). - service.rs: the deck directory falls back to a writable path off the miner so the editable dashboard saves in a dev run too. Verified on --serve-sim: the dashboard renders with an Edit toolbar, a deck saves and reloads from /api/dashboard and Reset restores the 5-block template, and every settings tab (system/tuning/pools/network/drivers/security/services/ monitor/logs/files/terminal) answers. 203 tests pass, clippy -D warnings clean, no emojis. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BdKQBPjAXpCwmigUov5eQk
368 lines
13 KiB
Rust
368 lines
13 KiB
Rust
// SPDX-License-Identifier: MIT
|
|
//! Schema-driven dashboard for the on-box UI.
|
|
//!
|
|
//! The sidebar, the tab strip and every settings control come from
|
|
//! `schema/alkane-bb.json` through `flare-ui` and `wschema`; this module is the
|
|
//! host boundary the crates expect: it owns the stored rows, applies a
|
|
//! submitted form only after `wschema` validates it, and keeps the JSON API as
|
|
//! the interface of record.
|
|
//!
|
|
//! Everything here is pure except `load` and `save`, which touch one file.
|
|
|
|
use std::collections::BTreeMap;
|
|
use std::fs;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use maud::Markup;
|
|
use serde_json::{Map, Value};
|
|
|
|
use flare_ui::assets::PageAssets;
|
|
use flare_ui::nav::{self, AllowAll, AppSet, CapSet, NavContext, VisibleNav};
|
|
use flare_ui::url::Routes;
|
|
use flare_ui::render::{self, View};
|
|
use flare_ui::shell::{self, Active};
|
|
use flare_ui::tokens;
|
|
use wschema::effective::{self, Effective};
|
|
use wschema::model::{Document, Surface};
|
|
use wschema::validate::{Op, Rows};
|
|
|
|
/// The schema document is the single source of the UI.
|
|
pub const SCHEMA: &str = include_str!("../schema/alkane-bb.json");
|
|
|
|
/// Capabilities this board reports, which decide what the sidebar shows.
|
|
pub fn board_caps() -> CapSet {
|
|
CapSet::new(["hashboard", "psu", "fan-map", "cgminer-api"])
|
|
}
|
|
|
|
/// The dashboard: an effective schema plus the stored rows.
|
|
pub struct Dashboard {
|
|
effective: Result<Effective, String>,
|
|
rows: Rows,
|
|
path: PathBuf,
|
|
}
|
|
|
|
impl Dashboard {
|
|
/// Load the schema and the stored settings, defaulting absent rows to the
|
|
/// schema's own defaults.
|
|
pub fn load(path: impl AsRef<Path>) -> Dashboard {
|
|
let path = path.as_ref().to_path_buf();
|
|
let effective = Document::from_json(SCHEMA)
|
|
.map_err(|error| error.to_string())
|
|
.and_then(|doc| {
|
|
effective::merge(&doc, &[]).map_err(|errors| {
|
|
errors
|
|
.iter()
|
|
.map(|error| error.msg.clone())
|
|
.collect::<Vec<_>>()
|
|
.join("; ")
|
|
})
|
|
});
|
|
let mut rows = Rows::new();
|
|
if let Ok(text) = fs::read_to_string(&path) {
|
|
if let Ok(Value::Object(map)) = serde_json::from_str::<Value>(&text) {
|
|
for (key, value) in map {
|
|
rows.insert(key, value);
|
|
}
|
|
}
|
|
}
|
|
Dashboard {
|
|
effective,
|
|
rows,
|
|
path,
|
|
}
|
|
}
|
|
|
|
pub fn schema(&self) -> Result<&Effective, String> {
|
|
self.effective.as_ref().map_err(|error| error.clone())
|
|
}
|
|
|
|
pub fn rows(&self) -> &Rows {
|
|
&self.rows
|
|
}
|
|
|
|
/// The visible navigation for this board and viewer.
|
|
pub fn nav(&self) -> Result<VisibleNav, String> {
|
|
let effective = self.effective.as_ref().map_err(|error| error.clone())?;
|
|
let caps = board_caps();
|
|
let apps = AppSet::default();
|
|
let routes = Routes::console();
|
|
let ctx = NavContext {
|
|
surface: Surface::Web,
|
|
principal: &AllowAll,
|
|
caps: &caps,
|
|
apps: &apps,
|
|
routes: &routes,
|
|
};
|
|
Ok(nav::visible(&effective.doc.menus, &ctx))
|
|
}
|
|
|
|
/// Stylesheets the shell needs, served from the crate's embedded assets.
|
|
pub fn assets() -> PageAssets {
|
|
PageAssets {
|
|
styles: vec![
|
|
"/assets/tokens.css".to_string(),
|
|
"/assets/components.css".to_string(),
|
|
"/assets/theme.css".to_string(),
|
|
],
|
|
scripts: Vec::new(),
|
|
streams: Vec::new(),
|
|
}
|
|
}
|
|
|
|
/// The three stylesheets, for the host to serve.
|
|
pub fn stylesheets() -> [(&'static str, &'static str); 3] {
|
|
[
|
|
("tokens.css", tokens::TOKENS_CSS),
|
|
("components.css", tokens::COMPONENTS_CSS),
|
|
("theme.css", tokens::THEME_CSS),
|
|
]
|
|
}
|
|
|
|
/// Render one page: the shell around the settings card of the tab.
|
|
///
|
|
/// `section` is the navigation section (`settings`), `tab` the tab slug
|
|
/// (`tuning`), and the settings card shows the group named by the tab.
|
|
///
|
|
/// `errors` carries per-path messages from a rejected submission, so the
|
|
/// same render can show what went wrong.
|
|
pub fn page(&self, section: &str, tab: &str, errors: &BTreeMap<String, String>) -> Markup {
|
|
let effective = match self.effective.as_ref() {
|
|
Ok(effective) => effective,
|
|
Err(error) => {
|
|
return maud::html! {
|
|
main class="bf-main" {
|
|
p class="bf-field-error bf-text-body" role="alert" { "Schema did not load: " (error) }
|
|
}
|
|
}
|
|
}
|
|
};
|
|
let nav = self.nav().unwrap_or_default();
|
|
let view = View {
|
|
eff: effective,
|
|
rows: &self.rows,
|
|
errors,
|
|
surface: Surface::Web,
|
|
can_write: true,
|
|
};
|
|
let title = effective
|
|
.doc
|
|
.menus
|
|
.iter()
|
|
.find(|menu| menu.slug == tab && menu.id.starts_with(&format!("{section}/")))
|
|
.map(|menu| menu.title.clone())
|
|
.unwrap_or_else(|| section.to_string());
|
|
let card = render::card(&title, tab, &view);
|
|
let body = maud::html! {
|
|
section class="bf-card" {
|
|
h1 class="bf-text-title" { (title) }
|
|
(card)
|
|
}
|
|
};
|
|
shell::page("Alkane OS", &Self::assets(), &nav, Active { section, tab }, body)
|
|
}
|
|
|
|
/// Apply a submitted form body (`application/x-www-form-urlencoded`).
|
|
///
|
|
/// Returns the per-path failures when the schema rejects the batch, and
|
|
/// persists nothing in that case. Unknown keys are ignored: they are not in
|
|
/// the schema, so they cannot be written.
|
|
pub fn submit(&mut self, body: &str) -> Result<(), BTreeMap<String, String>> {
|
|
let effective = match self.effective.as_ref() {
|
|
Ok(effective) => effective,
|
|
Err(error) => {
|
|
let mut failures = BTreeMap::new();
|
|
failures.insert(String::new(), error.clone());
|
|
return Err(failures);
|
|
}
|
|
};
|
|
let ops = self.parse_ops(effective, body);
|
|
let failures = render::validate_form(effective, &ops, &self.rows, wschema::validate::Origin::Web, None);
|
|
if !failures.is_empty() {
|
|
return Err(failures);
|
|
}
|
|
for op in &ops {
|
|
if let Op::Set { path, value } = op {
|
|
self.rows.insert(path.clone(), value.clone());
|
|
}
|
|
}
|
|
let map: Map<String, Value> = self
|
|
.rows
|
|
.iter()
|
|
.map(|(key, value)| (key.clone(), value.clone()))
|
|
.collect();
|
|
let text = serde_json::to_string_pretty(&Value::Object(map)).unwrap_or_else(|_| "{}".into());
|
|
if let Some(parent) = self.path.parent() {
|
|
let _ = fs::create_dir_all(parent);
|
|
}
|
|
// Persist only after validation passed; a failed write leaves the rows
|
|
// changed in memory but never on disk, which the API reports.
|
|
let _ = fs::write(&self.path, text);
|
|
Ok(())
|
|
}
|
|
|
|
/// Turn a form body into schema ops, coercing each value to its declared kind.
|
|
fn parse_ops(&self, effective: &Effective, body: &str) -> Vec<Op> {
|
|
let mut ops = Vec::new();
|
|
for pair in body.split('&') {
|
|
if pair.is_empty() {
|
|
continue;
|
|
}
|
|
let (raw_key, raw_value) = pair.split_once('=').unwrap_or((pair, ""));
|
|
let key = percent_decode(raw_key);
|
|
let raw = percent_decode(raw_value);
|
|
let setting = match effective.setting(&key) {
|
|
Some(setting) => setting,
|
|
None => continue,
|
|
};
|
|
let value = coerce(setting.kind.token(), &raw);
|
|
ops.push(Op::Set {
|
|
path: setting.path.clone(),
|
|
value,
|
|
});
|
|
}
|
|
ops
|
|
}
|
|
}
|
|
|
|
fn percent_decode(text: &str) -> String {
|
|
let bytes = text.as_bytes();
|
|
let mut out = Vec::with_capacity(bytes.len());
|
|
let mut index = 0;
|
|
while index < bytes.len() {
|
|
match bytes[index] {
|
|
b'+' => {
|
|
out.push(b' ');
|
|
index += 1;
|
|
}
|
|
b'%' if index + 2 < bytes.len() => {
|
|
let high = (bytes[index + 1] as char).to_digit(16);
|
|
let low = (bytes[index + 2] as char).to_digit(16);
|
|
match (high, low) {
|
|
(Some(high), Some(low)) => {
|
|
out.push((high * 16 + low) as u8);
|
|
index += 3;
|
|
}
|
|
_ => {
|
|
out.push(bytes[index]);
|
|
index += 1;
|
|
}
|
|
}
|
|
}
|
|
byte => {
|
|
out.push(byte);
|
|
index += 1;
|
|
}
|
|
}
|
|
}
|
|
String::from_utf8_lossy(&out).into_owned()
|
|
}
|
|
|
|
fn coerce(kind: &str, raw: &str) -> Value {
|
|
match kind {
|
|
"int" | "int_set" => raw
|
|
.trim()
|
|
.parse::<i64>()
|
|
.map(Value::from)
|
|
.unwrap_or_else(|_| Value::String(raw.to_string())),
|
|
"bool" => Value::Bool(matches!(raw, "true" | "on" | "1")),
|
|
_ => Value::String(raw.to_string()),
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn temp_path(name: &str) -> PathBuf {
|
|
let mut path = std::env::temp_dir();
|
|
path.push(format!("alkane-dashboard-{name}-{}.json", std::process::id()));
|
|
let _ = fs::remove_file(&path);
|
|
path
|
|
}
|
|
|
|
#[test]
|
|
fn the_schema_loads_and_yields_the_three_sections() {
|
|
let dash = Dashboard::load(temp_path("load"));
|
|
let effective = dash.schema().expect("schema loads");
|
|
assert_eq!(effective.doc.menus.len(), 20);
|
|
let nav = dash.nav().expect("nav builds");
|
|
assert_eq!(nav.sections.len(), 3);
|
|
assert_eq!(nav.sections[1].slug, "mining");
|
|
assert_eq!(nav.sections[1].tabs.len(), 4);
|
|
// Settings now carries the full tab set including drivers/services/monitor.
|
|
assert_eq!(nav.sections[2].slug, "settings");
|
|
assert_eq!(nav.sections[2].tabs.len(), 11);
|
|
}
|
|
|
|
#[test]
|
|
fn every_scaffolded_setting_is_in_the_schema() {
|
|
let dash = Dashboard::load(temp_path("settings"));
|
|
let effective = dash.schema().expect("schema loads");
|
|
for path in [
|
|
"tuning.mode",
|
|
"tuning.power_w",
|
|
"tuning.ceiling_mc",
|
|
"tuning.pid.kp_milli",
|
|
"tuning.pid.deadband_milli",
|
|
"fans.zone_count",
|
|
"fans.pwm_min",
|
|
"detect.chain_ports",
|
|
"detect.probe_budget",
|
|
"profiles.db",
|
|
"system.name",
|
|
] {
|
|
assert!(effective.setting(path).is_some(), "{path} is missing from the schema");
|
|
}
|
|
assert_eq!(effective.doc.settings.len(), 20);
|
|
}
|
|
|
|
#[test]
|
|
fn a_page_renders_its_settings_with_inputs() {
|
|
let dash = Dashboard::load(temp_path("page"));
|
|
let html = dash.page("settings", "tuning", &BTreeMap::new()).into_string();
|
|
assert!(html.contains("bf-sidebar"), "the unified sidebar is missing");
|
|
assert!(html.contains("bf-tabs"), "the tab strip is missing");
|
|
assert!(html.contains("Tuning target"), "a settings label is missing");
|
|
assert!(html.contains("tuning.power_w"), "the field path is missing");
|
|
assert!(html.contains("name=\"tuning.mode\""), "the mode field is missing");
|
|
}
|
|
|
|
#[test]
|
|
fn a_valid_submission_is_persisted_and_reloaded() {
|
|
let path = temp_path("submit");
|
|
let mut dash = Dashboard::load(&path);
|
|
dash.submit("tuning.power_w=1500&system.name=s19jpro").expect("valid form");
|
|
assert_eq!(dash.rows().get("tuning.power_w"), Some(&serde_json::json!(1500)));
|
|
let stored = fs::read_to_string(&path).expect("settings file written");
|
|
assert!(stored.contains("\"tuning.power_w\": 1500"), "{stored}");
|
|
let reloaded = Dashboard::load(&path);
|
|
assert_eq!(reloaded.rows().get("system.name"), Some(&serde_json::json!("s19jpro")));
|
|
let _ = fs::remove_file(&path);
|
|
}
|
|
|
|
#[test]
|
|
fn an_out_of_range_value_is_rejected_and_nothing_is_written() {
|
|
let path = temp_path("reject");
|
|
let mut dash = Dashboard::load(&path);
|
|
let failures = dash.submit("tuning.power_w=99999").expect_err("must be rejected");
|
|
assert!(failures.keys().any(|key| key.contains("tuning.power_w")), "{failures:?}");
|
|
assert!(!path.exists(), "a rejected submission must not be persisted");
|
|
assert_eq!(dash.rows().get("tuning.power_w"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn unknown_form_keys_are_ignored() {
|
|
let path = temp_path("unknown");
|
|
let mut dash = Dashboard::load(&path);
|
|
dash.submit("not.a.setting=1&tuning.ceiling_mc=650").expect("known key applies");
|
|
assert_eq!(dash.rows().get("not.a.setting"), None);
|
|
assert_eq!(dash.rows().get("tuning.ceiling_mc"), Some(&serde_json::json!(650)));
|
|
let _ = fs::remove_file(&path);
|
|
}
|
|
|
|
#[test]
|
|
fn form_values_are_percent_decoded() {
|
|
assert_eq!(percent_decode("a+b%2Fc"), "a b/c");
|
|
}
|
|
}
|