Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(release): backport #9148 and #9146 to v0.8.5 (update cleanup, Windows unit tests) (#9152)

James Dam8dc572ee2abf
diff --git a/.github/workflows/jan-linter-and-test.yml b/.github/workflows/jan-linter-and-test.yml
index 5a06231c7..b632c3727 100644
--- a/.github/workflows/jan-linter-and-test.yml
+++ b/.github/workflows/jan-linter-and-test.yml
@@ -261,6 +261,14 @@ jobs:
sudo apt update
sudo apt install -y libglib2.0-dev libatk1.0-dev libpango1.0-dev libgtk-3-dev libsoup-3.0-dev libwebkit2gtk-4.1-dev librsvg2-dev libfuse2 webkit2gtk-driver
+ # The agent-tools unit tests run the shell tool inside its Linux sandbox,
+ # bubblewrap, which needs unprivileged user namespaces; Ubuntu 24.04's
+ # AppArmor default refuses those.
+ - name: Install the shell sandbox
+ run: |
+ sudo apt install -y bubblewrap
+ sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
+
- name: 'Cleanup cache'
continue-on-error: true
run: |
diff --git a/Makefile b/Makefile
index 2d5eb28bf..d7d32a983 100644
--- a/Makefile
+++ b/Makefile
@@ -154,7 +154,9 @@ test-rust: stub-resources
cargo test --locked --manifest-path src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml
cargo test --locked --manifest-path src-tauri/utils/Cargo.toml
# No --locked: this crate gitignores its Cargo.lock, as rust-check.yml assumes.
- cargo test --manifest-path src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml --no-default-features --test sandbox_spawn
+ # The unit tests that run the shell for real are ignored on Windows, where
+ # sandbox_spawn covers them (it needs its own main to host the helper re-exec).
+ cargo test --manifest-path src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml --no-default-features --lib --test sandbox_spawn
# protocol/schema.json is committed, and core::cli::protocol_schema fails when it
# no longer matches the types that define the channel. This is the fix for that
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index cc0ce8d44..893effbdb 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -60,6 +60,7 @@ dependencies = [
"sha2",
"sqlx",
"syntect",
+ "sysinfo",
"tar",
"tauri",
"tauri-build",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 3289170d3..9bda35be9 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -294,6 +294,9 @@ reqwest13 = { package = "reqwest", version = "0.13", default-features = false, f
tauri-plugin-updater = { version = "2", optional = true }
once_cell = "1.18"
tauri-plugin-single-instance = { version = "2", features = ["deep-link"], optional = true }
+# Process table for the startup sweep of engines orphaned by an in-place update
+# (core/system/orphans.rs). Same version as the hardware and mlx plugins.
+sysinfo = "0.34.2"
[target.'cfg(any(target_os = "android", target_os = "ios"))'.dependencies]
reqwest = { version = "0.12", features = ["json", "blocking", "stream", "rustls-tls"], default-features = false }
diff --git a/src-tauri/jan-cli/Cargo.lock b/src-tauri/jan-cli/Cargo.lock
index 678895105..985ccc735 100644
--- a/src-tauri/jan-cli/Cargo.lock
+++ b/src-tauri/jan-cli/Cargo.lock
@@ -56,6 +56,7 @@ dependencies = [
"serde_yaml",
"sha2",
"syntect",
+ "sysinfo",
"tar",
"tauri-plugin-agent-tools",
"tauri-plugin-vector-db",
@@ -2285,7 +2286,7 @@ dependencies = [
"js-sys",
"log",
"wasm-bindgen",
- "windows-core",
+ "windows-core 0.62.2",
]
[[package]]
@@ -3104,6 +3105,15 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "ntapi"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae"
+dependencies = [
+ "winapi",
+]
+
[[package]]
name = "num"
version = "0.4.3"
@@ -3850,7 +3860,7 @@ dependencies = [
"nix 0.31.3",
"tokio",
"tracing",
- "windows",
+ "windows 0.62.2",
]
[[package]]
@@ -5147,6 +5157,19 @@ dependencies = [
"walkdir",
]
+[[package]]
+name = "sysinfo"
+version = "0.34.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4b93974b3d3aeaa036504b8eefd4c039dced109171c1ae973f1dc63b2c7e4b2"
+dependencies = [
+ "libc",
+ "memchr",
+ "ntapi",
+ "objc2-core-foundation",
+ "windows 0.57.0",
+]
+
[[package]]
name = "system-configuration"
version = "0.7.0"
@@ -6334,6 +6357,16 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+[[package]]
+name = "windows"
+version = "0.57.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12342cb4d8e3b046f3d80effd474a7a02447231330ef77d71daa6fbc40681143"
+dependencies = [
+ "windows-core 0.57.0",
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows"
version = "0.62.2"
@@ -6341,7 +6374,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections",
- "windows-core",
+ "windows-core 0.62.2",
"windows-future",
"windows-numerics",
]
@@ -6352,7 +6385,19 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
- "windows-core",
+ "windows-core 0.62.2",
+]
+
+[[package]]
+name = "windows-core"
+version = "0.57.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2ed2439a290666cd67ecce2b0ffaad89c2a56b976b736e6ece670297897832d"
+dependencies = [
+ "windows-implement 0.57.0",
+ "windows-interface 0.57.0",
+ "windows-result 0.1.2",
+ "windows-targets 0.52.6",
]
[[package]]
@@ -6361,10 +6406,10 @@ version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
- "windows-implement",
- "windows-interface",
+ "windows-implement 0.60.2",
+ "windows-interface 0.59.3",
"windows-link",
- "windows-result",
+ "windows-result 0.4.1",
"windows-strings",
]
@@ -6374,11 +6419,22 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
- "windows-core",
+ "windows-core 0.62.2",
"windows-link",
"windows-threading",
]
+[[package]]
+name = "windows-implement"
+version = "0.57.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9107ddc059d5b6fbfbffdfa7a7fe3e22a226def0b2608f72e9d552763d3e1ad7"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "windows-implement"
version = "0.60.2"
@@ -6390,6 +6446,17 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "windows-interface"
+version = "0.57.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29bee4b38ea3cde66011baa44dba677c432a78593e202392d1e9070cf2a7fca7"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "windows-interface"
version = "0.59.3"
@@ -6413,7 +6480,7 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
- "windows-core",
+ "windows-core 0.62.2",
"windows-link",
]
@@ -6424,10 +6491,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
dependencies = [
"windows-link",
- "windows-result",
+ "windows-result 0.4.1",
"windows-strings",
]
+[[package]]
+name = "windows-result"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows-result"
version = "0.4.1"
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
index 7098cc049..c92398cb9 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
@@ -1424,6 +1424,10 @@ mod tests {
/// the OS can confine it and is refused when it cannot. Asserting both arms
/// keeps the fallback honest on hosts (and CI images) with no backend.
#[tokio::test]
+ #[cfg_attr(
+ windows,
+ ignore = "re-execs the test binary as the AppContainer helper; covered by tests/sandbox_spawn.rs"
+ )]
async fn bash_runs_only_when_the_sandbox_can_enforce() {
let data = unique_data_folder();
let df = data.to_string_lossy().to_string();
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
index 0faf3111f..3dc916f15 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
@@ -2402,6 +2402,8 @@ mod tests {
async fn write_reports_resolved_path_when_it_escapes_the_project() {
let root = unique_root();
let outside = root.parent().unwrap().join("jan_escape_probe.txt");
+ // A probe left by an aborted run would turn this into a "No change" write.
+ let _ = std::fs::remove_file(&outside);
let out = execute_builtin(
lookup("write").unwrap(),
&json!({"path": "../jan_escape_probe.txt", "content": "x"}),
@@ -2409,11 +2411,24 @@ mod tests {
)
.await;
assert!(outside.exists(), "precondition: the write escapes the root");
+ assert!(!out.contains(".."), "must not echo the raw path: {out}");
+ // Compare the named path by what it resolves to, not by spelling: on
+ // Windows the message uses `/` separators, and the temp dir may be
+ // spelled with an 8.3 short name on one side and not the other.
+ let shown = out
+ .strip_prefix("Created ")
+ .and_then(|rest| rest.rsplit_once(" ("))
+ .map(|(path, _)| path)
+ .unwrap_or_else(|| panic!("unexpected message shape: {out}"));
assert!(
- out.contains(outside.to_str().unwrap()),
+ Path::new(shown).is_absolute(),
+ "an escape is named by its absolute path, got: {out}"
+ );
+ assert_eq!(
+ std::fs::canonicalize(shown).ok(),
+ std::fs::canonicalize(&outside).ok(),
"must name the real destination, got: {out}"
);
- assert!(!out.contains(".."), "must not echo the raw path: {out}");
let _ = std::fs::remove_file(&outside);
let _ = std::fs::remove_dir_all(&root);
}
@@ -3171,6 +3186,10 @@ mod tests {
/// output lands there when the command finishes, so the agent reads that file
/// to collect the result instead of a second tool call.
#[tokio::test]
+ #[cfg_attr(
+ windows,
+ ignore = "re-execs the test binary as the AppContainer helper; covered by tests/sandbox_spawn.rs"
+ )]
async fn backgrounded_output_lands_in_the_reported_file() {
let root = unique_root();
let started = execute_builtin(
@@ -3226,6 +3245,10 @@ mod tests {
}
#[tokio::test]
+ #[cfg_attr(
+ windows,
+ ignore = "re-execs the test binary as the AppContainer helper; covered by tests/sandbox_spawn.rs"
+ )]
async fn bash_nonzero_exit_is_not_error() {
let root = unique_root();
let out = execute_builtin(
@@ -3241,6 +3264,10 @@ mod tests {
}
#[tokio::test]
+ #[cfg_attr(
+ windows,
+ ignore = "re-execs the test binary as the AppContainer helper; covered by tests/sandbox_spawn.rs"
+ )]
async fn bash_success_emits_exit_0_marker() {
let root = unique_root();
let out = execute_builtin(
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs
index d3284393f..c1de5dc66 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs
@@ -1085,11 +1085,13 @@ mod shell_kind_tests {
// Relative paths resolve in the working directory it was started in.
let (code, stdout, _) = run("(Convert-Path .).TrimEnd('/', '\\')").await;
assert_eq!(code, Some(0));
+ // Compared resolved: PowerShell reports the physical path, so on macOS
+ // the `/var` temp dir comes back as `/private/var`.
let tmp = std::env::temp_dir();
assert_eq!(
- stdout,
- tmp.to_string_lossy().trim_end_matches(['/', '\\']),
- "starts in the working directory"
+ std::fs::canonicalize(&stdout).ok(),
+ std::fs::canonicalize(&tmp).ok(),
+ "starts in the working directory: {stdout}"
);
}
}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs
index 2a25f9fdc..dd9f98557 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs
@@ -593,11 +593,16 @@ mod tests {
file.to_string_lossy()
);
}
- // Outside the scratch the path is untouched either way.
+ // Outside the scratch the path is only lexically normalized, which on
+ // Windows also spells it with the native separator.
let other = PathBuf::from("/elsewhere/out.txt");
assert_eq!(
scratch_display_path(Some(&scratch), &other),
- other.to_string_lossy()
+ if cfg!(windows) {
+ r"\elsewhere\out.txt"
+ } else {
+ "/elsewhere/out.txt"
+ }
);
}
@@ -666,7 +671,10 @@ mod tests {
}
/// `/tmpx` and `/tmp-archive` are not descendants of `/tmp` and must not be
- /// silently redirected into the scratch.
+ /// silently redirected into the scratch. Unix only: the remap exists only
+ /// where a sandbox mounts the scratch over `/tmp`, and on Windows `/tmp` is
+ /// not an absolute path at all.
+ #[cfg(unix)]
#[test]
fn tmp_lookalikes_are_not_remapped() {
assert_eq!(tmp_relative("/tmp"), Some(String::new()));
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rs b/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rs
index 24c1fa4a1..a012c8d20 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rs
@@ -9,11 +9,15 @@
//! `harness = false` because the backend re-execs the running binary as its
//! helper: under libtest that re-exec would run the test suite again instead of
//! the spawn, so `main` hands control to the helper before anything else.
+//! For the same reason, the lib's unit tests that run the `shell` tool for real
+//! are ignored on Windows, and their assertions live in `shell_tool` instead.
fn main() {
tauri_plugin_agent_tools::run_sandbox_helper_if_requested();
#[cfg(windows)]
windows::run();
+ #[cfg(windows)]
+ shell_tool::run();
#[cfg(not(windows))]
eprintln!("sandbox_spawn: AppContainer only, nothing to run on this platform");
}
@@ -147,3 +151,95 @@ mod windows {
(out.status.code(), text)
}
}
+
+/// The `shell` tool end to end on Windows: the gate, the sandbox wrap, the spawn
+/// and the result formatting. Mirrors the lib unit tests that are ignored on
+/// Windows because they would re-exec libtest as the helper.
+#[cfg(windows)]
+mod shell_tool {
+ use serde_json::json;
+ use std::path::{Path, PathBuf};
+ use tauri_plugin_agent_tools::tools::{handlers, jail, lookup, ToolContext};
+
+ pub fn run() {
+ let base = std::env::temp_dir().join(format!("jan_shell_tool_{}", std::process::id()));
+ let ws = base.join("ws");
+ std::fs::create_dir_all(&ws).expect("create workspace");
+ // A store under the test's own dir, so nothing lands in the real Jan home.
+ let store = tauri_plugin_agent_tools::workspace::project_store_in(&base.join("home"), &ws);
+ let rt = tokio::runtime::Runtime::new().expect("runtime");
+ let shell = |command: &str, extra: serde_json::Value| {
+ let mut args = json!({ "command": command });
+ if let (Some(args), Some(extra)) = (args.as_object_mut(), extra.as_object()) {
+ args.extend(extra.clone());
+ }
+ let ctx = ToolContext::new(&ws, &store, &[]);
+ rt.block_on(handlers::execute_builtin(
+ lookup("shell").unwrap(),
+ &args,
+ &ctx,
+ ))
+ .0
+ };
+
+ // commands::tests::bash_runs_only_when_the_sandbox_can_enforce
+ let out = shell("echo hi", json!({}));
+ if jail::backend().enforces() {
+ assert!(
+ !out.starts_with("ERROR"),
+ "sandboxed shell should run: {out}"
+ );
+ assert!(out.contains("hi"), "got: {out}");
+ } else {
+ assert!(
+ out.contains("no OS sandbox"),
+ "the model must be told why: {out}"
+ );
+ }
+
+ // handlers::tests::bash_success_emits_exit_0_marker
+ let out = shell("echo done", json!({}));
+ assert!(!out.starts_with("ERROR"), "unexpected: {out}");
+ assert!(
+ out.contains("done") && out.contains("[exit 0]"),
+ "unexpected: {out}"
+ );
+
+ // handlers::tests::bash_nonzero_exit_is_not_error
+ let out = shell("echo hi; exit 3", json!({}));
+ assert!(!out.starts_with("ERROR"), "unexpected: {out}");
+ assert!(
+ out.contains("hi") && out.contains("[exit 3]"),
+ "unexpected: {out}"
+ );
+
+ // handlers::tests::backgrounded_output_lands_in_the_reported_file
+ let started = shell("sleep 0.2; echo done", json!({ "timeout": 0 }));
+ let path = started
+ .split("written to ")
+ .nth(1)
+ .and_then(|rest| rest.split(" once it finishes").next())
+ .map(str::trim)
+ .map(PathBuf::from)
+ .unwrap_or_else(|| panic!("notice names the output file: {started}"));
+ let body = wait_for(&path).expect("output file must appear after the command finishes");
+ assert!(body.contains("done"), "unexpected: {body}");
+ assert!(body.contains("[exit 0]"), "carries the exit marker: {body}");
+ let _ = std::fs::remove_file(&path);
+
+ eprintln!("sandbox_spawn: shell tool ok");
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ /// The backgrounded output file appears only once the command has finished
+ /// (atomic rename), so its existence is the completion signal.
+ fn wait_for(path: &Path) -> Option<String> {
+ for _ in 0..100 {
+ if path.exists() {
+ return std::fs::read_to_string(path).ok();
+ }
+ std::thread::sleep(std::time::Duration::from_millis(100));
+ }
+ None
+ }
+}
diff --git a/src-tauri/src/core/system/mod.rs b/src-tauri/src/core/system/mod.rs
index 82b6da3c0..e76eff015 100644
--- a/src-tauri/src/core/system/mod.rs
+++ b/src-tauri/src/core/system/mod.rs
@@ -1 +1,5 @@
pub mod commands;
+pub mod shutdown;
+// Process-table sweep; desktop-only, `sysinfo` is not a mobile dependency.
+#[cfg(not(any(target_os = "android", target_os = "ios")))]
+pub mod orphans;
diff --git a/src-tauri/src/core/system/orphans.rs b/src-tauri/src/core/system/orphans.rs
new file mode 100644
index 000000000..bcd2b3279
--- /dev/null
+++ b/src-tauri/src/core/system/orphans.rs
@@ -0,0 +1,408 @@
+//! Startup sweep for engines that an older Jan left running across an update.
+//!
+//! Up to 0.8.4 the engine was a `llama-server` router child of the desktop app.
+//! The in-app updater leaves the old app without running its exit cleanup (see
+//! `shutdown`), and 0.8.4 has shipped, so that version cannot be fixed. Every
+//! user who updates from it ends up with its router still running, holding RAM
+//! and VRAM and, on Linux, pinning the old AppImage mount. On Windows it also
+//! survives uninstalling Jan, because the binary lives in the data folder.
+//! The only place left to clean it up is the new version's startup.
+//!
+//! A process is swept only when all of these hold:
+//! - it is `llama-server`,
+//! - it was started with `--models-preset <data folder>/llamacpp/router.preset.ini`,
+//! the preset file Jan writes, so it belongs to this data folder,
+//! - its parent is gone or is not a Jan process, so a Jan that is still running
+//! (another instance, or this one) keeps its engine. That includes a detached
+//! `jan serve` from 0.8.4, which keeps its router as a live child.
+//!
+//! Its descendants, the per-model children the router spawns, go with it. A
+//! process counts as a descendant only if it started no earlier than the parent
+//! it names, because Windows never reparents and reuses pids.
+
+use std::collections::{HashMap, HashSet};
+use std::path::Path;
+
+use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};
+
+const ROUTER_BINARY: &str = "llama-server";
+const ROUTER_PRESET_FILE: &str = "router.preset.ini";
+const PRESET_FLAG: &str = "--models-preset";
+
+/// The slice of a process the matcher needs, so it can be tested without
+/// spawning anything.
+#[derive(Debug)]
+pub struct ProcInfo {
+ pub pid: u32,
+ pub parent: Option<u32>,
+ pub name: String,
+ pub cmd: Vec<String>,
+ /// Seconds since the epoch; 0 when the OS would not say.
+ pub start_time: u64,
+}
+
+fn normalize(path: &str) -> String {
+ path.replace('\\', "/").to_ascii_lowercase()
+}
+
+fn is_router_binary(name: &str) -> bool {
+ let name = name.to_ascii_lowercase();
+ let stem = name.strip_suffix(".exe").unwrap_or(&name);
+ stem == ROUTER_BINARY
+}
+
+/// The value of `--models-preset`, in either `--flag value` or `--flag=value`
+/// form.
+fn preset_arg(cmd: &[String]) -> Option<&str> {
+ let mut args = cmd.iter();
+ while let Some(arg) = args.next() {
+ if arg == PRESET_FLAG {
+ return args.next().map(String::as_str);
+ }
+ if let Some(value) = arg
+ .strip_prefix(PRESET_FLAG)
+ .and_then(|r| r.strip_prefix('='))
+ {
+ return Some(value);
+ }
+ }
+ None
+}
+
+/// Whether `proc` is a router started from Jan's preset under `llamacpp_dir`.
+fn is_jan_router(proc: &ProcInfo, llamacpp_dir: &str) -> bool {
+ if !is_router_binary(&proc.name) {
+ return false;
+ }
+ let Some(preset) = preset_arg(&proc.cmd) else {
+ return false;
+ };
+ let preset = normalize(preset);
+ preset.rsplit('/').next() == Some(ROUTER_PRESET_FILE)
+ && preset.starts_with(&format!("{llamacpp_dir}/"))
+}
+
+/// A Jan process, judged by name: `Jan`, `jan`, `Jan.exe`, `Jan-Desktop.exe`.
+fn is_jan(name: &str) -> bool {
+ name.to_ascii_lowercase().contains("jan")
+}
+
+/// Orphaned when the parent no longer exists, was adopted by init (pid 1), or is
+/// something other than Jan. The last case covers a systemd user session
+/// adopting the process on Linux, where the new parent is not pid 1.
+fn is_orphaned(proc: &ProcInfo, by_pid: &HashMap<u32, &ProcInfo>) -> bool {
+ match proc.parent {
+ None | Some(1) => true,
+ Some(parent) => by_pid.get(&parent).is_none_or(|p| !is_jan(&p.name)),
+ }
+}
+
+/// `root` and everything below it, each process listed before its children.
+///
+/// Each pid is listed once. Windows never reparents and reuses pids, so a dead
+/// parent's pid can be taken by one of its own later children, which makes the
+/// parent links a cycle.
+fn with_descendants(root: u32, children: &HashMap<u32, Vec<u32>>) -> Vec<u32> {
+ let mut order = vec![root];
+ let mut next = 0;
+ while let Some(&pid) = order.get(next) {
+ for &child in children.get(&pid).into_iter().flatten() {
+ if !order.contains(&child) {
+ order.push(child);
+ }
+ }
+ next += 1;
+ }
+ order
+}
+
+/// Pids to kill, children before their router.
+pub fn orphaned_engine_pids(procs: &[ProcInfo], data_folder: &Path) -> Vec<u32> {
+ let llamacpp_dir = normalize(&data_folder.join("llamacpp").to_string_lossy());
+ let llamacpp_dir = llamacpp_dir.trim_end_matches('/');
+ let by_pid: HashMap<u32, &ProcInfo> = procs.iter().map(|p| (p.pid, p)).collect();
+
+ let mut children: HashMap<u32, Vec<u32>> = HashMap::new();
+ for p in procs {
+ let Some(parent_pid) = p.parent else {
+ continue;
+ };
+ // A child cannot be older than its parent. Windows never reparents and
+ // reuses pids, so a live process can name a long-dead parent whose pid
+ // a router has since taken; without this check it would be swept as
+ // that router's child. An unknown start time (0) is left alone.
+ let started_after_parent = by_pid
+ .get(&parent_pid)
+ .is_some_and(|parent| p.start_time >= parent.start_time);
+ if started_after_parent {
+ children.entry(parent_pid).or_default().push(p.pid);
+ }
+ }
+
+ let mut victims = Vec::new();
+ let mut seen = HashSet::new();
+ for router in procs
+ .iter()
+ .filter(|p| is_jan_router(p, llamacpp_dir) && is_orphaned(p, &by_pid))
+ {
+ // Reversed, so killing the router never leaves a child to be adopted.
+ for pid in with_descendants(router.pid, &children).into_iter().rev() {
+ if seen.insert(pid) {
+ victims.push(pid);
+ }
+ }
+ }
+ victims
+}
+
+/// Kills every engine an older Jan left behind. Returns how many processes were
+/// killed. Blocking: run it off the async runtime.
+pub fn sweep_orphaned_engines(data_folder: &Path) -> usize {
+ // A fresh install, or a user who never ran the llama.cpp engine, has
+ // nothing to sweep and should not pay for a process-table scan.
+ if !data_folder.join("llamacpp").is_dir() {
+ return 0;
+ }
+
+ let mut system = System::new();
+ system.refresh_processes_specifics(
+ ProcessesToUpdate::All,
+ true,
+ ProcessRefreshKind::nothing().with_cmd(UpdateKind::Always),
+ );
+ let procs: Vec<ProcInfo> = system
+ .processes()
+ .values()
+ .map(|p| ProcInfo {
+ pid: p.pid().as_u32(),
+ parent: p.parent().map(Pid::as_u32),
+ name: p.name().to_string_lossy().into_owned(),
+ start_time: p.start_time(),
+ cmd: p
+ .cmd()
+ .iter()
+ .map(|a| a.to_string_lossy().into_owned())
+ .collect(),
+ })
+ .collect();
+
+ let victims = orphaned_engine_pids(&procs, data_folder);
+ let mut killed = 0;
+ for pid in victims {
+ let Some(process) = system.process(Pid::from_u32(pid)) else {
+ continue;
+ };
+ log::warn!(
+ "Killing llama-server left running by a previous Jan: pid {pid}, parent {:?}",
+ process.parent()
+ );
+ if process.kill() {
+ killed += 1;
+ } else {
+ log::warn!("Could not kill orphaned llama-server pid {pid}");
+ }
+ }
+ killed
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::path::PathBuf;
+
+ const DATA: &str = "/home/u/.local/share/Jan/data";
+ const PRESET: &str = "/home/u/.local/share/Jan/data/llamacpp/router.preset.ini";
+
+ fn proc(pid: u32, parent: Option<u32>, name: &str, cmd: &[&str]) -> ProcInfo {
+ ProcInfo {
+ pid,
+ parent,
+ name: name.to_string(),
+ start_time: 0,
+ cmd: cmd.iter().map(|s| s.to_string()).collect(),
+ }
+ }
+
+ fn router(pid: u32, parent: Option<u32>) -> ProcInfo {
+ proc(
+ pid,
+ parent,
+ "llama-server",
+ &[
+ "/opt/llama-server",
+ "--models-preset",
+ PRESET,
+ "--port",
+ "1337",
+ ],
+ )
+ }
+
+ fn sweep(procs: &[ProcInfo]) -> Vec<u32> {
+ orphaned_engine_pids(procs, &PathBuf::from(DATA))
+ }
+
+ fn started_at(mut p: ProcInfo, start_time: u64) -> ProcInfo {
+ p.start_time = start_time;
+ p
+ }
+
+ #[test]
+ fn a_router_adopted_by_init_is_swept_with_its_children_first() {
+ let procs = [
+ router(200, Some(1)),
+ proc(
+ 201,
+ Some(200),
+ "llama-server",
+ &["llama-server", "-m", "a.gguf"],
+ ),
+ proc(
+ 202,
+ Some(200),
+ "llama-server",
+ &["llama-server", "-m", "b.gguf"],
+ ),
+ ];
+ let victims = sweep(&procs);
+ assert_eq!(victims.last(), Some(&200), "router goes last: {victims:?}");
+ assert_eq!(victims.len(), 3);
+ }
+
+ #[test]
+ fn a_router_whose_jan_is_still_running_is_left_alone() {
+ // `jan-cli` is the 0.8.4 CLI: `jan serve --detach` keeps its router as
+ // a live child, so a detached server is not an orphan.
+ for jan in ["Jan", "jan", "Jan.exe", "Jan-Desktop.exe", "jan-cli"] {
+ let procs = [proc(50, Some(1), jan, &[jan]), router(200, Some(50))];
+ assert!(sweep(&procs).is_empty(), "{jan} still owns its engine");
+ }
+ }
+
+ #[test]
+ fn a_router_adopted_by_a_systemd_user_session_is_swept() {
+ let procs = [
+ proc(900, Some(1), "systemd", &["systemd", "--user"]),
+ router(200, Some(900)),
+ ];
+ assert_eq!(sweep(&procs), vec![200]);
+ }
+
+ #[test]
+ fn a_router_whose_parent_exited_is_swept() {
+ // Windows does not reparent: the parent pid just stops existing.
+ assert_eq!(sweep(&[router(200, Some(4242))]), vec![200]);
+ assert_eq!(sweep(&[router(200, None)]), vec![200]);
+ }
+
+ #[test]
+ fn a_router_of_another_data_folder_is_left_alone() {
+ let other = proc(
+ 200,
+ Some(1),
+ "llama-server",
+ &[
+ "llama-server",
+ "--models-preset",
+ "/srv/other/llamacpp/router.preset.ini",
+ ],
+ );
+ assert!(sweep(&[other]).is_empty());
+ }
+
+ #[test]
+ fn a_llama_server_that_is_not_a_jan_router_is_left_alone() {
+ // The user's own llama-server, with or without a preset of their own.
+ let plain = proc(
+ 200,
+ Some(1),
+ "llama-server",
+ &["llama-server", "-m", "a.gguf"],
+ );
+ let own_preset = proc(
+ 201,
+ Some(1),
+ "llama-server",
+ &[
+ "llama-server",
+ "--models-preset",
+ "/home/u/presets/mine.ini",
+ ],
+ );
+ // A preset with the right name but outside the data folder's llamacpp dir.
+ let lookalike = proc(
+ 202,
+ Some(1),
+ "llama-server",
+ &[
+ "llama-server",
+ "--models-preset",
+ "/home/u/.local/share/Jan/data/llamacpp-other/router.preset.ini",
+ ],
+ );
+ assert!(sweep(&[plain, own_preset, lookalike]).is_empty());
+ }
+
+ #[test]
+ fn the_equals_form_and_windows_paths_match() {
+ let eq = proc(
+ 200,
+ Some(4242),
+ "llama-server.exe",
+ &[
+ "C:\\Users\\u\\AppData\\Roaming\\Jan\\data\\llamacpp\\backends\\b1\\llama-server.exe",
+ "--models-preset=C:\\Users\\u\\AppData\\Roaming\\Jan\\data\\llamacpp\\router.preset.ini",
+ ],
+ );
+ let victims = orphaned_engine_pids(
+ &[eq],
+ &PathBuf::from("C:\\Users\\u\\AppData\\Roaming\\Jan\\data"),
+ );
+ assert_eq!(victims, vec![200]);
+ }
+
+ #[test]
+ fn a_parent_cycle_from_pid_reuse_terminates() {
+ // Windows never reparents and reuses pids: the router's dead parent's
+ // pid was taken by one of the router's own later children.
+ let procs = [
+ started_at(router(200, Some(201)), 100),
+ started_at(
+ proc(
+ 201,
+ Some(200),
+ "llama-server",
+ &["llama-server", "-m", "a.gguf"],
+ ),
+ 200,
+ ),
+ ];
+ let mut victims = sweep(&procs);
+ victims.sort_unstable();
+ assert_eq!(victims, vec![200, 201]);
+ }
+
+ #[test]
+ fn a_live_process_naming_a_reused_parent_pid_is_not_a_child() {
+ // Windows never reparents: explorer.exe still names the pid of a
+ // process that died long ago, and an orphaned router has since been
+ // given that pid. Explorer started before the router, so it is not
+ // the router's child and must not be swept.
+ let procs = [
+ started_at(router(200, Some(1)), 500),
+ started_at(proc(300, Some(200), "explorer.exe", &["explorer.exe"]), 100),
+ started_at(
+ proc(
+ 301,
+ Some(200),
+ "llama-server",
+ &["llama-server", "-m", "a.gguf"],
+ ),
+ 600,
+ ),
+ ];
+ let mut victims = sweep(&procs);
+ victims.sort_unstable();
+ assert_eq!(victims, vec![200, 301]);
+ }
+}
diff --git a/src-tauri/src/core/system/shutdown.rs b/src-tauri/src/core/system/shutdown.rs
new file mode 100644
index 000000000..278066a77
--- /dev/null
+++ b/src-tauri/src/core/system/shutdown.rs
@@ -0,0 +1,105 @@
+//! Teardown work that must run before the process goes away.
+//!
+//! `RunEvent::Exit` is the normal home for it, but the in-app updater leaves
+//! the process without raising that event: `tauri-plugin-updater` calls
+//! `std::process::exit(0)` itself after launching the Windows installer, and
+//! `AppHandle::restart()` execs the new binary directly. Whatever only
+//! `RunEvent::Exit` cleaned up (the engine, MCP servers, agent shells, pending
+//! settings writes) was therefore left running or unwritten across an update.
+
+use tauri::{AppHandle, Manager, Runtime};
+
+use crate::core::mcp::helpers::background_cleanup_mcp_servers;
+use crate::core::state::AppState;
+
+/// How long MCP servers get to stop before we move on to the engine.
+const MCP_CLEANUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
+
+/// Stops everything the app started and flushes pending writes.
+///
+/// Safe to run more than once: each step is a no-op when there is nothing left
+/// to stop, so the `RunEvent::Exit` handler can follow it.
+pub async fn shutdown_cleanup<R: Runtime>(app: &AppHandle<R>) {
+ // Drain debounced settings writes so the next version, and the jan CLI,
+ // never read a stale settings.json.
+ crate::core::app::settings_store::flush_settings();
+
+ // No agent shell (or child it spawned) may outlive the app.
+ tauri_plugin_agent_tools::tools::proc::kill_all();
+
+ let state = app.state::<AppState>();
+ match tokio::time::timeout(
+ MCP_CLEANUP_TIMEOUT,
+ background_cleanup_mcp_servers(app, &state),
+ )
+ .await
+ {
+ Ok(_) => log::info!("MCP cleanup completed successfully"),
+ Err(_) => log::warn!(
+ "MCP cleanup timed out after {} seconds",
+ MCP_CLEANUP_TIMEOUT.as_secs()
+ ),
+ }
+
+ if let Err(e) = tauri_plugin_llamacpp::cleanup_llama_processes(app.clone()).await {
+ log::warn!("Failed to shut down the llama.cpp engine: {}", e);
+ } else {
+ log::info!("llama.cpp engine shut down successfully");
+ }
+
+ #[cfg(target_os = "macos")]
+ {
+ if let Err(e) = tauri_plugin_mlx::cleanup_mlx_processes(app.clone()).await {
+ log::warn!("Failed to cleanup MLX processes: {}", e);
+ } else {
+ log::info!("MLX processes cleaned up successfully");
+ }
+ }
+
+ log::info!("App cleanup completed");
+}
+
+/// Runs the exit-time teardown ahead of an in-app update.
+///
+/// The frontend calls this after the update has downloaded and verified, right
+/// before the installer runs, so a failed download leaves the running app
+/// untouched. On Windows `tauri-plugin-updater` exits the process as soon as
+/// the installer is launched and offers no hook this crate can register, so
+/// this has to happen before `install()`.
+///
+/// If the installer then fails the app keeps running, and `restart_mcp_servers`
+/// restarts whatever is in `mcp_active_servers`. The teardown empties that map,
+/// so it is put back here: the servers stay stopped, but a failed install can
+/// bring them back.
+#[tauri::command]
+pub async fn shutdown_for_update<R: Runtime>(app: AppHandle<R>) {
+ let state = app.state::<AppState>();
+ let active_servers = state.mcp_active_servers.lock().await.clone();
+
+ shutdown_cleanup(&app).await;
+
+ *state.mcp_active_servers.lock().await = active_servers;
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tauri::test::mock_app;
+
+ #[tokio::test(flavor = "multi_thread")]
+ async fn the_servers_that_were_active_survive_for_a_restart_after_a_failed_install() {
+ let app = mock_app();
+ app.manage(AppState::default());
+ let state = app.state::<AppState>();
+ state
+ .mcp_active_servers
+ .lock()
+ .await
+ .insert("files".to_string(), serde_json::json!({ "command": "npx" }));
+
+ shutdown_for_update(app.handle().clone()).await;
+
+ let active = state.mcp_active_servers.lock().await;
+ assert!(active.contains_key("files"), "{active:?}");
+ }
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 49c5ee8a2..dd9efe0df 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -69,6 +69,7 @@ macro_rules! invoke_commands_with_extras {
core::server::provider_secrets::get_secret,
// System commands
core::system::commands::relaunch,
+ core::system::shutdown::shutdown_for_update,
core::system::commands::open_app_directory,
core::system::commands::factory_reset,
core::system::commands::take_pending_webdata_reset,
@@ -372,6 +373,19 @@ pub fn run() {
app.handle()
.plugin(tauri_plugin_updater::Builder::new().build())?;
+ // A Jan up to 0.8.4 leaves its llama-server router running across an
+ // in-app update; that version cannot be fixed, so reap it here.
+ #[cfg(not(any(target_os = "ios", target_os = "android")))]
+ {
+ let data_folder = get_jan_data_folder_path(app.handle().clone());
+ tauri::async_runtime::spawn_blocking(move || {
+ let killed = core::system::orphans::sweep_orphaned_engines(&data_folder);
+ if killed > 0 {
+ log::warn!("Reaped {killed} engine process(es) left by a previous Jan");
+ }
+ });
+ }
+
// Start migration
let mut store_path = get_jan_data_folder_path(app.handle().clone());
store_path.push("store.json");
@@ -499,10 +513,6 @@ pub fn run() {
if let RunEvent::Exit = event {
let app_handle = app.clone();
- // Drain any debounced settings writes before the process dies so
- // jan CLI never reads a stale settings.json.
- core::app::settings_store::flush_settings();
-
#[cfg(not(any(target_os = "ios", target_os = "android")))]
{
if let Some(window) = app_handle.get_webview_window("main") {
@@ -527,39 +537,9 @@ pub fn run() {
// Run cleanup synchronously and WAIT for it to complete
tokio::task::block_in_place(|| {
- tauri::async_runtime::block_on(async {
- use crate::core::mcp::helpers::background_cleanup_mcp_servers;
- use tauri_plugin_llamacpp::cleanup_llama_processes;
-
- let state = app_handle.state::<AppState>();
-
- // Increase timeout to 10 seconds and log if it times out
- let cleanup_future = background_cleanup_mcp_servers(&app_handle, &state);
- match tokio::time::timeout(tokio::time::Duration::from_secs(10), cleanup_future)
- .await
- {
- Ok(_) => log::info!("MCP cleanup completed successfully"),
- Err(_) => log::warn!("MCP cleanup timed out after 10 seconds"),
- }
-
- if let Err(e) = cleanup_llama_processes(app_handle.clone()).await {
- log::warn!("Failed to shut down the llama.cpp engine: {}", e);
- } else {
- log::info!("llama.cpp engine shut down successfully");
- }
-
- #[cfg(target_os = "macos")]
- {
- use tauri_plugin_mlx::cleanup_mlx_processes;
- if let Err(e) = cleanup_mlx_processes(app_handle.clone()).await {
- log::warn!("Failed to cleanup MLX processes: {}", e);
- } else {
- log::info!("MLX processes cleaned up successfully");
- }
- }
-
- log::info!("App cleanup completed");
- });
+ tauri::async_runtime::block_on(core::system::shutdown::shutdown_cleanup(
+ &app_handle,
+ ))
});
}
});
diff --git a/web-app/src/hooks/__tests__/useAppUpdater.test.ts b/web-app/src/hooks/__tests__/useAppUpdater.test.ts
index 547d419aa..b013e7dbf 100644
--- a/web-app/src/hooks/__tests__/useAppUpdater.test.ts
+++ b/web-app/src/hooks/__tests__/useAppUpdater.test.ts
@@ -296,8 +296,10 @@ describe('useAppUpdater', () => {
await result.current.downloadAndInstallUpdate()
})
- expect(mockStopAllModels).toHaveBeenCalled()
- expect(mockEventsEmit).toHaveBeenCalledWith('KILL_SIDECAR')
+ // Stopping the engine now happens in the updater service after the
+ // download has verified, so the hook itself must not touch it.
+ expect(mockStopAllModels).not.toHaveBeenCalled()
+ expect(mockEventsEmit).not.toHaveBeenCalled()
expect(mockUpdaterDownloadAndInstallWithProgress).toHaveBeenCalled()
expect(mockRelaunch).toHaveBeenCalled()
})
@@ -345,7 +347,7 @@ describe('useAppUpdater', () => {
await result.current.downloadAndInstallUpdate()
})
- expect(mockStopAllModels).not.toHaveBeenCalled()
+ expect(mockUpdaterDownloadAndInstallWithProgress).not.toHaveBeenCalled()
})
it('should emit progress events during download', async () => {
diff --git a/web-app/src/hooks/useAppUpdater.ts b/web-app/src/hooks/useAppUpdater.ts
index 5ec820e5c..29f7af5b0 100644
--- a/web-app/src/hooks/useAppUpdater.ts
+++ b/web-app/src/hooks/useAppUpdater.ts
@@ -2,7 +2,6 @@ import { isDev } from '@/lib/utils'
import { useState, useCallback, useEffect } from 'react'
import { events, AppEvent } from '@janhq/core'
import type { UpdateInfo } from '@/services/updater/types'
-import { SystemEvent } from '@/types/events'
import { getServiceHub } from '@/hooks/useServiceHub'
export interface UpdateState {
@@ -169,10 +168,10 @@ export const useAppUpdater = () => {
let downloaded = 0
let contentLength = 0
- await getServiceHub().models().stopAllModels()
- getServiceHub().events().emit(SystemEvent.KILL_SIDECAR)
- await new Promise((resolve) => setTimeout(resolve, 1000))
+ // The engine, MCP servers and agent shells are stopped by the updater
+ // service once the download has verified, not here: a failed download
+ // must not take them down.
await getServiceHub().updater().downloadAndInstallWithProgress((event) => {
switch (event.event) {
case 'Started':
diff --git a/web-app/src/services/updater/__tests__/tauri.test.ts b/web-app/src/services/updater/__tests__/tauri.test.ts
index 34e8b97f2..f55af1641 100644
--- a/web-app/src/services/updater/__tests__/tauri.test.ts
+++ b/web-app/src/services/updater/__tests__/tauri.test.ts
@@ -24,7 +24,7 @@ vi.mock('@tauri-apps/api/app', () => ({
getVersion: vi.fn().mockResolvedValue('1.0.0'),
}))
-import { check } from '@tauri-apps/plugin-updater'
+import { check, type Update } from '@tauri-apps/plugin-updater'
import { invoke } from '@tauri-apps/api/core'
import { TauriUpdaterService } from '../tauri'
import { DefaultUpdaterService } from '../default'
@@ -197,28 +197,37 @@ describe('TauriUpdaterService', () => {
})
describe('downloadAndInstallWithProgress()', () => {
- it('calls downloadAndInstall with progress callback', async () => {
- const mockDownloadAndInstall = vi.fn().mockImplementation(async (cb) => {
+ it('downloads, stops the app, then installs, in that order', async () => {
+ const calls: string[] = []
+ const download = vi.fn().mockImplementation(async (cb) => {
+ calls.push('download')
cb({ event: 'Started', data: { contentLength: 1000 } })
cb({ event: 'Progress', data: { chunkLength: 500 } })
cb({ event: 'Finished' })
})
+ const install = vi.fn().mockImplementation(async () => {
+ calls.push('install')
+ })
+ vi.mocked(invoke).mockImplementation(async (cmd: string) => {
+ calls.push(cmd)
+ })
vi.mocked(check).mockResolvedValueOnce({
version: '2.0.0',
- downloadAndInstall: mockDownloadAndInstall,
- } as any)
+ download,
+ install,
+ } as unknown as Update)
const progressCb = vi.fn()
await svc.downloadAndInstallWithProgress(progressCb)
- expect(mockDownloadAndInstall).toHaveBeenCalled()
+ expect(calls).toEqual(['download', 'shutdown_for_update', 'install'])
expect(progressCb).toHaveBeenCalledTimes(3)
expect(progressCb).toHaveBeenCalledWith({ event: 'Started', data: { contentLength: 1000 } })
expect(progressCb).toHaveBeenCalledWith({ event: 'Finished' })
})
it('throws when no update is available', async () => {
- vi.mocked(check).mockResolvedValueOnce(null as any)
+ vi.mocked(check).mockResolvedValueOnce(null)
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
await expect(svc.downloadAndInstallWithProgress(vi.fn())).rejects.toThrow(
@@ -227,12 +236,14 @@ describe('TauriUpdaterService', () => {
errorSpy.mockRestore()
})
- it('logs error and rethrows when download fails', async () => {
+ it('leaves the app running when the download or signature check fails', async () => {
const err = new Error('download error')
+ const install = vi.fn()
vi.mocked(check).mockResolvedValueOnce({
version: '2.0.0',
- downloadAndInstall: vi.fn().mockRejectedValue(err),
- } as any)
+ download: vi.fn().mockRejectedValue(err),
+ install,
+ } as unknown as Update)
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
await expect(svc.downloadAndInstallWithProgress(vi.fn())).rejects.toBe(err)
@@ -240,17 +251,72 @@ describe('TauriUpdaterService', () => {
'Error downloading update with progress in Tauri:',
err
)
+ expect(invoke).not.toHaveBeenCalledWith('shutdown_for_update')
+ expect(install).not.toHaveBeenCalled()
errorSpy.mockRestore()
})
+ it('does not run the installer when the shutdown fails', async () => {
+ const err = new Error('shutdown failed')
+ const install = vi.fn()
+ vi.mocked(invoke).mockRejectedValueOnce(err)
+ vi.mocked(check).mockResolvedValueOnce({
+ version: '2.0.0',
+ download: vi.fn().mockResolvedValue(undefined),
+ install,
+ } as unknown as Update)
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+
+ await expect(svc.downloadAndInstallWithProgress(vi.fn())).rejects.toBe(err)
+ expect(install).not.toHaveBeenCalled()
+ errorSpy.mockRestore()
+ })
+
+ it('restarts the MCP servers when the installer fails after the shutdown', async () => {
+ const err = new Error('install failed')
+ vi.mocked(invoke).mockResolvedValue(undefined)
+ vi.mocked(check).mockResolvedValueOnce({
+ version: '2.0.0',
+ download: vi.fn().mockResolvedValue(undefined),
+ install: vi.fn().mockRejectedValue(err),
+ } as unknown as Update)
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+
+ await expect(svc.downloadAndInstallWithProgress(vi.fn())).rejects.toBe(err)
+ expect(vi.mocked(invoke).mock.calls.map(([command]) => command)).toEqual([
+ 'shutdown_for_update',
+ 'restart_mcp_servers',
+ ])
+ errorSpy.mockRestore()
+ })
+
+ it('reports the install error when restarting the MCP servers fails too', async () => {
+ const err = new Error('install failed')
+ vi.mocked(invoke).mockImplementation(async (command: string) => {
+ if (command === 'restart_mcp_servers') throw new Error('restart failed')
+ })
+ vi.mocked(check).mockResolvedValueOnce({
+ version: '2.0.0',
+ download: vi.fn().mockResolvedValue(undefined),
+ install: vi.fn().mockRejectedValue(err),
+ } as unknown as Update)
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ await expect(svc.downloadAndInstallWithProgress(vi.fn())).rejects.toBe(err)
+ errorSpy.mockRestore()
+ warnSpy.mockRestore()
+ })
+
it('handles errors in progress callback gracefully', async () => {
- const mockDownloadAndInstall = vi.fn().mockImplementation(async (cb) => {
+ const download = vi.fn().mockImplementation(async (cb) => {
cb({ event: 'Started' })
})
vi.mocked(check).mockResolvedValueOnce({
version: '2.0.0',
- downloadAndInstall: mockDownloadAndInstall,
- } as any)
+ download,
+ install: vi.fn().mockResolvedValue(undefined),
+ } as unknown as Update)
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
const badCallback = vi.fn().mockImplementation(() => {
diff --git a/web-app/src/services/updater/tauri.ts b/web-app/src/services/updater/tauri.ts
index cc7c6392f..7c94ac712 100644
--- a/web-app/src/services/updater/tauri.ts
+++ b/web-app/src/services/updater/tauri.ts
@@ -147,8 +147,13 @@ export class TauriUpdaterService extends DefaultUpdaterService {
throw new Error('No update available')
}
- // Use Tauri's downloadAndInstall with progress callback
- await update.downloadAndInstall((event) => {
+ // Download and verify first, then stop everything the app started, then
+ // run the installer. `downloadAndInstall` would exit the process (Windows)
+ // or swap the bundle (macOS/Linux) without raising `RunEvent::Exit`, so
+ // the engine, MCP servers and agent shells would be left running. The
+ // cleanup sits between the two so a failed download or signature check
+ // leaves the running app untouched.
+ await update.download((event) => {
try {
// Forward the event to the callback
progressCallback(event as UpdateProgressEvent)
@@ -156,6 +161,18 @@ export class TauriUpdaterService extends DefaultUpdaterService {
console.warn('Error in download progress callback:', callbackError)
}
})
+ await invoke('shutdown_for_update')
+ try {
+ await update.install()
+ } catch (installError) {
+ // The app is still running, so bring back what `shutdown_for_update`
+ // stopped. The engine restarts on the next model load, MCP servers do
+ // not, and a failed restart must not hide the install error.
+ await invoke('restart_mcp_servers').catch((restartError) => {
+ console.warn('Could not restart MCP servers after a failed install:', restartError)
+ })
+ throw installError
+ }
} catch (error) {
console.error('Error downloading update with progress in Tauri:', error)
throw error