okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
22a3d7068
main
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 { 33if let Some ( dir) = std:: env:: var_os ( "STRATA_DESKTOP_DATA_DIR" ) { 34return PathBuf :: from ( dir); 35} 36platform_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 { 53let 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 { 62data_dir (). join ( "logs" ) 63} 64 65/// "20261018-014503" in UTC, from the system clock (no time crate). 66pub fn stamp ( now : SystemTime ) ->String { 67let secs = now. duration_since ( UNIX_EPOCH ). map ( |d| d. as_secs ()). unwrap_or ( 0 ) as i64 ; 68let ( days, rem) =( secs. div_euclid ( 86_400 ), secs. rem_euclid ( 86_400 )); 69// civil-from-days (Howard Hinnant), proleptic Gregorian 70let z = days +719_468 ; 71let era = z. div_euclid ( 146_097 ); 72let doe = z. rem_euclid ( 146_097 ); 73let yoe =( doe - doe /1_460 + doe /36_524 - doe /146_096 ) /365 ; 74let y = yoe + era* 400 ; 75let doy = doe -( 365 * yoe + yoe /4 - yoe /100 ); 76let mp =( 5 * doy +2 ) /153 ; 77let d = doy -( 153 * mp +2 ) /5 +1 ; 78let m =if mp <10 { mp +3 } else { mp -9 }; 79let y =if m <=2 { y +1 } else { y}; 80format! ( "{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 ) { 85let Ok ( read) = std:: fs:: read_dir ( dir) else { return }; 86let 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 (); 92while names. len () >KEEP { 93let _ = 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 { 102pub fn push ( & self , line : String ) { 103let mut q =self . 0 . lock (). unwrap (); 104if q. len () >=RING_LINES { 105 q. pop_front (); 106} 107 q. push_back ( line); 108} 109pub fn tail ( & self , n : usize ) ->Vec < String > { 110let 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 { 118file : Arc < Mutex < Option < std:: fs:: File >>>, 119pub path : Option < PathBuf >, 120} 121 122impl Log { 123pub fn open () ->Log { 124let dir =logs_dir (); 125let _ = std:: fs:: create_dir_all ( & dir); 126prune ( & dir, "desktop-" , true ); 127prune ( & dir, "desktop-crash-" , false ); 128let path = dir. join ( format! ( "desktop-{}.log" , stamp ( SystemTime :: now ()))); 129let file = std:: fs:: OpenOptions :: new (). create ( true ). append ( true ). open ( & path). ok (); 130let 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} 134pub fn line ( & self , who : & str , text : & str ) { 135// never panics: this runs inside the panic hook too 136if let Ok ( mut guard) =self . file . lock () { 137if let Some ( f) = guard. as_mut () { 138let _ =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 ) { 146eprintln! ( "[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 ||{ 153let mut r =BufReader :: new ( reader); 154let mut buf =Vec :: new (); 155loop { 156 buf. clear (); 157match r. read_until ( b'\n' , & mut buf) { 158Ok ( 0 ) |Err ( _) =>break , 159Ok ( _) =>{ 160let text =String :: from_utf8_lossy ( & buf); 161let text = text. trim_end_matches ([ '\r' , '\n' ]); 162if to_stderr{ 163eprintln! ( "{text}" ); 164} else { 165println! ( "{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 > { 188const 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]; 193NAMES . 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 { 198let Some ( appdir) = std:: env:: var_os ( "APPDIR" ) else { return "not an AppImage (the system's WebKitGTK is used)" . into () }; 199let lib =PathBuf :: from ( appdir). join ( "usr" ). join ( "lib" ); 200let mut found =Vec :: new (); 201if let Ok ( read) = std:: fs:: read_dir ( & lib) { 202for ein read. flatten () { 203let n = e. file_name (). to_string_lossy (). into_owned (); 204if n. starts_with ( "libwebkit2gtk-4.1.so" ) || n. starts_with ( "libjavascriptcoregtk-4.1.so" ) { 205let 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 (); 211if 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 > { 216let 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 () ?; 223let deadline = std:: time:: Instant :: now () +Duration :: from_secs ( 4 ); 224loop { 225match child. try_wait () { 226Ok ( Some ( _)) =>break , 227Ok ( None ) if std:: time:: Instant :: now () < deadline => std:: thread:: sleep ( Duration :: from_millis ( 50 )), 228 _ =>{ 229let _ = child. kill (); 230let _ = child. wait (); 231return None ; 232} 233} 234} 235let mut out =String :: new (); 236 child. stdout . take () ?. read_to_string ( & mut out). ok () ?; 237let out = out. trim (). to_string (); 238if 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 { 244let 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 ())); 251if 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" ); 256for lin graphics_environment () { 257 t. push_str ( & l); 258 t. push ( '\n' ); 259} 260if 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" ); 264match backtrace{ 265Some ( b) => t. push_str ( b), 266None => 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" ); 269for lin window_tail{ 270 t. push_str ( l); 271 t. push ( '\n' ); 272} 273 t. push_str ( "\n== Last lines of the host ==\n" ); 274for lin 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 > { 283let dir =logs_dir (); 284 std:: fs:: create_dir_all ( & dir). ok () ?; 285prune ( & dir, "desktop-crash-" , false ); 286let path = dir. join ( format! ( "desktop-crash-{}.log" , stamp ( SystemTime :: now ()))); 287let 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 () ?; 289Some ( path) 290} 291 292fn newest ( dir : & Path , prefix : & str , crash : bool ) ->Vec < PathBuf > { 293let Ok ( read) = std:: fs:: read_dir ( dir) else { return Vec :: new () }; 294let 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 { 305let text = std:: fs:: read_to_string ( path). unwrap_or_default (); 306let 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) ?; 313let path = out_dir. join ( format! ( "strata-logs-{}.txt" , stamp ( SystemTime :: now ()))); 314let 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 ())); 316if 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" ))); 320let dir =logs_dir (); 321let 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 ())); 323for pin crashes. iter (). take ( 3 ) { 324 t. push_str ( & format! ( "\n----- {}\n{}\n" , p. display (), std:: fs:: read_to_string ( p). unwrap_or_default ())); 325} 326let 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 ())); 328for pin runs. iter (). take ( 2 ) { 329 t. push_str ( & format! ( "\n----- {}\n{}\n" , p. display (), tail_lines ( p, 300 ))); 330} 331let runtime =data_dir (). join ( "runtime" ); 332if let Ok ( read) = std:: fs:: read_dir ( & runtime) { 333let 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 ())); 336for pin files{ 337 t. push_str ( & format! ( "\n----- {}\n{}\n" , p. display (), tail_lines ( & p, 200 ))); 338} 339} 340 std:: fs:: write ( & path, t) ?; 341Ok ( 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 { 350log : Log , 351dialog : 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 > { 360RUN . 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 ) { 366let dialog = dialog && std:: env:: var_os ( "STRATA_NO_DIALOG" ). is_none (); 367let log =Log :: open (); 368 log. line ( "shell" , & system_line ()); 369if RUN . set ( Run { log, dialog}). is_ok () { 370install_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 { 376format! ( "System: {} {}" , std:: env:: consts:: OS , system_version ()) 377} 378 379# [ cfg ( windows )] 380fn system_version () ->String { 381# [ repr ( C )] 382struct OsVersionInfo { 383size : u32 , 384major : u32 , 385minor : u32 , 386build : u32 , 387platform : u32 , 388csd : [ u16 ; 128 ], 389} 390# [ link ( name = "ntdll" )] 391extern "system" { 392fn RtlGetVersion ( info : * mut OsVersionInfo ) ->i32 ; 393} 394let 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) 396if unsafe { RtlGetVersion ( & mut info) } ==0 { 397format! ( "{}.{}.{}" , info. major , info. minor , info. build ) 398} else { 399"version unknown" . into () 400} 401} 402 403# [ cfg ( not ( windows ))] 404fn system_version () ->String { 405first_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 { 410let lower = detail. to_ascii_lowercase (); 411if lower. contains ( "webview2" ) || lower. contains ( "webview" ) { 412"Strata shows its window with Microsoft's WebView2 component, and it could not be started. \ 413Update or repair \"Microsoft Edge WebView2 Runtime\" (Settings > Apps > Installed apps), or install it from \ 414https://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. \ 418Allow 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 { 427let 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))); 434if 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 () ?; 443prune ( dir, "desktop-crash-" , false ); 444let 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 () ?; 446Some ( path) 447} 448 449/// The message box (Windows). Elsewhere the text goes to the terminal only. 450# [ cfg ( windows )] 451fn show_error ( text : & str ) { 452use std:: os:: windows:: ffi:: OsStrExt ; 453# [ link ( name = "user32" )] 454extern "system" { 455fn MessageBoxW ( window : * mut std:: ffi:: c_void , text : * const u16 , caption : * const u16 , kind : u32 ) ->i32 ; 456} 457const MB_ICONERROR : u32 =0x10 ; 458const MB_SETFOREGROUND : u32 =0x1_0000 ; 459const MB_TOPMOST : u32 =0x4_0000 ; 460let wide = |s : & str | std:: ffi:: OsStr :: new ( s). encode_wide (). chain ( std:: iter:: once ( 0 )). collect ::< Vec < u16 >>(); 461let ( text, caption) =( wide ( text), wide ( "Strata" )); 462unsafe { 463MessageBoxW ( 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 ) { 469eprintln! ( "[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 ) { 474let Some ( run) =RUN . get () else { 475eprintln! ( "[strata] {detail}" ); 476return ; 477}; 478 run. log . line ( "shell" , & format! ( "START FAILED: {detail}" )); 479let dir =logs_dir (); 480let saved =write_startup_failure ( & dir, detail, run. log . path . as_deref ()); 481if let Some ( p) =& saved{ 482 run. log . line ( "shell" , & format! ( "The crash file is {}" , p. display ())); 483} 484if run. dialog && !REPORTED . swap ( true , Ordering :: SeqCst ) { 485let short: String = detail. chars (). take ( 400 ). collect (); 486let place = saved. or_else ( || run. log . path . clone ()). map ( |p| p. display (). to_string ()). unwrap_or_else ( || dir. display (). to_string ()); 487show_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 ) -> !{ 493report_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 () { 500let previous = std:: panic:: take_hook (); 501 std:: panic:: set_hook ( Box :: new ( move |info|{ 502previous ( info); 503let 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}; 510let place = info. location (). map ( |l|format! ( "{}:{}" , l. file (), l. line ())). unwrap_or_else ( ||"an unknown place" . into ()); 511let thread = std:: thread:: current (). name (). unwrap_or ( "unnamed" ). to_string (); 512report_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{ 522use super :: * ; 523 524# [ test ] 525fn the_time_stamp_is_utc_civil_time () { 526assert_eq! ( stamp ( UNIX_EPOCH ), "19700101-000000" ); 527assert_eq! ( stamp ( UNIX_EPOCH +Duration :: from_secs ( 1_800_000_000 )), "20270115-080000" ); 528assert_eq! ( stamp ( UNIX_EPOCH +Duration :: from_secs ( 1_760_751_903 )), "20251018-014503" ); 529} 530 531# [ test ] 532fn the_ring_keeps_the_last_lines () { 533let ring =Ring :: default (); 534for iin 0 ..( RING_LINES +50 ) { 535 ring. push ( format! ( "line {i}" )); 536} 537let tail = ring. tail ( 3 ); 538assert_eq! ( tail, vec! [ format! ( "line {}" , RING_LINES +47 ), format! ( "line {}" , RING_LINES +48 ), format! ( "line {}" , RING_LINES +49 )]); 539assert_eq! ( ring. tail ( 10_000 ). len (), RING_LINES ); 540} 541 542# [ test ] 543fn the_crash_report_says_what_happened_in_plain_words_and_has_the_tails () { 544let 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" ))); 545for needlein [ "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" ] { 546assert! ( text. contains ( needle), "{needle}" ); 547} 548let with =crash_report ( "x" , 1 , & [], & [], Some ( "#0 AcceleratedBackingStore::update" ), "1" , None ); 549assert! ( with. contains ( "#0 AcceleratedBackingStore::update" ) && !with. contains ( "none kept" )); 550} 551 552# [ test ] 553fn logs_are_pruned_and_saved_into_one_file () { 554let dir = std:: env:: temp_dir (). join ( format! ( "strata-desktoplog-test-{}" , std:: process:: id ())); 555let _ = std:: fs:: remove_dir_all ( & dir); 556 std:: env:: set_var ( "STRATA_DESKTOP_DATA_DIR" , & dir); 557let logs =logs_dir (); 558 std:: fs:: create_dir_all ( & logs). unwrap (); 559for iin 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} 563prune ( & logs, "desktop-" , true ); 564prune ( & logs, "desktop-crash-" , false ); 565assert_eq! ( newest ( & logs, "desktop-" , false ). len (), KEEP ); 566assert_eq! ( newest ( & logs, "desktop-" , true ). len (), KEEP ); 567assert! ( 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 (); 570let saved =save_logs ( & dir. join ( "out" )). unwrap (); 571let text = std:: fs:: read_to_string ( saved). unwrap (); 572assert! ( text. contains ( "crash 13" ) && text. contains ( "run 13" ) && text. contains ( "engine line" )); 573 std:: env:: remove_var ( "STRATA_DESKTOP_DATA_DIR" ); 574let _ = std:: fs:: remove_dir_all ( & dir); 575} 576# [ test ] 577fn a_failed_start_is_explained_in_plain_words_and_written_to_a_crash_file () { 578let webview =plain_reason ( "Failed to setup app: error encountered during setup hook: WebView2 error: 0x8007139F" ); 579assert! ( webview. contains ( "WebView2" ) && webview. contains ( "go.microsoft.com" )); 580assert! ( plain_reason ( "the Strata App Host did not become healthy at http://127.0.0.1:47831/api/health" ). contains ( "background program" )); 581assert! ( plain_reason ( "something else" ). contains ( "log file" )); 582let dir = std:: env:: temp_dir (). join ( format! ( "strata-startlog-test-{}" , std:: process:: id ())); 583let _ = std:: fs:: remove_dir_all ( & dir); 584let path =write_startup_failure ( & dir, "the app stopped unexpectedly: boom (at main.rs:1, thread main)" , Some ( Path :: new ( "/x/desktop-1.log" ))). unwrap (); 585assert! ( path. file_name (). unwrap (). to_string_lossy (). starts_with ( "desktop-crash-" )); 586let text = std:: fs:: read_to_string ( & path). unwrap (); 587for needlein [ "boom" , "main.rs:1" , "/x/desktop-1.log" , env! ( "CARGO_PKG_VERSION" ), "System:" , "Meaning:" ] { 588assert! ( text. contains ( needle), "{needle}" ); 589} 590let _ = std:: fs:: remove_dir_all ( & dir); 591} 592 593# [ cfg ( windows )] 594# [ test ] 595fn on_windows_the_logs_sit_in_the_local_app_data_strata_folder () { 596let dir =platform_data_dir (); 597assert! ( dir. ends_with ( "Strata" ), "{}" , dir. display ()); 598assert! ( system_version (). split ( '.' ). count () ==3 , "{}" , system_version ()); 599} 600}