okami.mom/strata

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

Niko1221Merge main (87dfca0e7) into f-own-int: the 0.2.14 app branch, fixtures and CI fixes, the Qwen4-readiness tools, the shape-engine build scriptsffb3d9b31

main
30.7 KiB712 linesraw
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.
33    pub browser: bool,
34    /// `--quit`: end a running Strata and leave.
35    pub quit: bool,
36    /// `--window-child`: the window process (started by the shell, not by a person).
37    pub window_child: bool,
38    /// `--save-logs`: collect the logs into one file in Downloads and leave.
39    pub save_logs: bool,
40    pub help: bool,
41}
42
43pub fn parse_args(args: &[String], ui_env: Option<&str>) -> Options {
44    let mut o = Options { browser: matches!(ui_env.map(|v| v.trim().to_ascii_lowercase()).as_deref(), Some("browser")), ..Options::default() };
45    for a in args.iter().skip(1) {
46        match 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 {
67    if let Ok(image) = std::env::var("APPIMAGE") {
68        if let Some(name) = std::path::Path::new(&image).file_name() {
69            return 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 {
76    format!(
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.",
78        command_name()
79    )
80}
81
82pub fn open_by_hand_line(port: u16) -> String {
83    format!("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 {
90    pub pid: u32,
91    pub port: u16,
92    pub token: String,
93    pub mode: String,
94}
95
96fn session_path() -> PathBuf {
97    if let Some(p) = std::env::var_os("STRATA_APP_SESSION_FILE") {
98        return PathBuf::from(p);
99    }
100    let 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) {
105    let path = session_path();
106    if let Some(dir) = path.parent() {
107        let _ = std::fs::create_dir_all(dir);
108    }
109    let text = serde_json::json!({ "pid": s.pid, "port": s.port, "token": s.token, "mode": s.mode }).to_string();
110    let mut options = std::fs::OpenOptions::new();
111    options.write(true).create(true).truncate(true);
112    #[cfg(unix)]
113    {
114        use std::os::unix::fs::OpenOptionsExt;
115        options.mode(0o600);
116    }
117    match options.open(&path) {
118        Ok(mut f) => {
119            let _ = f.write_all(text.as_bytes());
120        }
121        Err(e) => eprintln!("[strata] could not write {}: {e}", path.display()),
122    }
123}
124
125pub fn read_session() -> Option<Session> {
126    let text = std::fs::read_to_string(session_path()).ok()?;
127    let v: serde_json::Value = serde_json::from_str(&text).ok()?;
128    Some(Session {
129        pid: v["pid"].as_u64()? as u32,
130        port: v["port"].as_u64()? as u16,
131        token: v["token"].as_str()?.to_string(),
132        mode: v["mode"].as_str().unwrap_or("window").to_string(),
133    })
134}
135
136pub fn remove_session(only_if_pid: u32) {
137    if read_session().map(|s| s.pid == only_if_pid).unwrap_or(false) {
138        let _ = 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    {
149        let _ = pid;
150        true
151    }
152}
153
154/// A Strata that is really running: its shell process exists and its host answers.
155pub fn live_session() -> Option<Session> {
156    let s = read_session()?;
157    if 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) {
158        Some(s)
159    } else {
160        None
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> {
168    let (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()))?;
169    if status.contains(" 200") || status.contains(" 202") {
170        Ok(text)
171    } else {
172        Err(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 {
178    let 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) {
184    let body = serde_json::json!({ "mode": "browser", "reason": reason, "notice": notice, "open": true });
185    match host_post(port, token, "/api/control/ui", &body) {
186        Ok(answer) => {
187            if !opened(&answer) {
188                eprintln!("[strata] {}", open_by_hand_line(port));
189            }
190        }
191        Err(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) {
197    match host_post(port, token, "/api/control/ui", &serde_json::json!({ "open": true })) {
198        Ok(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    {
206        use std::os::unix::process::ExitStatusExt;
207        if let Some(sig) = status.signal() {
208            let name = match sig {
209                6 => " (abort)",
210                11 => " (segmentation fault)",
211                7 => " (bus error)",
212                9 => " (killed)",
213                15 => " (terminated)",
214                _ => "",
215            };
216            return format!("signal {sig}{name}");
217        }
218    }
219    match status.code() {
220        Some(127) => "exit code 127: a program file it needs is missing".into(),
221        Some(126) => "exit code 126: a program file it needs could not be run".into(),
222        Some(c) => format!("exit code {c}"),
223        None => "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 {
240    Duration::from_secs(crate::HOST_STOP_SECONDS + 20)
241}
242
243fn b64_value(c: u8) -> Option<u32> {
244    match c {
245        b'A'..=b'Z' => Some((c - b'A') as u32),
246        b'a'..=b'z' => Some((c - b'a') as u32 + 26),
247        b'0'..=b'9' => Some((c - b'0') as u32 + 52),
248        b'+' => Some(62),
249        b'/' => 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>> {
256    let bytes: Vec<u8> = text.bytes().filter(|c| !c.is_ascii_whitespace()).collect();
257    let body = bytes.strip_suffix(b"==").or_else(|| bytes.strip_suffix(b"=")).unwrap_or(&bytes);
258    let mut out = Vec::with_capacity(body.len() * 3 / 4);
259    let (mut acc, mut bits) = (0u32, 0u32);
260    for &c in body {
261        acc = (acc << 6) | b64_value(c)?;
262        bits += 6;
263        if bits >= 8 {
264            bits -= 8;
265            out.push((acc >> bits) as u8);
266            acc &= (1 << bits) - 1;
267        }
268    }
269    Some(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)>> {
276    let mut text = record?.to_string();
277    let mut found = None;
278    for _ in 0..8 {
279        let raw = b64_decode(&text)?;
280        let vars: Vec<(String, String)> = raw
281            .split(|b| *b == 0)
282            .filter(|kv| !kv.is_empty())
283            .filter_map(|kv| {
284                let kv = String::from_utf8_lossy(kv);
285                let (k, v) = kv.split_once('=')?;
286                Some((k.to_string(), v.to_string()))
287            })
288            .collect();
289        let inner = vars.iter().find(|(k, _)| k == "STRATA_ORIGINAL_ENV").map(|(_, v)| v.clone());
290        found = Some(vars);
291        match inner {
292            Some(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) {
305    use std::os::fd::{FromRawFd, OwnedFd};
306    use 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.
309    unsafe {
310        cmd.pre_exec(|| {
311            for fd in 3..4096 {
312                drop(OwnedFd::from_raw_fd(fd));
313            }
314            Ok(())
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> {
321    if let Some(image) = std::env::var_os("APPIMAGE").filter(|v| !v.is_empty()) {
322        return Some(PathBuf::from(image));
323    }
324    let exe = std::env::current_exe().ok()?;
325    // a replaced executable reads as "<path> (deleted)" in /proc/self/exe
326    let text = exe.to_string_lossy();
327    Some(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 {
335    let log = Log::open();
336    let 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"));
338    if let Some(pid) = old.filter(|p| *p != std::process::id()) {
339        let deadline = Instant::now() + old_shell_wait();
340        while pid_alive(pid) {
341            if 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()));
343                return 0;
344            }
345            std::thread::sleep(Duration::from_millis(200));
346        }
347    }
348    if live_session().is_some() {
349        log.line("shell", "another Strata is already running: not starting a second one");
350        return 0;
351    }
352    let Some(program) = program_to_restart() else {
353        log.line("shell", "could not tell which program to start again");
354        return 1;
355    };
356    let mut cmd = Command::new(&program);
357    match original_environment(std::env::var("STRATA_ORIGINAL_ENV").ok().as_deref()) {
358        Some(vars) => {
359            cmd.env_clear().envs(vars);
360        }
361        None => {
362            for k in ["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    {
370        use std::os::unix::process::CommandExt;
371        cmd.process_group(0);
372        close_fds_in_child(&mut cmd);
373    }
374    match cmd.spawn() {
375        Ok(child) => {
376            log.line("shell", &format!("started {} again (process {})", program.display(), child.id()));
377            0
378        }
379        Err(e) => {
380            log.line("shell", &format!("could not start {} again: {e}", program.display()));
381            1
382        }
383    }
384}
385
386// ------------------------------------------------------------------------------------------------ the shell
387
388fn spawn_window(port: u16, token: &str) -> std::io::Result<Child> {
389    let exe = std::env::current_exe()?;
390    Command::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 {
403    let Some(s) = live_session() else {
404        println!("Strata is not running.");
405        let _ = std::fs::remove_file(session_path());
406        return 0;
407    };
408    match host_post(s.port, &s.token, "/api/control/shutdown", &serde_json::json!({})) {
409        Ok(_) => {}
410        Err(e) => {
411            eprintln!("[strata] could not ask Strata to stop ({e}).");
412            return 1;
413        }
414    }
415    let deadline = Instant::now() + Duration::from_secs(crate::HOST_STOP_SECONDS + 10);
416    while Instant::now() < deadline {
417        if !pid_alive(s.pid) {
418            println!("Strata has stopped.");
419            return 0;
420        }
421        std::thread::sleep(Duration::from_millis(200));
422    }
423    eprintln!("[strata] Strata is still stopping its engine. Try again in a moment.");
424    1
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 {
429    if browser || s.mode == "browser" {
430        println!("Strata is already running. Opening it in your browser.");
431        open_page_only(s.port, &s.token);
432        return 0;
433    }
434    // window mode: the window process's single-instance check brings the open window forward and exits at once
435    match spawn_window(s.port, &s.token).and_then(|mut c| c.wait()) {
436        Ok(status) if status.success() => 0,
437        Ok(status) => {
438            eprintln!("[strata] The app window stopped ({}). Opening Strata in your browser.", describe_exit(&status));
439            open_page_only(s.port, &s.token);
440            0
441        }
442        Err(e) => {
443            eprintln!("[strata] could not start the app window ({e}). Opening Strata in your browser.");
444            open_page_only(s.port, &s.token);
445            0
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());
453    let mut child = cmd.spawn()?;
454    if let Some(out) = child.stdout.take() {
455        desktoplog::tee(out, who, false, ring.clone(), log.clone());
456    }
457    if let Some(err) = child.stderr.take() {
458        desktoplog::tee(err, who, true, ring.clone(), log.clone());
459    }
460    Ok(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) {
465    say(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));
468    match desktoplog::write_crash_log(why, window_pid, window_ring, host_ring, log) {
469        Some(path) => say(log, &format!("The crash log is {}. To collect the logs for us: {} --save-logs", path.display(), command_name())),
470        None => say(log, &format!("The crash log could not be written. To collect the logs for us: {} --save-logs", command_name())),
471    }
472    say(log, BROWSER_NOTICE);
473    switch_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 {
478    if opts.help {
479        print!("{HELP}");
480        return 0;
481    }
482    if opts.save_logs {
483        return match desktoplog::save_logs(&desktoplog::downloads_dir()) {
484            Ok(path) => {
485                println!("Saved to {}. Please send this file to us.", path.display());
486                0
487            }
488            Err(e) => {
489                eprintln!("[strata] could not save the logs: {e}");
490                1
491            }
492        };
493    }
494    if opts.quit {
495        return quit_running();
496    }
497    if let Some(s) = live_session() {
498        return join_running(&s, opts.browser);
499    }
500
501    let log = Log::open();
502    let (host_ring, window_ring) = (Ring::default(), Ring::default());
503    let exe = std::env::current_exe().unwrap_or_default();
504    let res = crate::packaged_resource_dir(&exe).unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")));
505    let port = match crate::pick_stable_port() {
506        Ok(p) => p,
507        Err(e) => {
508            say(&log, &e);
509            return 1;
510        }
511    };
512    let token = crate::random_token();
513    let mode = if opts.browser { "browser" } else { "window" };
514    let mut cmd = match crate::host_command(&res, port, &token) {
515        Ok(c) => c,
516        Err(e) => {
517            say(&log, &e);
518            return 1;
519        }
520    };
521    cmd.env("STRATA_UI_MODE", mode).env("STRATA_APP_VERSION", env!("CARGO_PKG_VERSION"));
522    if opts.browser {
523        cmd.env("STRATA_UI_REASON", "chosen");
524    }
525    let mut host = match spawn_logged(&mut cmd, "host", &host_ring, &log) {
526        Ok(c) => c,
527        Err(e) => {
528            say(&log, &format!("could not start the App Host: {e}"));
529            return 1;
530        }
531    };
532    let health = crate::wait_for_health(port, Duration::from_secs(60), || match host.try_wait() {
533        Ok(Some(status)) => Some(format!("exit status {status}")),
534        _ => None,
535    });
536    if let Err(e) = health {
537        say(&log, &e);
538        let _ = host.kill();
539        let _ = host.wait();
540        return 1;
541    }
542    let me = std::process::id();
543    write_session(&Session { pid: me, port, token: token.clone(), mode: mode.into() });
544
545    let mut window: Option<Child> = None;
546    if opts.browser {
547        say(&log, &browser_chosen_line(port));
548        switch_host_to_browser(port, &token, "chosen", "");
549    } else {
550        let started = std::env::current_exe().and_then(|exe| {
551            let 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());
553            spawn_logged(&mut c, "window", &window_ring, &log)
554        });
555        match started {
556            Ok(c) => window = Some(c),
557            Err(e) => {
558                window_failed(&format!("it could not be started: {e}"), 0, &window_ring, &host_ring, &log, port, &token);
559                write_session(&Session { pid: me, port, token: token.clone(), mode: "browser".into() });
560            }
561        }
562    }
563
564    let 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.
567        if let Ok(Some(status)) = host.try_wait() {
568            if let Some(w) = window.as_mut() {
569                let _ = w.kill();
570                let _ = w.wait();
571            }
572            if status.success() {
573                log.line("shell", "the host stopped (Quit Strata or the window was closed)");
574                break 0;
575            }
576            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()));
577            break 1;
578        }
579        let Some(w) = window.as_mut() else { continue };
580        let window_pid = w.id();
581        let Ok(Some(status)) = w.try_wait() else { continue };
582        window = None;
583        if 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");
586            crate::stop_host_child(&mut host, Some(port), Some(&token));
587            break 0;
588        }
589        // The window stopped without being closed: keep Strata running and move to the browser.
590        window_failed(&describe_exit(&status), window_pid, &window_ring, &host_ring, &log, port, &token);
591        write_session(&Session { pid: me, port, token: token.clone(), mode: "browser".into() });
592    };
593    remove_session(me);
594    code
595}
596
597#[cfg(test)]
598mod tests {
599    use super::*;
600
601    fn args(list: &[&str]) -> Vec<String> {
602        std::iter::once("strata-desktop").chain(list.iter().copied()).map(String::from).collect()
603    }
604
605    #[test]
606    fn the_command_line_picks_browser_quit_and_the_window_child() {
607        assert_eq!(parse_args(&args(&[]), None), Options::default());
608        assert!(parse_args(&args(&["--browser"]), None).browser);
609        assert!(parse_args(&args(&[]), Some("browser")).browser);
610        assert!(parse_args(&args(&[]), Some(" Browser ")).browser);
611        assert!(!parse_args(&args(&[]), Some("window")).browser);
612        assert!(parse_args(&args(&["--quit"]), None).quit);
613        assert!(parse_args(&args(&["--window-child"]), None).window_child);
614        assert!(parse_args(&args(&["--save-logs"]), None).save_logs);
615        assert!(parse_args(&args(&["-h"]), None).help);
616        // anything else (a file the desktop hands over, an AppImage option) is ignored
617        assert_eq!(parse_args(&args(&["--appimage-extract-and-run", "x.gguf"]), None), Options::default());
618    }
619
620    #[test]
621    fn the_browser_message_is_the_plain_sentence_and_names_the_way_out() {
622        assert_eq!(BROWSER_NOTICE, "Strata opened in your browser because the app window couldn't start on this computer.");
623        let line = browser_chosen_line(47831);
624        assert!(line.contains("http://127.0.0.1:47831/") && line.contains("--quit") && line.contains("Quit Strata"));
625        assert!(open_by_hand_line(47831).contains("127.0.0.1:47831"));
626    }
627
628    #[test]
629    fn a_session_round_trips_and_is_private() {
630        let dir = std::env::temp_dir().join(format!("strata-session-test-{}", std::process::id()));
631        let _ = std::fs::remove_dir_all(&dir);
632        std::env::set_var("STRATA_APP_SESSION_FILE", dir.join("s.json"));
633        assert!(read_session().is_none());
634        let s = Session { pid: 4242, port: 47831, token: "ab".repeat(32), mode: "browser".into() };
635        write_session(&s);
636        assert_eq!(read_session(), Some(s.clone()));
637        #[cfg(unix)]
638        {
639            use std::os::unix::fs::PermissionsExt;
640            assert_eq!(std::fs::metadata(dir.join("s.json")).unwrap().permissions().mode() & 0o777, 0o600);
641        }
642        // only the owner removes it
643        remove_session(1);
644        assert!(read_session().is_some());
645        remove_session(4242);
646        assert!(read_session().is_none());
647        std::env::remove_var("STRATA_APP_SESSION_FILE");
648        let _ = std::fs::remove_dir_all(&dir);
649    }
650
651    #[test]
652    fn only_the_shell_that_is_the_parent_counts_as_the_shell() {
653        assert!(started_by_shell(Some("4242"), 4242));
654        assert!(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)
656        assert!(!started_by_shell(Some("4242"), 4300));
657        assert!(!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
659        assert!(!started_by_shell(None, 4242));
660        assert!(!started_by_shell(Some("x"), 4242));
661        assert!(!started_by_shell(Some("0"), 0));
662    }
663
664    #[test]
665    fn base64_decodes_what_base64_w0_writes() {
666        assert_eq!(b64_decode("").unwrap(), b"");
667        assert_eq!(b64_decode("YQ==").unwrap(), b"a");
668        assert_eq!(b64_decode("YWI=").unwrap(), b"ab");
669        assert_eq!(b64_decode("YWJj").unwrap(), b"abc");
670        assert_eq!(b64_decode("SE9NRT0vaG9tZS91AFBBVEg9L3Vzci9iaW4A").unwrap(), b"HOME=/home/u\0PATH=/usr/bin\0");
671        assert!(b64_decode("not base64!").is_none());
672    }
673
674    fn b64_encode(data: &[u8]) -> String {
675        const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
676        let mut out = String::new();
677        for chunk in data.chunks(3) {
678            let n = chunk.iter().enumerate().fold(0u32, |acc, (i, b)| acc | (*b as u32) << (16 - 8 * i));
679            for i in 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]
687    fn the_restart_gets_the_environment_the_person_started_strata_with() {
688        // the first start: AppRun records the person's environment
689        let person = b"HOME=/home/u\0PATH=/usr/bin\0STRATA_UPDATE_FEED=http://127.0.0.1:1/f.json\0";
690        let 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
692        let 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");
693        let second = b64_encode(inside.as_bytes());
694        let env = original_environment(Some(&second)).unwrap();
695        assert_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())]);
696        assert_eq!(original_environment(Some(&first)).unwrap().len(), 3);
697        assert!(original_environment(None).is_none());
698        assert!(original_environment(Some("%%%")).is_none());
699    }
700
701    #[test]
702    fn the_wait_for_the_old_app_covers_its_host_stop() {
703        assert!(old_shell_wait() > Duration::from_secs(crate::HOST_STOP_SECONDS));
704    }
705
706    #[test]
707    fn the_hosts_answer_tells_whether_a_browser_opened() {
708        assert!(opened("HTTP/1.1 200 OK\r\n\r\n{\"mode\":\"browser\",\"opened\":true}"));
709        assert!(!opened("HTTP/1.1 200 OK\r\n\r\n{\"mode\":\"browser\",\"opened\":false}"));
710        assert!(!opened("not json"));
711    }
712}