Skip to content

armgit / kokon

Public Imported from GitHub
0

Edit photos by describing the change, on your own GPU. A free, open-source alternative to Nano Banana and ChatGPT image editing: photos stay on your computer, no daily limit. One installer for Windows, Mac and Linux sets up the best open model (Qwen-Image 2.1). MCP server for AI agents.

Benchmark this Mac: the Mac engine's bench from Settings → Performance

Gabriele Lozupone87d5919934d5
diff --git a/crates/qls-core/src/engine.rs b/crates/qls-core/src/engine.rs
index d517ca1..397ba26 100644
--- a/crates/qls-core/src/engine.rs
+++ b/crates/qls-core/src/engine.rs
@@ -112,6 +112,8 @@ pub enum Event {
Gallery { id: String, change: &'static str },
/// A project changed (`rev`) or was removed: the other devices reload it.
Projects { id: String, rev: u64, deleted: bool },
+ /// Settings → Performance → Benchmark this Mac.
+ MacBench { bench: crate::mac_bench::BenchState },
}
pub struct Engine {
@@ -137,6 +139,7 @@ pub struct Engine {
devices: Mutex<Option<DeviceList>>,
/// First-run downloads (setup wizard).
pub installer: Arc<crate::installer::Installer>,
+ pub mac_bench: Arc<crate::mac_bench::MacBench>,
backend_version: Mutex<Option<String>>,
last_activity: Mutex<Instant>,
}
@@ -255,6 +258,7 @@ impl Engine {
gpus: Mutex::new((None, Vec::new())),
devices: Mutex::new(None),
installer: crate::installer::Installer::new(),
+ mac_bench: crate::mac_bench::MacBench::new(),
backend_version: Mutex::new(None),
last_activity: Mutex::new(Instant::now()),
}))
@@ -504,7 +508,46 @@ impl Engine {
}
pub fn has_pending_work(&self) -> bool {
- self.active.lock().unwrap().is_some() || self.jobs.lock().unwrap().values().any(|j| !j.view.status.is_terminal()) || self.installer.is_running()
+ self.has_jobs() || self.installer.is_running() || self.mac_bench.is_running()
+ }
+
+ fn has_jobs(&self) -> bool {
+ self.active.lock().unwrap().is_some() || self.jobs.lock().unwrap().values().any(|j| !j.view.status.is_terminal())
+ }
+
+ /// Starts Kokon's Mac engine benchmark on the active model files: refused while images or an install are
+ /// running; stops the server and keeps it stopped until the bench ends (the next job starts it again).
+ pub async fn start_mac_bench(self: &Arc<Self>, quick: bool) -> Result<crate::mac_bench::BenchState, AppError> {
+ use crate::mac_bench as mb;
+ let cfg = self.config();
+ if let Some(e) = mb::unavailable(&cfg) {
+ return Err(e);
+ }
+ if self.mac_bench.is_running() {
+ return Ok(self.mac_bench.state());
+ }
+ if self.has_jobs() || self.installer.is_running() {
+ return Err(AppError::new(ErrorCode::QueueFull, "Wait for the current images to finish, then run the benchmark."));
+ }
+ self.server.hold(Some("The Mac is running the benchmark: images can be made when it ends.".into()));
+ self.server.stop().await;
+ self.emit_server();
+ let report = mb::report_path(&self.data_dir);
+ let args = mb::bench_args(cfg.profile(), &report, quick);
+ let envs = vec![("KOKON_ENGINE_VERSION".to_string(), format!("0.1 (experimental), Kokon {APP_VERSION}"))];
+ let command = mb::BenchCommand { exe: cfg.server_exe(), args, envs, report, quick };
+ let (e1, e2) = (self.clone(), self.clone());
+ let r = self.mac_bench.start(
+ command,
+ move |bench| {
+ let _ = e1.events.send(Event::MacBench { bench });
+ },
+ move || e2.server.hold(None),
+ );
+ if r.is_err() {
+ self.server.hold(None);
+ }
+ r.map(|()| self.mac_bench.state())
}
/// Every graphics card found (refreshed every few seconds for the live memory use).
diff --git a/crates/qls-core/src/lib.rs b/crates/qls-core/src/lib.rs
index ed5f22f..c28cc41 100644
--- a/crates/qls-core/src/lib.rs
+++ b/crates/qls-core/src/lib.rs
@@ -13,6 +13,7 @@ pub mod imaging;
pub mod installer;
pub mod lora;
pub mod lut;
+pub mod mac_bench;
pub mod modelfile;
pub mod paths;
pub mod pipeline;
diff --git a/crates/qls-core/src/mac_bench.rs b/crates/qls-core/src/mac_bench.rs
new file mode 100644
index 0000000..41e6050
--- /dev/null
+++ b/crates/qls-core/src/mac_bench.rs
@@ -0,0 +1,506 @@
+//! Settings → Performance → "Benchmark this Mac": runs `kokon-engine-mac bench` on the active model files and
+//! keeps its state for the UI. The bench runs each configuration in a child process of its own and prints
+//! `PROGRESS k/N <what>` before each one; the report (markdown) goes to a file in the data folder.
+//!
+//! While it runs the inference server is stopped and held (see [`crate::process::ServerManager::hold`]): the bench
+//! needs the whole GPU and memory, and jobs would only slow it down and spoil its numbers.
+
+use std::collections::VecDeque;
+use std::path::{Path, PathBuf};
+use std::process::Stdio;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex};
+
+use serde::Serialize;
+use tokio::io::{AsyncBufReadExt, AsyncRead, BufReader};
+
+use crate::config::{AppConfig, ModelProfile};
+use crate::error::{AppError, AppResult, ErrorCode};
+
+/// Lines of the bench's output kept to explain a failure.
+pub const LOG_LINES: usize = 200;
+
+/// Where the report is written, in the app's data folder.
+pub fn report_path(data_dir: &Path) -> PathBuf {
+ data_dir.join("mac-bench-report.md")
+}
+
+/// `kokon-engine-mac bench` on the active profile's files (the ones `build_mac_engine_args` serves).
+pub fn bench_args(profile: &ModelProfile, out: &Path, quick: bool) -> Vec<String> {
+ let p = |p: &Path| p.to_string_lossy().into_owned();
+ let mut a: Vec<String> = vec![
+ "bench".into(),
+ "--encoder".into(),
+ p(&profile.text_encoder),
+ "--dit".into(),
+ p(&profile.diffusion_model),
+ "--vae".into(),
+ p(&profile.vae),
+ "--out".into(),
+ p(out),
+ ];
+ if quick {
+ a.push("--quick".into());
+ }
+ a
+}
+
+/// Why the bench cannot run with this configuration, if it cannot.
+pub fn unavailable(cfg: &AppConfig) -> Option<AppError> {
+ if !cfg.uses_mac_engine() {
+ return Some(AppError::invalid(
+ "Turn on Kokon's Mac engine in Settings → Performance and save first.",
+ ));
+ }
+ cfg.missing_files_error()
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Progress {
+ pub k: u32,
+ pub n: u32,
+ pub label: String,
+}
+
+/// `PROGRESS 3/7 KOKON_NA=0: accuracy at 512²` → (3, 7, label). Anything else is a human line.
+pub fn parse_progress(line: &str) -> Option<Progress> {
+ let rest = line.trim_end().strip_prefix("PROGRESS ")?;
+ let (frac, label) = rest.split_once(' ').unwrap_or((rest, ""));
+ let (k, n) = frac.split_once('/')?;
+ let (k, n) = (k.parse().ok()?, n.parse().ok()?);
+ (k >= 1 && k <= n).then(|| Progress {
+ k,
+ n,
+ label: label.trim().to_string(),
+ })
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize)]
+#[serde(tag = "state", rename_all = "snake_case")]
+pub enum BenchState {
+ Idle,
+ /// Step `k` of `n` (0 before the first progress line).
+ Running {
+ k: u32,
+ n: u32,
+ label: String,
+ started_at: String,
+ quick: bool,
+ },
+ Done {
+ report: String,
+ finished_at: String,
+ quick: bool,
+ },
+ Failed {
+ error: String,
+ log: String,
+ },
+}
+
+/// A failure's message: the engine's own `error: …` line when it printed one.
+fn failure_message(log: &[String], status: Option<i32>) -> String {
+ if let Some(e) = log
+ .iter()
+ .rev()
+ .find_map(|l| l.trim().strip_prefix("error: "))
+ {
+ let first = e.lines().next().unwrap_or(e);
+ return format!("The benchmark stopped: {first}");
+ }
+ match status {
+ Some(c) => format!("The benchmark stopped (exit code {c})."),
+ None => "The benchmark stopped: the engine was killed (out of memory?).".into(),
+ }
+}
+
+/// What [`MacBench::start`] runs.
+pub struct BenchCommand {
+ pub exe: PathBuf,
+ pub args: Vec<String>,
+ pub envs: Vec<(String, String)>,
+ /// The file the bench writes its report to (`--out`).
+ pub report: PathBuf,
+ pub quick: bool,
+}
+
+pub struct MacBench {
+ state: Mutex<BenchState>,
+ log: Mutex<VecDeque<String>>,
+ pid: Mutex<Option<u32>>,
+ cancelled: AtomicBool,
+}
+
+impl MacBench {
+ pub fn new() -> Arc<Self> {
+ Arc::new(Self {
+ state: Mutex::new(BenchState::Idle),
+ log: Mutex::new(VecDeque::new()),
+ pid: Mutex::new(None),
+ cancelled: AtomicBool::new(false),
+ })
+ }
+
+ pub fn state(&self) -> BenchState {
+ self.state.lock().unwrap().clone()
+ }
+
+ pub fn is_running(&self) -> bool {
+ matches!(*self.state.lock().unwrap(), BenchState::Running { .. })
+ }
+
+ fn push_line(&self, line: String) {
+ let mut log = self.log.lock().unwrap();
+ if log.len() == LOG_LINES {
+ log.pop_front();
+ }
+ log.push_back(line);
+ }
+
+ /// Spawns the bench and follows it; `changed` gets every new state. `on_exit` runs when it ends, before the
+ /// final state is published (the caller releases the server there).
+ pub fn start(
+ self: &Arc<Self>,
+ c: BenchCommand,
+ changed: impl Fn(BenchState) + Send + Sync + 'static,
+ on_exit: impl FnOnce() + Send + 'static,
+ ) -> AppResult<()> {
+ let BenchCommand {
+ exe,
+ args,
+ envs,
+ report,
+ quick,
+ } = c;
+ let mut cmd = tokio::process::Command::new(&exe);
+ cmd.args(&args)
+ .envs(envs)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .kill_on_drop(true);
+ if let Some(d) = exe.parent() {
+ cmd.current_dir(d);
+ }
+ // Its own process group, so Cancel stops the bench and the child it is running.
+ #[cfg(unix)]
+ cmd.process_group(0);
+ let _ = std::fs::remove_file(&report);
+ let mut child = cmd.spawn().map_err(|e| {
+ AppError::new(
+ ErrorCode::ServerStartFailed,
+ format!("Could not start the benchmark: {e}"),
+ )
+ })?;
+ self.log.lock().unwrap().clear();
+ self.cancelled.store(false, Ordering::Relaxed);
+ *self.pid.lock().unwrap() = child.id();
+ let started_at = chrono::Utc::now().to_rfc3339();
+ let running = BenchState::Running {
+ k: 0,
+ n: 0,
+ label: "Starting".into(),
+ started_at: started_at.clone(),
+ quick,
+ };
+ *self.state.lock().unwrap() = running.clone();
+ changed(running);
+
+ let changed = Arc::new(changed);
+ let (stdout, stderr) = (child.stdout.take(), child.stderr.take());
+ let me = self.clone();
+ tokio::spawn(async move {
+ let out = {
+ let (me, changed, started_at) = (me.clone(), changed.clone(), started_at.clone());
+ read_lines(stdout, move |line| {
+ if let Some(p) = parse_progress(&line) {
+ let s = BenchState::Running {
+ k: p.k,
+ n: p.n,
+ label: p.label,
+ started_at: started_at.clone(),
+ quick,
+ };
+ *me.state.lock().unwrap() = s.clone();
+ changed(s);
+ }
+ me.push_line(line);
+ })
+ };
+ let err = {
+ let me = me.clone();
+ read_lines(stderr, move |line| me.push_line(line))
+ };
+ tokio::join!(out, err);
+ let status = child.wait().await.ok();
+ *me.pid.lock().unwrap() = None;
+ on_exit();
+ let log: Vec<String> = me.log.lock().unwrap().iter().cloned().collect();
+ let fin = if me.cancelled.load(Ordering::Relaxed) {
+ BenchState::Idle
+ } else {
+ match (
+ status.filter(|s| s.success()),
+ std::fs::read_to_string(&report),
+ ) {
+ (Some(_), Ok(r)) if !r.trim().is_empty() => BenchState::Done {
+ report: r,
+ finished_at: chrono::Utc::now().to_rfc3339(),
+ quick,
+ },
+ _ => BenchState::Failed {
+ error: failure_message(&log, status.and_then(|s| s.code())),
+ log: log.join("\n"),
+ },
+ }
+ };
+ *me.state.lock().unwrap() = fin.clone();
+ changed(fin);
+ });
+ Ok(())
+ }
+
+ /// Stops the bench and the configuration it is running; the state goes back to idle when it has exited.
+ pub fn cancel(&self) {
+ let Some(pid) = *self.pid.lock().unwrap() else {
+ return;
+ };
+ self.cancelled.store(true, Ordering::Relaxed);
+ #[cfg(unix)]
+ {
+ // The whole group (see `start`); the children also exit on their own when the bench is gone.
+ let _ = std::process::Command::new("/bin/kill")
+ .args(["-KILL", "--", &format!("-{pid}")])
+ .status();
+ }
+ #[cfg(not(unix))]
+ {
+ let _ = std::process::Command::new("taskkill")
+ .args(["/F", "/T", "/PID", &pid.to_string()])
+ .status();
+ }
+ }
+
+ /// Forgets a finished report or failure (the card shows Run again).
+ pub fn clear(&self) {
+ let mut s = self.state.lock().unwrap();
+ if !matches!(*s, BenchState::Running { .. }) {
+ *s = BenchState::Idle;
+ }
+ }
+}
+
+async fn read_lines(pipe: Option<impl AsyncRead + Unpin>, mut each: impl FnMut(String)) {
+ let Some(pipe) = pipe else { return };
+ let mut lines = BufReader::new(pipe).lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ each(line);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn progress_lines() {
+ assert_eq!(
+ parse_progress("PROGRESS 1/7 Accuracy reference (512², most accurate path)"),
+ Some(Progress {
+ k: 1,
+ n: 7,
+ label: "Accuracy reference (512², most accurate path)".into()
+ })
+ );
+ assert_eq!(
+ parse_progress("PROGRESS 7/7 KOKON_NA=0: two images at 1024²\n"),
+ Some(Progress {
+ k: 7,
+ n: 7,
+ label: "KOKON_NA=0: two images at 1024²".into()
+ })
+ );
+ assert_eq!(
+ parse_progress("PROGRESS 2/3"),
+ Some(Progress {
+ k: 2,
+ n: 3,
+ label: String::new()
+ })
+ );
+ for human in [
+ "[1/3] default (paths above): accuracy at 512²",
+ "PROGRESS",
+ "PROGRESS 4/3 x",
+ "PROGRESS 0/3 x",
+ "PROGRESS a/b x",
+ " PROGRESS 1/2 x",
+ ] {
+ assert_eq!(parse_progress(human), None, "{human}");
+ }
+ }
+
+ #[test]
+ fn args_use_the_active_files() {
+ let profile = ModelProfile {
+ diffusion_model: PathBuf::from("/m/dit.gguf"),
+ vae: PathBuf::from("/m/vae.safetensors"),
+ text_encoder: PathBuf::from("/m/te.gguf"),
+ vision_projector: Some(PathBuf::from("/m/mmproj.gguf")),
+ ..ModelProfile::default()
+ };
+ let out = report_path(Path::new("/data"));
+ assert_eq!(out, PathBuf::from("/data/mac-bench-report.md"));
+ let a = bench_args(&profile, &out, false);
+ assert_eq!(
+ a,
+ [
+ "bench",
+ "--encoder",
+ "/m/te.gguf",
+ "--dit",
+ "/m/dit.gguf",
+ "--vae",
+ "/m/vae.safetensors",
+ "--out",
+ "/data/mac-bench-report.md"
+ ]
+ );
+ assert_eq!(
+ bench_args(&profile, &out, true).last().map(String::as_str),
+ Some("--quick")
+ );
+ }
+
+ #[test]
+ fn needs_the_mac_engine() {
+ let mut cfg = AppConfig::default();
+ cfg.mac_engine = false;
+ assert!(unavailable(&cfg).is_some_and(|e| e.message.contains("Mac engine")));
+ }
+
+ #[test]
+ fn failure_messages() {
+ let log = vec![
+ "accuracy at 512²…".to_string(),
+ "error: kernel(\"bench-run accuracy failed\")\nmore".to_string(),
+ ];
+ assert_eq!(
+ failure_message(&log, Some(1)),
+ "The benchmark stopped: kernel(\"bench-run accuracy failed\")"
+ );
+ assert_eq!(
+ failure_message(&[], Some(3)),
+ "The benchmark stopped (exit code 3)."
+ );
+ assert!(failure_message(&[], None).contains("killed"));
+ }
+
+ fn command(exe: &Path, args: Vec<String>, report: &Path, quick: bool) -> BenchCommand {
+ BenchCommand {
+ exe: exe.to_path_buf(),
+ args,
+ envs: vec![],
+ report: report.to_path_buf(),
+ quick,
+ }
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn runs_reports_and_cancels() {
+ let dir = tempfile::tempdir().unwrap();
+ let report = report_path(dir.path());
+ let script = dir.path().join("fake-bench.sh");
+ std::fs::write(&script, "#!/bin/sh\necho 'PROGRESS 1/2 one'\necho 'PROGRESS 2/2 two'\nprintf '### report' > \"$2\"\n").unwrap();
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
+
+ let bench = MacBench::new();
+ let seen = Arc::new(Mutex::new(Vec::new()));
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ let s = seen.clone();
+ let tx = Mutex::new(Some(tx));
+ bench
+ .start(
+ command(
+ &script,
+ vec!["--out".into(), report.to_string_lossy().into()],
+ &report,
+ true,
+ ),
+ move |st| {
+ let end = !matches!(st, BenchState::Running { .. });
+ s.lock().unwrap().push(st);
+ if end && let Some(tx) = tx.lock().unwrap().take() {
+ let _ = tx.send(());
+ }
+ },
+ || {},
+ )
+ .unwrap();
+ rx.await.unwrap();
+ let seen = seen.lock().unwrap();
+ assert!(
+ seen.iter()
+ .any(|s| matches!(s, BenchState::Running { k: 2, n: 2, .. }))
+ );
+ assert!(
+ matches!(seen.last(), Some(BenchState::Done { report, quick: true, .. }) if report == "### report")
+ );
+
+ // A bench that hangs: Cancel brings it back to idle, with no failure.
+ std::fs::write(&script, "#!/bin/sh\necho 'PROGRESS 1/3 one'\nsleep 30\n").unwrap();
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ let tx = Mutex::new(Some(tx));
+ bench
+ .start(
+ command(&script, vec![], &report, false),
+ move |st| {
+ if !matches!(st, BenchState::Running { .. })
+ && let Some(tx) = tx.lock().unwrap().take()
+ {
+ let _ = tx.send(st);
+ }
+ },
+ || {},
+ )
+ .unwrap();
+ tokio::time::sleep(std::time::Duration::from_millis(200)).await;
+ bench.cancel();
+ let end = tokio::time::timeout(std::time::Duration::from_secs(5), rx)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(end, BenchState::Idle);
+
+ // One that fails: its error line and the log.
+ std::fs::write(
+ &script,
+ "#!/bin/sh\necho 'starting'\necho 'error: no Metal device' >&2\nexit 1\n",
+ )
+ .unwrap();
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ let tx = Mutex::new(Some(tx));
+ bench
+ .start(
+ command(&script, vec![], &report, false),
+ move |st| {
+ if !matches!(st, BenchState::Running { .. })
+ && let Some(tx) = tx.lock().unwrap().take()
+ {
+ let _ = tx.send(st);
+ }
+ },
+ || {},
+ )
+ .unwrap();
+ match rx.await.unwrap() {
+ BenchState::Failed { error, log } => {
+ assert_eq!(error, "The benchmark stopped: no Metal device");
+ assert!(log.contains("starting"));
+ }
+ other => panic!("{other:?}"),
+ }
+ }
+}
diff --git a/crates/qls-core/src/process.rs b/crates/qls-core/src/process.rs
index 7a0fb83..ec16eae 100644
--- a/crates/qls-core/src/process.rs
+++ b/crates/qls-core/src/process.rs
@@ -376,6 +376,8 @@ pub struct ServerManager {
data_dir: PathBuf,
pub log: Arc<LogBuffer>,
lines_tx: broadcast::Sender<String>,
+ /// Why the server may not start now (the Mac benchmark needs the GPU): [`Self::ensure_ready`] refuses.
+ held: Mutex<Option<String>>,
}
#[cfg(windows)]
@@ -403,9 +405,15 @@ impl ServerManager {
data_dir,
log: Arc::new(LogBuffer::new(4000)),
lines_tx,
+ held: Mutex::new(None),
})
}
+ /// Keeps the server from starting until `None` (set it before [`Self::stop`]: a start in progress finishes first).
+ pub fn hold(&self, reason: Option<String>) {
+ *self.held.lock().unwrap() = reason;
+ }
+
/// Live stream of server log lines (only available for servers this app launched).
pub fn subscribe_lines(&self) -> broadcast::Receiver<String> {
self.lines_tx.subscribe()
@@ -459,6 +467,9 @@ impl ServerManager {
/// launches it. Serialized so concurrent callers never start two instances.
pub async fn ensure_ready(&self, cfg: &AppConfig) -> Result<Capabilities, AppError> {
let _guard = self.start_lock.lock().await;
+ if let Some(why) = self.held.lock().unwrap().clone() {
+ return Err(AppError::new(ErrorCode::ServerUnavailable, why).suggest("Wait for it to finish, or cancel it in Settings → Performance."));
+ }
let profile = cfg.profile().clone();
// Our server may run on a fallback port (see `launch_port`); otherwise the configured one.
let rec = self.read_record().filter(|r| process_alive(r.pid));
@@ -827,6 +838,15 @@ pub fn parse_device_list(text: &str) -> Vec<(String, String)> {
mod tests {
use super::*;
+ #[tokio::test]
+ async fn held_server_does_not_start() {
+ let dir = tempfile::tempdir().unwrap();
+ let m = ServerManager::new(dir.path().to_path_buf());
+ m.hold(Some("The Mac is running the benchmark.".into()));
+ let e = m.ensure_ready(&AppConfig::default()).await.unwrap_err();
+ assert_eq!((e.code, e.message.as_str()), (ErrorCode::ServerUnavailable, "The Mac is running the benchmark."));
+ }
+
#[test]
fn default_launch_args() {
let mut cfg = AppConfig::default();
diff --git a/crates/qls-service/src/api.rs b/crates/qls-service/src/api.rs
index f248033..f576ed9 100644
--- a/crates/qls-service/src/api.rs
+++ b/crates/qls-service/src/api.rs
@@ -81,6 +81,8 @@ pub fn router(state: Arc<AppState>, lan: bool) -> Router {
.route("/upscalers/{name}/download", post(download_upscaler))
.route("/config", get(get_config).put(put_config))
.route("/enhancer/defaults", get(enhancer_defaults))
+ .route("/mac-engine/bench", get(mac_bench_status).post(mac_bench_start).delete(mac_bench_clear))
+ .route("/mac-engine/bench/cancel", post(mac_bench_cancel))
.route("/backend/start", post(backend_start))
.route("/backend/stop", post(backend_stop))
.route("/backend/restart", post(backend_restart))
@@ -536,6 +538,33 @@ async fn put_config(State(s): St, Extension(caller): Extension<Caller>, Json(mut
Ok(Json(json!({ "saved": true, "backend_restart_needed": restart })))
}
+#[derive(Deserialize, Default)]
+struct BenchBody {
+ #[serde(default)]
+ quick: bool,
+}
+
+async fn mac_bench_status(State(s): St) -> Json<Value> {
+ Json(serde_json::to_value(s.engine.mac_bench.state()).unwrap())
+}
+
+/// Settings → Performance → Benchmark this Mac (see `qls_core::mac_bench`). `{"quick": true}`: one image per run.
+async fn mac_bench_start(State(s): St, body: Option<Json<BenchBody>>) -> ApiResult<Json<Value>> {
+ let quick = body.map(|b| b.0.quick).unwrap_or_default();
+ let state = s.engine.start_mac_bench(quick).await?;
+ Ok(Json(serde_json::to_value(state).unwrap()))
+}
+
+async fn mac_bench_cancel(State(s): St) -> Json<Value> {
+ s.engine.mac_bench.cancel();
+ Json(serde_json::to_value(s.engine.mac_bench.state()).unwrap())
+}
+
+async fn mac_bench_clear(State(s): St) -> Json<Value> {
+ s.engine.mac_bench.clear();
+ Json(serde_json::to_value(s.engine.mac_bench.state()).unwrap())
+}
+
async fn backend_start(State(s): St) -> ApiResult<Json<Value>> {
let cfg = s.engine.config();
let engine = s.engine.clone();
diff --git a/crates/qls-service/src/main.rs b/crates/qls-service/src/main.rs
index fa7c983..2aa9d2e 100644
--- a/crates/qls-service/src/main.rs
+++ b/crates/qls-service/src/main.rs
@@ -347,6 +347,7 @@ async fn run(args: Vec<String>) {
}
let _ = engine.clear_private();
+ engine.mac_bench.cancel();
// Shutdown: stop sd-server unless the user wants it kept loaded.
let cfg = engine.config();
if !cfg.keep_server_running {
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 72f2b36..6ac01c1 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -29,7 +29,9 @@ Windows, macOS (Apple Silicon, 15+) and Linux (`.deb`, `.rpm`). Installed copies
extending an image, about 64–67 s for 1 MP text to image and ~106 s for a 1 MP edit on the same Mac (peak memory 5 GB),
as an experimental switch in Settings → Performance (off by default). Since then (2026-10-26, not yet re-measured as
whole images): one denoising step ~5 % faster, the decoder ~1 s faster per image, an edit's image reading 2.6 → 1.7 s. LoRAs and the upscaler still need the standard
- engine (not planned for its first release).
+ engine (not planned for its first release). A "Benchmark this Mac" button in Settings → Performance runs the engine's
+ bench from the app (~10 min) and gives the report to paste in
+ [Discussion #43](https://github.com/GabrieleLozupone/kokon/discussions/43).
- The Windows installer is not code-signed: SmartScreen or Smart App Control may block it (README FAQ: Unblock).
- HEIC photos can't be opened on Linux yet.
@@ -41,8 +43,10 @@ Windows, macOS (Apple Silicon, 15+) and Linux (`.deb`, `.rpm`). Installed copies
- AMD RDNA3/RDNA4 owners who know HIP: compare a ROCm engine with Vulkan
([#38](https://github.com/GabrieleLozupone/kokon/issues/38)).
- Hardware reports: AMD and Intel on Windows and Linux, Linux on NVIDIA outside WSL, Macs other than an M2 Pro.
- For the Mac engine: `bash engine-mac/tools/bench.sh` on the `macos-optimization` branch prints a report to paste
- (M1, M3, M4 and M5 Macs are the most useful; see [engine-mac/README.md](../engine-mac/README.md#testing-on-your-mac-bench)).
+ For the Mac engine: Settings → Performance → Benchmark this Mac in a build of the `macos-optimization` branch, or
+ `bash engine-mac/tools/bench.sh` there, gives a report to paste in
+ [Discussion #43](https://github.com/GabrieleLozupone/kokon/discussions/43) (M1, M3, M4 and M5 Macs are the most
+ useful; see [engine-mac/README.md](../engine-mac/README.md#testing-on-your-mac-bench)).
- Model proposals that meet the switch rule: [Discussion #35](https://github.com/GabrieleLozupone/kokon/discussions/35).
## Recently shipped
diff --git a/engine-mac/README.md b/engine-mac/README.md
index 866e37b..a907b02 100644
--- a/engine-mac/README.md
+++ b/engine-mac/README.md
@@ -432,7 +432,11 @@ correctness test that runs on any Mac (`PerChipTests`). Only the M2 Pro has meas
## Testing on your Mac (`bench`)
-For anyone with an Apple Silicon Mac, to measure these paths on hardware we do not have (M1, M3, M4, M5, base chips):
+For anyone with an Apple Silicon Mac, to measure these paths on hardware we do not have (M1, M3, M4, M5, base chips).
+In Kokon: Settings → Performance, turn on Kokon's Mac engine and save, then **Benchmark this Mac → Run** (~10 min; the
+server is stopped while it runs and images wait). It runs the same `bench` on the app's engine and model files, shows
+the step it is on, and gives the report with Copy report and a link to
+[Discussion #43](https://github.com/GabrieleLozupone/kokon/discussions/43). From the source:
```bash
git clone https://github.com/GabrieleLozupone/kokon.git && cd kokon && git checkout macos-optimization
@@ -443,8 +447,8 @@ It needs the Xcode command line tools and Kokon's model files (Kokon set up once
and writes `kokon-bench-report.md`: chip, GPU family and cores, memory, macOS, the paths selected, the units' shares,
time per step and per image at 1024² (image 1 with the loading, image 2 with the engine already running), peak memory, and accuracy at
512² against the engine's own fp32 GPU path on the same Mac (the first step's velocity and the image, in 8-bit
-levels), then the same with each chip-specific path off (and the int8 path on, on M3 and later). Paste it in the
-GitHub discussion. A row with a path off that is faster than the default means that path should not be on for that
+levels), then the same with each chip-specific path off (and the int8 path on, on M3 and later). Paste it in
+[Discussion #43](https://github.com/GabrieleLozupone/kokon/discussions/43). A row with a path off that is faster than the default means that path should not be on for that
chip. Close other apps and keep the Mac plugged in: the units share one power and memory limit.
## Tried and not kept, the VAE, credits
diff --git a/engine-mac/Sources/KokonEngine/Bench.swift b/engine-mac/Sources/KokonEngine/Bench.swift
index 0c9fdbb..3cb4d1b 100644
--- a/engine-mac/Sources/KokonEngine/Bench.swift
+++ b/engine-mac/Sources/KokonEngine/Bench.swift
@@ -57,6 +57,15 @@ public enum Bench {
for mode in ["w8", "1"] { runs.append(Run(name: "KOKON_ANE_INT8=\(mode)", environment: ["KOKON_ANE_INT8": mode])) }
}
+ // `PROGRESS k/N <what>` before each child, for Kokon's Benchmark button (stdout is a pipe there).
+ let total = 1 + 2 * runs.count
+ var done = 0
+ func progress(_ label: String) {
+ done += 1
+ print("PROGRESS \(done)/\(total) \(label)")
+ fflush(stdout)
+ }
+
func child(_ mode: String, _ environment: [String: String], tag: String) throws -> [String: Any] {
let process = Process()
process.executableURL = URL(fileURLWithPath: Bundle.main.executablePath ?? CommandLine.arguments[0])
@@ -76,11 +85,14 @@ public enum Bench {
}
print("accuracy at 512²: the fp32 reference (GPU alone, ~1 min)…")
+ progress("Accuracy reference (512², most accurate path)")
let reference = try child("accuracy", Bench.reference, tag: "reference")
var rows: [[String: Any]] = []
for (i, run) in runs.enumerated() {
print("[\(i + 1)/\(runs.count)] \(run.name): accuracy at 512², then two images at 1024²…")
+ progress("\(run.name): accuracy at 512²")
var row = try child("accuracy", run.environment, tag: "run\(i)")
+ progress("\(run.name): " + (quick ? "one image" : "two images") + " at 1024²")
row.merge(try child("timing", run.environment, tag: "run\(i)")) { a, _ in a }
row["name"] = run.name
rows.append(row)
@@ -150,6 +162,12 @@ public enum Bench {
/// `bench-run accuracy|timing <encoder> <dit> <vae> <file prefix> [--quick]`: prints `BENCH {json}`.
public static func child(mode: String, encoder: String, dit: String, vae: String, prefix: String, quick: Bool) throws {
+ // Ends with the bench: when Kokon cancels it, the parent is killed and this child is handed to launchd.
+ let parent = getppid()
+ Thread.detachNewThread {
+ while getppid() == parent { Thread.sleep(forTimeInterval: 1) }
+ exit(1)
+ }
let pipeline = try QwenPipeline(encoder: encoder, dit: dit, vae: vae)
pipeline.keepModels = true
pipeline.log = { _ in }
diff --git a/engine-mac/Sources/kokon-engine-mac/main.swift b/engine-mac/Sources/kokon-engine-mac/main.swift
index 2bf452d..0fec545 100644
--- a/engine-mac/Sources/kokon-engine-mac/main.swift
+++ b/engine-mac/Sources/kokon-engine-mac/main.swift
@@ -192,6 +192,7 @@ do {
for path in [encoder, dit, vae] where !FileManager.default.fileExists(atPath: path) {
fail("\(path) not found: install Kokon's models, or pass --encoder, --dit and --vae")
}
+ setvbuf(stdout, nil, _IOLBF, 0) // Kokon reads the progress lines as they come
try Bench.run(encoder: encoder, dit: dit, vae: vae, quick: quick, out: out)
case "bench-run":
guard arguments.count >= 6 else { fail(usage) }
diff --git a/src/components/Settings.tsx b/src/components/Settings.tsx
index 6472115..b517a2c 100644
--- a/src/components/Settings.tsx
+++ b/src/components/Settings.tsx
@@ -5,18 +5,20 @@ import { api } from "../lib/api";
import { native } from "../lib/native";
import { inBrowser } from "../lib/platform";
import { getState, openModelSetup, refreshStatus, setState, startTour, toastError, toastInfo, useStore } from "../lib/store";
-import { formatBytes } from "../lib/logic";
+import { formatBytes, macBenchProgress } from "../lib/logic";
import { setThemeChoice, themeChoice, type ThemeChoice } from "../lib/theme";
import { LoraSettings } from "./LoraSettings";
import { RemoteAccess } from "./RemoteAccess";
import { UpscalerControls } from "./Upscalers";
import { WHATS_NEW_VERSION } from "./WhatsNew";
-import type { AppConfig, Check, ModelProfile, ModelsStatus, SetupReport, TextEncoderPlacement } from "../lib/types";
+import type { AppConfig, Check, MacBenchState, ModelProfile, ModelsStatus, SetupReport, TextEncoderPlacement } from "../lib/types";
import { IconButton, Seg, Switch } from "./ui";
import { autoCheckEnabled, checkForUpdate } from "../lib/updates";
const REPO_URL = "https://github.com/GabrieleLozupone/kokon";
const SUPPORT_URL = "https://kokon.app/support/";
+/** Where testers paste their Mac engine bench report. */
+const BENCH_DISCUSSION_URL = "https://github.com/GabrieleLozupone/kokon/discussions/43";
/** Top of Settings → General: where Kokon lives. */
export function RepoCard() {
@@ -126,6 +128,87 @@ function EnhancerPrompt(props: { label: string; help: string; value: string; bui
);
}
+/** Settings → Performance on a Mac: runs `kokon-engine-mac bench` on this Mac and gives the report to paste on
+ * GitHub. `blocked`: why it cannot run with the saved settings. */
+function MacBench({ blocked }: { blocked: string | null }) {
+ const bench = useStore((s) => s.macBench);
+ const [now, setNow] = useState(Date.now());
+ const [starting, setStarting] = useState(false);
+ useEffect(() => {
+ api.macBench().then((b) => setState({ macBench: b }), () => {});
+ }, []);
+ const running = bench?.state === "running";
+ useEffect(() => {
+ if (!running) return;
+ const t = window.setInterval(() => setNow(Date.now()), 15000);
+ return () => window.clearInterval(t);
+ }, [running]);
+ const progress = bench && macBenchProgress(bench, now);
+ const act = async (f: () => Promise<MacBenchState>) => {
+ try {
+ setState({ macBench: await f() });
+ } catch (e) {
+ toastError(e);
+ }
+ };
+ const run = async () => {
+ setStarting(true);
+ await act(() => api.startMacBench());
+ setStarting(false);
+ };
+ const report = bench?.state === "done" ? bench.report : "";
+ return (
+ <div className="field">
+ <div className="setting-card">
+ <div className="setting-card-text">
+ <strong>Benchmark this Mac</strong>
+ <span className="muted">
+ Measures Kokon's Mac engine on this Mac: speed, memory and accuracy, with each chip-specific path on and off. It takes about 10 minutes and
+ uses the whole Mac: close other apps and keep it plugged in. Images can't be made while it runs.
+ </span>
+ </div>
+ {running ? (
+ <button className="btn" onClick={() => act(api.cancelMacBench)}>
+ <X size={15} /> Cancel
+ </button>
+ ) : (
+ <button className="btn primary" disabled={!!blocked || starting} title={blocked ?? undefined} onClick={run}>
+ <Activity size={15} /> {bench?.state === "done" ? "Run again" : "Run"}
+ </button>
+ )}
+ </div>
+ {progress && (
+ <>
+ <div className="progress thick">
+ <i style={{ width: `${progress.frac * 100}%` }} />
+ </div>
+ <span className="muted">{progress.text}</span>
+ </>
+ )}
+ {bench?.state === "failed" && (
+ <>
+ <span className="muted">{bench.error}</span>
+ {bench.log && <pre className="diag" style={{ maxHeight: 180 }}>{bench.log}</pre>}
+ </>
+ )}
+ {report && (
+ <>
+ <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
+ <button className="btn" onClick={async () => (await writeText(report), toastInfo("Report copied"))}>
+ <Copy size={14} /> Copy report
+ </button>
+ <button className="btn" onClick={() => native.openLink(BENCH_DISCUSSION_URL).catch(toastError)}>
+ Share on GitHub
+ </button>
+ </div>
+ <span className="muted">Paste the report in the GitHub discussion: it shows which paths suit this chip. Nothing is sent by Kokon.</span>
+ <pre className="diag" style={{ maxHeight: 260 }}>{report}</pre>
+ </>
+ )}
+ </div>
+ );
+}
+
function Diagnostics() {
const [text, setText] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
@@ -590,8 +673,9 @@ export function Settings() {
<Switch on={!!cfg.macEngine} onChange={(v) => set({ macEngine: v })} />
</div>
<span className="muted" style={{ marginTop: -10 }}>
- Kokon's own engine for Apple Silicon: the GPU, the CPU's matrix unit and the Neural Engine work together, about 4 times faster for new images. Experimental: new images only for now. Edits, LoRAs, Prompt+ and the upscaler need it off.
+ Kokon's own engine for Apple Silicon: the GPU, the CPU's matrix unit and the Neural Engine work together, about 4 times faster. New images, edits, brushed edits, extending and Prompt+ work on it; LoRAs and the upscaler model still need it off.
</span>
+ {!inBrowser && <MacBench blocked={dirty ? "Save or discard your changes first" : !cfg.macEngine ? "Turn on Kokon's Mac engine and save first" : null} />}
{!cfg.macEngine && (
<div className="field">
<span>Model memory</span>
diff --git a/src/lib/api.ts b/src/lib/api.ts
index a07ac07..1b24a65 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -7,7 +7,7 @@ import { inBrowser } from "./platform";
import type { ProjectData } from "./store";
import type {
GpuBackend,
- AppConfig, AppErrorBody, GenerationRecord, GenerationRequest, HardwareReport, InputRecord, InstallStatus, JobView, LoraItem, LutEntry, ModelFileInfo, ModelScan, ModelSlot, ModelsStatus, Plan,
+ AppConfig, AppErrorBody, GenerationRecord, GenerationRequest, HardwareReport, InputRecord, InstallStatus, JobView, LoraItem, LutEntry, MacBenchState, ModelFileInfo, ModelScan, ModelSlot, ModelsStatus, Plan,
ServiceEvent, SetupReport, StatusResponse, UpscalerItem,
} from "./types";
@@ -116,6 +116,12 @@ export const api = {
legacyUpscalers: (keep: string) => call<{ files: string[]; bytes: number }>(`/setup/legacy-upscalers?keep=${encodeURIComponent(keep)}`),
/** `keep`: the model chosen in Settings, even if not saved yet. */
removeLegacyUpscalers: (keep: string) => call<{ freed_bytes: number }>(`/setup/legacy-upscalers?keep=${encodeURIComponent(keep)}`, { method: "DELETE" }),
+ /** Benchmark this Mac (Kokon's Mac engine); progress also arrives as `mac_bench` events. */
+ macBench: () => call<MacBenchState>("/mac-engine/bench"),
+ /** `quick`: one image per run instead of two. */
+ startMacBench: (quick = false) => call<MacBenchState>("/mac-engine/bench", { method: "POST", body: json({ quick }) }),
+ cancelMacBench: () => call<MacBenchState>("/mac-engine/bench/cancel", { method: "POST" }),
+ clearMacBench: () => call<MacBenchState>("/mac-engine/bench", { method: "DELETE" }),
installStatus: () => call<InstallStatus>("/setup/install"),
cancelInstall: () => call<InstallStatus>("/setup/install/cancel", { method: "POST" }),
config: () => call<AppConfig>("/config"),
diff --git a/src/lib/logic.test.ts b/src/lib/logic.test.ts
index 2a1663b..fe56993 100644
--- a/src/lib/logic.test.ts
+++ b/src/lib/logic.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import {
+ macBenchProgress,
activeLoras, activeOverrides, buildRequest, composing, editing, reviewRequest, wantsPromptReview, toggleLora, MAX_LORAS, jobPercent, compareBase, composerFromRecord, enhancerApplies, diffPixels, emptyComposer, expansionPixels, expansionPreset, jobLabel, jobSecondsLeft, lutInfo, moveRef, needsPrompt, normalizeQuality, persistentAdvanced, pipelineSummary,
planPipeline, remainingSeconds, sizeForWidth, timeAgo, upscaleRequest, upscaleTargets, versionLabels, type JobClock, type Ref,
neighbourAfterRemoval, pageOutdated, previewIndex, starPromptDue, STAR_PROMPT_AFTER, formatBytes, formatDuration, installItemShort, installItemText, installProgress, installStep, installTimeLeft, timelineLinks, undoTarget, aspectLabel, parseRatio, sizeForRatio, expandToRatio, expandToSize, arcLayout,
@@ -610,3 +611,19 @@ describe("opening a project in a browser", () => {
expect(goneVersions(items, { generations: {}, inputs: {} }, []).size).toBe(0);
});
});
+
+describe("macBenchProgress", () => {
+ const started_at = "2026-10-26T10:00:00Z";
+ const t0 = Date.parse(started_at);
+ it("shows the step, the run and the minutes", () => {
+ const p = macBenchProgress({ state: "running", k: 2, n: 7, label: "default (paths above): accuracy at 512²", started_at, quick: false }, t0 + 185_000);
+ expect(p).toEqual({ frac: 1 / 7, text: "Step 2 of 7 · Default: accuracy at 512² · 3 min" });
+ });
+ it("starts empty before the first step", () => {
+ expect(macBenchProgress({ state: "running", k: 0, n: 0, label: "Starting", started_at, quick: true }, t0)).toEqual({ frac: 0, text: "Starting · 0 min" });
+ });
+ it("is nothing when not running", () => {
+ expect(macBenchProgress({ state: "idle" }, t0)).toBeNull();
+ expect(macBenchProgress({ state: "done", report: "r", finished_at: started_at, quick: false }, t0)).toBeNull();
+ });
+});
diff --git a/src/lib/logic.ts b/src/lib/logic.ts
index cdab3d4..7558e04 100644
--- a/src/lib/logic.ts
+++ b/src/lib/logic.ts
@@ -1,6 +1,6 @@
// Pure UI logic (unit-tested in logic.test.ts).
-import type { Advanced, GenerationRecord, GenerationRequest, InpaintAction, InputRecord, InstallItem, JobView, LoraItem, LutInfo, Mode, OutpaintSpec, Plan, Quality, ResolutionMode, Size } from "./types";
+import type { Advanced, GenerationRecord, GenerationRequest, InpaintAction, InputRecord, InstallItem, JobView, LoraItem, LutInfo, MacBenchState, Mode, OutpaintSpec, Plan, Quality, ResolutionMode, Size } from "./types";
export interface Ref {
key: string;
@@ -642,6 +642,18 @@ export function formatBytes(n: number): string {
return `${Math.max(0, Math.round(n / 1e3))} KB`;
}
+/** Benchmark this Mac while it runs: the bar's fill and the line under it ("Step 2 of 7 · Default: accuracy at
+ * 512² · 3 min"). The engine names a run by the setting it changes; its first run is the default paths. */
+export function macBenchProgress(b: MacBenchState, now: number): { frac: number; text: string } | null {
+ if (b.state !== "running") return null;
+ const minutes = Math.max(0, Math.floor((now - Date.parse(b.started_at)) / 60000));
+ const elapsed = Number.isFinite(minutes) ? ` · ${minutes} min` : "";
+ if (b.n <= 0) return { frac: 0, text: `Starting${elapsed}` };
+ const label = b.label.replace(/^default \(paths above\)/, "Default");
+ // A step is done when the next one starts: k − 1 of n.
+ return { frac: (b.k - 1) / b.n, text: `Step ${b.k} of ${b.n}${label ? ` · ${label}` : ""}${elapsed}` };
+}
+
/** Overall download progress over the files that were not installed already. */
export function installProgress(items: InstallItem[]): { received: number; total: number; frac: number } {
const todo = items.filter((i) => i.state !== "present");
diff --git a/src/lib/store.ts b/src/lib/store.ts
index 860d2f1..8abd1c5 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -10,7 +10,7 @@ import { useSyncExternalStore } from "react";
import { markFresh } from "../components/Cocoon";
import { api, ApiError, setPrivateInputs, subscribe, urls } from "./api";
import { activeLoras, buildRequest, composing, emptyComposer, goneVersions, needsPrompt, newKey, pageOutdated, persistentAdvanced, refFromGen, refFromInput, reviewRequest, stageFitsPreview, starPromptDue, timelineLinks, undoTarget, versionLabels, wantsPromptReview, type CompareMode, type Composer, type Ref } from "./logic";
-import type { AppErrorBody, GenerationRecord, GenerationRequest, InputRecord, JobView, LoraItem, ServerState, StatusResponse } from "./types";
+import type { AppErrorBody, GenerationRecord, GenerationRequest, InputRecord, JobView, LoraItem, MacBenchState, ServerState, StatusResponse } from "./types";
export type Overlay = null | "gallery" | "settings" | "inpaint" | "expand" | "welcome" | "whats-new" | "prompt-tips" | "shortcuts";
@@ -74,6 +74,8 @@ export interface State {
compareUpscalers: boolean;
toasts: Toast[];
galleryVersion: number;
+ /** Benchmark this Mac: null until Settings asks the service. */
+ macBench: MacBenchState | null;
needsSetup: boolean;
/** Setup opens on "Use models I already have" or on the official download (Settings → Models). */
setupMode: "own" | "official" | null;
@@ -406,6 +408,7 @@ let state: State = {
compareUpscalers: false,
toasts: [],
galleryVersion: 0,
+ macBench: null,
needsSetup: false,
setupMode: null,
compare: "off",
@@ -562,6 +565,7 @@ export function startEvents() {
}
else if (ev.type === "gallery") setState((s) => ({ galleryVersion: s.galleryVersion + 1 }));
else if (ev.type === "projects") onProjectEvent(ev.id, ev.rev, ev.deleted);
+ else if (ev.type === "mac_bench") setState({ macBench: ev.bench });
},
(ok) => {
setState({ connected: ok });
diff --git a/src/lib/types.ts b/src/lib/types.ts
index a5d559c..322ff44 100644
--- a/src/lib/types.ts
+++ b/src/lib/types.ts
@@ -435,8 +435,17 @@ export interface HardwareReport {
issues_url: string;
}
+/** Settings → Performance → Benchmark this Mac (`qls_core::mac_bench::BenchState`). */
+export type MacBenchState =
+ | { state: "idle" }
+ /** Step `k` of `n`; `n` is 0 until the engine prints its first step. */
+ | { state: "running"; k: number; n: number; label: string; started_at: string; quick: boolean }
+ | { state: "done"; report: string; finished_at: string; quick: boolean }
+ | { state: "failed"; error: string; log: string };
+
export type ServiceEvent =
| { type: "job"; job: JobView }
| { type: "server"; state: ServerState; owned: boolean; error: AppErrorBody | null }
| { type: "gallery"; id: string; change: "added" | "updated" | "deleted" }
- | { type: "projects"; id: string; rev: number; deleted: boolean };
+ | { type: "projects"; id: string; rev: number; deleted: boolean }
+ | { type: "mac_bench"; bench: MacBenchState };