okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ffb3d9b31
main
1//! Linux: the process that owns the host, and what it does when the app window cannot run. 2//! 3//! WebKitGTK can crash the process that shows the window (a null pointer deep inside libwebkit2gtk was seen on Ubuntu 26.04 with 4//! NVIDIA on Wayland, and on Ubuntu 24.04 under Xvfb). When the window and the host lived in one process, that crash took the host 5//! and the engine down with it. So on Linux the work is split in two processes of this one executable: 6//! 7//! shell (this module; no GTK, no WebKit) starts the host, writes the session file, starts the window process, and watches both 8//! window (`--window-child`; Tauri + WebKitGTK) shows the page, registers the app updater with the host, and nothing else 9//! 10//! If the window process dies for any reason except the person closing the window (a signal such as SIGSEGV, an abort, a failed 11//! start, a missing library), the shell keeps the host running, tells the host to open the page in the default browser and to 12//! show one notification, and prints the same sentence on the terminal. This is "browser mode"; `--browser` or STRATA_UI=browser 13//! starts in it on purpose. In browser mode closing the tab does not stop the engine: the page has "Quit Strata", and `--quit` 14//! ends a running Strata from the command line. The host listens on 127.0.0.1 only (the shell sets STRATA_BIND itself). 15//! 16//! The session file (`~/.strata/app-session.json`, mode 0600: process id, port, the secret only this user can read, the mode) is how 17//! a second start finds the first one: it focuses the window (window mode) or opens another tab (browser mode) instead of 18//! starting a second host. 19 20use std:: io:: Write ; 21use std:: path:: PathBuf ; 22use std:: process::{ Child , Command , ExitStatus , Stdio }; 23use std:: time::{ Duration , Instant }; 24 25use crate :: desktoplog::{ self , say, Log , Ring }; 26 27pub const BROWSER_NOTICE : & str ="Strata opened in your browser because the app window couldn't start on this computer." ; 28 29/// What the command line asked for. 30# [ derive ( Debug , Default , PartialEq , Eq )] 31pub struct Options { 32/// `--browser` or STRATA_UI=browser: no app window, the page opens in the default browser. 33pub browser : bool , 34/// `--quit`: end a running Strata and leave. 35pub quit : bool , 36/// `--window-child`: the window process (started by the shell, not by a person). 37pub window_child : bool , 38/// `--save-logs`: collect the logs into one file in Downloads and leave. 39pub save_logs : bool , 40pub help : bool , 41} 42 43pub fn parse_args ( args : & [ String ], ui_env : Option < & str >) ->Options { 44let mut o =Options { browser : matches! ( ui_env. map ( |v| v. trim (). to_ascii_lowercase ()). as_deref (), Some ( "browser" )), ..Options :: default () }; 45for ain args. iter (). skip ( 1 ) { 46match a. as_str () { 47"--browser" => o. browser =true , 48"--quit" => o. quit =true , 49"--window-child" => o. window_child =true , 50"--save-logs" => o. save_logs =true , 51"--help" |"-h" => o. help =true , 52 _ =>{} 53} 54} 55 o 56} 57 58pub const HELP : & str ="Strata\n\ 59(no option) open the Strata app window\n\ 60--browser open Strata in your default browser instead of the app window (same as STRATA_UI=browser)\n\ 61--quit stop a running Strata (its engine too) and leave\n\ 62--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\ 63Closing the browser tab does not stop Strata in browser mode: use Quit Strata in the menu, or --quit.\n" ; 64 65/// The command a person types to run this app again, for the messages ("run: Strata.AppImage --quit"). 66pub fn command_name () ->String { 67if let Ok ( image) = std:: env:: var ( "APPIMAGE" ) { 68if let Some ( name) = std:: path:: Path :: new ( & image). file_name () { 69return format! ( "./{}" , name. to_string_lossy ()); 70} 71} 72 std:: env:: current_exe (). ok (). and_then ( |p| p. file_name (). map ( |n| n. to_string_lossy (). into_owned ())). unwrap_or_else ( ||"strata-desktop" . into ()) 73} 74 75pub fn browser_chosen_line ( port : u16 ) ->String { 76format! ( 77"Strata is open in your browser at http://127.0.0.1:{port}/. Closing the tab does not stop Strata: choose Quit Strata in the menu, or run {} --quit." , 78command_name () 79) 80} 81 82pub fn open_by_hand_line ( port : u16 ) ->String { 83format! ( "No browser could be opened. Open http://127.0.0.1:{port}/ in your browser." ) 84} 85 86// ------------------------------------------------------------------------------------------------ the session file 87 88# [ derive ( Debug , Clone , PartialEq , Eq )] 89pub struct Session { 90pub pid : u32 , 91pub port : u16 , 92pub token : String , 93pub mode : String , 94} 95 96fn session_path () ->PathBuf { 97if let Some ( p) = std:: env:: var_os ( "STRATA_APP_SESSION_FILE" ) { 98return PathBuf :: from ( p); 99} 100let home = std:: env:: var_os ( "HOME" ). map ( PathBuf :: from). unwrap_or_else ( std:: env:: temp_dir); 101 home. join ( ".strata" ). join ( "app-session.json" ) 102} 103 104pub fn write_session ( s : & Session ) { 105let path =session_path (); 106if let Some ( dir) = path. parent () { 107let _ = std:: fs:: create_dir_all ( dir); 108} 109let text = serde_json:: json!({ "pid" : s. pid , "port" : s. port , "token" : s. token , "mode" : s. mode }). to_string (); 110let mut options = std:: fs:: OpenOptions :: new (); 111 options. write ( true ). create ( true ). truncate ( true ); 112# [ cfg ( unix )] 113{ 114use std:: os:: unix:: fs:: OpenOptionsExt ; 115 options. mode ( 0o600 ); 116} 117match options. open ( & path) { 118Ok ( mut f) =>{ 119let _ = f. write_all ( text. as_bytes ()); 120} 121Err ( e) =>eprintln! ( "[strata] could not write {}: {e}" , path. display ()), 122} 123} 124 125pub fn read_session () ->Option < Session > { 126let text = std:: fs:: read_to_string ( session_path ()). ok () ?; 127let v: serde_json:: Value = serde_json:: from_str ( & text). ok () ?; 128Some ( Session { 129pid : v[ "pid" ]. as_u64 () ?as u32 , 130port : v[ "port" ]. as_u64 () ?as u16 , 131token : v[ "token" ]. as_str () ?. to_string (), 132mode : v[ "mode" ]. as_str (). unwrap_or ( "window" ). to_string (), 133}) 134} 135 136pub fn remove_session ( only_if_pid : u32 ) { 137if read_session (). map ( |s| s. pid == only_if_pid). unwrap_or ( false ) { 138let _ = std:: fs:: remove_file ( session_path ()); 139} 140} 141 142fn pid_alive ( pid : u32 ) ->bool { 143# [ cfg ( target_os = "linux" )] 144{ 145 std:: path:: Path :: new ( & format! ( "/proc/{pid}" )). exists () 146} 147# [ cfg ( not ( target_os = "linux" ))] 148{ 149let _ = pid; 150true 151} 152} 153 154/// A Strata that is really running: its shell process exists and its host answers. 155pub fn live_session () ->Option < Session > { 156let s =read_session () ?; 157if s. pid != std:: process:: id () &&pid_alive ( s. pid ) &&crate :: ureq_get_ok ( & format! ( "http://127.0.0.1:{}/api/health" , s. port )). unwrap_or ( false ) { 158Some ( s) 159} else { 160None 161} 162} 163 164// ------------------------------------------------------------------------------------------------ talking to the host 165 166/// POST to the host as the shell (the secret in the header). Returns the response body. 167fn host_post ( port : u16 , token : & str , path : & str , body : & serde_json:: Value ) ->Result < String , String > { 168let ( status, text) =crate :: http_request_body ( "POST" , & format! ( "http://127.0.0.1:{port}{path}" ), & [( "x-strata-shutdown" , token), ( "content-type" , "application/json" )], Some ( & body. to_string ())) ?; 169if status. contains ( " 200" ) || status. contains ( " 202" ) { 170Ok ( text) 171} else { 172Err ( format! ( "{status}: {text}" )) 173} 174} 175 176/// Did the host manage to open the page (the "opened" flag in its answer)? 177fn opened ( answer : & str ) ->bool { 178let body = answer. rsplit ( "\r\n\r\n" ). next (). unwrap_or ( answer); 179 serde_json:: from_str ::< serde_json:: Value >( body. trim ()). ok (). and_then ( |v| v[ "opened" ]. as_bool ()). unwrap_or ( false ) 180} 181 182/// Tell the host: everyone uses a browser tab now (and open it, and show `notice`). Prints what happened. 183pub fn switch_host_to_browser ( port : u16 , token : & str , reason : & str , notice : & str ) { 184let body = serde_json:: json!({ "mode" : "browser" , "reason" : reason, "notice" : notice, "open" : true }); 185match host_post ( port, token, "/api/control/ui" , & body) { 186Ok ( answer) =>{ 187if !opened ( & answer) { 188eprintln! ( "[strata] {}" , open_by_hand_line ( port)); 189} 190} 191Err ( e) =>eprintln! ( "[strata] could not tell the host to open your browser ({e}). Open http://127.0.0.1:{port}/ in your browser." ), 192} 193} 194 195/// Open the page in the default browser without changing the host's mode (a second start while Strata runs). 196fn open_page_only ( port : u16 , token : & str ) { 197match host_post ( port, token, "/api/control/ui" , & serde_json:: json!({ "open" : true })) { 198Ok ( answer) if opened ( & answer) =>{} 199 _ =>eprintln! ( "[strata] {}" , open_by_hand_line ( port)), 200} 201} 202 203pub fn describe_exit ( status : & ExitStatus ) ->String { 204# [ cfg ( unix )] 205{ 206use std:: os:: unix:: process:: ExitStatusExt ; 207if let Some ( sig) = status. signal () { 208let name =match sig{ 2096 =>" (abort)" , 21011 =>" (segmentation fault)" , 2117 =>" (bus error)" , 2129 =>" (killed)" , 21315 =>" (terminated)" , 214 _ =>"" , 215}; 216return format! ( "signal {sig}{name}" ); 217} 218} 219match status. code () { 220Some ( 127 ) =>"exit code 127: a program file it needs is missing" . into (), 221Some ( 126 ) =>"exit code 126: a program file it needs could not be run" . into (), 222Some ( c) =>format! ( "exit code {c}" ), 223None =>"ended without a code" . into (), 224} 225} 226 227// ------------------------------------------------------------------------------------------------ after an app update 228 229/// The shell's process id, given to the window process it starts. A window process whose parent is not that shell was started by something else: the 230/// app updater's restart (Tauri's `app.restart()` starts `$APPIMAGE --window-child` again from the window process, with the old shell's environment). 231pub const SHELL_PID_ENV : & str ="STRATA_SHELL_PID" ; 232 233/// Was this `--window-child` started by its shell? `shell_env` is SHELL_PID_ENV's value, `parent` this process's parent. 234pub fn started_by_shell ( shell_env : Option < & str >, parent : u32 ) ->bool { 235 shell_env. and_then ( |v| v. trim (). parse ::< u32 >(). ok ()). map ( |pid| pid !=0 && pid == parent). unwrap_or ( false ) 236} 237 238/// How long a restarted app waits for the old one (its shell stops the host and the engines first, up to HOST_STOP_SECONDS). 239pub fn old_shell_wait () ->Duration { 240Duration :: from_secs ( crate :: HOST_STOP_SECONDS +20 ) 241} 242 243fn b64_value ( c : u8 ) ->Option < u32 > { 244match c{ 245b'A' ..=b'Z' =>Some (( c -b'A' ) as u32 ), 246b'a' ..=b'z' =>Some (( c -b'a' ) as u32 +26 ), 247b'0' ..=b'9' =>Some (( c -b'0' ) as u32 +52 ), 248b'+' =>Some ( 62 ), 249b'/' =>Some ( 63 ), 250 _ =>None , 251} 252} 253 254/// Standard base64 (what `base64 -w0` writes); None on anything else. 255pub fn b64_decode ( text : & str ) ->Option < Vec < u8 >> { 256let bytes: Vec < u8 > = text. bytes (). filter ( |c| !c. is_ascii_whitespace ()). collect (); 257let body = bytes. strip_suffix ( b"==" ). or_else ( || bytes. strip_suffix ( b"=" )). unwrap_or ( & bytes); 258let mut out =Vec :: with_capacity ( body. len () * 3 /4 ); 259let ( mut acc, mut bits) =( 0u32 , 0u32 ); 260for & cin body{ 261 acc =( acc <<6 ) |b64_value ( c) ?; 262 bits +=6 ; 263if bits >=8 { 264 bits -=8 ; 265 out. push (( acc >> bits) as u8 ); 266 acc &=( 1 << bits) -1 ; 267} 268} 269Some ( out) 270} 271 272/// The environment a person started Strata with: the AppImage's launcher records it in STRATA_ORIGINAL_ENV (`env -0 | base64 -w0`, repack-appimage.sh) at 273/// every start. A start from inside a running Strata (the updater's restart) records Strata's own environment, which holds the first record: the innermost 274/// one is the person's. None when there is no record (an older AppImage, a package install). 275pub fn original_environment ( record : Option < & str >) ->Option < Vec <( String , String )>> { 276let mut text = record?. to_string (); 277let mut found =None ; 278for _in 0 ..8 { 279let raw =b64_decode ( & text) ?; 280let vars: Vec <( String , String )> = raw 281. split ( |b|* b ==0 ) 282. filter ( |kv| !kv. is_empty ()) 283. filter_map ( |kv|{ 284let kv =String :: from_utf8_lossy ( kv); 285let ( k, v) = kv. split_once ( '=' ) ?; 286Some (( k. to_string (), v. to_string ())) 287}) 288. collect (); 289let inner = vars. iter (). find ( |( k, _) | k =="STRATA_ORIGINAL_ENV" ). map ( |( _, v) | v. clone ()); 290 found =Some ( vars); 291match inner{ 292Some ( next) if !next. is_empty () => text = next, 293 _ =>break , 294} 295} 296 found. map ( |vars| vars. into_iter (). filter ( |( k, _) | k !="STRATA_ORIGINAL_ENV" ). collect ()) 297} 298 299/// The new Strata gets none of this process's files above stderr. This process got them from the window process that restarted it: the AppImage 300/// runtime's keep-alive pipe and its fd to /tmp/.mount_*, WebKit's /proc and cgroup files. A child that inherits them keeps the old AppImage's runtime and 301/// mount alive until the new app quits (seen in the 0.2.14 gate). They are closed in the child only, between fork and exec: closing them in this process 302/// would end this AppImage's own mount under it (the keep-alive pipe), which is what the first try did. 303# [ cfg ( unix )] 304fn close_fds_in_child ( cmd : & mut Command ) { 305use std:: os:: fd::{ FromRawFd , OwnedFd }; 306use std:: os:: unix:: process:: CommandExt ; 307// SAFETY: runs in the forked child before exec; close() is async-signal-safe, and nothing in the child uses these numbers (stdio is 0..=2, 308// already set to /dev/null). A number that is not open only gives EBADF, which the drop ignores. 309unsafe { 310 cmd. pre_exec ( ||{ 311for fdin 3 ..4096 { 312drop ( OwnedFd :: from_raw_fd ( fd)); 313} 314Ok (()) 315}); 316} 317} 318 319/// The program to start again: the AppImage file (the updater replaced it in place), else this executable. 320fn program_to_restart () ->Option < PathBuf > { 321if let Some ( image) = std:: env:: var_os ( "APPIMAGE" ). filter ( |v| !v. is_empty ()) { 322return Some ( PathBuf :: from ( image)); 323} 324let exe = std:: env:: current_exe (). ok () ?; 325// a replaced executable reads as "<path> (deleted)" in /proc/self/exe 326let text = exe. to_string_lossy (); 327Some ( text. strip_suffix ( " (deleted)" ). map ( PathBuf :: from). unwrap_or ( exe)) 328} 329 330/// A `--window-child` that its shell did not start: the app updater's restart after an update (0.2.13 and later restart this way; QAGUI-LIN 0213, scenario 12). 331/// The old shell is stopping its host and engines, because its window process ended. Wait until it is gone, then start Strata again the way a person does 332/// (a new shell, a new host), detached, and leave. If the old shell is still there after the wait, nothing is started: two Strata apps never run at once, 333/// and a person's next start joins or replaces the old one as usual. Prints nothing: the old shell owned this process's output and is gone. 334pub fn restart_after_update () ->i32 { 335let log =Log :: open (); 336let old = std:: env:: var ( SHELL_PID_ENV ). ok (). and_then ( |v| v. trim (). parse ::< u32 >(). ok ()). filter ( |p|* p !=0 ). or_else ( ||read_session (). map ( |s| s. pid )); 337 log. line ( "shell" , & format! ( "started as the app window by the app updater, not by Strata (old app process {old:?}): restarting Strata" )); 338if let Some ( pid) = old. filter ( |p|* p != std:: process:: id ()) { 339let deadline =Instant :: now () +old_shell_wait (); 340while pid_alive ( pid) { 341if Instant :: now () >= deadline{ 342 log. line ( "shell" , & format! ( "the old Strata (process {pid}) did not stop within {} s: not starting a second one" , old_shell_wait (). as_secs ())); 343return 0 ; 344} 345 std:: thread:: sleep ( Duration :: from_millis ( 200 )); 346} 347} 348if live_session (). is_some () { 349 log. line ( "shell" , "another Strata is already running: not starting a second one" ); 350return 0 ; 351} 352let Some ( program) =program_to_restart () else { 353 log. line ( "shell" , "could not tell which program to start again" ); 354return 1 ; 355}; 356let mut cmd =Command :: new ( & program); 357match original_environment ( std:: env:: var ( "STRATA_ORIGINAL_ENV" ). ok (). as_deref ()) { 358Some ( vars) =>{ 359 cmd. env_clear (). envs ( vars); 360} 361None =>{ 362for kin [ "STRATA_WINDOW_PORT" , "STRATA_SHUTDOWN_TOKEN" , SHELL_PID_ENV ] { 363 cmd. env_remove ( k); 364} 365} 366} 367 cmd. stdin ( Stdio :: null ()). stdout ( Stdio :: null ()). stderr ( Stdio :: null ()); 368# [ cfg ( unix )] 369{ 370use std:: os:: unix:: process:: CommandExt ; 371 cmd. process_group ( 0 ); 372close_fds_in_child ( & mut cmd); 373} 374match cmd. spawn () { 375Ok ( child) =>{ 376 log. line ( "shell" , & format! ( "started {} again (process {})" , program. display (), child. id ())); 3770 378} 379Err ( e) =>{ 380 log. line ( "shell" , & format! ( "could not start {} again: {e}" , program. display ())); 3811 382} 383} 384} 385 386// ------------------------------------------------------------------------------------------------ the shell 387 388fn spawn_window ( port : u16 , token : & str ) -> std:: io:: Result < Child > { 389let exe = std:: env:: current_exe () ?; 390Command :: new ( exe) 391. arg ( "--window-child" ) 392. env ( "STRATA_WINDOW_PORT" , port. to_string ()) 393. env ( "STRATA_SHUTDOWN_TOKEN" , token) 394. env ( SHELL_PID_ENV , std:: process:: id (). to_string ()) 395. stdin ( Stdio :: null ()) 396. stdout ( Stdio :: inherit ()) 397. stderr ( Stdio :: inherit ()) 398. spawn () 399} 400 401/// `--quit`: end a running Strata (the window, the host, the engines it started) and wait for it. 402pub fn quit_running () ->i32 { 403let Some ( s) =live_session () else { 404println! ( "Strata is not running." ); 405let _ = std:: fs:: remove_file ( session_path ()); 406return 0 ; 407}; 408match host_post ( s. port , & s. token , "/api/control/shutdown" , & serde_json:: json!({})) { 409Ok ( _) =>{} 410Err ( e) =>{ 411eprintln! ( "[strata] could not ask Strata to stop ({e})." ); 412return 1 ; 413} 414} 415let deadline =Instant :: now () +Duration :: from_secs ( crate :: HOST_STOP_SECONDS +10 ); 416while Instant :: now () < deadline{ 417if !pid_alive ( s. pid ) { 418println! ( "Strata has stopped." ); 419return 0 ; 420} 421 std:: thread:: sleep ( Duration :: from_millis ( 200 )); 422} 423eprintln! ( "[strata] Strata is still stopping its engine. Try again in a moment." ); 4241 425} 426 427/// A second start while Strata already runs: focus the window, or open another tab. Starts no second host. 428fn join_running ( s : & Session , browser : bool ) ->i32 { 429if browser || s. mode =="browser" { 430println! ( "Strata is already running. Opening it in your browser." ); 431open_page_only ( s. port , & s. token ); 432return 0 ; 433} 434// window mode: the window process's single-instance check brings the open window forward and exits at once 435match spawn_window ( s. port , & s. token ). and_then ( |mut c| c. wait ()) { 436Ok ( status) if status. success () =>0 , 437Ok ( status) =>{ 438eprintln! ( "[strata] The app window stopped ({}). Opening Strata in your browser." , describe_exit ( & status)); 439open_page_only ( s. port , & s. token ); 4400 441} 442Err ( e) =>{ 443eprintln! ( "[strata] could not start the app window ({e}). Opening Strata in your browser." ); 444open_page_only ( s. port , & s. token ); 4450 446} 447} 448} 449 450/// Start a child with its output copied to the terminal, the log and a ring (for the crash log). 451fn spawn_logged ( cmd : & mut Command , who : &' static str , ring : & Ring , log : & Log ) -> std:: io:: Result < Child > { 452 cmd. stdout ( Stdio :: piped ()). stderr ( Stdio :: piped ()); 453let mut child = cmd. spawn () ?; 454if let Some ( out) = child. stdout . take () { 455 desktoplog:: tee ( out, who, false , ring. clone (), log. clone ()); 456} 457if let Some ( err) = child. stderr . take () { 458 desktoplog:: tee ( err, who, true , ring. clone (), log. clone ()); 459} 460Ok ( child) 461} 462 463/// The window process died without being closed: say so in plain words, write the crash log, move everyone to the browser. 464fn window_failed ( why : & str , window_pid : u32 , window_ring : & Ring , host_ring : & Ring , log : & Log , port : u16 , token : & str ) { 465say ( log, & format! ( "The app window crashed ({why})." )); 466// let the copy threads read the last lines the dead process wrote 467 std:: thread:: sleep ( Duration :: from_millis ( 300 )); 468match desktoplog:: write_crash_log ( why, window_pid, window_ring, host_ring, log) { 469Some ( path) =>say ( log, & format! ( "The crash log is {}. To collect the logs for us: {} --save-logs" , path. display (), command_name ())), 470None =>say ( log, & format! ( "The crash log could not be written. To collect the logs for us: {} --save-logs" , command_name ())), 471} 472say ( log, BROWSER_NOTICE ); 473switch_host_to_browser ( port, token, "window-failed" , BROWSER_NOTICE ); 474} 475 476/// The shell. Returns the process exit code. 477pub fn run ( opts : & Options ) ->i32 { 478if opts. help { 479print! ( "{HELP}" ); 480return 0 ; 481} 482if opts. save_logs { 483return match desktoplog:: save_logs ( & desktoplog:: downloads_dir ()) { 484Ok ( path) =>{ 485println! ( "Saved to {}. Please send this file to us." , path. display ()); 4860 487} 488Err ( e) =>{ 489eprintln! ( "[strata] could not save the logs: {e}" ); 4901 491} 492}; 493} 494if opts. quit { 495return quit_running (); 496} 497if let Some ( s) =live_session () { 498return join_running ( & s, opts. browser ); 499} 500 501let log =Log :: open (); 502let ( host_ring, window_ring) =( Ring :: default (), Ring :: default ()); 503let exe = std:: env:: current_exe (). unwrap_or_default (); 504let res =crate :: packaged_resource_dir ( & exe). unwrap_or_else ( ||PathBuf :: from ( env! ( "CARGO_MANIFEST_DIR" ))); 505let port =match crate :: pick_stable_port () { 506Ok ( p) => p, 507Err ( e) =>{ 508say ( & log, & e); 509return 1 ; 510} 511}; 512let token =crate :: random_token (); 513let mode =if opts. browser { "browser" } else { "window" }; 514let mut cmd =match crate :: host_command ( & res, port, & token) { 515Ok ( c) => c, 516Err ( e) =>{ 517say ( & log, & e); 518return 1 ; 519} 520}; 521 cmd. env ( "STRATA_UI_MODE" , mode). env ( "STRATA_APP_VERSION" , env! ( "CARGO_PKG_VERSION" )); 522if opts. browser { 523 cmd. env ( "STRATA_UI_REASON" , "chosen" ); 524} 525let mut host =match spawn_logged ( & mut cmd, "host" , & host_ring, & log) { 526Ok ( c) => c, 527Err ( e) =>{ 528say ( & log, & format! ( "could not start the App Host: {e}" )); 529return 1 ; 530} 531}; 532let health =crate :: wait_for_health ( port, Duration :: from_secs ( 60 ), ||match host. try_wait () { 533Ok ( Some ( status)) =>Some ( format! ( "exit status {status}" )), 534 _ =>None , 535}); 536if let Err ( e) = health{ 537say ( & log, & e); 538let _ = host. kill (); 539let _ = host. wait (); 540return 1 ; 541} 542let me = std:: process:: id (); 543write_session ( & Session { pid : me, port, token : token. clone (), mode : mode. into () }); 544 545let mut window: Option < Child > =None ; 546if opts. browser { 547say ( & log, & browser_chosen_line ( port)); 548switch_host_to_browser ( port, & token, "chosen" , "" ); 549} else { 550let started = std:: env:: current_exe (). and_then ( |exe|{ 551let mut c =Command :: new ( exe); 552 c. arg ( "--window-child" ). env ( "STRATA_WINDOW_PORT" , port. to_string ()). env ( "STRATA_SHUTDOWN_TOKEN" , & token). env ( SHELL_PID_ENV , me. to_string ()). stdin ( Stdio :: null ()); 553spawn_logged ( & mut c, "window" , & window_ring, & log) 554}); 555match started{ 556Ok ( c) => window =Some ( c), 557Err ( e) =>{ 558window_failed ( & format! ( "it could not be started: {e}" ), 0 , & window_ring, & host_ring, & log, port, & token); 559write_session ( & Session { pid : me, port, token : token. clone (), mode : "browser" . into () }); 560} 561} 562} 563 564let code =loop { 565 std:: thread:: sleep ( Duration :: from_millis ( 200 )); 566// The host ended (Quit Strata, a crash, someone killed it): nothing is left to show. 567if let Ok ( Some ( status)) = host. try_wait () { 568if let Some ( w) = window. as_mut () { 569let _ = w. kill (); 570let _ = w. wait (); 571} 572if status. success () { 573 log. line ( "shell" , "the host stopped (Quit Strata or the window was closed)" ); 574break 0 ; 575} 576say ( & 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 ())); 577break 1 ; 578} 579let Some ( w) = window. as_mut () else { continue }; 580let window_pid = w. id (); 581let Ok ( Some ( status)) = w. try_wait () else { continue }; 582 window =None ; 583if status. success () { 584// the person closed the window: stop the host and the engines this app started, as before 585 log. line ( "shell" , "the window was closed: stopping the host" ); 586crate :: stop_host_child ( & mut host, Some ( port), Some ( & token)); 587break 0 ; 588} 589// The window stopped without being closed: keep Strata running and move to the browser. 590window_failed ( & describe_exit ( & status), window_pid, & window_ring, & host_ring, & log, port, & token); 591write_session ( & Session { pid : me, port, token : token. clone (), mode : "browser" . into () }); 592}; 593remove_session ( me); 594 code 595} 596 597# [ cfg ( test )] 598mod tests{ 599use super :: * ; 600 601fn args ( list : & [ & str ]) ->Vec < String > { 602 std:: iter:: once ( "strata-desktop" ). chain ( list. iter (). copied ()). map ( String :: from). collect () 603} 604 605# [ test ] 606fn the_command_line_picks_browser_quit_and_the_window_child () { 607assert_eq! ( parse_args ( & args ( & []), None ), Options :: default ()); 608assert! ( parse_args ( & args ( & [ "--browser" ]), None ). browser ); 609assert! ( parse_args ( & args ( & []), Some ( "browser" )). browser ); 610assert! ( parse_args ( & args ( & []), Some ( " Browser " )). browser ); 611assert! ( !parse_args ( & args ( & []), Some ( "window" )). browser ); 612assert! ( parse_args ( & args ( & [ "--quit" ]), None ). quit ); 613assert! ( parse_args ( & args ( & [ "--window-child" ]), None ). window_child ); 614assert! ( parse_args ( & args ( & [ "--save-logs" ]), None ). save_logs ); 615assert! ( parse_args ( & args ( & [ "-h" ]), None ). help ); 616// anything else (a file the desktop hands over, an AppImage option) is ignored 617assert_eq! ( parse_args ( & args ( & [ "--appimage-extract-and-run" , "x.gguf" ]), None ), Options :: default ()); 618} 619 620# [ test ] 621fn the_browser_message_is_the_plain_sentence_and_names_the_way_out () { 622assert_eq! ( BROWSER_NOTICE , "Strata opened in your browser because the app window couldn't start on this computer." ); 623let line =browser_chosen_line ( 47831 ); 624assert! ( line. contains ( "http://127.0.0.1:47831/" ) && line. contains ( "--quit" ) && line. contains ( "Quit Strata" )); 625assert! ( open_by_hand_line ( 47831 ). contains ( "127.0.0.1:47831" )); 626} 627 628# [ test ] 629fn a_session_round_trips_and_is_private () { 630let dir = std:: env:: temp_dir (). join ( format! ( "strata-session-test-{}" , std:: process:: id ())); 631let _ = std:: fs:: remove_dir_all ( & dir); 632 std:: env:: set_var ( "STRATA_APP_SESSION_FILE" , dir. join ( "s.json" )); 633assert! ( read_session (). is_none ()); 634let s =Session { pid : 4242 , port : 47831 , token : "ab" . repeat ( 32 ), mode : "browser" . into () }; 635write_session ( & s); 636assert_eq! ( read_session (), Some ( s. clone ())); 637# [ cfg ( unix )] 638{ 639use std:: os:: unix:: fs:: PermissionsExt ; 640assert_eq! ( std:: fs:: metadata ( dir. join ( "s.json" )). unwrap (). permissions (). mode () & 0o777 , 0o600 ); 641} 642// only the owner removes it 643remove_session ( 1 ); 644assert! ( read_session (). is_some ()); 645remove_session ( 4242 ); 646assert! ( read_session (). is_none ()); 647 std:: env:: remove_var ( "STRATA_APP_SESSION_FILE" ); 648let _ = std:: fs:: remove_dir_all ( & dir); 649} 650 651# [ test ] 652fn only_the_shell_that_is_the_parent_counts_as_the_shell () { 653assert! ( started_by_shell ( Some ( "4242" ), 4242 )); 654assert! ( started_by_shell ( Some ( " 4242\n" ), 4242 )); 655// the updater's restart: the old shell's pid is inherited, but the parent is the old window process (or init once it is gone) 656assert! ( !started_by_shell ( Some ( "4242" ), 4300 )); 657assert! ( !started_by_shell ( Some ( "4242" ), 1 )); 658// 0.2.13's shell never set it: a 0.2.14 window process started by a 0.2.13 updater restart 659assert! ( !started_by_shell ( None , 4242 )); 660assert! ( !started_by_shell ( Some ( "x" ), 4242 )); 661assert! ( !started_by_shell ( Some ( "0" ), 0 )); 662} 663 664# [ test ] 665fn base64_decodes_what_base64_w0_writes () { 666assert_eq! ( b64_decode ( "" ). unwrap (), b"" ); 667assert_eq! ( b64_decode ( "YQ==" ). unwrap (), b"a" ); 668assert_eq! ( b64_decode ( "YWI=" ). unwrap (), b"ab" ); 669assert_eq! ( b64_decode ( "YWJj" ). unwrap (), b"abc" ); 670assert_eq! ( b64_decode ( "SE9NRT0vaG9tZS91AFBBVEg9L3Vzci9iaW4A" ). unwrap (), b"HOME=/home/u\0PATH=/usr/bin\0" ); 671assert! ( b64_decode ( "not base64!" ). is_none ()); 672} 673 674fn b64_encode ( data : & [ u8 ]) ->String { 675const T : & [ u8 ; 64 ] =b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" ; 676let mut out =String :: new (); 677for chunkin data. chunks ( 3 ) { 678let n = chunk. iter (). enumerate (). fold ( 0u32 , |acc, ( i, b) | acc |( * bas u32 ) <<( 16 -8 * i)); 679for iin 0 ..4 { 680 out. push ( if i <= chunk. len () { T [(( n >>( 18 -6 * i)) & 63 ) as usize ] as char } else { '=' }); 681} 682} 683 out 684} 685 686# [ test ] 687fn the_restart_gets_the_environment_the_person_started_strata_with () { 688// the first start: AppRun records the person's environment 689let person =b"HOME=/home/u\0PATH=/usr/bin\0STRATA_UPDATE_FEED=http://127.0.0.1:1/f.json\0" ; 690let first =b64_encode ( person); 691// inside Strata (the old window process): the old AppRun's own variables plus that record; the updater's restart records THAT 692let inside =format! ( "HOME=/home/u\0PATH=/tmp/.mount_old/usr/bin:/usr/bin\0APPDIR=/tmp/.mount_old\0STRATA_WINDOW_PORT=47958\0STRATA_ORIGINAL_ENV={first}\0" ); 693let second =b64_encode ( inside. as_bytes ()); 694let env =original_environment ( Some ( & second)). unwrap (); 695assert_eq! ( env, vec! [( "HOME" . into (), "/home/u" . into ()), ( "PATH" . into (), "/usr/bin" . into ()), ( "STRATA_UPDATE_FEED" . into (), "http://127.0.0.1:1/f.json" . into ())]); 696assert_eq! ( original_environment ( Some ( & first)). unwrap (). len (), 3 ); 697assert! ( original_environment ( None ). is_none ()); 698assert! ( original_environment ( Some ( "%%%" )). is_none ()); 699} 700 701# [ test ] 702fn the_wait_for_the_old_app_covers_its_host_stop () { 703assert! ( old_shell_wait () >Duration :: from_secs ( crate :: HOST_STOP_SECONDS )); 704} 705 706# [ test ] 707fn the_hosts_answer_tells_whether_a_browser_opened () { 708assert! ( opened ( "HTTP/1.1 200 OK\r\n\r\n{\"mode\":\"browser\",\"opened\":true}" )); 709assert! ( !opened ( "HTTP/1.1 200 OK\r\n\r\n{\"mode\":\"browser\",\"opened\":false}" )); 710assert! ( !opened ( "not json" )); 711} 712}