Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
desktop shell: logs, crash log, --save-logs; the window blocks startViewTransition; one app version (Cargo.toml, 0.2.0-beta); banner while the bundled engine unpacks; diagnostics include the desktop logs
Niko12211b003bd406df
diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 2076d0af2..a539619b1 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -1,7 +1,7 @@{"name": "strata-desktop","productName": "Strata",- "version": "0.1.0",+ "version": "0.2.0-beta","private": true,"description": "Strata Desktop - local AI, tuned to one model.","scripts": {diff --git a/apps/desktop/scripts/make-dmg.sh b/apps/desktop/scripts/make-dmg.shindex 6bcc67dc1..909579f87 100755--- a/apps/desktop/scripts/make-dmg.sh+++ b/apps/desktop/scripts/make-dmg.sh@@ -15,7 +15,8 @@ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"DESKTOP="$(cd "$HERE/.." && pwd)"BUNDLE="$DESKTOP/src-tauri/target/release/bundle"APP="$BUNDLE/macos/Strata.app"-OUT="${1:-$BUNDLE/dmg/Strata_0.1.0_aarch64.dmg}"+VERSION="$(grep -m1 '^version = ' "$DESKTOP/src-tauri/Cargo.toml" | cut -d'"' -f2)" # the one place the app version is written+OUT="${1:-$BUNDLE/dmg/Strata_${VERSION}_aarch64.dmg}"if [ ! -d "$APP" ]; thenecho "error: $APP does not exist; run 'cargo tauri build --bundles app' first" >&2@@ -45,7 +46,7 @@ rm -f "$OUT"# --skip-jenkins: no Finder AppleScript. Everything else is the same code path Tauri uses."$SCRIPT" \- --volname "Strata 0.1.0" \+ --volname "Strata $VERSION" \--volicon "$BUNDLE/macos/Strata.app/Contents/Resources/Strata.icns" \--app-drop-link 400 200 \--skip-jenkins \diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex ebd2f4769..fa2c738a8 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "strata-desktop"-version = "0.1.0"+version = "0.2.0-beta"description = "Strata Desktop — local AI, tuned to one model."edition = "2021"rust-version = "1.77"diff --git a/apps/desktop/src-tauri/src/desktoplog.rs b/apps/desktop/src-tauri/src/desktoplog.rsnew file mode 100644index 000000000..5d95b6e4e--- /dev/null+++ b/apps/desktop/src-tauri/src/desktoplog.rs@@ -0,0 +1,378 @@+//! The desktop shell's own logs (Linux): what the host and the window process printed, a crash log when the window dies, and+//! `--save-logs`, which collects everything a person can send us without the window (the window is what may be crashing).+//!+//! Files, in `<data>/logs` (`$XDG_DATA_HOME/strata/logs`, usually `~/.local/share/strata/logs`; the newest ten of each kind are kept):+//! desktop-<UTC time>.log one per start: the shell's lines, and every line the host (`[host]`) and the window (`[window]`) printed+//! desktop-crash-<UTC time>.log written when the window process dies without being closed: what happened in plain words, the system,+//! the graphics session, the last lines of the window and of the host, and a backtrace when the system keeps one+//!+//! `strata-desktop --save-logs` puts the newest crash log, the tails of the newest shell logs and the engine server logs into one text file+//! in the Downloads folder. The same pieces go into Settings > Engine > Diagnostics > Save logs (the host reads this folder).++use std::collections::VecDeque;+use std::io::{BufRead, BufReader, Read, Write};+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex};+use std::time::{Duration, SystemTime, UNIX_EPOCH};++const KEEP: usize = 10;+const RING_LINES: usize = 300;++/// `<data>/` : where Strata keeps its engine, runtime and logs on this system.+pub fn data_dir() -> PathBuf {+ if let Some(dir) = std::env::var_os("STRATA_DESKTOP_DATA_DIR") {+ return PathBuf::from(dir);+ }+ let base = std::env::var_os("XDG_DATA_HOME")+ .map(PathBuf::from)+ .filter(|p| p.is_absolute())+ .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local").join("share")))+ .unwrap_or_else(std::env::temp_dir);+ base.join("strata")+}++pub fn logs_dir() -> PathBuf {+ data_dir().join("logs")+}++/// "20261018-014503" in UTC, from the system clock (no time crate).+pub fn stamp(now: SystemTime) -> String {+ let secs = now.duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) as i64;+ let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));+ // civil-from-days (Howard Hinnant), proleptic Gregorian+ let z = days + 719_468;+ let era = z.div_euclid(146_097);+ let doe = z.rem_euclid(146_097);+ let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;+ let y = yoe + era * 400;+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+ let mp = (5 * doy + 2) / 153;+ let d = doy - (153 * mp + 2) / 5 + 1;+ let m = if mp < 10 { mp + 3 } else { mp - 9 };+ let y = if m <= 2 { y + 1 } else { y };+ format!("{y:04}{m:02}{d:02}-{:02}{:02}{:02}", rem / 3600, rem % 3600 / 60, rem % 60)+}++/// Keep the newest `KEEP` files whose name starts with `prefix` and ends with `.log` (names sort by their time stamp).+fn prune(dir: &Path, prefix: &str, skip_crash: bool) {+ let Ok(read) = std::fs::read_dir(dir) else { return };+ let mut names: Vec<String> = read+ .flatten()+ .filter_map(|e| e.file_name().into_string().ok())+ .filter(|n| n.starts_with(prefix) && n.ends_with(".log") && !(skip_crash && n.starts_with("desktop-crash-")))+ .collect();+ names.sort();+ while names.len() > KEEP {+ let _ = std::fs::remove_file(dir.join(names.remove(0)));+ }+}++/// The last lines a process printed (kept in memory for the crash log).+#[derive(Clone, Default)]+pub struct Ring(Arc<Mutex<VecDeque<String>>>);++impl Ring {+ pub fn push(&self, line: String) {+ let mut q = self.0.lock().unwrap();+ if q.len() >= RING_LINES {+ q.pop_front();+ }+ q.push_back(line);+ }+ pub fn tail(&self, n: usize) -> Vec<String> {+ let q = self.0.lock().unwrap();+ q.iter().skip(q.len().saturating_sub(n)).cloned().collect()+ }+}++/// This run's log file, shared by the shell and the threads that copy the children's output.+#[derive(Clone)]+pub struct Log {+ file: Arc<Mutex<Option<std::fs::File>>>,+ pub path: Option<PathBuf>,+}++impl Log {+ pub fn open() -> Log {+ let dir = logs_dir();+ let _ = std::fs::create_dir_all(&dir);+ prune(&dir, "desktop-", true);+ prune(&dir, "desktop-crash-", false);+ let path = dir.join(format!("desktop-{}.log", stamp(SystemTime::now())));+ let file = std::fs::OpenOptions::new().create(true).append(true).open(&path).ok();+ let log = Log { file: Arc::new(Mutex::new(file)), path: Some(path) };+ log.line("shell", &format!("Strata desktop {} starting (pid {})", env!("CARGO_PKG_VERSION"), std::process::id()));+ log+ }+ /// A log that writes nowhere (tests).+ pub fn none() -> Log {+ Log { file: Arc::new(Mutex::new(None)), path: None }+ }+ pub fn line(&self, who: &str, text: &str) {+ if let Some(f) = self.file.lock().unwrap().as_mut() {+ let _ = writeln!(f, "[{who}] {text}");+ }+ }+}++/// Print what the shell says (terminal and log).+pub fn say(log: &Log, text: &str) {+ eprintln!("[strata] {text}");+ log.line("shell", text);+}++/// Copy a child's output line by line: to our own stdout/stderr (as before), to the log file, and into the ring.+pub fn tee<R: Read + Send + 'static>(reader: R, who: &'static str, to_stderr: bool, ring: Ring, log: Log) {+ std::thread::spawn(move || {+ let mut r = BufReader::new(reader);+ let mut buf = Vec::new();+ loop {+ buf.clear();+ match r.read_until(b'\n', &mut buf) {+ Ok(0) | Err(_) => break,+ Ok(_) => {+ let text = String::from_utf8_lossy(&buf);+ let text = text.trim_end_matches(['\r', '\n']);+ if to_stderr {+ eprintln!("{text}");+ } else {+ println!("{text}");+ }+ ring.push(text.to_string());+ log.line(who, text);+ }+ }+ }+ });+}++fn first_line(path: &str) -> Option<String> {+ std::fs::read_to_string(path).ok().and_then(|t| t.lines().next().map(str::to_string))+}++fn os_pretty_name() -> String {+ std::fs::read_to_string("/etc/os-release")+ .ok()+ .and_then(|t| t.lines().find_map(|l| l.strip_prefix("PRETTY_NAME=").map(|v| v.trim_matches('"').to_string())))+ .unwrap_or_else(|| "unknown".into())+}++/// The environment variables that decide how the window draws; nothing private.+fn graphics_environment() -> Vec<String> {+ const NAMES: &[&str] = &[+ "XDG_SESSION_TYPE", "XDG_CURRENT_DESKTOP", "DESKTOP_SESSION", "DISPLAY", "WAYLAND_DISPLAY", "GDK_BACKEND", "GTK_THEME",+ "WEBKIT_DISABLE_DMABUF_RENDERER", "WEBKIT_DISABLE_COMPOSITING_MODE", "WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS", "LIBGL_ALWAYS_SOFTWARE",+ "GALLIUM_DRIVER", "__GLX_VENDOR_LIBRARY_NAME", "__NV_PRIME_RENDER_OFFLOAD", "MESA_LOADER_DRIVER_OVERRIDE", "APPIMAGE", "APPDIR",+ ];+ NAMES.iter().filter_map(|n| std::env::var(n).ok().map(|v| format!(" {n}={v}"))).collect()+}++/// The WebKitGTK files inside the AppImage (the version is in the file name or its link target).+fn bundled_webkit() -> String {+ let Some(appdir) = std::env::var_os("APPDIR") else { return "not an AppImage (the system's WebKitGTK is used)".into() };+ let lib = PathBuf::from(appdir).join("usr").join("lib");+ let mut found = Vec::new();+ if let Ok(read) = std::fs::read_dir(&lib) {+ for e in read.flatten() {+ let n = e.file_name().to_string_lossy().into_owned();+ if n.starts_with("libwebkit2gtk-4.1.so") || n.starts_with("libjavascriptcoregtk-4.1.so") {+ let target = std::fs::read_link(e.path()).map(|t| format!(" -> {}", t.display())).unwrap_or_default();+ found.push(format!("{n}{target}"));+ }+ }+ }+ found.sort();+ if found.is_empty() { "no WebKitGTK file found in the AppImage".into() } else { found.join("; ") }+}++/// A backtrace of the dead window process when the system keeps one (systemd-coredump); None when it does not.+fn system_backtrace(pid: u32) -> Option<String> {+ let mut child = std::process::Command::new("coredumpctl")+ .args(["info", &pid.to_string(), "--no-pager"])+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::null())+ .spawn()+ .ok()?;+ let deadline = std::time::Instant::now() + Duration::from_secs(4);+ loop {+ match child.try_wait() {+ Ok(Some(_)) => break,+ Ok(None) if std::time::Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),+ _ => {+ let _ = child.kill();+ let _ = child.wait();+ return None;+ }+ }+ }+ let mut out = String::new();+ child.stdout.take()?.read_to_string(&mut out).ok()?;+ let out = out.trim().to_string();+ if out.is_empty() || out.contains("No coredumps found") { None } else { Some(out) }+}++/// What the crash log says, as text (so it can be tested without a crash).+#[allow(clippy::too_many_arguments)]+pub fn crash_report(what: &str, pid: u32, window_tail: &[String], host_tail: &[String], backtrace: Option<&str>, app_version: &str, log_path: Option<&Path>) -> String {+ let mut t = String::new();+ t.push_str("Strata app window crash\n=======================\n\n");+ t.push_str(&format!("When: {} UTC\n", stamp(SystemTime::now())));+ t.push_str(&format!("What: the app window process (pid {pid}) stopped without being closed: {what}\n"));+ t.push_str("Effect: Strata kept running and opened in the web browser instead (browser mode); nothing was lost.\n");+ t.push_str(&format!("App: Strata desktop {app_version}\n"));+ t.push_str(&format!("System: {} / {}\n", os_pretty_name(), first_line("/proc/version").unwrap_or_default()));+ if let Some(v) = first_line("/proc/driver/nvidia/version") {+ t.push_str(&format!("NVIDIA: {v}\n"));+ }+ t.push_str(&format!("WebKit: {}\n", bundled_webkit()));+ t.push_str("Graphics session:\n");+ for l in graphics_environment() {+ t.push_str(&l);+ t.push('\n');+ }+ if let Some(p) = log_path {+ t.push_str(&format!("\nFull log of this run: {}\n", p.display()));+ }+ t.push_str("\n== Backtrace ==\n");+ match backtrace {+ Some(b) => t.push_str(b),+ None => t.push_str("none kept by this system (no systemd-coredump). To get one: run coredumpctl gdb or start the AppImage under gdb --args ./<file>.AppImage --appimage-extract-and-run --window-child and type bt after the crash.\n"),+ }+ t.push_str("\n\n== Last lines of the window process ==\n");+ for l in window_tail {+ t.push_str(l);+ t.push('\n');+ }+ t.push_str("\n== Last lines of the host ==\n");+ for l in host_tail {+ t.push_str(l);+ t.push('\n');+ }+ t+}++/// Write the crash log; returns where it is.+pub fn write_crash_log(what: &str, pid: u32, window: &Ring, host: &Ring, log: &Log) -> Option<PathBuf> {+ let dir = logs_dir();+ std::fs::create_dir_all(&dir).ok()?;+ prune(&dir, "desktop-crash-", false);+ let path = dir.join(format!("desktop-crash-{}.log", stamp(SystemTime::now())));+ let text = crash_report(what, pid, &window.tail(120), &host.tail(80), system_backtrace(pid).as_deref(), env!("CARGO_PKG_VERSION"), log.path.as_deref());+ std::fs::write(&path, text).ok()?;+ Some(path)+}++fn newest(dir: &Path, prefix: &str, crash: bool) -> Vec<PathBuf> {+ let Ok(read) = std::fs::read_dir(dir) else { return Vec::new() };+ let mut names: Vec<String> = read+ .flatten()+ .filter_map(|e| e.file_name().into_string().ok())+ .filter(|n| n.starts_with(prefix) && n.ends_with(".log") && (n.starts_with("desktop-crash-") == crash))+ .collect();+ names.sort();+ names.reverse();+ names.into_iter().map(|n| dir.join(n)).collect()+}++fn tail_lines(path: &Path, n: usize) -> String {+ let text = std::fs::read_to_string(path).unwrap_or_default();+ let lines: Vec<&str> = text.lines().collect();+ lines[lines.len().saturating_sub(n)..].join("\n")+}++/// `--save-logs`: one text file with what we need to look at a crash. Returns its path.+pub fn save_logs(out_dir: &Path) -> std::io::Result<PathBuf> {+ std::fs::create_dir_all(out_dir)?;+ let path = out_dir.join(format!("strata-logs-{}.txt", stamp(SystemTime::now())));+ let mut t = String::new();+ t.push_str(&format!("Strata desktop logs {} UTC\nApp {}\nSystem: {} / {}\n", stamp(SystemTime::now()), env!("CARGO_PKG_VERSION"), os_pretty_name(), first_line("/proc/version").unwrap_or_default()));+ if let Some(v) = first_line("/proc/driver/nvidia/version") {+ t.push_str(&format!("NVIDIA: {v}\n"));+ }+ t.push_str(&format!("WebKit: {}\nGraphics session:\n{}\n", bundled_webkit(), graphics_environment().join("\n")));+ let dir = logs_dir();+ let crashes = newest(&dir, "desktop-crash-", true);+ t.push_str(&format!("\n\n##### Window crash logs ({} found, newest first, at most 3 shown)\n", crashes.len()));+ for p in crashes.iter().take(3) {+ t.push_str(&format!("\n----- {}\n{}\n", p.display(), std::fs::read_to_string(p).unwrap_or_default()));+ }+ let runs = newest(&dir, "desktop-", false);+ t.push_str(&format!("\n\n##### Shell logs ({} found, last 300 lines of the newest 2)\n", runs.len()));+ for p in runs.iter().take(2) {+ t.push_str(&format!("\n----- {}\n{}\n", p.display(), tail_lines(p, 300)));+ }+ let runtime = data_dir().join("runtime");+ if let Ok(read) = std::fs::read_dir(&runtime) {+ let mut files: Vec<PathBuf> = read.flatten().map(|e| e.path()).filter(|p| p.to_string_lossy().ends_with(".server.log")).collect();+ files.sort();+ t.push_str(&format!("\n\n##### Engine server logs ({} found, last 200 lines each)\n", files.len()));+ for p in files {+ t.push_str(&format!("\n----- {}\n{}\n", p.display(), tail_lines(&p, 200)));+ }+ }+ std::fs::write(&path, t)?;+ Ok(path)+}++pub fn downloads_dir() -> PathBuf {+ std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Downloads")).unwrap_or_else(std::env::temp_dir)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_time_stamp_is_utc_civil_time() {+ assert_eq!(stamp(UNIX_EPOCH), "19700101-000000");+ assert_eq!(stamp(UNIX_EPOCH + Duration::from_secs(1_800_000_000)), "20270115-080000");+ assert_eq!(stamp(UNIX_EPOCH + Duration::from_secs(1_760_751_903)), "20251018-014503");+ }++ #[test]+ fn the_ring_keeps_the_last_lines() {+ let ring = Ring::default();+ for i in 0..(RING_LINES + 50) {+ ring.push(format!("line {i}"));+ }+ let tail = ring.tail(3);+ assert_eq!(tail, vec![format!("line {}", RING_LINES + 47), format!("line {}", RING_LINES + 48), format!("line {}", RING_LINES + 49)]);+ assert_eq!(ring.tail(10_000).len(), RING_LINES);+ }++ #[test]+ fn the_crash_report_says_what_happened_in_plain_words_and_has_the_tails() {+ let text = crash_report("signal 11 (segmentation fault)", 4242, &["window said a".into(), "window said b".into()], &["host said x".into()], None, "0.2.0-beta", Some(Path::new("/x/desktop-1.log")));+ for needle in ["signal 11 (segmentation fault)", "pid 4242", "opened in the web browser instead", "0.2.0-beta", "window said b", "host said x", "/x/desktop-1.log", "none kept by this system"] {+ assert!(text.contains(needle), "{needle}");+ }+ let with = crash_report("x", 1, &[], &[], Some("#0 AcceleratedBackingStore::update"), "1", None);+ assert!(with.contains("#0 AcceleratedBackingStore::update") && !with.contains("none kept"));+ }++ #[test]+ fn logs_are_pruned_and_saved_into_one_file() {+ let dir = std::env::temp_dir().join(format!("strata-desktoplog-test-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::env::set_var("STRATA_DESKTOP_DATA_DIR", &dir);+ let logs = logs_dir();+ std::fs::create_dir_all(&logs).unwrap();+ for i in 0..14 {+ std::fs::write(logs.join(format!("desktop-20260101-0000{i:02}.log")), format!("run {i}\n")).unwrap();+ std::fs::write(logs.join(format!("desktop-crash-20260101-0000{i:02}.log")), format!("crash {i}\n")).unwrap();+ }+ prune(&logs, "desktop-", true);+ prune(&logs, "desktop-crash-", false);+ assert_eq!(newest(&logs, "desktop-", false).len(), KEEP);+ assert_eq!(newest(&logs, "desktop-", true).len(), KEEP);+ assert!(newest(&logs, "desktop-", false)[0].to_string_lossy().ends_with("000013.log"), "the newest are kept");+ std::fs::create_dir_all(dir.join("runtime")).unwrap();+ std::fs::write(dir.join("runtime").join("app-1.server.log"), "engine line\n").unwrap();+ let saved = save_logs(&dir.join("out")).unwrap();+ let text = std::fs::read_to_string(saved).unwrap();+ assert!(text.contains("crash 13") && text.contains("run 13") && text.contains("engine line"));+ std::env::remove_var("STRATA_DESKTOP_DATA_DIR");+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rsindex 7c0e45cb7..80d87c1dc 100644--- a/apps/desktop/src-tauri/src/main.rs+++ b/apps/desktop/src-tauri/src/main.rs@@ -39,6 +39,8 @@ use tauri::{Manager, WebviewUrl, WebviewWindowBuilder};mod updater;#[cfg(target_os = "linux")]+mod desktoplog;+#[cfg(target_os = "linux")]mod supervisor;/// The kill-on-close Job Object that holds everything this app starts (Windows). Its only handle is this process's,@@ -874,11 +876,16 @@ fn run_embedded() {fn open_window(app: &tauri::App, port: u16) -> Result<(), Box<dyn std::error::Error>> {let origin = format!("http://127.0.0.1:{port}");let url = origin.parse().expect("a valid loopback URL");- WebviewWindowBuilder::new(app, "main", WebviewUrl::External(url))- .title("Strata")- .inner_size(1440.0, 920.0)- .min_inner_size(900.0, 600.0)- .build()?;+ let builder = WebviewWindowBuilder::new(app, "main", WebviewUrl::External(url)).title("Strata").inner_size(1440.0, 920.0).min_inner_size(900.0, 600.0);+ // WebKitGTK (2.50 to 2.52 at least) dereferences a null pointer in AcceleratedBackingStore::update in its UI process when a page calls+ // document.startViewTransition (the web process asks the UI process to enter accelerated compositing, and the backing store is not+ // there). The page itself does not call it on that engine (apps/host/src/lib/router.ts), and this line keeps any other script from doing+ // it either: the API is simply absent, as in older WebKit versions.+ #[cfg(target_os = "linux")]+ let builder = builder.initialization_script(+ "try { Object.defineProperty(Document.prototype, 'startViewTransition', { value: undefined, configurable: true, writable: true }); } catch (e) {}",+ );+ builder.build()?;Ok(())}diff --git a/apps/desktop/src-tauri/src/supervisor.rs b/apps/desktop/src-tauri/src/supervisor.rsindex 46ced3891..d1983eb67 100644--- a/apps/desktop/src-tauri/src/supervisor.rs+++ b/apps/desktop/src-tauri/src/supervisor.rs@@ -22,6 +22,8 @@ use std::path::PathBuf;use std::process::{Child, Command, ExitStatus, Stdio};use std::time::{Duration, Instant};+use crate::desktoplog::{self, say, Log, Ring};+pub const BROWSER_NOTICE: &str = "Strata opened in your browser because the app window couldn't start on this computer.";/// What the command line asked for.@@ -33,6 +35,8 @@ pub struct Options {pub quit: bool,/// `--window-child`: the window process (started by the shell, not by a person).pub window_child: bool,+ /// `--save-logs`: collect the logs into one file in Downloads and leave.+ pub save_logs: bool,pub help: bool,}@@ -43,6 +47,7 @@ pub fn parse_args(args: &[String], ui_env: Option<&str>) -> Options {"--browser" => o.browser = true,"--quit" => o.quit = true,"--window-child" => o.window_child = true,+ "--save-logs" => o.save_logs = true,"--help" | "-h" => o.help = true,_ => {}}@@ -54,6 +59,7 @@ pub const HELP: &str = "Strata\n\(no option) open the Strata app window\n\--browser open Strata in your default browser instead of the app window (same as STRATA_UI=browser)\n\--quit stop a running Strata (its engine too) and leave\n\+ --save-logs put the logs (including the log of an app window crash) into one file in your Downloads folder, to send to us\n\Closing the browser tab does not stop Strata in browser mode: use Quit Strata in the menu, or --quit.\n";/// The command a person types to run this app again, for the messages ("run: Strata.AppImage --quit").@@ -211,6 +217,8 @@ pub fn describe_exit(status: &ExitStatus) -> String {}}match status.code() {+ Some(127) => "exit code 127: a program file it needs is missing".into(),+ Some(126) => "exit code 126: a program file it needs could not be run".into(),Some(c) => format!("exit code {c}"),None => "ended without a code".into(),}@@ -279,12 +287,50 @@ fn join_running(s: &Session, browser: bool) -> i32 {}}+/// Start a child with its output copied to the terminal, the log and a ring (for the crash log).+fn spawn_logged(cmd: &mut Command, who: &'static str, ring: &Ring, log: &Log) -> std::io::Result<Child> {+ cmd.stdout(Stdio::piped()).stderr(Stdio::piped());+ let mut child = cmd.spawn()?;+ if let Some(out) = child.stdout.take() {+ desktoplog::tee(out, who, false, ring.clone(), log.clone());+ }+ if let Some(err) = child.stderr.take() {+ desktoplog::tee(err, who, true, ring.clone(), log.clone());+ }+ Ok(child)+}++/// The window process died without being closed: say so in plain words, write the crash log, move everyone to the browser.+fn window_failed(why: &str, window_pid: u32, window_ring: &Ring, host_ring: &Ring, log: &Log, port: u16, token: &str) {+ say(log, &format!("The app window crashed ({why})."));+ // let the copy threads read the last lines the dead process wrote+ std::thread::sleep(Duration::from_millis(300));+ match desktoplog::write_crash_log(why, window_pid, window_ring, host_ring, log) {+ Some(path) => say(log, &format!("The crash log is {}. To collect the logs for us: {} --save-logs", path.display(), command_name())),+ None => say(log, &format!("The crash log could not be written. To collect the logs for us: {} --save-logs", command_name())),+ }+ say(log, BROWSER_NOTICE);+ switch_host_to_browser(port, token, "window-failed", BROWSER_NOTICE);+}+/// The shell. Returns the process exit code.pub fn run(opts: &Options) -> i32 {if opts.help {print!("{HELP}");return 0;}+ if opts.save_logs {+ return match desktoplog::save_logs(&desktoplog::downloads_dir()) {+ Ok(path) => {+ println!("Saved to {}. Please send this file to us.", path.display());+ 0+ }+ Err(e) => {+ eprintln!("[strata] could not save the logs: {e}");+ 1+ }+ };+ }if opts.quit {return quit_running();}@@ -292,12 +338,14 @@ pub fn run(opts: &Options) -> i32 {return join_running(&s, opts.browser);}+ let log = Log::open();+ let (host_ring, window_ring) = (Ring::default(), Ring::default());let exe = std::env::current_exe().unwrap_or_default();let res = crate::packaged_resource_dir(&exe).unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")));let port = match crate::pick_stable_port() {Ok(p) => p,Err(e) => {- eprintln!("[strata] {e}");+ say(&log, &e);return 1;}};@@ -306,7 +354,7 @@ pub fn run(opts: &Options) -> i32 {let mut cmd = match crate::host_command(&res, port, &token) {Ok(c) => c,Err(e) => {- eprintln!("[strata] {e}");+ say(&log, &e);return 1;}};@@ -314,10 +362,10 @@ pub fn run(opts: &Options) -> i32 {if opts.browser {cmd.env("STRATA_UI_REASON", "chosen");}- let mut host = match cmd.spawn() {+ let mut host = match spawn_logged(&mut cmd, "host", &host_ring, &log) {Ok(c) => c,Err(e) => {- eprintln!("[strata] could not start the App Host: {e}");+ say(&log, &format!("could not start the App Host: {e}"));return 1;}};@@ -326,7 +374,7 @@ pub fn run(opts: &Options) -> i32 {_ => None,});if let Err(e) = health {- eprintln!("[strata] {e}");+ say(&log, &e);let _ = host.kill();let _ = host.wait();return 1;@@ -334,19 +382,20 @@ pub fn run(opts: &Options) -> i32 {let me = std::process::id();write_session(&Session { pid: me, port, token: token.clone(), mode: mode.into() });- let mut in_browser = opts.browser;let mut window: Option<Child> = None;- if in_browser {- eprintln!("[strata] {}", browser_chosen_line(port));+ if opts.browser {+ say(&log, &browser_chosen_line(port));switch_host_to_browser(port, &token, "chosen", "");} else {- match spawn_window(port, &token) {+ let started = std::env::current_exe().and_then(|exe| {+ let mut c = Command::new(exe);+ c.arg("--window-child").env("STRATA_WINDOW_PORT", port.to_string()).env("STRATA_SHUTDOWN_TOKEN", &token).stdin(Stdio::null());+ spawn_logged(&mut c, "window", &window_ring, &log)+ });+ match started {Ok(c) => window = Some(c),Err(e) => {- eprintln!("[strata] could not start the app window ({e}).");- eprintln!("[strata] {BROWSER_NOTICE}");- in_browser = true;- switch_host_to_browser(port, &token, "window-failed", BROWSER_NOTICE);+ window_failed(&format!("it could not be started: {e}"), 0, &window_ring, &host_ring, &log, port, &token);write_session(&Session { pid: me, port, token: token.clone(), mode: "browser".into() });}}@@ -360,24 +409,27 @@ pub fn run(opts: &Options) -> i32 {let _ = w.kill();let _ = w.wait();}- break if status.success() { 0 } else { eprintln!("[strata] The App Host stopped ({}).", describe_exit(&status)); 1 };+ if status.success() {+ log.line("shell", "the host stopped (Quit Strata or the window was closed)");+ break 0;+ }+ say(&log, &format!("The App Host stopped ({}). The last lines it printed are in {}.", describe_exit(&status), log.path.as_ref().map(|p| p.display().to_string()).unwrap_or_default()));+ break 1;}let Some(w) = window.as_mut() else { continue };+ let window_pid = w.id();let Ok(Some(status)) = w.try_wait() else { continue };window = None;if status.success() {// the person closed the window: stop the host and the engines this app started, as before+ log.line("shell", "the window was closed: stopping the host");crate::stop_host_child(&mut host, Some(port), Some(&token));break 0;}// The window stopped without being closed: keep Strata running and move to the browser.- eprintln!("[strata] The app window stopped unexpectedly ({}).", describe_exit(&status));- eprintln!("[strata] {BROWSER_NOTICE}");- in_browser = true;- switch_host_to_browser(port, &token, "window-failed", BROWSER_NOTICE);+ window_failed(&describe_exit(&status), window_pid, &window_ring, &host_ring, &log, port, &token);write_session(&Session { pid: me, port, token: token.clone(), mode: "browser".into() });};- let _ = in_browser;remove_session(me);code}@@ -399,6 +451,7 @@ mod tests {assert!(!parse_args(&args(&[]), Some("window")).browser);assert!(parse_args(&args(&["--quit"]), None).quit);assert!(parse_args(&args(&["--window-child"]), None).window_child);+ assert!(parse_args(&args(&["--save-logs"]), None).save_logs);assert!(parse_args(&args(&["-h"]), None).help);// anything else (a file the desktop hands over, an AppImage option) is ignoredassert_eq!(parse_args(&args(&["--appimage-extract-and-run", "x.gguf"]), None), Options::default());diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.jsonindex 0d5c53956..c762d7369 100644--- a/apps/desktop/src-tauri/tauri.conf.json+++ b/apps/desktop/src-tauri/tauri.conf.json@@ -1,7 +1,6 @@{"$schema": "https://schema.tauri.app/config/2","productName": "Strata",- "version": "0.1.0","identifier": "ai.strata.desktop","build": {"frontendDist": "../../host/dist"diff --git a/apps/host/server/app-version.mjs b/apps/host/server/app-version.mjsnew file mode 100644index 000000000..ee915fafc--- /dev/null+++ b/apps/host/server/app-version.mjs@@ -0,0 +1,19 @@+/**+ * The app's version, from one place. The desktop shell reports its own (apps/desktop/src-tauri/Cargo.toml, which Tauri also uses for+ * the installer and file names) in STRATA_APP_VERSION. Outside the app, in a source checkout, the same file is read; otherwise 'dev'.+ */+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++const VERSION = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/;++export function appVersionFrom({ env = process.env, here }) {+ const given = String(env.STRATA_APP_VERSION ?? '').trim();+ if (VERSION.test(given)) return given;+ try {+ const toml = readFileSync(join(here, '..', '..', 'desktop', 'src-tauri', 'Cargo.toml'), 'utf8');+ const found = /^version\s*=\s*"([^"]+)"/m.exec(toml);+ if (found && VERSION.test(found[1])) return found[1];+ } catch { /* not a checkout */ }+ return 'dev';+}diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjsindex 888c337bc..8d07ea305 100644--- a/apps/host/server/index.mjs+++ b/apps/host/server/index.mjs@@ -58,6 +58,7 @@ import { createChatFolders, openFile, resolveChatFile, previewFile, rawFile, creimport { createLlmProxy, samplingFromExpert } from './agent/llm-shape.mjs';import { checkUpdates, checkComponentUpdates } from './updates.mjs';import { createAppUi } from './app-ui.mjs';+import { appVersionFrom } from './app-version.mjs';import { createImageModels } from './image-models.mjs';import { createRuntimeModels } from './runtime-models.mjs';import { createNativeControl } from './native-control.mjs';@@ -113,6 +114,8 @@ const control = createControl({ control: CONTROL });if (control && process.platform === 'win32' && !process.env.STRATA_NO_REPAIR_ACCESS) void control.repairAccess().catch(() => {});/* Which window shows the page (the app window or, when that cannot run, a browser tab) and what only the app window can do: app-ui.mjs. */const appUi = createAppUi({ shutdown: () => shutdown() });+/* The app's version has one source: the desktop shell passes it (STRATA_APP_VERSION, from apps/desktop/src-tauri/Cargo.toml). Outside the app it is read from the same file in a checkout, else 'dev'. */+function appVersion() { return appVersionFrom({ env: process.env, here: HERE }); }const appUpdater = appUi.updater;/* The engine that ships inside the installer is put in the components folder when this PC has none (or an older one); no network, hashes checked. The model list waits for it. */const bundledEngine = control && !process.env.STRATA_NO_BUNDLED_ENGINE@@ -214,7 +217,7 @@ const backend = await detectBackend({ force: true });console.log(`strata host · http://${HOST}:${PORT}`);console.log(`hardware · ${boot.accelerator.label} / ${boot.accelerator.backend} / ${boot.cpu.cores} cores / ${Math.round(boot.memory.totalGb)} GB`);-console.log(`inference · ${models.REAL ? backend.name : 'simulated (design iteration) — set STRATA_REAL_ENGINE=1 for a real engine'}`);+console.log(`inference · ${models.REAL ? (bundledEngineSettled ? backend.name : 'unpacking the bundled engine… (about a minute the first time)') : 'simulated (design iteration) — set STRATA_REAL_ENGINE=1 for a real engine'}`);console.log(`models dir · ${store.MODELS_DIR}`);console.log(`workspace · ${WORKSPACE}`);@@ -230,7 +233,7 @@ function setupState() {flowVersion: 2,completedAt: s.setup.completedAt,history: s.setup.history ?? [],- app: { version: '0.1.0', modelsDir: store.MODELS_DIR, dataDir: store.DATA_DIR },+ app: { version: appVersion(), modelsDir: store.MODELS_DIR, dataDir: store.DATA_DIR },};}@@ -929,6 +932,7 @@ async function api(req, res, path, method, url) {const lines=[`Strata diagnostics ${new Date().toISOString()}`,`Version ${native.state().version??'unknown'}`,'','== Engine messages =='];for(const l of native.logs())lines.push(`${l.at} ${l.instanceId}: ${l.line}`);lines.push('','== Operations ==');for(const j of native.state().jobs)lines.push(`${j.startedAt} ${j.kind} ${j.state}${j.error?`: ${j.error}`:''}${j.details?`${NL} ${j.details}`:''}`);+ try{const logs=join(dirname(componentsDirectory()),'logs');const names=readdirSync(logs).filter(n=>/^desktop-.*\.log$/.test(n)).sort();const crash=names.filter(n=>n.startsWith('desktop-crash-')).slice(-3).reverse();const runs=names.filter(n=>!n.startsWith('desktop-crash-')).slice(-2).reverse();lines.push('',`== Desktop shell: window crash logs (${crash.length} newest) ==`);for(const n of crash)lines.push('',`-- ${n}`,readFileSync(join(logs,n),'utf8'));lines.push('',`== Desktop shell: last lines of the newest ${runs.length} run logs ==`);for(const n of runs)lines.push('',`-- ${n}`,...readFileSync(join(logs,n),'utf8').split(NL).slice(-300));}catch{/* no desktop logs (not the Linux app, or no crash) */}try{const runtime=process.env.STRATA_RUNTIME_DIR??join(dirname(componentsDirectory()),'runtime');for(const name of readdirSync(runtime).filter(n=>n.endsWith('.server.log'))){lines.push('',`== ${name} (last lines) ==`,...readFileSync(join(runtime,name),'utf8').split(NL).slice(-200));}}catch{/* no server logs yet */}const folder=join(process.env.USERPROFILE??process.env.HOME??homedir(),'Downloads');mkdirSync(folder,{recursive:true});const file=join(folder,`strata-diagnostics-${new Date().toISOString().replace(/[:.]/g,'-').slice(0,19)}.txt`);writeFileSync(file,lines.join(NL),'utf8');diff --git a/apps/host/tests/app-version.test.mjs b/apps/host/tests/app-version.test.mjsnew file mode 100644index 000000000..9e90ede8a--- /dev/null+++ b/apps/host/tests/app-version.test.mjs@@ -0,0 +1,30 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { readFile, mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { appVersionFrom } from '../server/app-version.mjs';++const here = fileURLToPath(new URL('../server', import.meta.url));++test('the shell passes the version; a bad value is ignored', () => {+ assert.equal(appVersionFrom({ env: { STRATA_APP_VERSION: '0.2.0-beta' }, here: '/nowhere/a/b' }), '0.2.0-beta');+ assert.equal(appVersionFrom({ env: { STRATA_APP_VERSION: ' 1.2.3 ' }, here: '/nowhere/a/b' }), '1.2.3');+ assert.equal(appVersionFrom({ env: { STRATA_APP_VERSION: 'latest' }, here: '/nowhere/a/b' }), 'dev');+ assert.equal(appVersionFrom({ env: {}, here: '/nowhere/a/b' }), 'dev');+});++test('in a checkout the same file the shell is built from is read, so there is one source', async () => {+ const toml = await readFile(join(here, '..', '..', 'desktop', 'src-tauri', 'Cargo.toml'), 'utf8');+ const declared = /^version\s*=\s*"([^"]+)"/m.exec(toml)[1];+ assert.equal(appVersionFrom({ env: {}, here }), declared);+ assert.notEqual(declared, '0.1.0', 'the app version is the product version, not the 0.1.0 placeholder');+ const dir = await mkdtemp(join(tmpdir(), 'strata-appver-'));+ try {+ await mkdir(join(dir, 'host', 'server'), { recursive: true });+ await mkdir(join(dir, 'desktop', 'src-tauri'), { recursive: true });+ await writeFile(join(dir, 'desktop', 'src-tauri', 'Cargo.toml'), '[package]\nname = "x"\nversion = "9.8.7-rc.1"\n');+ assert.equal(appVersionFrom({ env: {}, here: join(dir, 'host', 'server') }), '9.8.7-rc.1');+ } finally { await rm(dir, { recursive: true, force: true }); }+});diff --git a/strata_control/feed.py b/strata_control/feed.pyindex 1401db286..307c062d5 100644--- a/strata_control/feed.py+++ b/strata_control/feed.py@@ -60,6 +60,15 @@ def version_key(value: str) -> tuple[int, ...]:return tuple(parts + [0] * (4 - len(parts)))+def app_version_key(value: str) -> tuple[int, ...]:+ """Compare the INSTALLED app's version: like `version_key`, but a pre-release (0.2.0-beta) is allowed and sorts below the same number without+ the suffix. The feed's own versions stay strict (`version_key`)."""+ base, dash, pre = str(value).partition("-")+ if dash and not re.fullmatch(r"[0-9A-Za-z.]+", pre):+ raise FeedError(f"{value!r} is not a version number (expected like 0.2.0 or 0.2.0-beta)")+ return version_key(base) + (0 if dash else 1,)++def _need(obj: dict, key: str, kind, where: str):value = obj.get(key)if not isinstance(value, kind) or isinstance(value, bool) and kind is int:diff --git a/strata_control/updater.py b/strata_control/updater.pyindex b83cc869f..2a2e2368c 100644--- a/strata_control/updater.py+++ b/strata_control/updater.py@@ -957,7 +957,7 @@ def decide_app(feed: feedmod.Feed, ctx: Context) -> dict:if not ctx.app_version:report["status"] = "unknown-installed"else:- report["status"] = "available" if feedmod.version_key(feed.app.version) > feedmod.version_key(ctx.app_version) else "current"+ report["status"] = "available" if feedmod.app_version_key(feed.app.version) > feedmod.app_version_key(ctx.app_version) else "current"return reportdiff --git a/tests/desktop/test_app_version.py b/tests/desktop/test_app_version.pynew file mode 100644index 000000000..cfb807f7c--- /dev/null+++ b/tests/desktop/test_app_version.py@@ -0,0 +1,34 @@+"""The desktop app's version is written in one place: apps/desktop/src-tauri/Cargo.toml (Tauri reads it for the installer and file names when+tauri.conf.json has no version; the shell passes it to the host as STRATA_APP_VERSION; the host reads the same file in a checkout)."""+import json+import re+import unittest+from pathlib import Path++DESKTOP = Path(__file__).resolve().parents[2] / "apps" / "desktop"+++def cargo_version() -> str:+ return re.search(r'^version\s*=\s*"([^"]+)"', (DESKTOP / "src-tauri" / "Cargo.toml").read_text(encoding="utf-8"), re.M).group(1)+++class AppVersionTests(unittest.TestCase):+ def test_the_version_is_the_product_version_not_the_placeholder(self):+ self.assertRegex(cargo_version(), r"^\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?$")+ self.assertNotEqual(cargo_version(), "0.1.0")++ def test_tauri_conf_does_not_carry_a_second_copy(self):+ conf = json.loads((DESKTOP / "src-tauri" / "tauri.conf.json").read_text(encoding="utf-8"))+ self.assertNotIn("version", conf)++ def test_the_npm_package_follows_it(self):+ self.assertEqual(json.loads((DESKTOP / "package.json").read_text(encoding="utf-8"))["version"], cargo_version())++ def test_no_script_hard_codes_a_file_name_with_a_version(self):+ text = (DESKTOP / "scripts" / "make-dmg.sh").read_text(encoding="utf-8")+ self.assertNotRegex(text, r"Strata_\d+\.\d+\.\d+")+ self.assertIn("Cargo.toml", text)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/terminal/test_app_prerelease_version.py b/tests/terminal/test_app_prerelease_version.pynew file mode 100644index 000000000..0b6957a05--- /dev/null+++ b/tests/terminal/test_app_prerelease_version.py@@ -0,0 +1,23 @@+"""The app reports its version as 0.2.0-beta; the update check must compare it, not choke on it."""+import unittest++from strata_control import feed as feedmod+++class AppPrereleaseVersionTests(unittest.TestCase):+ def test_a_pre_release_sorts_below_the_same_number_and_above_the_older_one(self):+ key = feedmod.app_version_key+ self.assertLess(key("0.2.0-beta"), key("0.2.0"))+ self.assertGreater(key("0.2.0-beta"), key("0.1.46"))+ self.assertLess(key("0.2.0-beta"), key("0.2.0.1"))+ self.assertEqual(key("0.2.0"), key("0.2.0"))++ def test_the_feeds_own_versions_stay_strict(self):+ with self.assertRaises(feedmod.FeedError):+ feedmod.version_key("0.2.0-beta")+ with self.assertRaises(feedmod.FeedError):+ feedmod.app_version_key("0.2.0-be ta")+++if __name__ == "__main__":+ unittest.main()