desktop (Linux): the shell owns the host, the window is its own process; a crashed window moves Strata to the browser (--browser, STRATA_UI=browser, --quit, session file)

This commit is contained in:
Niko1221 committed 2026-10-18 00:58:54 +02:00
1 parent e01f766118
commit 8be9e0976f
5 files changed
+592 -41

No files matched your search

+144 -41
View File
@@ -37,6 +37,8 @@ use std::time::{Duration, Instant};
use tauri::{Manager, WebviewUrl, WebviewWindowBuilder};
mod updater;
#[cfg(target_os = "linux")]
mod supervisor;
/// The kill-on-close Job Object that holds everything this app starts (Windows). Its only handle is this process's,
/// which the system closes however the process ends; closing the last handle ends every process in the job.
@@ -185,12 +187,15 @@ fn contain_app() -> bool {
}
/// The running App Host, kept so it can be stopped on exit.
#[cfg(not(target_os = "linux"))]
struct HostProcess(Mutex<Option<Child>>);
/// The port the App Host bound, so the window (and the frontend) can be pointed at it.
#[cfg(not(target_os = "linux"))]
struct HostPort(Mutex<Option<u16>>);
/// The secret that lets this shell (and nothing else) ask the host for a clean stop.
#[cfg(not(target_os = "linux"))]
struct ShutdownToken(Mutex<Option<String>>);
/// 256 random bits as hex, from the standard library's per-process random hasher keys (no extra crate).
@@ -260,6 +265,7 @@ fn pick_stable_port() -> Result<u16, String> {
/// In a packaged `.app` Tauri places `bundle.resources` under `Contents/Resources`. During
/// development they are not copied, so the repository layout is the fallback. Both are tried so
/// `tauri dev` and the packaged bundle behave the same way.
#[cfg(not(target_os = "linux"))]
fn resource_dir(app: &tauri::AppHandle) -> Result<PathBuf, String> {
if let Ok(dir) = app.path().resource_dir() {
if dir.join("host").join("server").join("index.mjs").exists() {
@@ -363,6 +369,11 @@ fn http_get_body(url: &str) -> Result<(String, String), String> {
}
fn http_request(method: &str, url: &str, headers: &[(&str, &str)]) -> Result<(String, String), String> {
http_request_body(method, url, headers, None)
}
/// Like `http_request`, with an optional body (sent as given; the caller sets content-type in `headers`).
fn http_request_body(method: &str, url: &str, headers: &[(&str, &str)], body: Option<&str>) -> Result<(String, String), String> {
use std::io::{Read, Write};
let rest = url.strip_prefix("http://").ok_or("only http:// is supported")?;
let (authority, path) = match rest.find('/') {
@@ -377,13 +388,13 @@ fn http_request(method: &str, url: &str, headers: &[(&str, &str)]) -> Result<(St
stream.set_read_timeout(Some(Duration::from_secs(20))).map_err(|e| e.to_string())?;
let extra: String = headers.iter().map(|(k, v)| format!("{k}: {v}\r\n")).collect();
stream
.write_all(format!("{method} {path} HTTP/1.1\r\nHost: {authority}\r\n{extra}Content-Length: 0\r\nConnection: close\r\n\r\n").as_bytes())
.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())
.map_err(|e| e.to_string())?;
let mut buf = String::new();
stream.read_to_string(&mut buf).map_err(|e| e.to_string())?;
let status = buf.lines().next().unwrap_or_default().to_string();
let body = buf.split_once("\r\n\r\n").map(|(_, b)| b.to_string()).unwrap_or_default();
Ok((status, body))
let response = buf.split_once("\r\n\r\n").map(|(_, b)| b.to_string()).unwrap_or_default();
Ok((status, response))
}
/// A minimal blocking HTTP GET, so the shell needs no async runtime for one health probe.
@@ -413,9 +424,9 @@ fn ureq_get_ok(url: &str) -> Result<bool, String> {
Ok(status.contains(" 200") || status.contains(" 204"))
}
/// Start the App Host and return the port it should serve on.
fn start_host(app: &tauri::AppHandle) -> Result<u16, String> {
let res = resource_dir(app)?;
/// 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.
/// `shutdown_token` is the secret that lets the shell (and nothing else) ask the host for a clean stop.
fn host_command(res: &Path, port: u16, shutdown_token: &str) -> Result<Command, String> {
let host_dir = if res.join("host").join("server").join("index.mjs").exists() {
res.join("host")
} else {
@@ -432,9 +443,7 @@ fn start_host(app: &tauri::AppHandle) -> Result<u16, String> {
dist.display()
));
}
let node = node_binary(&res)?;
let port = pick_stable_port()?;
let node = node_binary(res)?;
let mut cmd = Command::new(&node);
cmd.arg(&entry)
@@ -449,23 +458,35 @@ fn start_host(app: &tauri::AppHandle) -> Result<u16, String> {
.env("STRATA_REAL_ENGINE", "1")
// the host leaves, after stopping what this app started, when this shell is gone (killed, crashed)
.env("STRATA_EXIT_WITH_PARENT", "1")
// the host listens on the loopback address only, whatever the caller's environment says
.env("STRATA_BIND", "127.0.0.1")
.env("STRATA_SHUTDOWN_TOKEN", shutdown_token)
.stdin(Stdio::null())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
apply_runtime_policy(&mut cmd, &res);
// The signed app updater (Tauri) is reached by the host through a token-protected loopback bridge.
let bridge = updater::start(app, random_token());
updater::apply_env(&mut cmd, app, bridge.as_ref());
let token = random_token();
cmd.env("STRATA_SHUTDOWN_TOKEN", &token);
*app.state::<ShutdownToken>().0.lock().unwrap() = Some(token);
apply_runtime_policy(&mut cmd, res);
hide_console(&mut cmd);
// A user with the Strata API worker on a different port sets this; unset means the worker's
// documented loopback default.
if let Ok(url) = std::env::var("STRATA_SERVER_URL") {
cmd.env("STRATA_SERVER_URL", url);
}
Ok(cmd)
}
/// Windows and macOS: start the App Host from inside the app process and return the port it serves on.
#[cfg(not(target_os = "linux"))]
fn start_host(app: &tauri::AppHandle) -> Result<u16, String> {
let res = resource_dir(app)?;
let port = pick_stable_port()?;
let token = random_token();
let mut cmd = host_command(&res, port, &token)?;
// The signed app updater (Tauri) is reached by the host through a token-protected loopback bridge.
let bridge = updater::start(app, random_token());
updater::apply_env(&mut cmd, app, bridge.as_ref());
*app.state::<ShutdownToken>().0.lock().unwrap() = Some(token);
let node = node_binary(&res)?;
let child = cmd
.spawn()
.map_err(|e| format!("could not start the App Host on {}: {e}", node.display()))?;
@@ -493,30 +514,34 @@ const HOST_STOP_SECONDS: u64 = 60;
/// The host stops them through Control (profiles `app-N`), then exits. Engines another client started (the
/// Terminal's `strata runtime start`) are not touched. If the host does not finish in time it is ended, and the
/// engines are ended by the job object (Windows) or by their owners following the host (`--die-with-pid`).
#[cfg(not(target_os = "linux"))]
fn stop_host(app: &tauri::AppHandle) {
let port = app.try_state::<HostPort>().and_then(|s| *s.0.lock().unwrap());
let token = app.try_state::<ShutdownToken>().and_then(|s| s.0.lock().unwrap().clone());
if let Some(state) = app.try_state::<HostProcess>() {
if let Some(mut child) = state.0.lock().unwrap().take() {
// A clean stop first: the host stops, through Control, the engines this app started, then exits.
// Engines another client started (the Terminal) are not touched. If it does not finish in time the
// process is ended as before.
if let (Some(port), Some(token)) = (port, token) {
let _ = http_post(&format!("http://127.0.0.1:{port}/api/control/shutdown"), &[("x-strata-shutdown", token.as_str())]);
let deadline = Instant::now() + Duration::from_secs(HOST_STOP_SECONDS);
while Instant::now() < deadline {
if let Ok(Some(_)) = child.try_wait() {
return;
}
std::thread::sleep(Duration::from_millis(100));
}
}
let _ = child.kill();
let _ = child.wait();
stop_host_child(&mut child, port, token.as_deref());
}
}
}
/// A clean stop first: the host stops, through Control, the engines this app started, then exits. Engines another client
/// started (the Terminal) are not touched. If it does not finish in time the process is ended.
fn stop_host_child(child: &mut Child, port: Option<u16>, token: Option<&str>) {
if let (Some(port), Some(token)) = (port, token) {
let _ = http_post(&format!("http://127.0.0.1:{port}/api/control/shutdown"), &[("x-strata-shutdown", token)]);
let deadline = Instant::now() + Duration::from_secs(HOST_STOP_SECONDS);
while Instant::now() < deadline {
if let Ok(Some(_)) = child.try_wait() {
return;
}
std::thread::sleep(Duration::from_millis(100));
}
}
let _ = child.kill();
let _ = child.wait();
}
/// Where a packaged build keeps `bundle.resources`, found from the executable's own path.
///
/// macOS `.app`: `Contents/MacOS/<exe>` -> `Contents/Resources`. Windows NSIS: next to the exe.
@@ -788,6 +813,23 @@ fn main() {
std::process::exit(code);
}
// Linux: this executable is two programs. The shell (no GTK, no WebKit) owns the host and survives a crash of the window; the
// window process (`--window-child`) only shows the page. See supervisor.rs.
#[cfg(target_os = "linux")]
{
let options = supervisor::parse_args(&args, std::env::var("STRATA_UI").ok().as_deref());
if !options.window_child {
std::process::exit(supervisor::run(&options));
}
run_window_process();
}
#[cfg(not(target_os = "linux"))]
run_embedded();
}
/// Windows and macOS: one process owns the host and the window.
#[cfg(not(target_os = "linux"))]
fn run_embedded() {
tauri::Builder::default()
// First, as the plugin requires: a second launch ends here after telling the running app to show itself.
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
@@ -809,16 +851,7 @@ fn main() {
eprintln!("[strata] {e}");
Box::<dyn std::error::Error>::from(e)
})?;
let origin = format!("http://127.0.0.1:{port}");
let url = origin.parse().expect("a valid loopback URL");
WebviewWindowBuilder::new(app, "main", WebviewUrl::External(url))
.title("Strata")
.inner_size(1440.0, 920.0)
.min_inner_size(900.0, 600.0)
.build()?;
open_window(app, port)?;
Ok(())
})
.on_window_event(|window, event| {
@@ -835,6 +868,76 @@ fn main() {
});
}
/// The one window, on the host's own origin so the page and its API share an origin exactly as the browser build does.
fn open_window(app: &tauri::App, port: u16) -> Result<(), Box<dyn std::error::Error>> {
let origin = format!("http://127.0.0.1:{port}");
let url = origin.parse().expect("a valid loopback URL");
WebviewWindowBuilder::new(app, "main", WebviewUrl::External(url))
.title("Strata")
.inner_size(1440.0, 920.0)
.min_inner_size(900.0, 600.0)
.build()?;
Ok(())
}
/// Linux window process: shows the page of the host the shell started and registers the app updater with it. It starts no host and
/// stops nothing: when the window closes it just exits, and the shell stops the host. If WebKit crashes this process, only this
/// process dies; the shell moves to browser mode.
#[cfg(target_os = "linux")]
fn run_window_process() -> ! {
let port: u16 = std::env::var("STRATA_WINDOW_PORT").ok().and_then(|v| v.parse().ok()).unwrap_or(PREFERRED_PORT);
let token = std::env::var("STRATA_SHUTDOWN_TOKEN").unwrap_or_default();
// 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.
if std::env::var_os("STRATA_WINDOW_TEST_CRASH").is_some() {
eprintln!("[strata] STRATA_WINDOW_TEST_CRASH is set: the window process aborts on purpose.");
std::process::abort();
}
// The shell is this process's parent: when it is gone (killed, crashed, logged off) the window goes too.
let parent = std::os::unix::process::parent_id();
std::thread::spawn(move || loop {
std::thread::sleep(Duration::from_secs(1));
if std::os::unix::process::parent_id() != parent {
std::process::exit(0);
}
});
tauri::Builder::default()
// First, as the plugin requires: a second window process ends here after telling the open window to show itself.
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
if let Some(window) = tauri::Manager::get_webview_window(app, "main") {
let _ = window.unminimize();
let _ = window.show();
let _ = window.set_focus();
}
}))
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.setup(move |app| {
// The signed app updater (Tauri) is reached by the host through a token-protected loopback bridge; tell the host where it is.
let bridge_token = random_token();
if let Some(bridge) = updater::start(app.handle(), bridge_token) {
let body = serde_json::json!({ "bridge": { "url": bridge.url, "token": bridge.token } }).to_string();
if let Err(e) = http_request_body(
"POST",
&format!("http://127.0.0.1:{port}/api/control/ui"),
&[("x-strata-shutdown", token.as_str()), ("content-type", "application/json")],
Some(&body),
) {
eprintln!("[strata] the app updater could not be registered with the host: {e}");
}
}
open_window(app, port)
})
.on_window_event(|window, event| {
if let tauri::WindowEvent::Destroyed = event {
window.app_handle().exit(0);
}
})
.build(tauri::generate_context!())
.expect("error while building the Strata application")
.run(|_app, _event| {});
std::process::exit(0)
}
#[cfg(test)]
mod tests {
use super::*;
+444
View File
@@ -0,0 +1,444 @@
//! Linux: the process that owns the host, and what it does when the app window cannot run.
//!
//! WebKitGTK can crash the process that shows the window (a null pointer deep inside libwebkit2gtk was seen on Ubuntu 26.04 with
//! 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
//! and the engine down with it. So on Linux the work is split in two processes of this one executable:
//!
//! shell (this module; no GTK, no WebKit) starts the host, writes the session file, starts the window process, and watches both
//! window (`--window-child`; Tauri + WebKitGTK) shows the page, registers the app updater with the host, and nothing else
//!
//! If the window process dies for any reason except the person closing the window (a signal such as SIGSEGV, an abort, a failed
//! start, a missing library), the shell keeps the host running, tells the host to open the page in the default browser and to
//! show one notification, and prints the same sentence on the terminal. This is "browser mode"; `--browser` or STRATA_UI=browser
//! starts in it on purpose. In browser mode closing the tab does not stop the engine: the page has "Quit Strata", and `--quit`
//! ends a running Strata from the command line. The host listens on 127.0.0.1 only (the shell sets STRATA_BIND itself).
//!
//! The session file (`~/.strata/app-session.json`, mode 0600: process id, port, the secret only this user can read, the mode) is how
//! a second start finds the first one: it focuses the window (window mode) or opens another tab (browser mode) instead of
//! starting a second host.
use std::io::Write;
use std::path::PathBuf;
use std::process::{Child, Command, ExitStatus, Stdio};
use std::time::{Duration, Instant};
pub const BROWSER_NOTICE: &str = "Strata opened in your browser because the app window couldn't start on this computer.";
/// What the command line asked for.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Options {
/// `--browser` or STRATA_UI=browser: no app window, the page opens in the default browser.
pub browser: bool,
/// `--quit`: end a running Strata and leave.
pub quit: bool,
/// `--window-child`: the window process (started by the shell, not by a person).
pub window_child: bool,
pub help: bool,
}
pub fn parse_args(args: &[String], ui_env: Option<&str>) -> Options {
let mut o = Options { browser: matches!(ui_env.map(|v| v.trim().to_ascii_lowercase()).as_deref(), Some("browser")), ..Options::default() };
for a in args.iter().skip(1) {
match a.as_str() {
"--browser" => o.browser = true,
"--quit" => o.quit = true,
"--window-child" => o.window_child = true,
"--help" | "-h" => o.help = true,
_ => {}
}
}
o
}
pub const HELP: &str = "Strata\n\
(no option) open the Strata app window\n\
--browser open Strata in your default browser instead of the app window (same as STRATA_UI=browser)\n\
--quit stop a running Strata (its engine too) and leave\n\
Closing the browser tab does not stop Strata in browser mode: use Quit Strata in the menu, or --quit.\n";
/// The command a person types to run this app again, for the messages ("run: Strata.AppImage --quit").
pub fn command_name() -> String {
if let Ok(image) = std::env::var("APPIMAGE") {
if let Some(name) = std::path::Path::new(&image).file_name() {
return format!("./{}", name.to_string_lossy());
}
}
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())
}
pub fn browser_chosen_line(port: u16) -> String {
format!(
"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.",
command_name()
)
}
pub fn open_by_hand_line(port: u16) -> String {
format!("No browser could be opened. Open http://127.0.0.1:{port}/ in your browser.")
}
// ------------------------------------------------------------------------------------------------ the session file
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Session {
pub pid: u32,
pub port: u16,
pub token: String,
pub mode: String,
}
fn session_path() -> PathBuf {
if let Some(p) = std::env::var_os("STRATA_APP_SESSION_FILE") {
return PathBuf::from(p);
}
let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_else(std::env::temp_dir);
home.join(".strata").join("app-session.json")
}
pub fn write_session(s: &Session) {
let path = session_path();
if let Some(dir) = path.parent() {
let _ = std::fs::create_dir_all(dir);
}
let text = serde_json::json!({ "pid": s.pid, "port": s.port, "token": s.token, "mode": s.mode }).to_string();
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
match options.open(&path) {
Ok(mut f) => {
let _ = f.write_all(text.as_bytes());
}
Err(e) => eprintln!("[strata] could not write {}: {e}", path.display()),
}
}
pub fn read_session() -> Option<Session> {
let text = std::fs::read_to_string(session_path()).ok()?;
let v: serde_json::Value = serde_json::from_str(&text).ok()?;
Some(Session {
pid: v["pid"].as_u64()? as u32,
port: v["port"].as_u64()? as u16,
token: v["token"].as_str()?.to_string(),
mode: v["mode"].as_str().unwrap_or("window").to_string(),
})
}
pub fn remove_session(only_if_pid: u32) {
if read_session().map(|s| s.pid == only_if_pid).unwrap_or(false) {
let _ = std::fs::remove_file(session_path());
}
}
fn pid_alive(pid: u32) -> bool {
#[cfg(target_os = "linux")]
{
std::path::Path::new(&format!("/proc/{pid}")).exists()
}
#[cfg(not(target_os = "linux"))]
{
let _ = pid;
true
}
}
/// A Strata that is really running: its shell process exists and its host answers.
pub fn live_session() -> Option<Session> {
let s = read_session()?;
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) {
Some(s)
} else {
None
}
}
// ------------------------------------------------------------------------------------------------ talking to the host
/// POST to the host as the shell (the secret in the header). Returns the response body.
fn host_post(port: u16, token: &str, path: &str, body: &serde_json::Value) -> Result<String, String> {
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()))?;
if status.contains(" 200") || status.contains(" 202") {
Ok(text)
} else {
Err(format!("{status}: {text}"))
}
}
/// Did the host manage to open the page (the "opened" flag in its answer)?
fn opened(answer: &str) -> bool {
let body = answer.rsplit("\r\n\r\n").next().unwrap_or(answer);
serde_json::from_str::<serde_json::Value>(body.trim()).ok().and_then(|v| v["opened"].as_bool()).unwrap_or(false)
}
/// Tell the host: everyone uses a browser tab now (and open it, and show `notice`). Prints what happened.
pub fn switch_host_to_browser(port: u16, token: &str, reason: &str, notice: &str) {
let body = serde_json::json!({ "mode": "browser", "reason": reason, "notice": notice, "open": true });
match host_post(port, token, "/api/control/ui", &body) {
Ok(answer) => {
if !opened(&answer) {
eprintln!("[strata] {}", open_by_hand_line(port));
}
}
Err(e) => eprintln!("[strata] could not tell the host to open your browser ({e}). Open http://127.0.0.1:{port}/ in your browser."),
}
}
/// Open the page in the default browser without changing the host's mode (a second start while Strata runs).
fn open_page_only(port: u16, token: &str) {
match host_post(port, token, "/api/control/ui", &serde_json::json!({ "open": true })) {
Ok(answer) if opened(&answer) => {}
_ => eprintln!("[strata] {}", open_by_hand_line(port)),
}
}
pub fn describe_exit(status: &ExitStatus) -> String {
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
if let Some(sig) = status.signal() {
let name = match sig {
6 => " (abort)",
11 => " (segmentation fault)",
7 => " (bus error)",
9 => " (killed)",
15 => " (terminated)",
_ => "",
};
return format!("signal {sig}{name}");
}
}
match status.code() {
Some(c) => format!("exit code {c}"),
None => "ended without a code".into(),
}
}
// ------------------------------------------------------------------------------------------------ the shell
fn spawn_window(port: u16, token: &str) -> std::io::Result<Child> {
let exe = std::env::current_exe()?;
Command::new(exe)
.arg("--window-child")
.env("STRATA_WINDOW_PORT", port.to_string())
.env("STRATA_SHUTDOWN_TOKEN", token)
.stdin(Stdio::null())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.spawn()
}
/// `--quit`: end a running Strata (the window, the host, the engines it started) and wait for it.
pub fn quit_running() -> i32 {
let Some(s) = live_session() else {
println!("Strata is not running.");
let _ = std::fs::remove_file(session_path());
return 0;
};
match host_post(s.port, &s.token, "/api/control/shutdown", &serde_json::json!({})) {
Ok(_) => {}
Err(e) => {
eprintln!("[strata] could not ask Strata to stop ({e}).");
return 1;
}
}
let deadline = Instant::now() + Duration::from_secs(crate::HOST_STOP_SECONDS + 10);
while Instant::now() < deadline {
if !pid_alive(s.pid) {
println!("Strata has stopped.");
return 0;
}
std::thread::sleep(Duration::from_millis(200));
}
eprintln!("[strata] Strata is still stopping its engine. Try again in a moment.");
1
}
/// A second start while Strata already runs: focus the window, or open another tab. Starts no second host.
fn join_running(s: &Session, browser: bool) -> i32 {
if browser || s.mode == "browser" {
println!("Strata is already running. Opening it in your browser.");
open_page_only(s.port, &s.token);
return 0;
}
// window mode: the window process's single-instance check brings the open window forward and exits at once
match spawn_window(s.port, &s.token).and_then(|mut c| c.wait()) {
Ok(status) if status.success() => 0,
Ok(status) => {
eprintln!("[strata] The app window stopped ({}). Opening Strata in your browser.", describe_exit(&status));
open_page_only(s.port, &s.token);
0
}
Err(e) => {
eprintln!("[strata] could not start the app window ({e}). Opening Strata in your browser.");
open_page_only(s.port, &s.token);
0
}
}
}
/// The shell. Returns the process exit code.
pub fn run(opts: &Options) -> i32 {
if opts.help {
print!("{HELP}");
return 0;
}
if opts.quit {
return quit_running();
}
if let Some(s) = live_session() {
return join_running(&s, opts.browser);
}
let exe = std::env::current_exe().unwrap_or_default();
let res = crate::packaged_resource_dir(&exe).unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")));
let port = match crate::pick_stable_port() {
Ok(p) => p,
Err(e) => {
eprintln!("[strata] {e}");
return 1;
}
};
let token = crate::random_token();
let mode = if opts.browser { "browser" } else { "window" };
let mut cmd = match crate::host_command(&res, port, &token) {
Ok(c) => c,
Err(e) => {
eprintln!("[strata] {e}");
return 1;
}
};
cmd.env("STRATA_UI_MODE", mode).env("STRATA_APP_VERSION", env!("CARGO_PKG_VERSION"));
if opts.browser {
cmd.env("STRATA_UI_REASON", "chosen");
}
let mut host = match cmd.spawn() {
Ok(c) => c,
Err(e) => {
eprintln!("[strata] could not start the App Host: {e}");
return 1;
}
};
let health = crate::wait_for_health(port, Duration::from_secs(60), || match host.try_wait() {
Ok(Some(status)) => Some(format!("exit status {status}")),
_ => None,
});
if let Err(e) = health {
eprintln!("[strata] {e}");
let _ = host.kill();
let _ = host.wait();
return 1;
}
let me = std::process::id();
write_session(&Session { pid: me, port, token: token.clone(), mode: mode.into() });
let mut in_browser = opts.browser;
let mut window: Option<Child> = None;
if in_browser {
eprintln!("[strata] {}", browser_chosen_line(port));
switch_host_to_browser(port, &token, "chosen", "");
} else {
match spawn_window(port, &token) {
Ok(c) => window = Some(c),
Err(e) => {
eprintln!("[strata] could not start the app window ({e}).");
eprintln!("[strata] {BROWSER_NOTICE}");
in_browser = true;
switch_host_to_browser(port, &token, "window-failed", BROWSER_NOTICE);
write_session(&Session { pid: me, port, token: token.clone(), mode: "browser".into() });
}
}
}
let code = loop {
std::thread::sleep(Duration::from_millis(200));
// The host ended (Quit Strata, a crash, someone killed it): nothing is left to show.
if let Ok(Some(status)) = host.try_wait() {
if let Some(w) = window.as_mut() {
let _ = w.kill();
let _ = w.wait();
}
break if status.success() { 0 } else { eprintln!("[strata] The App Host stopped ({}).", describe_exit(&status)); 1 };
}
let Some(w) = window.as_mut() else { continue };
let Ok(Some(status)) = w.try_wait() else { continue };
window = None;
if status.success() {
// the person closed the window: stop the host and the engines this app started, as before
crate::stop_host_child(&mut host, Some(port), Some(&token));
break 0;
}
// The window stopped without being closed: keep Strata running and move to the browser.
eprintln!("[strata] The app window stopped unexpectedly ({}).", describe_exit(&status));
eprintln!("[strata] {BROWSER_NOTICE}");
in_browser = true;
switch_host_to_browser(port, &token, "window-failed", BROWSER_NOTICE);
write_session(&Session { pid: me, port, token: token.clone(), mode: "browser".into() });
};
let _ = in_browser;
remove_session(me);
code
}
#[cfg(test)]
mod tests {
use super::*;
fn args(list: &[&str]) -> Vec<String> {
std::iter::once("strata-desktop").chain(list.iter().copied()).map(String::from).collect()
}
#[test]
fn the_command_line_picks_browser_quit_and_the_window_child() {
assert_eq!(parse_args(&args(&[]), None), Options::default());
assert!(parse_args(&args(&["--browser"]), None).browser);
assert!(parse_args(&args(&[]), Some("browser")).browser);
assert!(parse_args(&args(&[]), Some(" Browser ")).browser);
assert!(!parse_args(&args(&[]), Some("window")).browser);
assert!(parse_args(&args(&["--quit"]), None).quit);
assert!(parse_args(&args(&["--window-child"]), None).window_child);
assert!(parse_args(&args(&["-h"]), None).help);
// anything else (a file the desktop hands over, an AppImage option) is ignored
assert_eq!(parse_args(&args(&["--appimage-extract-and-run", "x.gguf"]), None), Options::default());
}
#[test]
fn the_browser_message_is_the_plain_sentence_and_names_the_way_out() {
assert_eq!(BROWSER_NOTICE, "Strata opened in your browser because the app window couldn't start on this computer.");
let line = browser_chosen_line(47831);
assert!(line.contains("http://127.0.0.1:47831/") && line.contains("--quit") && line.contains("Quit Strata"));
assert!(open_by_hand_line(47831).contains("127.0.0.1:47831"));
}
#[test]
fn a_session_round_trips_and_is_private() {
let dir = std::env::temp_dir().join(format!("strata-session-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::env::set_var("STRATA_APP_SESSION_FILE", dir.join("s.json"));
assert!(read_session().is_none());
let s = Session { pid: 4242, port: 47831, token: "ab".repeat(32), mode: "browser".into() };
write_session(&s);
assert_eq!(read_session(), Some(s.clone()));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(std::fs::metadata(dir.join("s.json")).unwrap().permissions().mode() & 0o777, 0o600);
}
// only the owner removes it
remove_session(1);
assert!(read_session().is_some());
remove_session(4242);
assert!(read_session().is_none());
std::env::remove_var("STRATA_APP_SESSION_FILE");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_hosts_answer_tells_whether_a_browser_opened() {
assert!(opened("HTTP/1.1 200 OK\r\n\r\n{\"mode\":\"browser\",\"opened\":true}"));
assert!(!opened("HTTP/1.1 200 OK\r\n\r\n{\"mode\":\"browser\",\"opened\":false}"));
assert!(!opened("not json"));
}
}
+1
View File
@@ -231,6 +231,7 @@ pub fn start(app: &AppHandle, token: String) -> Option<Bridge> {
}
/// Environment for the App Host: where the bridge is, which app version this is.
#[allow(dead_code)]
pub fn apply_env(cmd: &mut std::process::Command, app: &AppHandle, bridge: Option<&Bridge>) {
cmd.env("STRATA_APP_VERSION", app.package_info().version.to_string());
if let Some(bridge) = bridge {
+2
View File
@@ -89,6 +89,8 @@ export function createAppUi({ env = process.env, shutdown = () => {}, open = ope
bridge = createUpdater({ env: { STRATA_SHELL_BRIDGE: url, STRATA_SHELL_TOKEN: token } });
return true;
},
/** Open the page in the default browser without changing the mode (a second start while Strata runs). */
openPage: url => open(url),
/** The shell moves everyone to a browser tab: the window could not start or has stopped. */
async switchToBrowser({ url, reason: why = 'window-failed', notice = '', openPage = true } = {}) {
mode = 'browser'; reason = String(why).slice(0, 40); bridge = null;
+1
View File
@@ -1230,6 +1230,7 @@ async function api(req, res, path, method, url) {
try {
if (body.bridge) appUi.setBridge(body.bridge);
if (body.mode === 'browser') return json(res, 200, await appUi.switchToBrowser({ url: `http://127.0.0.1:${PORT}/`, reason: body.reason, notice: typeof body.notice === 'string' ? body.notice.slice(0, 300) : '', openPage: body.open !== false }));
if (body.open === true) return json(res, 200, { ...appUi.state(), opened: await appUi.openPage(`http://127.0.0.1:${PORT}/`) });
return json(res, 200, appUi.state());
} catch (err) { return error(res, 400, err.message); }
}