Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
app: one instance, and closing always ends the engines this app started
Niko1221322790aff08e
diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lockindex 6b526ffe8..8a8322e3b 100644--- a/apps/desktop/src-tauri/Cargo.lock+++ b/apps/desktop/src-tauri/Cargo.lock@@ -47,6 +47,137 @@ version = "1.0.104"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"+[[package]]+name = "async-broadcast"+version = "0.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"+dependencies = [+ "event-listener",+ "event-listener-strategy",+ "futures-core",+ "pin-project-lite",+]++[[package]]+name = "async-channel"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"+dependencies = [+ "concurrent-queue",+ "event-listener-strategy",+ "futures-core",+ "pin-project-lite",+]++[[package]]+name = "async-executor"+version = "1.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"+dependencies = [+ "async-task",+ "concurrent-queue",+ "fastrand",+ "futures-lite",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "async-io"+version = "2.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"+dependencies = [+ "autocfg",+ "cfg-if",+ "concurrent-queue",+ "futures-io",+ "futures-lite",+ "parking",+ "polling",+ "rustix",+ "slab",+ "windows-sys 0.61.2",+]++[[package]]+name = "async-lock"+version = "3.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"+dependencies = [+ "event-listener",+ "event-listener-strategy",+ "pin-project-lite",+]++[[package]]+name = "async-process"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"+dependencies = [+ "async-channel",+ "async-io",+ "async-lock",+ "async-signal",+ "async-task",+ "blocking",+ "cfg-if",+ "event-listener",+ "futures-lite",+ "rustix",+]++[[package]]+name = "async-recursion"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]++[[package]]+name = "async-signal"+version = "0.2.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"+dependencies = [+ "async-io",+ "async-lock",+ "atomic-waker",+ "cfg-if",+ "futures-core",+ "futures-io",+ "rustix",+ "signal-hook-registry",+ "slab",+ "windows-sys 0.61.2",+]++[[package]]+name = "async-task"+version = "4.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"++[[package]]+name = "async-trait"+version = "0.1.92"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]+[[package]]name = "atk"version = "0.18.2"@@ -148,6 +279,19 @@ dependencies = ["objc2",]+[[package]]+name = "blocking"+version = "1.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa"+dependencies = [+ "async-channel",+ "async-task",+ "futures-io",+ "futures-lite",+ "piper",+]+[[package]]name = "brotli"version = "9.0.0"@@ -338,6 +482,15 @@ dependencies = ["memchr",]+[[package]]+name = "concurrent-queue"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"+dependencies = [+ "crossbeam-utils",+]+[[package]]name = "cookie"version = "0.18.2"@@ -734,6 +887,33 @@ dependencies = ["simdutf8",]+[[package]]+name = "endi"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"++[[package]]+name = "enumflags2"+version = "0.7.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"+dependencies = [+ "enumflags2_derive",+ "serde",+]++[[package]]+name = "enumflags2_derive"+version = "0.7.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "equivalent"version = "1.0.3"@@ -751,6 +931,36 @@ dependencies = ["typeid",]+[[package]]+name = "errno"+version = "0.3.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "event-listener"+version = "5.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"+dependencies = [+ "parking",+ "pin-project-lite",+]++[[package]]+name = "event-listener-strategy"+version = "0.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"+dependencies = [+ "event-listener",+ "pin-project-lite",+]+[[package]]name = "fastrand"version = "2.5.0"@@ -873,6 +1083,19 @@ version = "0.3.34"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"+[[package]]+name = "futures-lite"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"+dependencies = [+ "fastrand",+ "futures-core",+ "futures-io",+ "parking",+ "pin-project-lite",+]+[[package]]name = "futures-macro"version = "0.3.34"@@ -1216,6 +1439,12 @@ version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"+[[package]]+name = "hermit-abi"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"+[[package]]name = "hex"version = "0.4.3"@@ -1743,6 +1972,12 @@ dependencies = ["libc",]+[[package]]+name = "linux-raw-sys"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"+[[package]]name = "litemap"version = "0.8.3"@@ -2146,6 +2381,16 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"+[[package]]+name = "ordered-stream"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"+dependencies = [+ "futures-core",+ "pin-project-lite",+]+[[package]]name = "os_pipe"version = "1.2.3"@@ -2181,6 +2426,12 @@ dependencies = ["system-deps",]+[[package]]+name = "parking"+version = "2.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"+[[package]]name = "parking_lot"version = "0.12.5"@@ -2269,6 +2520,17 @@ version = "0.2.17"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"+[[package]]+name = "piper"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"+dependencies = [+ "atomic-waker",+ "fastrand",+ "futures-io",+]+[[package]]name = "pkg-config"version = "0.3.34"@@ -2314,6 +2576,20 @@ dependencies = ["miniz_oxide 0.8.9",]+[[package]]+name = "polling"+version = "3.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"+dependencies = [+ "cfg-if",+ "concurrent-queue",+ "hermit-abi",+ "pin-project-lite",+ "rustix",+ "windows-sys 0.61.2",+]+[[package]]name = "portable-atomic"version = "1.15.0"@@ -2565,6 +2841,19 @@ dependencies = ["semver",]+[[package]]+name = "rustix"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"+dependencies = [+ "bitflags 2.13.2",+ "errno",+ "libc",+ "linux-raw-sys",+ "windows-sys 0.61.2",+]+[[package]]name = "rustversion"version = "1.0.23"@@ -2852,6 +3141,16 @@ version = "2.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"+[[package]]+name = "signal-hook-registry"+version = "1.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"+dependencies = [+ "errno",+ "libc",+]+[[package]]name = "simd-adler32"version = "0.3.10"@@ -2961,6 +3260,7 @@ dependencies = ["tauri","tauri-build","tauri-plugin-shell",+ "tauri-plugin-single-instance",][[package]]@@ -3280,6 +3580,22 @@ dependencies = ["windows-sys 0.60.2",]+[[package]]+name = "tauri-plugin-single-instance"+version = "2.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "561cd99484561bc39c954768e7b41a66cebbe1ac3d9d081c34361f740c489e2c"+dependencies = [+ "serde",+ "serde_json",+ "tauri",+ "thiserror 2.0.21",+ "tokio",+ "tracing",+ "windows-sys 0.61.2",+ "zbus",+]+[[package]]name = "tauri-runtime"version = "2.12.2"@@ -3380,6 +3696,19 @@ dependencies = ["toml 1.1.8+spec-1.1.0",]+[[package]]+name = "tempfile"+version = "3.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"+dependencies = [+ "fastrand",+ "getrandom 0.4.3",+ "once_cell",+ "rustix",+ "windows-sys 0.61.2",+]+[[package]]name = "tendril"version = "0.5.1"@@ -3650,9 +3979,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"dependencies = ["pin-project-lite",+ "tracing-attributes","tracing-core",]+[[package]]+name = "tracing-attributes"+version = "0.1.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "tracing-core"version = "0.1.36"@@ -3702,6 +4043,17 @@ version = "1.20.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"+[[package]]+name = "uds_windows"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"+dependencies = [+ "memoffset",+ "tempfile",+ "windows-sys 0.61.2",+]+[[package]]name = "unicode-ident"version = "1.0.27"@@ -4445,6 +4797,76 @@ dependencies = ["synstructure",]+[[package]]+name = "zbus"+version = "5.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907"+dependencies = [+ "async-broadcast",+ "async-executor",+ "async-io",+ "async-lock",+ "async-process",+ "async-recursion",+ "async-task",+ "async-trait",+ "blocking",+ "enumflags2",+ "event-listener",+ "futures-core",+ "futures-lite",+ "hex",+ "libc",+ "ordered-stream",+ "rustix",+ "serde",+ "serde_repr",+ "tracing",+ "uds_windows",+ "uuid",+ "windows-sys 0.61.2",+ "winnow 1.0.4",+ "zbus_macros",+ "zbus_names",+ "zvariant",+]++[[package]]+name = "zbus_macros"+version = "5.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40"+dependencies = [+ "proc-macro-crate 3.5.0",+ "proc-macro2",+ "quote",+ "syn 3.0.9",+ "zbus_names",+ "zvariant",+ "zvariant_utils",+]++[[package]]+name = "zbus_names"+version = "4.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e"+dependencies = [+ "serde",+ "winnow 1.0.4",+ "zvariant",+]++[[package]]+name = "zcheapstr"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473"+dependencies = [+ "serde",+]+[[package]]name = "zerofrom"version = "0.1.8"@@ -4510,3 +4932,44 @@ name = "zmij"version = "1.0.23"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"++[[package]]+name = "zvariant"+version = "5.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c1d34c27cc6cdd1f458427519dd6b8612f7b7e3f7b9a0b2355d041dda9869147"+dependencies = [+ "endi",+ "enumflags2",+ "serde",+ "winnow 1.0.4",+ "zcheapstr",+ "zvariant_derive",+ "zvariant_utils",+]++[[package]]+name = "zvariant_derive"+version = "5.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "864155e69b4352db0c7f374917bf45d1e0c8d17659c8b3dbf9795f3673f8c497"+dependencies = [+ "proc-macro-crate 3.5.0",+ "proc-macro2",+ "quote",+ "syn 3.0.9",+ "zvariant_utils",+]++[[package]]+name = "zvariant_utils"+version = "4.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3"+dependencies = [+ "proc-macro2",+ "quote",+ "serde",+ "syn 3.0.9",+ "winnow 1.0.4",+]diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex 6b4884870..6285977b3 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -12,6 +12,7 @@ tauri-build = { version = "2", features = [] }[dependencies]tauri = { version = "2", features = [] }tauri-plugin-shell = "2"+tauri-plugin-single-instance = "2"serde = { version = "1", features = ["derive"] }serde_json = "1"diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rsindex 4d6e1e295..775c0877a 100644--- a/apps/desktop/src-tauri/src/main.rs+++ b/apps/desktop/src-tauri/src/main.rs@@ -7,7 +7,19 @@//! 2. opens one webview window on the host's own origin, so the renderer and the API share an//! origin exactly as the browser build does and the supplied UI's relative `/api/...` calls//! keep working with no rewrite;-//! 3. stops the host when the app exits.+//! 3. stops the host when the app exits, and sees to it that nothing the app started outlives it.+//!+//! One app instance runs at a time (the single-instance plugin): a second launch focuses the window that is+//! already open and starts nothing, so two apps never fight over the `app-N` engine slots. One app can still run+//! several engines (one per GPU, say): the host gives each its own `app-N` profile under Strata Control.+//!+//! Closing ends the engines this app started, on every path:+//! - a normal exit and the window's X: the host is asked to stop them through Control (drained, then ended), with a+//! deadline after which the host is ended;+//! - the shell is killed, crashes, or the user logs off: on Windows the shell owns a kill-on-close Job Object that+//! contains the host, Control, the owner host, the server and the engine, so they end with it; everywhere the host+//! watches its parent and each engine's owner is told to follow the host (`--die-with-pid`).+//! Engines the Terminal started are not in any of this and are left alone.//!//! Ownership stays where the architecture puts it. The App Host owns the local client API and the//! engine lifecycle; Strata Control owns components, models, profiles and jobs; DeepSeek Harness@@ -24,6 +36,130 @@ use std::time::{Duration, Instant};use tauri::{Manager, WebviewUrl, WebviewWindowBuilder};+/// 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.+#[cfg(windows)]+mod job {+ use std::ffi::c_void;++ type Handle = *mut c_void;+ const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: u32 = 0x2000;+ const JOB_OBJECT_EXTENDED_LIMIT_INFORMATION: i32 = 9;++ #[repr(C)]+ #[derive(Default)]+ struct BasicLimits {+ per_process_user_time_limit: i64,+ per_job_user_time_limit: i64,+ limit_flags: u32,+ minimum_working_set_size: usize,+ maximum_working_set_size: usize,+ active_process_limit: u32,+ affinity: usize,+ priority_class: u32,+ scheduling_class: u32,+ }++ #[repr(C)]+ #[derive(Default)]+ struct IoCounters {+ counts: [u64; 6],+ }++ #[repr(C)]+ #[derive(Default)]+ struct ExtendedLimits {+ basic: BasicLimits,+ io: IoCounters,+ process_memory_limit: usize,+ job_memory_limit: usize,+ peak_process_memory_used: usize,+ peak_job_memory_used: usize,+ }++ #[link(name = "kernel32")]+ extern "system" {+ fn CreateJobObjectW(attributes: *mut c_void, name: *const u16) -> Handle;+ fn SetInformationJobObject(job: Handle, class: i32, info: *mut c_void, len: u32) -> i32;+ fn AssignProcessToJobObject(job: Handle, process: Handle) -> i32;+ fn GetCurrentProcess() -> Handle;+ fn CloseHandle(handle: Handle) -> i32;+ }++ pub struct Job(Handle);++ // The handle is a plain kernel object handle, usable from any thread.+ unsafe impl Send for Job {}+ unsafe impl Sync for Job {}++ impl Job {+ /// A new job that ends all of its processes when its last handle closes. None if the system refuses.+ pub fn kill_on_close() -> Option<Job> {+ unsafe {+ let handle = CreateJobObjectW(std::ptr::null_mut(), std::ptr::null());+ if handle.is_null() {+ return None;+ }+ let mut info = ExtendedLimits::default();+ info.basic.limit_flags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;+ let ok = SetInformationJobObject(+ handle,+ JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,+ &mut info as *mut ExtendedLimits as *mut c_void,+ std::mem::size_of::<ExtendedLimits>() as u32,+ );+ if ok == 0 {+ CloseHandle(handle);+ return None;+ }+ Some(Job(handle))+ }+ }++ /// Put a process (by handle) in the job; everything it starts later joins too.+ pub fn assign_raw(&self, process: *mut c_void) -> bool {+ unsafe { AssignProcessToJobObject(self.0, process) != 0 }+ }++ /// Put this very process in the job, so the host and everything below it are contained.+ pub fn assign_current(&self) -> bool {+ self.assign_raw(unsafe { GetCurrentProcess() })+ }+ }++ impl Drop for Job {+ fn drop(&mut self) {+ unsafe {+ CloseHandle(self.0);+ }+ }+ }+}++/// Held for the life of the process. The handle is deliberately never closed by us: the system closes it when the+/// process ends, by any route, and that is the moment the job ends what is left in it.+#[cfg(windows)]+static APP_JOB: std::sync::OnceLock<job::Job> = std::sync::OnceLock::new();++/// Put this process (and so everything it starts) in a kill-on-close job. True if it is contained now.+fn contain_app() -> bool {+ #[cfg(windows)]+ {+ if let Some(job) = job::Job::kill_on_close() {+ if job.assign_current() {+ let _ = APP_JOB.set(job);+ return true;+ }+ }+ eprintln!("[strata] could not put the app in a job object; engines are stopped by the host and their owners instead");+ false+ }+ #[cfg(not(windows))]+ {+ false+ }+}+/// The running App Host, kept so it can be stopped on exit.struct HostProcess(Mutex<Option<Child>>);@@ -271,6 +407,8 @@ fn start_host(app: &tauri::AppHandle) -> Result<u16, String> {// for the same reason, so the monitor reports `none` instead of fabricated numbers..env("STRATA_PACKAGED", "1").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").stdin(Stdio::null()).stdout(Stdio::inherit()).stderr(Stdio::inherit());@@ -303,11 +441,15 @@ fn start_host(app: &tauri::AppHandle) -> Result<u16, String> {Ok(port)}-/// Stop the App Host.+/// How long the host gets to stop the engines this app started (drain, then end) before it is ended. The host's own+/// deadline is shorter; whatever is still running when the shell exits is ended by the job object / the owners.+const HOST_STOP_SECONDS: u64 = 60;++/// Stop the App Host, and with it the engines this app started.///-/// Only this process is signalled. The engine worker and any jobs belong to Strata Control and are-/// deliberately not touched here: quitting the window must not kill inference another client is-/// using.+/// 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`).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());@@ -318,7 +460,7 @@ fn stop_host(app: &tauri::AppHandle) {// 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(80);+ let deadline = Instant::now() + Duration::from_secs(HOST_STOP_SECONDS);while Instant::now() < deadline {if let Ok(Some(_)) = child.try_wait() {return;@@ -584,12 +726,21 @@ fn main() {// at the screen — the lesson from the Electron attempt, where a packaged app that never started// its host hung with no output at all.let args: Vec<String> = std::env::args().collect();+ contain_app();if let Some(path) = self_test_path(&args) {let code = run_self_test(&path);std::process::exit(code);}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| {+ if let Some(window) = app.get_webview_window("main") {+ let _ = window.unminimize();+ let _ = window.show();+ let _ = window.set_focus();+ }+ })).plugin(tauri_plugin_shell::init()).manage(HostProcess(Mutex::new(None))).manage(HostPort(Mutex::new(None)))@@ -674,6 +825,32 @@ mod tests {let _ = std::fs::remove_dir_all(&res);}+ #[cfg(windows)]+ #[test]+ fn a_process_in_the_job_ends_when_the_job_is_closed() {+ use std::os::windows::io::AsRawHandle;+ let job = job::Job::kill_on_close().expect("a job object");+ let mut child = Command::new("ping").args(["-n", "120", "127.0.0.1"]).stdout(Stdio::null()).spawn().expect("ping");+ assert!(job.assign_raw(child.as_raw_handle() as *mut std::ffi::c_void), "the child joins the job");+ assert!(child.try_wait().unwrap().is_none(), "it runs while the job is open");+ drop(job); // what the system does when the app ends, by any route+ let deadline = Instant::now() + Duration::from_secs(10);+ while child.try_wait().unwrap().is_none() && Instant::now() < deadline {+ std::thread::sleep(Duration::from_millis(50));+ }+ let ended = child.try_wait().unwrap().is_some();+ if !ended {+ let _ = child.kill();+ }+ assert!(ended, "closing the job must end its processes");+ }++ #[test]+ fn the_shells_wait_for_the_host_exceeds_the_hosts_own_deadline_and_stays_bounded() {+ // the host ends itself after 45 s (server/index.mjs); the shell must wait longer than that, but not for ever+ assert!(HOST_STOP_SECONDS > 45 && HOST_STOP_SECONDS <= 90);+ }+#[test]fn shutdown_tokens_are_long_and_different() {let (a, b) = (random_token(), random_token());diff --git a/apps/host/server/control-runtime.mjs b/apps/host/server/control-runtime.mjsindex dc8a7a177..c266ed66f 100644--- a/apps/host/server/control-runtime.mjs+++ b/apps/host/server/control-runtime.mjs@@ -124,11 +124,18 @@ export function createControl({ control = findControl(), env = process.env, runif (result.code !== 0) throw failure(result, 'The model profile could not be saved.');return result.json;},- async start(name, { waitSeconds = 300 } = {}) {- const result = await call(['runtime', 'start', '--profile', name, '--wait', String(waitSeconds), '--output', 'json'], { timeoutMs: (waitSeconds + 60) * 1000 });+ // The app owns the engines it starts: `--die-with-pid` makes the owner stop its engine (drained) when this host is+ // gone, however the host ended (a crash, a kill, the shell's death). A Terminal's `runtime start` has no such tie.+ async start(name, { waitSeconds = 300, dieWithPid = process.pid, drainSeconds = 15 } = {}) {+ const result = await call(['runtime', 'start', '--profile', name, '--wait', String(waitSeconds), '--shutdown-timeout', String(drainSeconds), ...(dieWithPid ? ['--die-with-pid', String(dieWithPid)] : []), '--output', 'json'], { timeoutMs: (waitSeconds + 60) * 1000 });if (result.code !== 0 || !result.json?.ok) throw failure(result, 'The engine did not start.');return result.json;},+ /** End servers and engines Strata started whose owner is gone (each is re-checked by PID, start time and command line). */+ async cleanup() {+ const result = await call(['runtime', 'cleanup', '--output', 'json'], { timeoutMs: 120_000 });+ return result.json ?? { ok: false, error: result.stderr };+ },async status(name) {const result = await call(['runtime', 'status', '--profile', name, '--output', 'json'], { timeoutMs: 30_000 });return result.json ?? { ok: false, state: 'unknown', error: result.stderr };diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjsindex ffcda5d1d..ebd1313e7 100644--- a/apps/host/server/index.mjs+++ b/apps/host/server/index.mjs@@ -1641,18 +1641,30 @@ async function staticFile(req, res, path) {server.listen(PORT, HOST, () => {if (process.send) process.send({ type: 'strata-ready', port: PORT });+ // Engines a lost owner left behind (an earlier crash, an older version): ended after a PID + start time + command-line check.+ if (control && process.env.STRATA_PACKAGED === '1') control.cleanup().catch(() => {});});let stopping=false;const shutdown = async () => {if(stopping)return;stopping=true;clearInterval(taskTimer);tasks.close();- const timeout=setTimeout(()=>process.exit(0),control?75000:10000);timeout.unref(); // stopping an engine through Control can take a while+ const timeout=setTimeout(()=>process.exit(0),control?45000:10000);timeout.unref(); // stopping an engine through Control: drained (15 s), then ended; the shell's deadline is longerserver.close();server.closeAllConnections?.();await Promise.allSettled([localShare.stop(),cloudflare.stop(),native.close(),agent.close()]);process.exit(0);};-process.on('SIGINT', shutdown);-process.on('SIGTERM', shutdown);+// Every ordinary way of being told to stop takes the clean path: Ctrl+C, kill, the terminal closing (SIGHUP), Ctrl+Break.+for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGBREAK']) { try { process.on(signal, shutdown); } catch { /* not on this platform */ } }+// Started by the desktop shell: when the shell is gone (killed, crashed, logged off) stop what this app started and leave.+// POSIX re-parents us (ppid changes); Windows keeps the old ppid, so the pid is probed (signal 0 never signals).+if (process.env.STRATA_EXIT_WITH_PARENT === '1') {+ const parent = process.ppid;+ const gone = () => {+ if (process.ppid !== parent) return true;+ try { process.kill(parent, 0); return false; } catch (e) { return e.code === 'ESRCH'; }+ };+ setInterval(() => { if (gone()) void shutdown(); }, 1000).unref();+}export { server, VARIANTS };diff --git a/apps/host/tests/host-lifecycle.test.mjs b/apps/host/tests/host-lifecycle.test.mjsnew file mode 100644index 000000000..ca333a619--- /dev/null+++ b/apps/host/tests/host-lifecycle.test.mjs@@ -0,0 +1,97 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createServer } from 'node:net';+import { fileURLToPath } from 'node:url';+import { createControl } from '../server/control-runtime.mjs';++/**+ * The host's side of "closing always ends what this app started":+ * - it asks Control to tie each engine's life to the host's own (--die-with-pid),+ * - it takes every ordinary stop signal down the clean path,+ * - started by the desktop shell, it leaves when the shell is gone (a kill or a crash is not announced).+ * The owner runtime's side (the engine ends when the host's pid is gone) is tested in tests/terminal.+ */+const root = fileURLToPath(new URL('..', import.meta.url));+const delay = ms => new Promise(r => setTimeout(r, ms));+async function freePort() { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }+const alive = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };+async function until(fn, ms = 15000) { const end = Date.now() + ms; while (Date.now() < end) { if (await fn()) return true; await delay(100); } return false; }++test('start asks Control to end the engine with this host; cleanup asks it to end what a lost owner left', async () => {+ const seen = [];+ const control = createControl({+ control: { dir: '/c', python: '/p', cli: '/c/strata.py', bundle: { version: '9' } },+ run: async args => { seen.push(args.join(' ')); return { code: 0, json: { ok: true }, text: '', stderr: '' }; },+ });+ await control.start('app-1');+ await control.start('app-2', { dieWithPid: 4242 });+ await control.start('app-3', { dieWithPid: null });+ await control.cleanup();+ assert.deepEqual(seen, [+ `runtime start --profile app-1 --wait 300 --shutdown-timeout 15 --die-with-pid ${process.pid} --output json`,+ 'runtime start --profile app-2 --wait 300 --shutdown-timeout 15 --die-with-pid 4242 --output json',+ 'runtime start --profile app-3 --wait 300 --shutdown-timeout 15 --output json',+ 'runtime cleanup --output json',+ ]);+});++async function startHost(extraEnv = {}, spawnOptions = {}) {+ const home = await mkdtemp(join(tmpdir(), 'strata-host-life-'));+ const port = await freePort();+ const host = spawn(process.execPath, ['server/index.mjs'], {+ cwd: root, stdio: 'ignore', ...spawnOptions,+ env: { ...process.env, STRATA_HOME: home, STRATA_MODELS_DIR: join(home, 'models'), STRATA_PORT: String(port), STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()), STRATA_REAL_ENGINE: '1', ...extraEnv },+ });+ let up = false;+ for (let i = 0; i < 120 && !up; i++) { try { up = (await fetch(`http://127.0.0.1:${port}/api/health`)).ok; } catch { await delay(100); } }+ assert.ok(up, 'host started');+ return { host, port, home, done: () => rm(home, { recursive: true, force: true }) };+}++test('SIGTERM and SIGHUP end the host through the clean shutdown (exit 0)', { skip: process.platform === 'win32' && 'Windows has no SIGTERM/SIGHUP to send' }, async t => {+ for (const signal of ['SIGTERM', 'SIGHUP']) {+ const h = await startHost();+ t.after(h.done);+ const exited = new Promise(r => h.host.once('exit', (code, sig) => r({ code, sig })));+ h.host.kill(signal);+ const result = await Promise.race([exited, delay(20000).then(() => 'timeout')]);+ assert.notEqual(result, 'timeout', `${signal}: the host did not end`);+ assert.deepEqual(result, { code: 0, sig: null }, signal);+ }+});++test('Started by the shell (STRATA_EXIT_WITH_PARENT=1), the host leaves when its parent is killed', async t => {+ // a stand-in shell: it starts the host and then waits to be killed hard+ const home = await mkdtemp(join(tmpdir(), 'strata-host-parent-'));+ t.after(() => rm(home, { recursive: true, force: true }));+ const port = await freePort();+ const shell = spawn(process.execPath, ['-e', `+ const {spawn}=require('node:child_process');+ const h=spawn(process.execPath,['server/index.mjs'],{cwd:${JSON.stringify(root)},stdio:'ignore',env:{...process.env,STRATA_EXIT_WITH_PARENT:'1',STRATA_HOME:${JSON.stringify(home)},STRATA_MODELS_DIR:${JSON.stringify(join(home, 'models'))},STRATA_PORT:'${port}',STRATA_SHARE_PORT:'${await freePort()}',STRATA_TUNNEL_PORT:'${await freePort()}',STRATA_REAL_ENGINE:'1'}});+ console.log(h.pid);+ setInterval(()=>{},1000);+ `], { cwd: root, stdio: ['ignore', 'pipe', 'inherit'] });+ const hostPid = await new Promise(r => shell.stdout.once('data', c => r(Number(String(c).trim()))));+ t.after(() => { try { process.kill(hostPid, 'SIGKILL'); } catch { /* gone */ } shell.kill('SIGKILL'); });+ let up = false;+ for (let i = 0; i < 120 && !up; i++) { try { up = (await fetch(`http://127.0.0.1:${port}/api/health`)).ok; } catch { await delay(100); } }+ assert.ok(up, 'host started');+ assert.ok(alive(hostPid));+ shell.kill('SIGKILL'); // TerminateProcess on Windows: nothing is announced+ assert.ok(await until(() => !alive(hostPid), 20000), 'the host outlived its killed shell');+ let reachable = true;+ try { await fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(1500) }); } catch { reachable = false; }+ assert.equal(reachable, false, 'the port is free again');+});++test('Without STRATA_EXIT_WITH_PARENT a host started from a source checkout does not follow its parent', async t => {+ const h = await startHost();+ t.after(h.done);+ t.after(() => h.host.kill('SIGKILL'));+ await delay(2500);+ assert.equal(alive(h.host.pid), true);+});diff --git a/apps/host/tests/packaged-control.test.mjs b/apps/host/tests/packaged-control.test.mjsindex ed357ad74..9f5029f1b 100644--- a/apps/host/tests/packaged-control.test.mjs+++ b/apps/host/tests/packaged-control.test.mjs@@ -205,7 +205,7 @@ test('createControl asks the CLI for the engine, models and runtime and reads th'models list --installed --install-dir D:\\Strata --output json','profile list --output json','profile create app-1 --from-config C:\\x.json --output json',- 'runtime start --profile app-1 --wait 300 --output json',+ `runtime start --profile app-1 --wait 300 --shutdown-timeout 15 --die-with-pid ${process.pid} --output json`,'runtime stop --profile app-1 --wait 120 --output json',]);assert.equal(createControl({ control: null }), null);