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
67.4 KiB1468 linesraw
1//! Strata Desktop — Tauri shell.
2//!
3//! The shell is a *carrier*, not an owner. It does exactly three things:
4//!
5//!   1. finds its bundled resources (the private Node runtime, the App Host, the built UI) and
6//!      starts the App Host on a free loopback port;
7//!   2. opens one webview window on the host's own origin, so the renderer and the API share an
8//!      origin exactly as the browser build does and the supplied UI's relative `/api/...` calls
9//!      keep working with no rewrite;
10//!   3. stops the host when the app exits, and sees to it that nothing the app started outlives it.
11//!
12//! One app instance runs at a time (the single-instance plugin): a second launch focuses the window that is
13//! already open and starts nothing, so two apps never fight over the `app-N` engine slots. One app can still run
14//! several engines (one per GPU, say): the host gives each its own `app-N` profile under Strata Control.
15//!
16//! Closing ends the engines this app started, on every path:
17//!   - a normal exit and the window's X: the host is asked to stop them through Control (drained, then ended), with a
18//!     deadline after which the host is ended;
19//!   - the shell is killed, crashes, or the user logs off: on Windows the shell owns a kill-on-close Job Object that
20//!     contains the host, Control, the owner host, the server and the engine, so they end with it; everywhere the host
21//!     watches its parent and each engine's owner is told to follow the host (`--die-with-pid`).
22//! Engines the Terminal started are not in any of this and are left alone.
23//!
24//! Ownership stays where the architecture puts it. The App Host owns the local client API and the
25//! engine lifecycle; Strata Control owns components, models, profiles and jobs; DeepSeek Harness
26//! owns the agent loop and durable sessions. There is deliberately no second supervisor, no
27//! conversation store and no agent loop in this file.
28
29#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
30
31use std::net::TcpListener;
32use std::path::{Path, PathBuf};
33use std::process::{Child, Command, Stdio};
34#[cfg(not(target_os = "linux"))]
35use std::sync::Mutex;
36use std::time::{Duration, Instant};
37
38use tauri::{Manager, WebviewUrl, WebviewWindowBuilder};
39
40mod updater;
41mod desktoplog;
42mod recovery;
43mod shell;
44// Plain std, built on every platform so its decisions are tested everywhere; only the Linux window process uses it.
45#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
46mod fontguard;
47#[cfg(target_os = "linux")]
48mod supervisor;
49
50/// The kill-on-close Job Object that holds everything this app starts (Windows). Its only handle is this process's,
51/// which the system closes however the process ends; closing the last handle ends every process in the job.
52#[cfg(windows)]
53mod job {
54    use std::ffi::c_void;
55
56    type Handle = *mut c_void;
57    const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: u32 = 0x2000;
58    /// A process may ask to start a child outside the job (CREATE_BREAKAWAY_FROM_JOB). Only the app updater does, for the
59    /// installer that replaces this app: it must outlive the app, which the kill-on-close job would otherwise prevent.
60    const JOB_OBJECT_LIMIT_BREAKAWAY_OK: u32 = 0x0800;
61    const JOB_OBJECT_EXTENDED_LIMIT_INFORMATION: i32 = 9;
62
63    #[repr(C)]
64    #[derive(Default)]
65    struct BasicLimits {
66        per_process_user_time_limit: i64,
67        per_job_user_time_limit: i64,
68        limit_flags: u32,
69        minimum_working_set_size: usize,
70        maximum_working_set_size: usize,
71        active_process_limit: u32,
72        affinity: usize,
73        priority_class: u32,
74        scheduling_class: u32,
75    }
76
77    #[repr(C)]
78    #[derive(Default)]
79    struct IoCounters {
80        counts: [u64; 6],
81    }
82
83    #[repr(C)]
84    #[derive(Default)]
85    struct ExtendedLimits {
86        basic: BasicLimits,
87        io: IoCounters,
88        process_memory_limit: usize,
89        job_memory_limit: usize,
90        peak_process_memory_used: usize,
91        peak_job_memory_used: usize,
92    }
93
94    #[link(name = "kernel32")]
95    extern "system" {
96        fn CreateJobObjectW(attributes: *mut c_void, name: *const u16) -> Handle;
97        fn SetInformationJobObject(job: Handle, class: i32, info: *mut c_void, len: u32) -> i32;
98        fn AssignProcessToJobObject(job: Handle, process: Handle) -> i32;
99        fn GetCurrentProcess() -> Handle;
100        fn CloseHandle(handle: Handle) -> i32;
101        fn IsProcessInJob(process: Handle, job: Handle, result: *mut i32) -> i32;
102    }
103
104    /// Is this process inside any job object? (The self-test asks, so an installed build proves it is contained.)
105    pub fn current_process_in_a_job() -> bool {
106        let mut result = 0i32;
107        unsafe { IsProcessInJob(GetCurrentProcess(), std::ptr::null_mut(), &mut result) != 0 && result != 0 }
108    }
109
110    pub struct Job(Handle);
111
112    // The handle is a plain kernel object handle, usable from any thread.
113    unsafe impl Send for Job {}
114    unsafe impl Sync for Job {}
115
116    impl Job {
117        /// A new job that ends all of its processes when its last handle closes. None if the system refuses.
118        pub fn kill_on_close() -> Option<Job> {
119            unsafe {
120                let handle = CreateJobObjectW(std::ptr::null_mut(), std::ptr::null());
121                if handle.is_null() {
122                    return None;
123                }
124                let mut info = ExtendedLimits::default();
125                info.basic.limit_flags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_BREAKAWAY_OK;
126                let ok = SetInformationJobObject(
127                    handle,
128                    JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
129                    &mut info as *mut ExtendedLimits as *mut c_void,
130                    std::mem::size_of::<ExtendedLimits>() as u32,
131                );
132                if ok == 0 {
133                    CloseHandle(handle);
134                    return None;
135                }
136                Some(Job(handle))
137            }
138        }
139
140        /// Put a process (by handle) in the job; everything it starts later joins too.
141        pub fn assign_raw(&self, process: *mut c_void) -> bool {
142            unsafe { AssignProcessToJobObject(self.0, process) != 0 }
143        }
144
145        /// Put this very process in the job, so the host and everything below it are contained.
146        pub fn assign_current(&self) -> bool {
147            self.assign_raw(unsafe { GetCurrentProcess() })
148        }
149    }
150
151    impl Drop for Job {
152        fn drop(&mut self) {
153            unsafe {
154                CloseHandle(self.0);
155            }
156        }
157    }
158}
159
160/// Held for the life of the process. The handle is deliberately never closed by us: the system closes it when the
161/// process ends, by any route, and that is the moment the job ends what is left in it.
162#[cfg(windows)]
163static APP_JOB: std::sync::OnceLock<job::Job> = std::sync::OnceLock::new();
164
165/// Is the app inside a job object right now? Always false off Windows.
166fn app_is_contained() -> bool {
167    #[cfg(windows)]
168    {
169        job::current_process_in_a_job()
170    }
171    #[cfg(not(windows))]
172    {
173        false
174    }
175}
176
177/// Put this process (and so everything it starts) in a kill-on-close job. True if it is contained now.
178fn contain_app() -> bool {
179    #[cfg(windows)]
180    {
181        if let Some(job) = job::Job::kill_on_close() {
182            if job.assign_current() {
183                let _ = APP_JOB.set(job);
184                return true;
185            }
186        }
187        eprintln!("[strata] could not put the app in a job object; engines are stopped by the host and their owners instead");
188        false
189    }
190    #[cfg(not(windows))]
191    {
192        false
193    }
194}
195
196/// The running App Host, kept so it can be stopped on exit.
197#[cfg(not(target_os = "linux"))]
198struct HostProcess(Mutex<Option<Child>>);
199
200/// The port the App Host bound, so the window (and the frontend) can be pointed at it.
201#[cfg(not(target_os = "linux"))]
202struct HostPort(Mutex<Option<u16>>);
203
204/// The secret that lets this shell (and nothing else) ask the host for a clean stop.
205#[cfg(not(target_os = "linux"))]
206struct ShutdownToken(Mutex<Option<String>>);
207
208/// 256 random bits as hex, from the standard library's per-process random hasher keys (no extra crate).
209fn random_token() -> String {
210    use std::collections::hash_map::RandomState;
211    use std::hash::{BuildHasher, Hasher};
212    (0..4)
213        .map(|i| {
214            let mut h = RandomState::new().build_hasher();
215            h.write_u32(i);
216            h.write_u128(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0));
217            format!("{:016x}", h.finish())
218        })
219        .collect()
220}
221
222/// The Control component that ships beside the host (`<resources>/control`): the bundled CPython, the locked
223/// wheels, strata_control and the API server. None in a development checkout.
224fn control_dir(res: &Path) -> Option<PathBuf> {
225    let dir = res.join("control");
226    let python = if cfg!(windows) { dir.join("python").join("python.exe") } else { dir.join("python").join("bin").join("python3") };
227    if python.exists() && dir.join("strata.py").exists() {
228        Some(dir)
229    } else {
230        None
231    }
232}
233
234/// What every host start gets, packaged or self-test: acquiring is forbidden, Control is where the bundle put it.
235fn apply_runtime_policy(cmd: &mut Command, res: &Path) {
236    cmd.env("STRATA_NO_ACQUIRE", "1");
237    if let Some(dir) = control_dir(res) {
238        cmd.env("STRATA_CONTROL_DIR", dir);
239    }
240}
241
242/// Ask the OS for an unused loopback port.
243///
244/// The port is released before the host binds it, so there is a small race; the host reports a
245/// clear "port already in use" error if another process takes it first, and that surfaces in the
246/// window instead of failing silently.
247fn pick_port() -> Result<u16, String> {
248    let listener = TcpListener::bind(("127.0.0.1", 0)).map_err(|e| format!("bind: {e}"))?;
249    let port = listener.local_addr().map_err(|e| format!("addr: {e}"))?.port();
250    drop(listener);
251    Ok(port)
252}
253
254/// The port the app prefers. The window's origin is `http://127.0.0.1:<port>`, and the browser storage that holds the
255/// theme, text size, language and the chat list belongs to that origin, so a port that changed on every launch lost all
256/// of it. The preferred port is fixed; only when something else holds it does the app fall back to a free one (and that
257/// launch starts with empty storage, as before).
258const PREFERRED_PORT: u16 = 47831;
259
260/// Set when the port the person (or the app) wanted was busy: "busy:<wanted>:<used>". The host gets it as STRATA_PORT_NOTICE and tells the
261/// person (the chats and settings saved on the page belong to the port, so a different port starts empty) (#3402).
262static PORT_NOTICE: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
263
264fn pick_stable_port() -> Result<u16, String> {
265    // The person may have chosen a port in Settings (shell-prefs.json); otherwise the app's usual one.
266    let wanted = shell::wanted_port(&shell::read_prefs(), PREFERRED_PORT);
267    *PORT_NOTICE.lock().unwrap() = None;
268    match TcpListener::bind(("127.0.0.1", wanted)) {
269        Ok(listener) => {
270            drop(listener);
271            Ok(wanted)
272        }
273        Err(_) => {
274            let used = pick_port()?;
275            *PORT_NOTICE.lock().unwrap() = Some(shell::busy_notice(wanted, used));
276            Ok(used)
277        }
278    }
279}
280
281/// Locate a bundled resource.
282///
283/// In a packaged `.app` Tauri places `bundle.resources` under `Contents/Resources`. During
284/// development they are not copied, so the repository layout is the fallback. Both are tried so
285/// `tauri dev` and the packaged bundle behave the same way.
286#[cfg(not(target_os = "linux"))]
287fn resource_dir(app: &tauri::AppHandle) -> Result<PathBuf, String> {
288    if let Ok(dir) = app.path().resource_dir() {
289        if dir.join("host").join("server").join("index.mjs").exists() {
290            return Ok(plain_path(dir));
291        }
292    }
293    // development: apps/desktop/src-tauri -> ../../host  and  ./resources
294    let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
295    Ok(manifest)
296}
297
298/// Tauri returns Windows paths in the verbatim form (`\\?\C:\...`). Node cannot take such a path as
299/// its entry script (`EISDIR ... lstat 'C:'`), so the host died at once and the window sat
300/// unresponsive until the health wait gave up. Use the ordinary drive (or UNC) form.
301#[cfg_attr(target_os = "linux", allow(dead_code))]
302fn plain_path(p: PathBuf) -> PathBuf {
303    let text = p.to_string_lossy().into_owned();
304    if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
305        return PathBuf::from(format!(r"\\{rest}"));
306    }
307    match text.strip_prefix(r"\\?\") {
308        Some(rest) => PathBuf::from(rest),
309        None => p,
310    }
311}
312
313/// File name of the bundled Node runtime: `node.exe` on Windows, `node` elsewhere.
314const NODE_EXE: &str = if cfg!(windows) { "node.exe" } else { "node" };
315
316/// Where `tauri dev` finds a Node sidecar prepared next to the checkout (`toolchain/node`).
317fn dev_node_candidate(res: &Path) -> PathBuf {
318    let root = res.join("..").join("..").join("..").join("toolchain").join("node");
319    if cfg!(windows) {
320        // the Windows zip has node.exe at the top of the folder, not under bin/
321        root.join("node-v24.12.0-win-x64").join("node.exe")
322    } else {
323        root.join("node-v24.12.0-darwin-arm64").join("bin").join("node")
324    }
325}
326
327/// The private Node runtime that ships with the bundle.
328fn node_binary(res: &Path) -> Result<PathBuf, String> {
329    let bundled = res.join("node").join(NODE_EXE);
330    if bundled.exists() {
331        return Ok(bundled);
332    }
333    // development fallback: the sidecar prepared alongside the checkout
334    let dev = dev_node_candidate(res);
335    if dev.exists() {
336        return Ok(dev);
337    }
338    Err(format!(
339        "the bundled Node runtime is missing (looked for {} and {})",
340        bundled.display(),
341        dev.display()
342    ))
343}
344
345/// A packaged GUI app must not flash a console window for the host process on Windows.
346#[cfg(windows)]
347fn hide_console(cmd: &mut Command) {
348    use std::os::windows::process::CommandExt;
349    const CREATE_NO_WINDOW: u32 = 0x0800_0000;
350    cmd.creation_flags(CREATE_NO_WINDOW);
351}
352
353#[cfg(not(windows))]
354fn hide_console(_cmd: &mut Command) {}
355
356/// Wait until the host answers `/api/health`, or give up.
357fn wait_for_health(
358    port: u16,
359    timeout: Duration,
360    mut exited: impl FnMut() -> Option<String>,
361) -> Result<(), String> {
362    let deadline = Instant::now() + timeout;
363    let url = format!("http://127.0.0.1:{port}/api/health");
364    let mut last = String::from("no attempt made");
365    while Instant::now() < deadline {
366        // A host that already died will never answer: say so now instead of after the timeout.
367        if let Some(why) = exited() {
368            return Err(format!("the Strata App Host stopped before it became healthy: {why}"));
369        }
370        match ureq_get_ok(&url) {
371            Ok(true) => return Ok(()),
372            Ok(false) => last = "the host answered with a non-2xx status".into(),
373            Err(e) => last = e,
374        }
375        std::thread::sleep(Duration::from_millis(250));
376    }
377    Err(format!("the Strata App Host did not become healthy at {url}: {last}"))
378}
379
380/// A minimal blocking HTTP POST with no body (the shell's one clean-stop request). Returns the status line.
381fn http_post(url: &str, headers: &[(&str, &str)]) -> Result<String, String> {
382    http_request("POST", url, headers).map(|(status, _)| status)
383}
384
385/// GET returning the response body (the self-test reads `/api/control/status`).
386fn http_get_body(url: &str) -> Result<(String, String), String> {
387    http_request("GET", url, &[])
388}
389
390fn http_request(method: &str, url: &str, headers: &[(&str, &str)]) -> Result<(String, String), String> {
391    http_request_body(method, url, headers, None)
392}
393
394/// Like `http_request`, with an optional body (sent as given; the caller sets content-type in `headers`).
395fn http_request_body(method: &str, url: &str, headers: &[(&str, &str)], body: Option<&str>) -> Result<(String, String), String> {
396    use std::io::{Read, Write};
397    let rest = url.strip_prefix("http://").ok_or("only http:// is supported")?;
398    let (authority, path) = match rest.find('/') {
399        Some(i) => (&rest[..i], &rest[i..]),
400        None => (rest, "/"),
401    };
402    let mut stream = std::net::TcpStream::connect_timeout(
403        &authority.parse().map_err(|e| format!("bad authority {authority}: {e}"))?,
404        Duration::from_millis(800),
405    )
406    .map_err(|e| e.to_string())?;
407    stream.set_read_timeout(Some(Duration::from_secs(20))).map_err(|e| e.to_string())?;
408    let extra: String = headers.iter().map(|(k, v)| format!("{k}: {v}\r\n")).collect();
409    stream
410        .write_all(format!("{method} {path} HTTP/1.1\r\nHost: {authority}\r\n{extra}Content-Length: {}\r\nConnection: close\r\n\r\n{}", body.map(str::len).unwrap_or(0), body.unwrap_or("")).as_bytes())
411        .map_err(|e| e.to_string())?;
412    let mut buf = String::new();
413    stream.read_to_string(&mut buf).map_err(|e| e.to_string())?;
414    let status = buf.lines().next().unwrap_or_default().to_string();
415    let response = buf.split_once("\r\n\r\n").map(|(_, b)| b.to_string()).unwrap_or_default();
416    Ok((status, response))
417}
418
419/// A minimal blocking HTTP GET, so the shell needs no async runtime for one health probe.
420fn ureq_get_ok(url: &str) -> Result<bool, String> {
421    use std::io::{Read, Write};
422    let rest = url.strip_prefix("http://").ok_or("only http:// is supported")?;
423    let (authority, path) = match rest.find('/') {
424        Some(i) => (&rest[..i], &rest[i..]),
425        None => (rest, "/"),
426    };
427    let mut stream = std::net::TcpStream::connect_timeout(
428        &authority
429            .parse()
430            .map_err(|e| format!("bad authority {authority}: {e}"))?,
431        Duration::from_millis(800),
432    )
433    .map_err(|e| e.to_string())?;
434    stream
435        .set_read_timeout(Some(Duration::from_millis(1500)))
436        .map_err(|e| e.to_string())?;
437    stream
438        .write_all(format!("GET {path} HTTP/1.1\r\nHost: {authority}\r\nConnection: close\r\n\r\n").as_bytes())
439        .map_err(|e| e.to_string())?;
440    let mut buf = String::new();
441    stream.read_to_string(&mut buf).map_err(|e| e.to_string())?;
442    let status = buf.lines().next().unwrap_or_default();
443    Ok(status.contains(" 200") || status.contains(" 204"))
444}
445
446/// The App Host's command, ready to start: the bundled Node runs the host on `port`, serving the built UI, on 127.0.0.1 only.
447/// `shutdown_token` is the secret that lets the shell (and nothing else) ask the host for a clean stop.
448fn host_command(res: &Path, port: u16, shutdown_token: &str) -> Result<Command, String> {
449    let host_dir = if res.join("host").join("server").join("index.mjs").exists() {
450        res.join("host")
451    } else {
452        res.join("..").join("host")
453    };
454    let entry = host_dir.join("server").join("index.mjs");
455    if !entry.exists() {
456        return Err(format!("the App Host entry is missing at {}", entry.display()));
457    }
458    let dist = host_dir.join("dist");
459    if !dist.exists() {
460        return Err(format!(
461            "the built UI is missing at {}; run \"npm --prefix host run build\"",
462            dist.display()
463        ));
464    }
465    let node = node_binary(res)?;
466
467    let mut cmd = Command::new(&node);
468    cmd.arg(&entry)
469        .current_dir(&host_dir)
470        .env("STRATA_PORT", port.to_string())
471        .env("STRATA_DIST", &dist)
472        .env("NODE_ENV", "production")
473        // U12: a packaged build must have no success path that uses demo responses or demo
474        // metrics. `STRATA_PACKAGED` makes the host refuse to simulate; `STRATA_REAL_ENGINE` is set
475        // for the same reason, so the monitor reports `none` instead of fabricated numbers.
476        .env("STRATA_PACKAGED", "1")
477        .env("STRATA_REAL_ENGINE", "1")
478        // the host leaves, after stopping what this app started, when this shell is gone (killed, crashed)
479        .env("STRATA_EXIT_WITH_PARENT", "1")
480        // the host listens on the loopback address only, whatever the caller's environment says
481        .env("STRATA_BIND", "127.0.0.1")
482        .env("STRATA_SHUTDOWN_TOKEN", shutdown_token)
483        .stdin(Stdio::null())
484        .stdout(Stdio::inherit())
485        .stderr(Stdio::inherit());
486    apply_runtime_policy(&mut cmd, res);
487    hide_console(&mut cmd);
488    if let Some(notice) = PORT_NOTICE.lock().unwrap().clone() {
489        cmd.env("STRATA_PORT_NOTICE", notice);
490    }
491    // A user with the Strata API worker on a different port sets this; unset means the worker's
492    // documented loopback default.
493    if let Ok(url) = std::env::var("STRATA_SERVER_URL") {
494        cmd.env("STRATA_SERVER_URL", url);
495    }
496    Ok(cmd)
497}
498
499/// Windows and macOS: start the App Host from inside the app process and return the port it serves on.
500#[cfg(not(target_os = "linux"))]
501fn start_host(app: &tauri::AppHandle) -> Result<u16, String> {
502    let res = resource_dir(app)?;
503    let port = pick_stable_port()?;
504    let token = random_token();
505    let mut cmd = host_command(&res, port, &token)?;
506    // The signed app updater (Tauri) is reached by the host through a token-protected loopback bridge.
507    let bridge = updater::start(app, random_token());
508    updater::apply_env(&mut cmd, app, bridge.as_ref());
509    *app.state::<ShutdownToken>().0.lock().unwrap() = Some(token);
510
511    let node = node_binary(&res)?;
512    // The host's lines go to the run log (a packaged Windows app has no console, so they were lost before).
513    let log = desktoplog::run_log();
514    if log.is_some() {
515        cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
516    }
517    let mut child = cmd
518        .spawn()
519        .map_err(|e| format!("could not start the App Host on {}: {e}", node.display()))?;
520    if let Some(log) = log {
521        let ring = desktoplog::Ring::default();
522        if let Some(out) = child.stdout.take() {
523            desktoplog::tee(out, "host", false, ring.clone(), log.clone());
524        }
525        if let Some(err) = child.stderr.take() {
526            desktoplog::tee(err, "host", true, ring, log);
527        }
528    }
529    *app.state::<HostProcess>().0.lock().unwrap() = Some(child);
530    *app.state::<HostPort>().0.lock().unwrap() = Some(port);
531
532    let state_app = app.clone();
533    wait_for_health(port, Duration::from_secs(60), move || {
534        let state = state_app.state::<HostProcess>();
535        let mut guard = state.0.lock().unwrap();
536        match guard.as_mut().map(|c| c.try_wait()) {
537            Some(Ok(Some(status))) => Some(format!("exit status {status}")),
538            _ => None,
539        }
540    })?;
541    Ok(port)
542}
543
544/// How long the host gets to stop the engines this app started (drain, then end) before it is ended. The host's own
545/// deadline is shorter; whatever is still running when the shell exits is ended by the job object / the owners.
546const HOST_STOP_SECONDS: u64 = 60;
547
548/// Stop the App Host, and with it the engines this app started.
549///
550/// The host stops them through Control (profiles `app-N`), then exits. Engines another client started (the
551/// Terminal's `strata runtime start`) are not touched. If the host does not finish in time it is ended, and the
552/// engines are ended by the job object (Windows) or by their owners following the host (`--die-with-pid`).
553#[cfg(not(target_os = "linux"))]
554fn stop_host(app: &tauri::AppHandle) {
555    let port = app.try_state::<HostPort>().and_then(|s| *s.0.lock().unwrap());
556    let token = app.try_state::<ShutdownToken>().and_then(|s| s.0.lock().unwrap().clone());
557    if let Some(state) = app.try_state::<HostProcess>() {
558        if let Some(mut child) = state.0.lock().unwrap().take() {
559            stop_host_child(&mut child, port, token.as_deref());
560        }
561    }
562}
563
564/// End the host at once, without the clean stop (a start that failed: there is nothing to drain).
565#[cfg(not(target_os = "linux"))]
566fn kill_host(app: &tauri::AppHandle) {
567    if let Some(state) = app.try_state::<HostProcess>() {
568        if let Ok(mut guard) = state.0.lock() {
569            if let Some(mut child) = guard.take() {
570                let _ = child.kill();
571                let _ = child.wait();
572            }
573        }
574    }
575}
576
577/// A clean stop first: the host stops, through Control, the engines this app started, then exits. Engines another client
578/// started (the Terminal) are not touched. If it does not finish in time the process is ended.
579fn stop_host_child(child: &mut Child, port: Option<u16>, token: Option<&str>) {
580    if let (Some(port), Some(token)) = (port, token) {
581        let _ = http_post(&format!("http://127.0.0.1:{port}/api/control/shutdown"), &[("x-strata-shutdown", token)]);
582        let deadline = Instant::now() + Duration::from_secs(HOST_STOP_SECONDS);
583        while Instant::now() < deadline {
584            if let Ok(Some(_)) = child.try_wait() {
585                return;
586            }
587            std::thread::sleep(Duration::from_millis(100));
588        }
589    }
590    let _ = child.kill();
591    let _ = child.wait();
592}
593
594/// Where a packaged build keeps `bundle.resources`, found from the executable's own path.
595///
596/// macOS `.app`: `Contents/MacOS/<exe>` -> `Contents/Resources`. Windows NSIS: next to the exe.
597/// Linux deb/AppImage: `<prefix>/bin/<exe>` -> `<prefix>/lib/<productName>`.
598fn packaged_resource_dir(exe: &Path) -> Option<PathBuf> {
599    let dir = exe.parent()?;
600    let mut candidates = vec![dir.to_path_buf()];
601    if let Some(up) = dir.parent() {
602        candidates.push(up.join("Resources"));
603        candidates.push(up.join("lib").join("Strata"));
604        candidates.push(up.join("lib").join("strata-desktop"));
605    }
606    candidates
607        .into_iter()
608        .find(|p| p.join("host").join("server").join("index.mjs").exists())
609}
610
611/// Parse `--self-test[=path]`; returns the report path when the flag is present.
612fn self_test_path(args: &[String]) -> Option<String> {
613    for a in args.iter().skip(1) {
614        if a == "--self-test" {
615            return Some(
616                std::env::temp_dir()
617                    .join("strata-desktop-self-test.json")
618                    .to_string_lossy()
619                    .into_owned(),
620            );
621        }
622        if let Some(rest) = a.strip_prefix("--self-test=") {
623            return Some(rest.to_string());
624        }
625    }
626    None
627}
628
629/// Run `strata.py --version` on the bundle's own interpreter with a scrubbed environment.
630fn control_runs(dir: &Path) -> (bool, String) {
631    let python = if cfg!(windows) { dir.join("python").join("python.exe") } else { dir.join("python").join("bin").join("python3") };
632    let mut cmd = Command::new(&python);
633    cmd.arg(dir.join("strata.py")).arg("--version").current_dir(dir)
634        .env_remove("PYTHONHOME").env_remove("PYTHONPATH").env_remove("VIRTUAL_ENV")
635        .env("PYTHONNOUSERSITE", "1").env("PYTHONDONTWRITEBYTECODE", "1").env("STRATA_NO_ACQUIRE", "1");
636    hide_console(&mut cmd);
637    match cmd.output() {
638        Ok(out) => {
639            let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
640            let ok = out.status.success() && text.contains("python 3.12") && text.contains(&dir.display().to_string());
641            (ok, if text.is_empty() { String::from_utf8_lossy(&out.stderr).trim().to_string() } else { text })
642        }
643        Err(e) => (false, format!("could not start {}: {e}", python.display())),
644    }
645}
646
647/// With an empty component folder Control must say there is no engine and name the explicit command, exit 5,
648/// and must not create or fetch anything.
649fn control_engine_notice(dir: &Path) -> (bool, String) {
650    let python = if cfg!(windows) { dir.join("python").join("python.exe") } else { dir.join("python").join("bin").join("python3") };
651    let empty = std::env::temp_dir().join(format!("strata-self-test-components-{}", std::process::id()));
652    let _ = std::fs::remove_dir_all(&empty);
653    let mut cmd = Command::new(&python);
654    cmd.arg(dir.join("strata.py")).args(["components", "engine", "--backend", "cuda", "--output", "json"])
655        .arg("--components-dir").arg(&empty).current_dir(dir)
656        .env_remove("PYTHONHOME").env_remove("PYTHONPATH")
657        .env("PYTHONNOUSERSITE", "1").env("PYTHONDONTWRITEBYTECODE", "1").env("STRATA_NO_ACQUIRE", "1");
658    hide_console(&mut cmd);
659    let result = match cmd.output() {
660        Ok(out) => {
661            let text = String::from_utf8_lossy(&out.stdout).to_string();
662            let notice = text.contains("never downloads an engine");
663            let created = empty.exists();
664            (out.status.code() == Some(5) && notice && !created, format!("exit {:?}; notice={notice}; folder created={created}", out.status.code()))
665        }
666        Err(e) => (false, e.to_string()),
667    };
668    let _ = std::fs::remove_dir_all(&empty);
669    result
670}
671
672/// Start the host from the packaged resources and report what actually happened.
673fn run_self_test(report_path: &str) -> i32 {
674    let mut steps: Vec<(String, bool, String)> = Vec::new();
675    let mut record = |name: &str, ok: bool, detail: String| {
676        steps.push((name.to_string(), ok, detail));
677    };
678
679    // Resolve resources the same way the real app does: `Contents/Resources` next to the
680    // executable when packaged, the repository layout otherwise.
681    let exe = std::env::current_exe().unwrap_or_default();
682    let packaged_res = packaged_resource_dir(&exe);
683
684    let res = match packaged_res {
685        Some(p) => {
686            record("resources-packaged", true, p.display().to_string());
687            p
688        }
689        None => {
690            let dev = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
691            record(
692                "resources-packaged",
693                false,
694                format!("not a packaged layout; using development root {}", dev.display()),
695            );
696            dev
697        }
698    };
699
700    let host_dir = if res.join("host").join("server").join("index.mjs").exists() {
701        res.join("host")
702    } else {
703        res.join("..").join("host")
704    };
705    let entry = host_dir.join("server").join("index.mjs");
706    let dist = host_dir.join("dist");
707    record("host-entry-present", entry.exists(), entry.display().to_string());
708    record("ui-dist-present", dist.join("index.html").exists(), dist.display().to_string());
709
710    let node = match node_binary(&res) {
711        Ok(n) => {
712            let mut probe = Command::new(&n);
713            probe.arg("--version");
714            hide_console(&mut probe);
715            let version_ok = probe
716                .output()
717                .map(|o| o.status.success())
718                .unwrap_or(false);
719            record("private-node-runtime", version_ok, n.display().to_string());
720            n
721        }
722        Err(e) => {
723            record("private-node-runtime", false, e.clone());
724            return write_self_test_report(report_path, steps, &e);
725        }
726    };
727
728    // Closing must always end what the app started: on Windows the shell sits in a kill-on-close job object.
729    if cfg!(windows) {
730        record("shell-contained-in-kill-on-close-job", app_is_contained(), "IsProcessInJob".into());
731    }
732
733    let port = match pick_port() {
734        Ok(p) => p,
735        Err(e) => return write_self_test_report(report_path, steps, &e),
736    };
737
738    let mut cmd = Command::new(&node);
739    cmd.arg(&entry)
740        .current_dir(&host_dir)
741        .env("STRATA_PORT", port.to_string())
742        .env("STRATA_DIST", &dist)
743        .env("STRATA_PACKAGED", "1")
744        .env("STRATA_REAL_ENGINE", "1")
745        .stdin(Stdio::null())
746        .stdout(Stdio::null())
747        .stderr(Stdio::null());
748    apply_runtime_policy(&mut cmd, &res);
749    hide_console(&mut cmd);
750    let mut child = match cmd.spawn() {
751        Ok(c) => {
752            record("host-spawned", true, format!("pid {}", c.id()));
753            c
754        }
755        Err(e) => {
756            let msg = format!("spawn failed: {e}");
757            record("host-spawned", false, msg.clone());
758            return write_self_test_report(report_path, steps, &msg);
759        }
760    };
761
762    let healthy = wait_for_health(port, Duration::from_secs(45), || match child.try_wait() {
763        Ok(Some(status)) => Some(format!("exit status {status}")),
764        _ => None,
765    });
766    record("host-healthy", healthy.is_ok(), match &healthy {
767        Ok(()) => format!("http://127.0.0.1:{port}/api/health answered 2xx"),
768        Err(e) => e.clone(),
769    });
770
771    // The UI must actually be served from the bundle, not merely present on disk.
772    let ui_ok = ureq_get_ok(&format!("http://127.0.0.1:{port}/")).unwrap_or(false);
773    record("ui-served", ui_ok, format!("http://127.0.0.1:{port}/"));
774
775    // The API the renderer will call must be reachable on the same origin.
776    let api_ok = ureq_get_ok(&format!("http://127.0.0.1:{port}/api/health")).unwrap_or(false);
777    record("api-reachable-on-same-origin", api_ok, "GET /api/health".into());
778
779    // The bundled Control component: present, runs on its own interpreter, and the host sees it with acquiring forbidden.
780    match control_dir(&res) {
781        Some(dir) => {
782            record("control-component-present", true, dir.display().to_string());
783            let (ok, detail) = control_runs(&dir);
784            record("control-runs-on-bundled-python", ok, detail);
785            let (ok, detail) = control_engine_notice(&dir);
786            record("engine-missing-is-a-notice-not-a-download", ok, detail);
787        }
788        None => record("control-component-present", false, format!("no control component under {}", res.display())),
789    }
790    let status = http_get_body(&format!("http://127.0.0.1:{port}/api/control/status"));
791    let (status_ok, status_detail) = match &status {
792        Ok((line, body)) => {
793            let parsed: serde_json::Value = serde_json::from_str(body).unwrap_or(serde_json::Value::Null);
794            let forbidden = parsed["acquisition"]["forbidden"] == serde_json::Value::Bool(true);
795            let control = parsed["control"]["python"].is_string();
796            (line.contains(" 200") && forbidden && control, format!("{line}; acquisition.forbidden={forbidden}; control={control}"))
797        }
798        Err(e) => (false, e.clone()),
799    };
800    record("host-sees-control-and-forbids-acquiring", status_ok, status_detail);
801
802    let _ = child.kill();
803    let _ = child.wait();
804
805    let msg = if steps.iter().all(|(_, ok, _)| *ok) {
806        String::new()
807    } else {
808        "one or more steps failed".into()
809    };
810    write_self_test_report(report_path, steps, &msg)
811}
812
813/// Write the JSON report and return the process exit code.
814fn write_self_test_report(path: &str, steps: Vec<(String, bool, String)>, error: &str) -> i32 {
815    let ok = !steps.is_empty() && steps.iter().all(|(_, o, _)| *o);
816    let steps_json: Vec<serde_json::Value> = steps
817        .iter()
818        .map(|(name, ok, detail)| {
819            serde_json::json!({ "name": name, "ok": ok, "detail": detail })
820        })
821        .collect();
822    let report = serde_json::json!({
823        "schemaVersion": 1,
824        "kind": "strata-desktop-self-test",
825        "carrier": "tauri",
826        "ok": ok,
827        "error": error,
828        "steps": steps_json,
829    });
830    let text = serde_json::to_string_pretty(&report).unwrap_or_else(|_| "{}".into());
831    if let Err(e) = std::fs::write(path, &text) {
832        eprintln!("[strata] could not write the self-test report to {path}: {e}");
833    }
834    println!("{text}");
835    if ok {
836        0
837    } else {
838        1
839    }
840}
841
842fn main() {
843    // ------------------------------------------------------------------ self-test
844    //
845    // `Strata.app/Contents/MacOS/strata-desktop --self-test[=path]` starts the App Host from the
846    // *packaged resources*, waits for it to answer, checks that it serves the supplied UI, writes a
847    // JSON report and exits 0/1. This is what makes the shipped artifact verifiable without a human
848    // at the screen — the lesson from the Electron attempt, where a packaged app that never started
849    // its host hung with no output at all.
850    let args: Vec<String> = std::env::args().collect();
851    // Windows and macOS: the run log and the panic hook come first, before anything that can fail. A start that goes wrong then leaves a
852    // log, a crash file and a message box instead of a process that is gone with 0xc0000409 and nothing else (Linux: supervisor.rs).
853    #[cfg(not(target_os = "linux"))]
854    desktoplog::init_startup(self_test_path(&args).is_none());
855    contain_app();
856    #[cfg(target_os = "linux")]
857    {
858        // WebKitGTK's DMA-BUF renderer shows a blank window on several NVIDIA + Wayland desktops (and some virtual GPUs); the plain
859        // renderer is slower to start by a hair and always works. Anyone who set the variable themselves keeps their choice.
860        if std::env::var_os("WEBKIT_DISABLE_DMABUF_RENDERER").is_none() {
861            std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
862        }
863    }
864    if let Some(path) = self_test_path(&args) {
865        let code = run_self_test(&path);
866        std::process::exit(code);
867    }
868
869    // Linux: this executable is two programs. The shell (no GTK, no WebKit) owns the host and survives a crash of the window; the
870    // window process (`--window-child`) only shows the page. See supervisor.rs.
871    #[cfg(target_os = "linux")]
872    {
873        let options = supervisor::parse_args(&args, std::env::var("STRATA_UI").ok().as_deref());
874        if !options.window_child {
875            std::process::exit(supervisor::run(&options));
876        }
877        // A window process its shell did not start is the app updater's restart (the shell that owned the window is stopping): start Strata again normally.
878        if !supervisor::started_by_shell(std::env::var(supervisor::SHELL_PID_ENV).ok().as_deref(), std::os::unix::process::parent_id()) {
879            std::process::exit(supervisor::restart_after_update());
880        }
881        run_window_process();
882    }
883    #[cfg(not(target_os = "linux"))]
884    run_embedded();
885}
886
887/// Windows and macOS: one process owns the host and the window.
888#[cfg(not(target_os = "linux"))]
889fn run_embedded() {
890    let builder = tauri::Builder::default();
891    // macOS: WKWebView ends the page's web content process under memory pressure and leaves a blank window; the page is loaded again (#5079).
892    #[cfg(target_os = "macos")]
893    let builder = builder.on_web_content_process_terminate(|webview| {
894        let port = webview.app_handle().state::<HostPort>().0.lock().ok().and_then(|p| *p);
895        let Some(port) = port else { return };
896        let failed = webview.url().ok().map(|u| u.to_string());
897        let target = webview.clone();
898        on_renderer_failure(format!("http://127.0.0.1:{port}"), recovery::Failure::RendererExited, "web content process terminated".to_string(), failed, move |url| {
899            if let Ok(url) = url.parse::<tauri::Url>() { let _ = target.navigate(url); }
900        });
901    });
902    builder
903        // First, as the plugin requires: a second launch ends here after telling the running app to show itself.
904        .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
905            if let Some(window) = app.get_webview_window("main") {
906                let _ = window.unminimize();
907                let _ = window.show();
908                let _ = window.set_focus();
909            }
910        }))
911        .plugin(tauri_plugin_shell::init())
912        .plugin(tauri_plugin_updater::Builder::new().build())
913        .plugin(tauri_plugin_notification::init())
914        .manage(HostProcess(Mutex::new(None)))
915        .manage(HostPort(Mutex::new(None)))
916        .manage(ShutdownToken(Mutex::new(None)))
917        .setup(|app| {
918            // A way to prove the safety net on a computer where the app starts fine (tests only): a panic at the place a setup error ends in.
919            if std::env::var_os("STRATA_DESKTOP_TEST_PANIC").is_some() {
920                panic!("STRATA_DESKTOP_TEST_PANIC is set: the app panics on purpose");
921            }
922            let handle = app.handle().clone();
923            // A setup error would become a panic inside Tauri ("Failed to setup app"), and with panic = "abort" a crash with no message.
924            // A failed start is reported (log, crash file, message box) and ends the app here instead.
925            let port = match start_host(&handle) {
926                Ok(port) => port,
927                Err(e) => {
928                    kill_host(&handle);
929                    desktoplog::startup_failed(&e)
930                }
931            };
932            let shell_token = handle.state::<ShutdownToken>().0.lock().map(|t| t.clone().unwrap_or_default()).unwrap_or_default();
933            if let Err(e) = open_window(app, port, &shell_token) {
934                kill_host(&handle);
935                desktoplog::startup_failed(&format!("the Strata window could not be opened: {e}"))
936            }
937            Ok(())
938        })
939        .on_window_event(|window, event| {
940            // "Minimise to tray" (Settings, off by default): closing the main window hides it and keeps Strata running in the tray; Quit in the
941            // tray menu ends it (#3477). If no tray could be made the window closes as before.
942            if let tauri::WindowEvent::CloseRequested { api, .. } = event {
943                if window.label() == "main" {
944                    let prefs = shell::read_prefs();
945                    if prefs.tray {
946                        api.prevent_close();
947                        shell::hide_to_tray(&window.app_handle().clone(), &prefs.language);
948                        if !shell::tray_exists(&window.app_handle().clone()) {
949                            let _ = window.destroy();
950                        }
951                    }
952                }
953            }
954            if let tauri::WindowEvent::Destroyed = event {
955                stop_host(&window.app_handle().clone());
956            }
957        })
958        .build(tauri::generate_context!())
959        .unwrap_or_else(|e| desktoplog::startup_failed(&format!("the Strata application could not be built: {e}")))
960        .run(|app, event| {
961            if let tauri::RunEvent::ExitRequested { .. } | tauri::RunEvent::Exit = event {
962                stop_host(app);
963            }
964        });
965}
966
967/// The one window, on the host's own origin so the page and its API share an origin exactly as the browser build does.
968#[cfg_attr(windows, allow(unused_variables))]
969fn open_window(app: &tauri::App, port: u16, shell_token: &str) -> Result<(), Box<dyn std::error::Error>> {
970    let origin = format!("http://127.0.0.1:{port}");
971    let url = origin.parse().expect("a valid loopback URL");
972    let builder = WebviewWindowBuilder::new(app, "main", WebviewUrl::External(url)).title("Strata").inner_size(1440.0, 920.0).min_inner_size(900.0, 600.0);
973    // Dropping pictures on the chat (QA report 1, item 4). Windows: the shell's own file-drop handler is off, because with it on the system hands
974    // the dropped file to the shell and the page never sees it; with it off the page gets ordinary drag and drop events (apps/host DropZone), as
975    // in a browser. Linux and macOS: the page gets the drag events but WebKit gives it no files, so the handler stays on and the shell passes the
976    // drop on (see drop_script and hand_over_drop below).
977    #[cfg(windows)]
978    let builder = builder.disable_drag_drop_handler();
979    // WebKitGTK (2.50 to 2.52 at least) dereferences a null pointer in AcceleratedBackingStore::update in its UI process when a page calls
980    // document.startViewTransition (the web process asks the UI process to enter accelerated compositing, and the backing store is not
981    // there). The page itself does not call it on that engine (apps/host/src/lib/router.ts), and this line keeps any other script from doing
982    // it either: the API is simply absent, as in older WebKit versions.
983    #[cfg(target_os = "linux")]
984    let builder = builder.initialization_script(
985        "try { Object.defineProperty(Document.prototype, 'startViewTransition', { value: undefined, configurable: true, writable: true }); } catch (e) {}",
986    );
987    #[cfg_attr(windows, allow(unused_variables))]
988    let window = builder.build()?;
989    #[cfg(not(windows))]
990    {
991        let target = window.clone();
992        let token = shell_token.to_string();
993        window.on_webview_event(move |event| {
994            if let tauri::WebviewEvent::DragDrop(drag) = event {
995                match drag {
996                    tauri::DragDropEvent::Enter { .. } => { let _ = target.eval(&drag_script("enter")); }
997                    tauri::DragDropEvent::Leave => { let _ = target.eval(&drag_script("leave")); }
998                    tauri::DragDropEvent::Drop { paths, .. } => {
999                        let _ = target.eval(&drag_script("leave"));
1000                        let paths: Vec<String> = paths.iter().map(|p| p.to_string_lossy().into_owned()).collect();
1001                        hand_over_drop(target.clone(), port, token.clone(), paths);
1002                    }
1003                    _ => {}
1004                }
1005            }
1006        });
1007    }
1008    #[cfg(target_os = "linux")]
1009    hook_linux_drops(&window, port, shell_token);
1010    #[cfg(windows)]
1011    hook_renderer_failures(&window, port);
1012    Ok(())
1013}
1014
1015/// Milliseconds since the first failure report or window (a clock that only goes forward, for the recovery limit).
1016#[cfg(not(target_os = "linux"))]
1017fn uptime_ms() -> u64 {
1018    static START: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
1019    START.get_or_init(Instant::now).elapsed().as_millis() as u64
1020}
1021
1022/// The page's renderer is gone (#5079). Writes it to the run log, and, when the window needs the page again, loads it again through
1023/// `navigate` after a short wait: the same screen with `?recovery=1` the first time (the page then starts with the sidebar previews
1024/// closed once), the home screen the second time, and nothing after two in two minutes. The chats are the host's and are not touched.
1025#[cfg(not(target_os = "linux"))]
1026fn on_renderer_failure(origin: String, failure: recovery::Failure, detail: String, failed: Option<String>, navigate: impl FnOnce(String) + Send + 'static) {
1027    static GUARD: Mutex<recovery::Guard> = Mutex::new(recovery::Guard::new());
1028    let say = |text: &str| { if let Some(log) = desktoplog::run_log() { log.line("shell", text); } };
1029    say(&format!("the page's {} ({detail}); it was showing {}", failure.name(), failed.as_deref().unwrap_or("an unknown address")));
1030    let plan = match GUARD.lock() {
1031        Ok(mut guard) => recovery::plan(&mut guard, uptime_ms(), &origin, failure, failed.as_deref()),
1032        Err(_) => recovery::Plan::Stop,
1033    };
1034    match plan {
1035        recovery::Plan::Ignore => {}
1036        recovery::Plan::Stop => say("the page's renderer failed again within two minutes of two recoveries; the window is left as it is (Reload in the page loads it again)"),
1037        recovery::Plan::Reload { attempt, url } => {
1038            say(&format!("loading the page again (recovery {attempt}): {url}"));
1039            std::thread::spawn(move || {
1040                std::thread::sleep(Duration::from_millis(recovery::RELOAD_DELAY_MS));
1041                navigate(url);
1042            });
1043        }
1044    }
1045}
1046
1047/// Windows: WebView2 tells the shell when a process of the page fails; the page's renderer dying is recovered by on_renderer_failure.
1048#[cfg(windows)]
1049fn hook_renderer_failures(window: &tauri::WebviewWindow, port: u16) {
1050    use webview2_com::Microsoft::Web::WebView2::Win32::{ICoreWebView2ProcessFailedEventArgs2, COREWEBVIEW2_PROCESS_FAILED_KIND};
1051    use webview2_com::{take_pwstr, ProcessFailedEventHandler};
1052    use windows_core::{Interface, PWSTR};
1053    let target = window.clone();
1054    let origin = format!("http://127.0.0.1:{port}");
1055    let _ = window.with_webview(move |platform| unsafe {
1056        let Ok(core) = platform.controller().CoreWebView2() else { return };
1057        let handler = ProcessFailedEventHandler::create(Box::new(move |sender, args| {
1058            let Some(args) = args else { return Ok(()) };
1059            let mut kind = COREWEBVIEW2_PROCESS_FAILED_KIND::default();
1060            args.ProcessFailedKind(&mut kind)?;
1061            let mut detail = format!("kind {}", kind.0);
1062            if let Ok(more) = args.cast::<ICoreWebView2ProcessFailedEventArgs2>() {
1063                let mut reason = Default::default();
1064                let mut exit_code = 0i32;
1065                if more.Reason(&mut reason).is_ok() { detail = format!("{detail}, reason {}", recovery::reason_name(reason.0)); }
1066                if more.ExitCode(&mut exit_code).is_ok() { detail = format!("{detail}, exit code {exit_code:#x}"); }
1067            }
1068            let failed = sender.and_then(|view| {
1069                let mut source = PWSTR::null();
1070                view.Source(&mut source).ok()?;
1071                Some(take_pwstr(source))
1072            });
1073            let window = target.clone();
1074            on_renderer_failure(origin.clone(), recovery::Failure::from_webview2(kind.0), detail, failed, move |url| {
1075                if let Ok(url) = url.parse::<tauri::Url>() { let _ = window.navigate(url); }
1076            });
1077            Ok(())
1078        }));
1079        let mut token = 0i64;
1080        let _ = core.add_ProcessFailed(&handler, &mut token);
1081    });
1082}
1083
1084/// A file:// address from a drag, as a path (percent-escapes decoded); anything else (http, mailto, text) is not a dropped file.
1085#[cfg_attr(windows, allow(dead_code))]
1086fn file_uri_to_path(uri: &str) -> Option<String> {
1087    let rest = uri.trim().strip_prefix("file://")?;
1088    // file://host/path: only an empty or local host is a file on this computer
1089    let rest = match rest.find('/') { Some(0) => rest, Some(i) if rest[..i].eq_ignore_ascii_case("localhost") => &rest[i..], _ => return None };
1090    let bytes = rest.as_bytes();
1091    let mut out = Vec::with_capacity(bytes.len());
1092    let mut i = 0;
1093    while i < bytes.len() {
1094        if bytes[i] == b'%' && i + 2 < bytes.len() {
1095            if let Some(v) = std::str::from_utf8(&bytes[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok()) { out.push(v); i += 3; continue; }
1096        }
1097        out.push(bytes[i]);
1098        i += 1;
1099    }
1100    let path = String::from_utf8(out).ok()?;
1101    if path.contains('\0') { None } else { Some(path) }
1102}
1103
1104/// Linux: WebKitGTK 2.52 gives the page a file drag without the files, and the window library's own drop handler never sees one, so the
1105/// shell reads the drop itself from the GTK drag signals of the page widget: the file:// addresses arrive with the drag data, the drop hands
1106/// them to the host exactly as the other systems do (hand_over_drop), and the page shows its drop box meanwhile (QA, drop on the chat).
1107#[cfg(target_os = "linux")]
1108fn hook_linux_drops(window: &tauri::WebviewWindow, port: u16, token: &str) {
1109    use gtk::prelude::*;
1110    use std::cell::{Cell, RefCell};
1111    use std::rc::Rc;
1112    let target = window.clone();
1113    let token = token.to_string();
1114    let _ = window.with_webview(move |platform| {
1115        let view = platform.inner();
1116        let paths: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
1117        let hovering = Rc::new(Cell::new(false));
1118        let generation = Rc::new(Cell::new(0u32));
1119        {
1120            let (paths, hovering, generation, target) = (paths.clone(), hovering.clone(), generation.clone(), target.clone());
1121            view.connect_drag_data_received(move |_, _, _, _, data, _, _| {
1122                let list: Vec<String> = data.uris().iter().filter_map(|u| file_uri_to_path(u.as_str())).collect();
1123                if list.is_empty() { return; }
1124                *paths.borrow_mut() = list;
1125                generation.set(generation.get() + 1);
1126                if !hovering.replace(true) { let _ = target.eval(&drag_script("enter")); }
1127            });
1128        }
1129        {
1130            // WebKit only accepts a drag when the page says so, and the page is not given the files: once the addresses of a file drag are known,
1131            // the shell accepts it (as a copy) itself, so GTK goes on to deliver the drop.
1132            let paths = paths.clone();
1133            view.connect_drag_motion(move |_, ctx, _, _, time| {
1134                if paths.borrow().is_empty() { return false; }
1135                ctx.drag_status(gtk::gdk::DragAction::COPY, time);
1136                true
1137            });
1138        }
1139        {
1140            let (paths, hovering, generation, target) = (paths.clone(), hovering.clone(), generation.clone(), target.clone());
1141            let token = token.clone();
1142            view.connect_drag_drop(move |_, ctx, _, _, time| {
1143                generation.set(generation.get() + 1);
1144                let list = std::mem::take(&mut *paths.borrow_mut());
1145                if list.is_empty() { return false; }   // not a file: the page deals with it
1146                hovering.set(false);
1147                ctx.drop_finish(true, time);
1148                let _ = target.eval(&drag_script("leave"));
1149                hand_over_drop(target.clone(), port, token.clone(), list);
1150                true
1151            });
1152        }
1153        {
1154            let (paths, hovering, target, token) = (paths.clone(), hovering.clone(), target.clone(), token.clone());
1155            view.connect_drag_leave(move |widget, _, _| {
1156                // WebKit's own handling of a drop never reaches this widget's drop signal, but GTK does say "leave" at the moment of the drop:
1157                // a leave with every mouse button already up (and a file drag known) is the drop. A leave with the button still down is the
1158                // pointer going out of the window.
1159                if hovering.get() && !paths.borrow().is_empty() && pointer_buttons_up(widget) {
1160                    let list = std::mem::take(&mut *paths.borrow_mut());
1161                    hovering.set(false);
1162                    let _ = target.eval(&drag_script("leave"));
1163                    hand_over_drop(target.clone(), port, token.clone(), list);
1164                }
1165            });
1166        }
1167        view.connect_drag_leave(move |_, _, _| {
1168            // only a leave that nothing follows ends the drag (a drop is handled above and clears the state)
1169            let seen = generation.get();
1170            let (paths, hovering, generation, target) = (paths.clone(), hovering.clone(), generation.clone(), target.clone());
1171            gtk::glib::idle_add_local_once(move || {
1172                if generation.get() == seen && hovering.replace(false) {
1173                    paths.borrow_mut().clear();
1174                    let _ = target.eval(&drag_script("leave"));
1175                }
1176            });
1177        });
1178    });
1179}
1180
1181/// True when no mouse button is held down (GTK drag drop: the button is already up when the drop arrives).
1182#[cfg(target_os = "linux")]
1183fn pointer_buttons_up(widget: &webkit2gtk::WebView) -> bool {
1184    use gtk::prelude::*;
1185    let Some(window) = widget.window() else { return false };
1186    let Some(pointer) = gtk::gdk::Display::default().and_then(|d| d.default_seat()).and_then(|s| s.pointer()) else { return false };
1187    let (_, _, _, mask) = window.device_position(&pointer);
1188    !mask.intersects(gtk::gdk::ModifierType::BUTTON1_MASK | gtk::gdk::ModifierType::BUTTON2_MASK | gtk::gdk::ModifierType::BUTTON3_MASK)
1189}
1190
1191/// The script that tells the page a file drag is over the window (`state` is "enter" or "leave"); the page shows its drop box (apps/host DropZone).
1192#[cfg_attr(windows, allow(dead_code))]
1193fn drag_script(state: &str) -> String {
1194    format!("window.dispatchEvent(new CustomEvent('strata:native-drag', {{ detail: '{state}' }}));")
1195}
1196
1197/// The script that tells the page which dropped files the host holds for it (`files_json` is the host's own JSON array of { id, name, type, size }).
1198#[cfg_attr(windows, allow(dead_code))]
1199fn drop_script(files_json: &str) -> String {
1200    format!("window.dispatchEvent(new CustomEvent('strata:native-drop', {{ detail: {files_json} }}));")
1201}
1202
1203/// The files of one drop, by path, to the host (which reads them and keeps each for the page to fetch once); then the page is told.
1204/// Off the window's own thread, so the window never waits for a big picture to be read.
1205#[cfg(not(windows))]
1206fn hand_over_drop(window: tauri::WebviewWindow, port: u16, token: String, paths: Vec<String>) {
1207    std::thread::spawn(move || {
1208        let body = serde_json::json!({ "paths": paths }).to_string();
1209        let answer = http_request_body(
1210            "POST",
1211            &format!("http://127.0.0.1:{port}/api/app/drop"),
1212            &[("x-strata-shutdown", token.as_str()), ("content-type", "application/json")],
1213            Some(&body),
1214        );
1215        let files = match answer {
1216            Ok((status, text)) if status.contains(" 200") => serde_json::from_str::<serde_json::Value>(&text).ok().and_then(|v| v.get("files").cloned()),
1217            Ok((status, _)) => { eprintln!("[strata] the host did not take the dropped files: {status}"); None }
1218            Err(e) => { eprintln!("[strata] the dropped files could not be handed to the host: {e}"); None }
1219        };
1220        let json = files.map(|f| f.to_string()).unwrap_or_else(|| "[]".to_string());
1221        let _ = window.eval(&drop_script(&json));
1222    });
1223}
1224
1225/// Linux window process: shows the page of the host the shell started and registers the app updater with it. It starts no host and
1226/// stops nothing: when the window closes it just exits, and the shell stops the host. If WebKit crashes this process, only this
1227/// process dies; the shell moves to browser mode.
1228#[cfg(target_os = "linux")]
1229fn run_window_process() -> ! {
1230    let port: u16 = std::env::var("STRATA_WINDOW_PORT").ok().and_then(|v| v.parse().ok()).unwrap_or(PREFERRED_PORT);
1231    let token = std::env::var("STRATA_SHUTDOWN_TOKEN").unwrap_or_default();
1232    // A way to prove the safety net on a computer where the window works (tests only): this process dies the way a WebKit crash does.
1233    if std::env::var_os("STRATA_WINDOW_TEST_CRASH").is_some() {
1234        eprintln!("[strata] STRATA_WINDOW_TEST_CRASH is set: the window process aborts on purpose.");
1235        std::process::abort();
1236    }
1237    // WebKitGTK aborts while it draws a COLRv1 colour emoji font (fontguard.rs, #4533): this process is told to leave that font out. Only this
1238    // process, and before WebKit starts its own: the host, the engine and the agent keep the fonts the person chose.
1239    {
1240        let env = |k: &str| std::env::var(k).ok();
1241        let dirs = fontguard::font_dirs(&env);
1242        if let Some(conf) = fontguard::config_for(&env, &desktoplog::data_dir().join("fonts"), &dirs, Path::new(fontguard::SYSTEM_CONFIG)) {
1243            std::env::set_var("FONTCONFIG_FILE", conf);
1244        }
1245    }
1246    // The shell is this process's parent: when it is gone (killed, crashed, logged off) the window goes too.
1247    let parent = std::os::unix::process::parent_id();
1248    std::thread::spawn(move || loop {
1249        std::thread::sleep(Duration::from_secs(1));
1250        if std::os::unix::process::parent_id() != parent {
1251            std::process::exit(0);
1252        }
1253    });
1254    tauri::Builder::default()
1255        // First, as the plugin requires: a second window process ends here after telling the open window to show itself.
1256        .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
1257            if let Some(window) = tauri::Manager::get_webview_window(app, "main") {
1258                let _ = window.unminimize();
1259                let _ = window.show();
1260                let _ = window.set_focus();
1261            }
1262        }))
1263        .plugin(tauri_plugin_shell::init())
1264        .plugin(tauri_plugin_updater::Builder::new().build())
1265        .setup(move |app| {
1266            // The signed app updater (Tauri) is reached by the host through a token-protected loopback bridge; tell the host where it is.
1267            let bridge_token = random_token();
1268            if let Some(bridge) = updater::start(app.handle(), bridge_token) {
1269                let body = serde_json::json!({ "bridge": { "url": bridge.url, "token": bridge.token } }).to_string();
1270                if let Err(e) = http_request_body(
1271                    "POST",
1272                    &format!("http://127.0.0.1:{port}/api/control/ui"),
1273                    &[("x-strata-shutdown", token.as_str()), ("content-type", "application/json")],
1274                    Some(&body),
1275                ) {
1276                    eprintln!("[strata] the app updater could not be registered with the host: {e}");
1277                }
1278            }
1279            open_window(app, port, &token)
1280        })
1281        .on_window_event(|window, event| {
1282            if let tauri::WindowEvent::Destroyed = event {
1283                window.app_handle().exit(0);
1284            }
1285        })
1286        .build(tauri::generate_context!())
1287        .expect("error while building the Strata application")
1288        .run(|_app, _event| {});
1289    std::process::exit(0)
1290}
1291
1292#[cfg(test)]
1293mod tests {
1294    use super::*;
1295
1296    #[test]
1297    fn dropped_file_addresses_become_paths_and_nothing_else_does() {
1298        assert_eq!(file_uri_to_path("file:///home/me/My%20Pictures/a%2Bb.png").as_deref(), Some("/home/me/My Pictures/a+b.png"));
1299        assert_eq!(file_uri_to_path("file://localhost/tmp/x.txt").as_deref(), Some("/tmp/x.txt"));
1300        assert_eq!(file_uri_to_path("  file:///tmp/%C4%8C.txt\r\n").as_deref(), Some("/tmp/\u{10C}.txt"));
1301        for bad in ["http://example.com/a.png", "file://otherhost/tmp/x", "mailto:a@b.c", "/tmp/plain", "file://", "file:///tmp/a%00b"] { assert_eq!(file_uri_to_path(bad), None, "{bad}"); }
1302        assert_eq!(file_uri_to_path("file:///100%").as_deref(), Some("/100%"));
1303    }
1304
1305    #[test]
1306    fn the_scripts_the_shell_sends_the_page_for_a_file_drop() {
1307        assert_eq!(drag_script("enter"), "window.dispatchEvent(new CustomEvent('strata:native-drag', { detail: 'enter' }));");
1308        let files = r#"[{"id":"a","name":"x.png","type":"image/png","size":3}]"#;
1309        let script = drop_script(files);
1310        assert!(script.starts_with("window.dispatchEvent(new CustomEvent('strata:native-drop', { detail: [{"));
1311        assert!(script.contains("x.png") && script.ends_with("}));"));
1312    }
1313
1314    #[test]
1315    fn the_window_origin_is_stable_unless_the_port_is_taken() {
1316        // free (or already ours from a previous run): the same port every launch, so browser storage survives a restart
1317        let first = pick_stable_port().unwrap();
1318        let second = pick_stable_port().unwrap();
1319        if first == PREFERRED_PORT {
1320            // (when another program already holds the preferred port, as an installed Strata does on a dev PC, every call falls back to a fresh port)
1321            assert_eq!(first, second);
1322        }
1323        // held by another program: a different free port, not a failure
1324        if first == PREFERRED_PORT {
1325            let held = TcpListener::bind(("127.0.0.1", PREFERRED_PORT)).unwrap();
1326            let fallback = pick_stable_port().unwrap();
1327            assert_ne!(fallback, PREFERRED_PORT);
1328            drop(held);
1329        }
1330    }
1331
1332    fn scratch(name: &str) -> PathBuf {
1333        let dir = std::env::temp_dir().join(format!("strata-desktop-{name}-{}", std::process::id()));
1334        let _ = std::fs::remove_dir_all(&dir);
1335        std::fs::create_dir_all(&dir).unwrap();
1336        dir
1337    }
1338
1339    #[test]
1340    fn bundled_node_uses_the_platform_file_name() {
1341        let res = scratch("node");
1342        assert!(node_binary(&res).is_err());
1343        let dir = res.join("node");
1344        std::fs::create_dir_all(&dir).unwrap();
1345        std::fs::write(dir.join(NODE_EXE), b"").unwrap();
1346        assert_eq!(node_binary(&res).unwrap(), dir.join(NODE_EXE));
1347        assert_eq!(NODE_EXE, if cfg!(windows) { "node.exe" } else { "node" });
1348        let _ = std::fs::remove_dir_all(&res);
1349    }
1350
1351    #[test]
1352    fn verbatim_windows_paths_are_made_plain() {
1353        assert_eq!(plain_path(PathBuf::from(r"\\?\C:\a\b")), PathBuf::from(r"C:\a\b"));
1354        assert_eq!(
1355            plain_path(PathBuf::from(r"\\?\UNC\srv\share\x")),
1356            PathBuf::from(r"\\srv\share\x")
1357        );
1358        assert_eq!(plain_path(PathBuf::from("/usr/lib/Strata")), PathBuf::from("/usr/lib/Strata"));
1359    }
1360
1361    #[test]
1362    fn control_is_found_only_when_whole() {
1363        let res = scratch("control");
1364        assert!(control_dir(&res).is_none());
1365        let dir = res.join("control");
1366        let py = if cfg!(windows) { dir.join("python").join("python.exe") } else { dir.join("python").join("bin").join("python3") };
1367        std::fs::create_dir_all(py.parent().unwrap()).unwrap();
1368        std::fs::write(&py, b"").unwrap();
1369        assert!(control_dir(&res).is_none(), "no strata.py yet");
1370        std::fs::write(dir.join("strata.py"), b"").unwrap();
1371        assert_eq!(control_dir(&res), Some(dir));
1372        let _ = std::fs::remove_dir_all(&res);
1373    }
1374
1375    #[cfg(windows)]
1376    #[test]
1377    fn a_process_in_the_job_ends_when_the_job_is_closed() {
1378        use std::os::windows::io::AsRawHandle;
1379        let job = job::Job::kill_on_close().expect("a job object");
1380        let mut child = Command::new("ping").args(["-n", "120", "127.0.0.1"]).stdout(Stdio::null()).spawn().expect("ping");
1381        assert!(job.assign_raw(child.as_raw_handle() as *mut std::ffi::c_void), "the child joins the job");
1382        assert!(child.try_wait().unwrap().is_none(), "it runs while the job is open");
1383        drop(job); // what the system does when the app ends, by any route
1384        let deadline = Instant::now() + Duration::from_secs(10);
1385        while child.try_wait().unwrap().is_none() && Instant::now() < deadline {
1386            std::thread::sleep(Duration::from_millis(50));
1387        }
1388        let ended = child.try_wait().unwrap().is_some();
1389        if !ended {
1390            let _ = child.kill();
1391        }
1392        assert!(ended, "closing the job must end its processes");
1393    }
1394
1395    #[test]
1396    fn the_shells_wait_for_the_host_exceeds_the_hosts_own_deadline_and_stays_bounded() {
1397        // the host ends itself after 45 s (server/index.mjs); the shell must wait longer than that, but not for ever
1398        assert!(HOST_STOP_SECONDS > 45 && HOST_STOP_SECONDS <= 90);
1399    }
1400
1401    #[test]
1402    fn shutdown_tokens_are_long_and_different() {
1403        let (a, b) = (random_token(), random_token());
1404        assert_eq!(a.len(), 64);
1405        assert_ne!(a, b);
1406        assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
1407    }
1408
1409    #[test]
1410    fn a_bare_node_is_not_taken_for_the_windows_runtime() {
1411        if !cfg!(windows) {
1412            return;
1413        }
1414        let res = scratch("bare");
1415        let dir = res.join("node");
1416        std::fs::create_dir_all(&dir).unwrap();
1417        std::fs::write(dir.join("node"), b"").unwrap();
1418        assert!(node_binary(&res).is_err());
1419        let _ = std::fs::remove_dir_all(&res);
1420    }
1421
1422    #[test]
1423    fn packaged_resources_are_found_for_each_platform_layout() {
1424        let root = scratch("layout");
1425        for (exe_rel, res_rel) in [
1426            ("Contents/MacOS/strata-desktop", "Contents/Resources"),
1427            ("install/strata-desktop.exe", "install"),
1428            ("usr/bin/strata-desktop", "usr/lib/Strata"),
1429        ] {
1430            let exe = root.join(exe_rel);
1431            let res = root.join(res_rel);
1432            assert!(packaged_resource_dir(&exe).is_none(), "{exe_rel}");
1433            let server = res.join("host").join("server");
1434            std::fs::create_dir_all(&server).unwrap();
1435            std::fs::write(server.join("index.mjs"), b"").unwrap();
1436            assert_eq!(packaged_resource_dir(&exe), Some(res), "{exe_rel}");
1437        }
1438        let _ = std::fs::remove_dir_all(&root);
1439    }
1440
1441    #[test]
1442    fn the_host_command_listens_on_loopback_only_and_carries_the_shutdown_secret() {
1443        let res = scratch("hostcmd");
1444        let server = res.join("host").join("server");
1445        std::fs::create_dir_all(&server).unwrap();
1446        std::fs::write(server.join("index.mjs"), b"").unwrap();
1447        std::fs::create_dir_all(res.join("host").join("dist")).unwrap();
1448        std::fs::create_dir_all(res.join("node")).unwrap();
1449        std::fs::write(res.join("node").join(NODE_EXE), b"").unwrap();
1450        // a caller's environment must not widen the bind address: the command sets it itself
1451        std::env::set_var("STRATA_BIND", "0.0.0.0");
1452        let cmd = host_command(&res, 47831, "s3cret").expect("a host command");
1453        std::env::remove_var("STRATA_BIND");
1454        let env: std::collections::HashMap<String, String> = cmd
1455            .get_envs()
1456            .filter_map(|(k, v)| Some((k.to_string_lossy().into_owned(), v?.to_string_lossy().into_owned())))
1457            .collect();
1458        assert_eq!(env.get("STRATA_BIND").map(String::as_str), Some("127.0.0.1"));
1459        assert_eq!(env.get("STRATA_PORT").map(String::as_str), Some("47831"));
1460        assert_eq!(env.get("STRATA_SHUTDOWN_TOKEN").map(String::as_str), Some("s3cret"));
1461        assert_eq!(env.get("STRATA_PACKAGED").map(String::as_str), Some("1"));
1462        assert_eq!(env.get("STRATA_NO_ACQUIRE").map(String::as_str), Some("1"));
1463        assert!(env.get("STRATA_DIST").unwrap().ends_with("dist"));
1464        // a layout without the built UI or the host is refused in plain words
1465        assert!(host_command(&scratch("empty"), 1, "x").unwrap_err().contains("App Host entry is missing"));
1466        let _ = std::fs::remove_dir_all(&res);
1467    }
1468}