okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-guidata (4c4596746) into f-0213-int22a3d7068

main
27.5 KiB600 linesraw
1//! The desktop shell's own logs (Linux): what the host and the window process printed, a crash log when the window dies, and
2//! `--save-logs`, which collects everything a person can send us without the window (the window is what may be crashing).
3//!
4//! Files, in `<data>/logs` (`$XDG_DATA_HOME/strata/logs`, usually `~/.local/share/strata/logs`; the newest ten of each kind are kept):
5//!   desktop-<UTC time>.log         one per start: the shell's lines, and every line the host (`[host]`) and the window (`[window]`) printed
6//!   desktop-crash-<UTC time>.log   written when the window process dies without being closed: what happened in plain words, the system,
7//!                                  the graphics session, the last lines of the window and of the host, and a backtrace when the system keeps one
8//!
9//! `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
10//! in the Downloads folder. The same pieces go into Settings > Engine > Diagnostics > Save logs (the host reads this folder).
11//!
12//! Windows and macOS (one process owns the host and the window) use the same folder and file names for what happens while the app starts:
13//! `init_startup` opens the run log first thing in `main`, before anything that can fail, and installs a panic hook; a start that fails
14//! (the host does not come up, the window cannot be made, any panic) ends in `startup_failed`: the reason goes into the run log and a
15//! `desktop-crash-` file, and the person sees a plain message box instead of a process that vanished with no trace. On Windows the folder
16//! is `%LOCALAPPDATA%\Strata\logs`, next to the components folder.
17
18// Linux uses the shell log, the crash log and --save-logs; Windows and macOS use the start-up half. Each side leaves the other unused.
19#![allow(dead_code)]
20
21use std::collections::VecDeque;
22use std::io::{BufRead, BufReader, Read, Write};
23use std::path::{Path, PathBuf};
24use std::sync::atomic::{AtomicBool, Ordering};
25use std::sync::{Arc, Mutex, OnceLock};
26use std::time::{Duration, SystemTime, UNIX_EPOCH};
27
28const KEEP: usize = 10;
29const RING_LINES: usize = 300;
30
31/// `<data>/` : where Strata keeps its engine, runtime and logs on this system.
32pub fn data_dir() -> PathBuf {
33    if let Some(dir) = std::env::var_os("STRATA_DESKTOP_DATA_DIR") {
34        return PathBuf::from(dir);
35    }
36    platform_data_dir()
37}
38
39/// Windows: `%LOCALAPPDATA%\Strata`, the folder the host and Control already use for the components and the install.
40#[cfg(windows)]
41fn platform_data_dir() -> PathBuf {
42    std::env::var_os("LOCALAPPDATA")
43        .map(PathBuf::from)
44        .filter(|p| p.is_absolute())
45        .or_else(|| std::env::var_os("USERPROFILE").map(|h| PathBuf::from(h).join("AppData").join("Local")))
46        .unwrap_or_else(std::env::temp_dir)
47        .join("Strata")
48}
49
50/// Linux and macOS: `$XDG_DATA_HOME/strata`, usually `~/.local/share/strata`.
51#[cfg(not(windows))]
52fn platform_data_dir() -> PathBuf {
53    let base = std::env::var_os("XDG_DATA_HOME")
54        .map(PathBuf::from)
55        .filter(|p| p.is_absolute())
56        .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local").join("share")))
57        .unwrap_or_else(std::env::temp_dir);
58    base.join("strata")
59}
60
61pub fn logs_dir() -> PathBuf {
62    data_dir().join("logs")
63}
64
65/// "20261018-014503" in UTC, from the system clock (no time crate).
66pub fn stamp(now: SystemTime) -> String {
67    let secs = now.duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) as i64;
68    let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
69    // civil-from-days (Howard Hinnant), proleptic Gregorian
70    let z = days + 719_468;
71    let era = z.div_euclid(146_097);
72    let doe = z.rem_euclid(146_097);
73    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
74    let y = yoe + era * 400;
75    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
76    let mp = (5 * doy + 2) / 153;
77    let d = doy - (153 * mp + 2) / 5 + 1;
78    let m = if mp < 10 { mp + 3 } else { mp - 9 };
79    let y = if m <= 2 { y + 1 } else { y };
80    format!("{y:04}{m:02}{d:02}-{:02}{:02}{:02}", rem / 3600, rem % 3600 / 60, rem % 60)
81}
82
83/// Keep the newest `KEEP` files whose name starts with `prefix` and ends with `.log` (names sort by their time stamp).
84fn prune(dir: &Path, prefix: &str, skip_crash: bool) {
85    let Ok(read) = std::fs::read_dir(dir) else { return };
86    let mut names: Vec<String> = read
87        .flatten()
88        .filter_map(|e| e.file_name().into_string().ok())
89        .filter(|n| n.starts_with(prefix) && n.ends_with(".log") && !(skip_crash && n.starts_with("desktop-crash-")))
90        .collect();
91    names.sort();
92    while names.len() > KEEP {
93        let _ = std::fs::remove_file(dir.join(names.remove(0)));
94    }
95}
96
97/// The last lines a process printed (kept in memory for the crash log).
98#[derive(Clone, Default)]
99pub struct Ring(Arc<Mutex<VecDeque<String>>>);
100
101impl Ring {
102    pub fn push(&self, line: String) {
103        let mut q = self.0.lock().unwrap();
104        if q.len() >= RING_LINES {
105            q.pop_front();
106        }
107        q.push_back(line);
108    }
109    pub fn tail(&self, n: usize) -> Vec<String> {
110        let q = self.0.lock().unwrap();
111        q.iter().skip(q.len().saturating_sub(n)).cloned().collect()
112    }
113}
114
115/// This run's log file, shared by the shell and the threads that copy the children's output.
116#[derive(Clone)]
117pub struct Log {
118    file: Arc<Mutex<Option<std::fs::File>>>,
119    pub path: Option<PathBuf>,
120}
121
122impl Log {
123    pub fn open() -> Log {
124        let dir = logs_dir();
125        let _ = std::fs::create_dir_all(&dir);
126        prune(&dir, "desktop-", true);
127        prune(&dir, "desktop-crash-", false);
128        let path = dir.join(format!("desktop-{}.log", stamp(SystemTime::now())));
129        let file = std::fs::OpenOptions::new().create(true).append(true).open(&path).ok();
130        let log = Log { file: Arc::new(Mutex::new(file)), path: Some(path) };
131        log.line("shell", &format!("Strata desktop {} starting (pid {})", env!("CARGO_PKG_VERSION"), std::process::id()));
132        log
133    }
134    pub fn line(&self, who: &str, text: &str) {
135        // never panics: this runs inside the panic hook too
136        if let Ok(mut guard) = self.file.lock() {
137            if let Some(f) = guard.as_mut() {
138                let _ = writeln!(f, "[{who}] {text}");
139            }
140        }
141    }
142}
143
144/// Print what the shell says (terminal and log).
145pub fn say(log: &Log, text: &str) {
146    eprintln!("[strata] {text}");
147    log.line("shell", text);
148}
149
150/// Copy a child's output line by line: to our own stdout/stderr (as before), to the log file, and into the ring.
151pub fn tee<R: Read + Send + 'static>(reader: R, who: &'static str, to_stderr: bool, ring: Ring, log: Log) {
152    std::thread::spawn(move || {
153        let mut r = BufReader::new(reader);
154        let mut buf = Vec::new();
155        loop {
156            buf.clear();
157            match r.read_until(b'\n', &mut buf) {
158                Ok(0) | Err(_) => break,
159                Ok(_) => {
160                    let text = String::from_utf8_lossy(&buf);
161                    let text = text.trim_end_matches(['\r', '\n']);
162                    if to_stderr {
163                        eprintln!("{text}");
164                    } else {
165                        println!("{text}");
166                    }
167                    ring.push(text.to_string());
168                    log.line(who, text);
169                }
170            }
171        }
172    });
173}
174
175fn first_line(path: &str) -> Option<String> {
176    std::fs::read_to_string(path).ok().and_then(|t| t.lines().next().map(str::to_string))
177}
178
179fn os_pretty_name() -> String {
180    std::fs::read_to_string("/etc/os-release")
181        .ok()
182        .and_then(|t| t.lines().find_map(|l| l.strip_prefix("PRETTY_NAME=").map(|v| v.trim_matches('"').to_string())))
183        .unwrap_or_else(|| "unknown".into())
184}
185
186/// The environment variables that decide how the window draws; nothing private.
187fn graphics_environment() -> Vec<String> {
188    const NAMES: &[&str] = &[
189        "XDG_SESSION_TYPE", "XDG_CURRENT_DESKTOP", "DESKTOP_SESSION", "DISPLAY", "WAYLAND_DISPLAY", "GDK_BACKEND", "GTK_THEME",
190        "WEBKIT_DISABLE_DMABUF_RENDERER", "WEBKIT_DISABLE_COMPOSITING_MODE", "WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS", "LIBGL_ALWAYS_SOFTWARE",
191        "FONTCONFIG_FILE", "FONTCONFIG_PATH", "STRATA_FONT_CONFIG", "GALLIUM_DRIVER", "__GLX_VENDOR_LIBRARY_NAME", "__NV_PRIME_RENDER_OFFLOAD", "MESA_LOADER_DRIVER_OVERRIDE", "APPIMAGE", "APPDIR",
192    ];
193    NAMES.iter().filter_map(|n| std::env::var(n).ok().map(|v| format!("  {n}={v}"))).collect()
194}
195
196/// The WebKitGTK files inside the AppImage (the version is in the file name or its link target).
197fn bundled_webkit() -> String {
198    let Some(appdir) = std::env::var_os("APPDIR") else { return "not an AppImage (the system's WebKitGTK is used)".into() };
199    let lib = PathBuf::from(appdir).join("usr").join("lib");
200    let mut found = Vec::new();
201    if let Ok(read) = std::fs::read_dir(&lib) {
202        for e in read.flatten() {
203            let n = e.file_name().to_string_lossy().into_owned();
204            if n.starts_with("libwebkit2gtk-4.1.so") || n.starts_with("libjavascriptcoregtk-4.1.so") {
205                let target = std::fs::read_link(e.path()).map(|t| format!(" -> {}", t.display())).unwrap_or_default();
206                found.push(format!("{n}{target}"));
207            }
208        }
209    }
210    found.sort();
211    if found.is_empty() { "no WebKitGTK file found in the AppImage".into() } else { found.join("; ") }
212}
213
214/// A backtrace of the dead window process when the system keeps one (systemd-coredump); None when it does not.
215fn system_backtrace(pid: u32) -> Option<String> {
216    let mut child = std::process::Command::new("coredumpctl")
217        .args(["info", &pid.to_string(), "--no-pager"])
218        .stdin(std::process::Stdio::null())
219        .stdout(std::process::Stdio::piped())
220        .stderr(std::process::Stdio::null())
221        .spawn()
222        .ok()?;
223    let deadline = std::time::Instant::now() + Duration::from_secs(4);
224    loop {
225        match child.try_wait() {
226            Ok(Some(_)) => break,
227            Ok(None) if std::time::Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
228            _ => {
229                let _ = child.kill();
230                let _ = child.wait();
231                return None;
232            }
233        }
234    }
235    let mut out = String::new();
236    child.stdout.take()?.read_to_string(&mut out).ok()?;
237    let out = out.trim().to_string();
238    if out.is_empty() || out.contains("No coredumps found") { None } else { Some(out) }
239}
240
241/// What the crash log says, as text (so it can be tested without a crash).
242#[allow(clippy::too_many_arguments)]
243pub fn crash_report(what: &str, pid: u32, window_tail: &[String], host_tail: &[String], backtrace: Option<&str>, app_version: &str, log_path: Option<&Path>) -> String {
244    let mut t = String::new();
245    t.push_str("Strata app window crash\n=======================\n\n");
246    t.push_str(&format!("When:     {} UTC\n", stamp(SystemTime::now())));
247    t.push_str(&format!("What:     the app window process (pid {pid}) stopped without being closed: {what}\n"));
248    t.push_str("Effect:   Strata kept running and opened in the web browser instead (browser mode); nothing was lost.\n");
249    t.push_str(&format!("App:      Strata desktop {app_version}\n"));
250    t.push_str(&format!("System:   {} / {}\n", os_pretty_name(), first_line("/proc/version").unwrap_or_default()));
251    if let Some(v) = first_line("/proc/driver/nvidia/version") {
252        t.push_str(&format!("NVIDIA:   {v}\n"));
253    }
254    t.push_str(&format!("WebKit:   {}\n", bundled_webkit()));
255    t.push_str("Graphics session:\n");
256    for l in graphics_environment() {
257        t.push_str(&l);
258        t.push('\n');
259    }
260    if let Some(p) = log_path {
261        t.push_str(&format!("\nFull log of this run: {}\n", p.display()));
262    }
263    t.push_str("\n== Backtrace ==\n");
264    match backtrace {
265        Some(b) => t.push_str(b),
266        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"),
267    }
268    t.push_str("\n\n== Last lines of the window process ==\n");
269    for l in window_tail {
270        t.push_str(l);
271        t.push('\n');
272    }
273    t.push_str("\n== Last lines of the host ==\n");
274    for l in host_tail {
275        t.push_str(l);
276        t.push('\n');
277    }
278    t
279}
280
281/// Write the crash log; returns where it is.
282pub fn write_crash_log(what: &str, pid: u32, window: &Ring, host: &Ring, log: &Log) -> Option<PathBuf> {
283    let dir = logs_dir();
284    std::fs::create_dir_all(&dir).ok()?;
285    prune(&dir, "desktop-crash-", false);
286    let path = dir.join(format!("desktop-crash-{}.log", stamp(SystemTime::now())));
287    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());
288    std::fs::write(&path, text).ok()?;
289    Some(path)
290}
291
292fn newest(dir: &Path, prefix: &str, crash: bool) -> Vec<PathBuf> {
293    let Ok(read) = std::fs::read_dir(dir) else { return Vec::new() };
294    let mut names: Vec<String> = read
295        .flatten()
296        .filter_map(|e| e.file_name().into_string().ok())
297        .filter(|n| n.starts_with(prefix) && n.ends_with(".log") && (n.starts_with("desktop-crash-") == crash))
298        .collect();
299    names.sort();
300    names.reverse();
301    names.into_iter().map(|n| dir.join(n)).collect()
302}
303
304fn tail_lines(path: &Path, n: usize) -> String {
305    let text = std::fs::read_to_string(path).unwrap_or_default();
306    let lines: Vec<&str> = text.lines().collect();
307    lines[lines.len().saturating_sub(n)..].join("\n")
308}
309
310/// `--save-logs`: one text file with what we need to look at a crash. Returns its path.
311pub fn save_logs(out_dir: &Path) -> std::io::Result<PathBuf> {
312    std::fs::create_dir_all(out_dir)?;
313    let path = out_dir.join(format!("strata-logs-{}.txt", stamp(SystemTime::now())));
314    let mut t = String::new();
315    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()));
316    if let Some(v) = first_line("/proc/driver/nvidia/version") {
317        t.push_str(&format!("NVIDIA: {v}\n"));
318    }
319    t.push_str(&format!("WebKit: {}\nGraphics session:\n{}\n", bundled_webkit(), graphics_environment().join("\n")));
320    let dir = logs_dir();
321    let crashes = newest(&dir, "desktop-crash-", true);
322    t.push_str(&format!("\n\n##### Window crash logs ({} found, newest first, at most 3 shown)\n", crashes.len()));
323    for p in crashes.iter().take(3) {
324        t.push_str(&format!("\n----- {}\n{}\n", p.display(), std::fs::read_to_string(p).unwrap_or_default()));
325    }
326    let runs = newest(&dir, "desktop-", false);
327    t.push_str(&format!("\n\n##### Shell logs ({} found, last 300 lines of the newest 2)\n", runs.len()));
328    for p in runs.iter().take(2) {
329        t.push_str(&format!("\n----- {}\n{}\n", p.display(), tail_lines(p, 300)));
330    }
331    let runtime = data_dir().join("runtime");
332    if let Ok(read) = std::fs::read_dir(&runtime) {
333        let mut files: Vec<PathBuf> = read.flatten().map(|e| e.path()).filter(|p| p.to_string_lossy().ends_with(".server.log")).collect();
334        files.sort();
335        t.push_str(&format!("\n\n##### Engine server logs ({} found, last 200 lines each)\n", files.len()));
336        for p in files {
337            t.push_str(&format!("\n----- {}\n{}\n", p.display(), tail_lines(&p, 200)));
338        }
339    }
340    std::fs::write(&path, t)?;
341    Ok(path)
342}
343
344// ---------------------------------------------------------------------------------------------------------------------------------
345// Start-up failures (Windows and macOS)
346// ---------------------------------------------------------------------------------------------------------------------------------
347
348/// The run log and whether a failure may show a message box. Set once, first thing in `main`.
349struct Run {
350    log: Log,
351    dialog: bool,
352}
353
354static RUN: OnceLock<Run> = OnceLock::new();
355/// One message box per run: a failure inside the panic hook and the abort that follows must not show two.
356static REPORTED: AtomicBool = AtomicBool::new(false);
357
358/// This run's log, once `init_startup` has opened it.
359pub fn run_log() -> Option<Log> {
360    RUN.get().map(|r| r.log.clone())
361}
362
363/// Open the run log and install the panic hook. Call it first in `main`: nothing that can fail runs before it. `dialog` is false for
364/// the self-test (no person to read a message box); `STRATA_NO_DIALOG` does the same for scripted runs.
365pub fn init_startup(dialog: bool) {
366    let dialog = dialog && std::env::var_os("STRATA_NO_DIALOG").is_none();
367    let log = Log::open();
368    log.line("shell", &system_line());
369    if RUN.set(Run { log, dialog }).is_ok() {
370        install_panic_hook();
371    }
372}
373
374/// "Windows 10.0.26300 (64-bit)" or the name of the system; one line for the log and the crash file.
375pub fn system_line() -> String {
376    format!("System: {} {}", std::env::consts::OS, system_version())
377}
378
379#[cfg(windows)]
380fn system_version() -> String {
381    #[repr(C)]
382    struct OsVersionInfo {
383        size: u32,
384        major: u32,
385        minor: u32,
386        build: u32,
387        platform: u32,
388        csd: [u16; 128],
389    }
390    #[link(name = "ntdll")]
391    extern "system" {
392        fn RtlGetVersion(info: *mut OsVersionInfo) -> i32;
393    }
394    let mut info = OsVersionInfo { size: std::mem::size_of::<OsVersionInfo>() as u32, major: 0, minor: 0, build: 0, platform: 0, csd: [0; 128] };
395    // RtlGetVersion reports the real version (GetVersionEx lies to apps without a manifest entry)
396    if unsafe { RtlGetVersion(&mut info) } == 0 {
397        format!("{}.{}.{}", info.major, info.minor, info.build)
398    } else {
399        "version unknown".into()
400    }
401}
402
403#[cfg(not(windows))]
404fn system_version() -> String {
405    first_line("/etc/os-release").unwrap_or_default()
406}
407
408/// What to tell a person, in plain words, for a technical reason. Always ends with the one next step.
409pub fn plain_reason(detail: &str) -> String {
410    let lower = detail.to_ascii_lowercase();
411    if lower.contains("webview2") || lower.contains("webview") {
412        "Strata shows its window with Microsoft's WebView2 component, and it could not be started. \
413         Update or repair \"Microsoft Edge WebView2 Runtime\" (Settings > Apps > Installed apps), or install it from \
414         https://go.microsoft.com/fwlink/p/?LinkId=2124703, then start Strata again."
415            .into()
416    } else if lower.contains("app host") || lower.contains("node runtime") || lower.contains("could not start the app host") {
417        "Strata's background program did not start. Security software may have blocked a file in the Strata folder. \
418         Allow the Strata folder in it (or reinstall Strata) and start Strata again."
419            .into()
420    } else {
421        "Strata stopped while it was starting. Starting it again may work; if it does not, please send us the log file named below.".into()
422    }
423}
424
425/// The text of the crash file for a failed start, as text (so it can be tested without a failure).
426pub fn startup_report(detail: &str, app_version: &str, log_path: Option<&Path>) -> String {
427    let mut t = String::new();
428    t.push_str("Strata app start failure\n========================\n\n");
429    t.push_str(&format!("When:     {} UTC\n", stamp(SystemTime::now())));
430    t.push_str(&format!("App:      Strata desktop {app_version}\n"));
431    t.push_str(&format!("{}\n", system_line()));
432    t.push_str(&format!("What:     {detail}\n"));
433    t.push_str(&format!("Meaning:  {}\n", plain_reason(detail)));
434    if let Some(p) = log_path {
435        t.push_str(&format!("\nFull log of this run: {}\n", p.display()));
436    }
437    t
438}
439
440/// Write the crash file of a failed start into `dir`; returns where it is.
441pub fn write_startup_failure(dir: &Path, detail: &str, log_path: Option<&Path>) -> Option<PathBuf> {
442    std::fs::create_dir_all(dir).ok()?;
443    prune(dir, "desktop-crash-", false);
444    let path = dir.join(format!("desktop-crash-{}.log", stamp(SystemTime::now())));
445    std::fs::write(&path, startup_report(detail, env!("CARGO_PKG_VERSION"), log_path)).ok()?;
446    Some(path)
447}
448
449/// The message box (Windows). Elsewhere the text goes to the terminal only.
450#[cfg(windows)]
451fn show_error(text: &str) {
452    use std::os::windows::ffi::OsStrExt;
453    #[link(name = "user32")]
454    extern "system" {
455        fn MessageBoxW(window: *mut std::ffi::c_void, text: *const u16, caption: *const u16, kind: u32) -> i32;
456    }
457    const MB_ICONERROR: u32 = 0x10;
458    const MB_SETFOREGROUND: u32 = 0x1_0000;
459    const MB_TOPMOST: u32 = 0x4_0000;
460    let wide = |s: &str| std::ffi::OsStr::new(s).encode_wide().chain(std::iter::once(0)).collect::<Vec<u16>>();
461    let (text, caption) = (wide(text), wide("Strata"));
462    unsafe {
463        MessageBoxW(std::ptr::null_mut(), text.as_ptr(), caption.as_ptr(), MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST);
464    }
465}
466
467#[cfg(not(windows))]
468fn show_error(text: &str) {
469    eprintln!("[strata] {text}");
470}
471
472/// Record a failed start (run log and crash file) and tell the person. Runs inside the panic hook as well, so it cannot panic.
473fn report_failure(detail: &str) {
474    let Some(run) = RUN.get() else {
475        eprintln!("[strata] {detail}");
476        return;
477    };
478    run.log.line("shell", &format!("START FAILED: {detail}"));
479    let dir = logs_dir();
480    let saved = write_startup_failure(&dir, detail, run.log.path.as_deref());
481    if let Some(p) = &saved {
482        run.log.line("shell", &format!("The crash file is {}", p.display()));
483    }
484    if run.dialog && !REPORTED.swap(true, Ordering::SeqCst) {
485        let short: String = detail.chars().take(400).collect();
486        let place = saved.or_else(|| run.log.path.clone()).map(|p| p.display().to_string()).unwrap_or_else(|| dir.display().to_string());
487        show_error(&format!("Strata could not start.\n\n{}\n\nWhat happened: {short}\n\nA log was saved here, please send it to us:\n{place}", plain_reason(detail)));
488    }
489}
490
491/// A start that cannot go on: say why (log, crash file, message box) and end the process with a failure code. Never returns.
492pub fn startup_failed(detail: &str) -> ! {
493    report_failure(detail);
494    std::process::exit(1)
495}
496
497/// Every panic in the app (a Tauri setup error is one) ends in an abort with panic = "abort", which Windows reports as 0xc0000409 with
498/// nothing else. The hook runs before the abort: it writes what the panic said and where, and shows the message box.
499fn install_panic_hook() {
500    let previous = std::panic::take_hook();
501    std::panic::set_hook(Box::new(move |info| {
502        previous(info);
503        let message = if let Some(s) = info.payload().downcast_ref::<&str>() {
504            (*s).to_string()
505        } else if let Some(s) = info.payload().downcast_ref::<String>() {
506            s.clone()
507        } else {
508            "a panic without a message".to_string()
509        };
510        let place = info.location().map(|l| format!("{}:{}", l.file(), l.line())).unwrap_or_else(|| "an unknown place".into());
511        let thread = std::thread::current().name().unwrap_or("unnamed").to_string();
512        report_failure(&format!("the app stopped unexpectedly: {message} (at {place}, thread {thread})"));
513    }));
514}
515
516pub fn downloads_dir() -> PathBuf {
517    std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(|h| PathBuf::from(h).join("Downloads")).unwrap_or_else(std::env::temp_dir)
518}
519
520#[cfg(test)]
521mod tests {
522    use super::*;
523
524    #[test]
525    fn the_time_stamp_is_utc_civil_time() {
526        assert_eq!(stamp(UNIX_EPOCH), "19700101-000000");
527        assert_eq!(stamp(UNIX_EPOCH + Duration::from_secs(1_800_000_000)), "20270115-080000");
528        assert_eq!(stamp(UNIX_EPOCH + Duration::from_secs(1_760_751_903)), "20251018-014503");
529    }
530
531    #[test]
532    fn the_ring_keeps_the_last_lines() {
533        let ring = Ring::default();
534        for i in 0..(RING_LINES + 50) {
535            ring.push(format!("line {i}"));
536        }
537        let tail = ring.tail(3);
538        assert_eq!(tail, vec![format!("line {}", RING_LINES + 47), format!("line {}", RING_LINES + 48), format!("line {}", RING_LINES + 49)]);
539        assert_eq!(ring.tail(10_000).len(), RING_LINES);
540    }
541
542    #[test]
543    fn the_crash_report_says_what_happened_in_plain_words_and_has_the_tails() {
544        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")));
545        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"] {
546            assert!(text.contains(needle), "{needle}");
547        }
548        let with = crash_report("x", 1, &[], &[], Some("#0 AcceleratedBackingStore::update"), "1", None);
549        assert!(with.contains("#0 AcceleratedBackingStore::update") && !with.contains("none kept"));
550    }
551
552    #[test]
553    fn logs_are_pruned_and_saved_into_one_file() {
554        let dir = std::env::temp_dir().join(format!("strata-desktoplog-test-{}", std::process::id()));
555        let _ = std::fs::remove_dir_all(&dir);
556        std::env::set_var("STRATA_DESKTOP_DATA_DIR", &dir);
557        let logs = logs_dir();
558        std::fs::create_dir_all(&logs).unwrap();
559        for i in 0..14 {
560            std::fs::write(logs.join(format!("desktop-20260101-0000{i:02}.log")), format!("run {i}\n")).unwrap();
561            std::fs::write(logs.join(format!("desktop-crash-20260101-0000{i:02}.log")), format!("crash {i}\n")).unwrap();
562        }
563        prune(&logs, "desktop-", true);
564        prune(&logs, "desktop-crash-", false);
565        assert_eq!(newest(&logs, "desktop-", false).len(), KEEP);
566        assert_eq!(newest(&logs, "desktop-", true).len(), KEEP);
567        assert!(newest(&logs, "desktop-", false)[0].to_string_lossy().ends_with("000013.log"), "the newest are kept");
568        std::fs::create_dir_all(dir.join("runtime")).unwrap();
569        std::fs::write(dir.join("runtime").join("app-1.server.log"), "engine line\n").unwrap();
570        let saved = save_logs(&dir.join("out")).unwrap();
571        let text = std::fs::read_to_string(saved).unwrap();
572        assert!(text.contains("crash 13") && text.contains("run 13") && text.contains("engine line"));
573        std::env::remove_var("STRATA_DESKTOP_DATA_DIR");
574        let _ = std::fs::remove_dir_all(&dir);
575    }
576    #[test]
577    fn a_failed_start_is_explained_in_plain_words_and_written_to_a_crash_file() {
578        let webview = plain_reason("Failed to setup app: error encountered during setup hook: WebView2 error: 0x8007139F");
579        assert!(webview.contains("WebView2") && webview.contains("go.microsoft.com"));
580        assert!(plain_reason("the Strata App Host did not become healthy at http://127.0.0.1:47831/api/health").contains("background program"));
581        assert!(plain_reason("something else").contains("log file"));
582        let dir = std::env::temp_dir().join(format!("strata-startlog-test-{}", std::process::id()));
583        let _ = std::fs::remove_dir_all(&dir);
584        let path = write_startup_failure(&dir, "the app stopped unexpectedly: boom (at main.rs:1, thread main)", Some(Path::new("/x/desktop-1.log"))).unwrap();
585        assert!(path.file_name().unwrap().to_string_lossy().starts_with("desktop-crash-"));
586        let text = std::fs::read_to_string(&path).unwrap();
587        for needle in ["boom", "main.rs:1", "/x/desktop-1.log", env!("CARGO_PKG_VERSION"), "System:", "Meaning:"] {
588            assert!(text.contains(needle), "{needle}");
589        }
590        let _ = std::fs::remove_dir_all(&dir);
591    }
592
593    #[cfg(windows)]
594    #[test]
595    fn on_windows_the_logs_sit_in_the_local_app_data_strata_folder() {
596        let dir = platform_data_dir();
597        assert!(dir.ends_with("Strata"), "{}", dir.display());
598        assert!(system_version().split('.').count() == 3, "{}", system_version());
599    }
600}