From c33f63c48cf8625415be3fdc0bdd059ec10449ce Mon Sep 17 00:00:00 2001 From: BytePioneer-AI <28417416@qq.com> Date: Sat, 28 Nov 2026 13:52:04 +0800 Subject: [PATCH] fix(updater): relaunch desktop shell after update and preserve preflight errors Fixes two Rust update/restart failures reproduced in end-to-end isolated update testing: 1. Preserve Desktop Shell across updates: - Detect an active Desktop Shell (desktop-shell-ready.json with live owner) in launcher service_update::prepare_request and pass backward-compatible restart_desktop_shell: true in UpdateRequest (keeping restart_target unchanged for official Codex Desktop and background Web coexistence). - After codexhost-updater finishes restoring services and writes terminal status-v1.json (on both update success and successful failure rollback), relaunch the updated Desktop Shell via detached `codexhost app` with CODEXHOST_DATA_DIR and npm runtime env vars preserved. 2. Preserve updater preflight failure errors during handshake: - Parse status-v1.json's error field in launcher active_update::wait_for_updater_ready (including a final re-read after child exit to avoid the exit race) and avoid clobbering an already-recorded non-empty failed error in service_update::record_failure. --- crates/launcher/src/active_update.rs | 117 ++++++-- crates/launcher/src/desktop_shell.rs | 22 +- crates/launcher/src/service_update.rs | 101 ++++++- crates/launcher/tests/web_service.rs | 20 ++ crates/updater/src/install.rs | 2 + crates/updater/src/main.rs | 18 +- crates/updater/src/request.rs | 27 +- crates/updater/src/restart.rs | 106 +++++++- crates/updater/tests/background_services.rs | 285 ++++++++++++++++++++ 9 files changed, 649 insertions(+), 49 deletions(-) diff --git a/crates/launcher/src/active_update.rs b/crates/launcher/src/active_update.rs index a8eac6584c..5442115829 100644 --- a/crates/launcher/src/active_update.rs +++ b/crates/launcher/src/active_update.rs @@ -35,6 +35,8 @@ struct ActiveUpdateLock { struct UpdateStatusProbe { schema_version: u8, phase: String, + #[serde(default)] + error: Option, } #[derive(Deserialize)] @@ -215,7 +217,7 @@ pub(crate) fn update_waiting_for_launcher_exit() -> io::Result { ) } -fn read_update_phase(status_path: &Path) -> io::Result> { +fn read_update_status(status_path: &Path) -> io::Result> { let Some(status_bytes) = read_bounded_regular_file(status_path)? else { return Ok(None); }; @@ -224,28 +226,42 @@ fn read_update_phase(status_path: &Path) -> io::Result> { if status.schema_version != 1 { return Err(invalid("active update status schema is unsupported")); } - Ok(Some(status.phase)) + Ok(Some(status)) +} + +fn evaluate_updater_status(status: Option, service: bool) -> io::Result { + let Some(status) = status else { + return Ok(false); + }; + match status.phase.as_str() { + "waiting-for-exit" => Ok(true), + "installing" | "restarting" | "succeeded" if service => Ok(true), + "prepared" => Ok(false), + "failed" => { + let message = status + .error + .as_deref() + .map(str::trim) + .filter(|message| !message.is_empty()) + .unwrap_or("background Updater failed before waiting for Launcher exit"); + Err(invalid(message)) + } + phase => Err(invalid(format!( + "background Updater reported unexpected phase {phase} before waiting for Launcher exit" + ))), + } } fn wait_for_updater_ready(child: &mut Child, status_path: &Path, service: bool) -> io::Result<()> { let started = Instant::now(); loop { - match read_update_phase(status_path)?.as_deref() { - Some("waiting-for-exit") => return Ok(()), - Some("installing" | "restarting" | "succeeded") if service => return Ok(()), - Some("prepared") | None => {} - Some("failed") => { - return Err(invalid( - "background Updater failed before waiting for Launcher exit", - )); - } - Some(phase) => { - return Err(invalid(format!( - "background Updater reported unexpected phase {phase} before waiting for Launcher exit" - ))); - } + if evaluate_updater_status(read_update_status(status_path)?, service)? { + return Ok(()); } if let Some(status) = child.try_wait()? { + if evaluate_updater_status(read_update_status(status_path)?, service)? { + return Ok(()); + } return Err(invalid(format!( "background Updater exited before waiting for Launcher exit: {status}" ))); @@ -390,9 +406,11 @@ mod tests { use serde_json::json; - use super::{ACTIVE_UPDATE_LOCK_FILE, PendingUpdate, waiting_for_launcher_exit_at}; #[cfg(target_os = "macos")] - use super::{STATUS_FILE, atomic_replace_file, wait_for_updater_ready}; + use super::atomic_replace_file; + use super::{ACTIVE_UPDATE_LOCK_FILE, PendingUpdate, waiting_for_launcher_exit_at}; + #[cfg(unix)] + use super::{STATUS_FILE, wait_for_updater_ready}; use super::{pending_startable_update_at, pending_update_at, transfer_lock_to_updater}; fn fixture_directory(label: &str) -> PathBuf { @@ -603,4 +621,67 @@ mod tests { assert!(!waiting_for_launcher_exit_at(&root, 43, &launcher).unwrap()); fs::remove_dir_all(fixture).expect("remove waiting update fixture"); } + + #[cfg(unix)] + #[test] + fn preserves_preflight_failure_error_written_by_updater() { + let fixture = fixture_directory("updater-preflight-error"); + let status_path = fixture.join(STATUS_FILE); + let original_error = "npm uses a different global installation than /opt/custom/codexhost; update manually with the npm that installed codexhost"; + fs::write( + &status_path, + format!( + "{}\n", + json!({ + "schemaVersion": 1, + "version": "1.2.3", + "installation": "npm", + "phase": "prepared", + "updatedAt": 1, + }) + ), + ) + .expect("write prepared status fixture"); + let script = format!( + "tmp=\"{}.tmp\"\nprintf '%s\\n' '{}' > \"$tmp\"\nmv \"$tmp\" \"{}\"\nexit 1\n", + status_path.display(), + json!({ + "schemaVersion": 1, + "version": "1.2.3", + "installation": "npm", + "phase": "failed", + "updatedAt": 2, + "error": original_error, + }), + status_path.display(), + ); + let mut child = std::process::Command::new("/bin/sh") + .args(["-c", &script]) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .expect("spawn failing updater fixture"); + + let error = wait_for_updater_ready(&mut child, &status_path, true) + .expect_err("preflight failure must error"); + let _ = child.wait(); + assert_eq!(error.to_string(), original_error); + + crate::service_update::record_failure( + &status_path, + &std::io::Error::new( + std::io::ErrorKind::InvalidData, + "background Updater failed before waiting for Launcher exit", + ), + ) + .expect("record failure should preserve existing updater error"); + let status: serde_json::Value = + serde_json::from_slice(&fs::read(&status_path).expect("read status")) + .expect("parse status"); + assert_eq!(status["phase"], "failed"); + assert_eq!(status["error"], original_error); + assert_eq!(status["updatedAt"], 2); + fs::remove_dir_all(fixture).expect("remove preflight error fixture"); + } } diff --git a/crates/launcher/src/desktop_shell.rs b/crates/launcher/src/desktop_shell.rs index a5ed5e26da..c51bbd5b55 100644 --- a/crates/launcher/src/desktop_shell.rs +++ b/crates/launcher/src/desktop_shell.rs @@ -81,14 +81,25 @@ fn read_record(path: &Path) -> std::io::Result>> { } } +fn live_owner(bytes: &[u8]) -> Option { + serde_json::from_slice::(bytes) + .ok() + .and_then(|record| process_instance(record.pid, record.started_at_micros)) +} + +pub fn running(data: &Path) -> std::io::Result { + Ok(read_record(&data.join(READY))? + .as_deref() + .and_then(live_owner) + .is_some()) +} + pub fn stop(data: &Path) -> Result> { let path = data.join(READY); let Some(bytes) = read_record(&path)? else { return Ok(false); }; - let owner = serde_json::from_slice::(&bytes) - .ok() - .and_then(|record| process_instance(record.pid, record.started_at_micros)); + let owner = live_owner(&bytes); if let Some(owner) = owner { stop_instance(owner)?; } @@ -112,6 +123,7 @@ mod tests { let data = std::env::temp_dir().join(format!("codexhost-shell-stop-{}", std::process::id())); fs::create_dir(&data).unwrap(); + assert!(!running(&data).unwrap()); assert!(!stop(&data).unwrap()); let current = codexhost_platform::process_identity(std::process::id()).unwrap(); @@ -125,6 +137,7 @@ mod tests { assert_eq!(serde_json::to_value(&record).unwrap(), fixture); let path = data.join(READY); fs::write(&path, serde_json::to_vec(&record).unwrap()).unwrap(); + assert!(!running(&data).unwrap()); assert!(!stop(&data).unwrap()); assert!(!path.exists()); assert!(process_instance(current.id, current.started_at_micros).is_some()); @@ -139,6 +152,7 @@ mod tests { let path = data.join(READY); fs::write(&path, b"{\"pid\":").unwrap(); + assert!(!running(&data).unwrap()); assert!(!stop(&data).unwrap()); assert!(!path.exists()); fs::remove_dir_all(data).unwrap(); @@ -174,9 +188,11 @@ mod tests { }; let path = data.join(READY); fs::write(&path, serde_json::to_vec(&record).unwrap()).unwrap(); + assert!(running(&data).unwrap()); let reaper = thread::spawn(move || shell.wait().unwrap()); assert!(stop(&data).unwrap()); assert!(reaper.join().unwrap().success()); + assert!(!running(&data).unwrap()); assert!(!path.exists()); fs::remove_dir_all(data).unwrap(); } diff --git a/crates/launcher/src/service_update.rs b/crates/launcher/src/service_update.rs index 9e47bb2a97..36018ee5d3 100644 --- a/crates/launcher/src/service_update.rs +++ b/crates/launcher/src/service_update.rs @@ -10,7 +10,12 @@ fn invalid(message: impl Into) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message.into()) } -fn bind_request(request: &mut Value, data: &Path, desktop_running: bool) -> io::Result<()> { +fn bind_request( + request: &mut Value, + data: &Path, + desktop_running: bool, + desktop_shell_running: bool, +) -> io::Result<()> { if request["service_managed"] != true { return Err(invalid( "The Host supervisor requires a service-managed update", @@ -26,8 +31,18 @@ fn bind_request(request: &mut Value, data: &Path, desktop_running: bool) -> io:: "The update belongs to a different Host data directory", )); } - request["restart_target"] = - Value::String(if desktop_running { "desktop" } else { "web" }.into()); + let object = request + .as_object_mut() + .ok_or_else(|| invalid("The update request must be a JSON object"))?; + object.insert( + "restart_target".into(), + Value::String(if desktop_running { "desktop" } else { "web" }.into()), + ); + if desktop_shell_running { + object.insert("restart_desktop_shell".into(), Value::Bool(true)); + } else { + object.remove("restart_desktop_shell"); + } Ok(()) } @@ -35,13 +50,21 @@ pub(super) fn prepare_request(path: &Path, data: &Path) -> io::Result<()> { let mut request: Value = serde_json::from_slice(&fs::read(path)?)?; let desktop_running = crate::desktop_attachment::running_for_update(data) .map_err(|error| invalid(error.to_string()))?; - bind_request(&mut request, data, desktop_running)?; + let desktop_shell_running = crate::desktop_shell::running(data)?; + bind_request(&mut request, data, desktop_running, desktop_shell_running)?; crate::host_service::publish_status(path, &format!("{}\n", serde_json::to_string(&request)?)) .map_err(|error| invalid(error.to_string())) } pub(super) fn record_failure(path: &Path, error: &io::Error) -> io::Result<()> { let mut status: Value = serde_json::from_slice(&fs::read(path)?)?; + if status["phase"].as_str() == Some("failed") + && status["error"] + .as_str() + .is_some_and(|message| !message.trim().is_empty()) + { + return Ok(()); + } status["phase"] = Value::String("failed".into()); status["error"] = Value::String(error.to_string().chars().take(500).collect()); status["updatedAt"] = Value::from( @@ -135,12 +158,28 @@ mod tests { use serde_json::json; #[test] - fn service_request_keeps_its_operation_and_uses_the_actual_desktop_state() { + fn service_request_keeps_its_operation_and_uses_the_actual_desktop_and_shell_state() { let data = std::env::temp_dir().canonicalize().unwrap(); - for (running, target) in [(true, "desktop"), (false, "web")] { - let mut request = json!({"service_managed":true,"data_directory":data,"restart_target":"desktop","status_path":"original-status"}); - bind_request(&mut request, &data, running).unwrap(); + for (desktop_running, shell_running, target) in [ + (true, false, "desktop"), + (false, false, "web"), + (false, true, "web"), + (true, true, "desktop"), + ] { + let mut request = json!({ + "service_managed": true, + "data_directory": data, + "restart_target": "desktop", + "restart_desktop_shell": true, + "status_path": "original-status", + }); + bind_request(&mut request, &data, desktop_running, shell_running).unwrap(); assert_eq!(request["restart_target"], target); + if shell_running { + assert_eq!(request["restart_desktop_shell"], true); + } else { + assert!(request.get("restart_desktop_shell").is_none()); + } assert_eq!(request["status_path"], "original-status"); } } @@ -149,11 +188,51 @@ mod tests { fn service_request_rejects_a_different_owner_or_data_directory() { let data = std::env::temp_dir().canonicalize().unwrap(); let mut request = json!({"data_directory":data}); - assert!(bind_request(&mut request, &data, false).is_err()); + assert!(bind_request(&mut request, &data, false, false).is_err()); request["service_managed"] = Value::Bool(true); request["data_directory"] = Value::String("relative".into()); - assert!(bind_request(&mut request, &data, false).is_err()); + assert!(bind_request(&mut request, &data, false, false).is_err()); request["data_directory"] = Value::String(data.to_string_lossy().into_owned()); - assert!(bind_request(&mut request, data.parent().unwrap(), false).is_err()); + assert!(bind_request(&mut request, data.parent().unwrap(), false, false).is_err()); + } + + #[test] + fn record_failure_preserves_existing_failed_error_and_writes_otherwise() { + let root = + std::env::temp_dir().join(format!("codexhost-record-failure-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + let status_path = root.join("status-v1.json"); + + fs::write( + &status_path, + serde_json::to_vec(&json!({ + "schemaVersion": 1, + "version": "1.2.3", + "installation": "npm", + "phase": "failed", + "error": "npm prefix mismatch", + "updatedAt": 10, + })) + .unwrap(), + ) + .unwrap(); + record_failure(&status_path, &invalid("generic handoff failure")).unwrap(); + let preserved: Value = serde_json::from_slice(&fs::read(&status_path).unwrap()).unwrap(); + assert_eq!(preserved["phase"], "failed"); + assert_eq!(preserved["error"], "npm prefix mismatch"); + assert_eq!(preserved["updatedAt"], 10); + + for initial in [ + json!({"schemaVersion": 1, "phase": "prepared", "updatedAt": 10}), + json!({"schemaVersion": 1, "phase": "failed", "error": " ", "updatedAt": 10}), + ] { + fs::write(&status_path, serde_json::to_vec(&initial).unwrap()).unwrap(); + record_failure(&status_path, &invalid("launcher handoff error")).unwrap(); + let updated: Value = serde_json::from_slice(&fs::read(&status_path).unwrap()).unwrap(); + assert_eq!(updated["phase"], "failed"); + assert_eq!(updated["error"], "launcher handoff error"); + } + fs::remove_dir_all(root).unwrap(); } } diff --git a/crates/launcher/tests/web_service.rs b/crates/launcher/tests/web_service.rs index cd8519d02d..fcc9d7f2cc 100644 --- a/crates/launcher/tests/web_service.rs +++ b/crates/launcher/tests/web_service.rs @@ -1179,6 +1179,20 @@ setInterval(() => {{ ); fs::write(&helper, helper_source).unwrap(); fs::set_permissions(&helper, fs::Permissions::from_mode(0o700)).unwrap(); + if attempt == 2 { + let current = codexhost_platform::process_snapshot(std::process::id()).unwrap(); + fs::write( + fixture.root.join("desktop-shell-ready.json"), + serde_json::to_vec(&serde_json::json!({ + "pid": current.id, + "started_at_micros": current.started_at_micros, + "executable": current.executable, + "version": env!("CARGO_PKG_VERSION"), + })) + .unwrap(), + ) + .unwrap(); + } fs::write(&request, serde_json::to_vec(&serde_json::json!({ "schema_version":1,"wait_pid":owner,"wait_executable":environment["CODEXHOST_LAUNCHER_EXECUTABLE"], "status_path":status,"service_managed":true,"restart_target":"desktop","data_directory":fixture.root @@ -1207,6 +1221,12 @@ setInterval(() => {{ thread::sleep(Duration::from_millis(20)); }; assert_eq!(observed["request"]["restart_target"], "web"); + if attempt == 1 { + assert!(observed["request"].get("restart_desktop_shell").is_none()); + } else { + assert_eq!(observed["request"]["restart_desktop_shell"], true); + fs::remove_file(fixture.root.join("desktop-shell-ready.json")).unwrap(); + } let updater = observed["pid"].as_u64().unwrap() as u32; let until = deadline(); loop { diff --git a/crates/updater/src/install.rs b/crates/updater/src/install.rs index fa0529517f..3a35505310 100644 --- a/crates/updater/src/install.rs +++ b/crates/updater/src/install.rs @@ -595,6 +595,7 @@ printf '{{"schemaVersion":1,"version":"%s","distribution":"npm","target":"fixtur wait_executable: "/unused".into(), runtime_descriptor_path: "/unused".into(), restart_target: RestartTarget::Desktop, + restart_desktop_shell: false, data_directory: None, service_managed: false, status_path: directory.join("status.json"), @@ -700,6 +701,7 @@ printf '{{"schemaVersion":1,"version":"%s","distribution":"npm","target":"fixtur wait_executable: path.clone(), runtime_descriptor_path: path.clone(), restart_target: RestartTarget::Desktop, + restart_desktop_shell: false, data_directory: None, service_managed: false, status_path: path.clone(), diff --git a/crates/updater/src/main.rs b/crates/updater/src/main.rs index 15ce980d93..936dc1aaa1 100644 --- a/crates/updater/src/main.rs +++ b/crates/updater/src/main.rs @@ -85,13 +85,22 @@ fn apply(request_path: &Path) -> Result<(), Box> { write_status(&request, "restarting", None, service_stop_output.as_deref())?; restart::restore(&request, Some(&request.version))?; write_status(&request, "succeeded", None, service_stop_output.as_deref())?; + if request.restart_desktop_shell + && let Err(shell_error) = restart::relaunch_desktop_shell(&request) + { + eprintln!("codexhost updater: desktop shell relaunch failed: {shell_error}"); + } Ok(()) })(); if let Err(error) = &result { let mut message = error.to_string(); + let mut recovered = false; if stopping_started { match restart::restore(&request, None) { - Ok(()) => message.push_str("; service recovery succeeded"), + Ok(()) => { + recovered = true; + message.push_str("; service recovery succeeded"); + } Err(recovery) => { message.push_str(&format!("; service recovery failed: {recovery}")) } @@ -103,6 +112,12 @@ fn apply(request_path: &Path) -> Result<(), Box> { Some(&message), service_stop_output.as_deref(), ); + if recovered + && request.restart_desktop_shell + && let Err(shell_error) = restart::relaunch_desktop_shell(&request) + { + eprintln!("codexhost updater: desktop shell recovery failed: {shell_error}"); + } } result } @@ -163,6 +178,7 @@ mod tests { wait_executable: wrong_executable.clone(), runtime_descriptor_path: directory.join("runtime.json"), restart_target: Default::default(), + restart_desktop_shell: false, data_directory: None, service_managed: false, status_path: status_path.clone(), diff --git a/crates/updater/src/request.rs b/crates/updater/src/request.rs index 9dd8474bd5..5c2ba27bcd 100644 --- a/crates/updater/src/request.rs +++ b/crates/updater/src/request.rs @@ -17,6 +17,8 @@ pub(crate) struct UpdateRequest { #[serde(default)] pub(crate) restart_target: RestartTarget, #[serde(default)] + pub(crate) restart_desktop_shell: bool, + #[serde(default)] pub(crate) data_directory: Option, #[serde(default)] pub(crate) service_managed: bool, @@ -281,7 +283,10 @@ impl UpdateRequest { require_absolute_path(&self.status_path, "update status path")?; if let Some(data) = &self.data_directory { require_absolute_path(data, "service data directory")?; - } else if self.restart_target == RestartTarget::Web || self.service_managed { + } else if self.restart_target == RestartTarget::Web + || self.restart_desktop_shell + || self.service_managed + { return Err("service updates require an explicit data directory".into()); } match &self.installation { @@ -380,6 +385,7 @@ mod tests { }); let legacy: UpdateRequest = serde_json::from_value(value.clone()).unwrap(); assert_eq!(legacy.restart_target, RestartTarget::Desktop); + assert!(!legacy.restart_desktop_shell); assert!(!legacy.service_managed); legacy.validate().unwrap(); value["restart_target"] = "web".into(); @@ -401,9 +407,25 @@ mod tests { .unwrap() .validate() .unwrap(); + value["restart_desktop_shell"] = true.into(); + let shell_web: UpdateRequest = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(shell_web.restart_target, RestartTarget::Web); + assert!(shell_web.restart_desktop_shell); + shell_web.validate().unwrap(); value["restart_target"] = "desktop".into(); - value["service_managed"] = true.into(); + let shell_desktop: UpdateRequest = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(shell_desktop.restart_target, RestartTarget::Desktop); + assert!(shell_desktop.restart_desktop_shell); + shell_desktop.validate().unwrap(); value.as_object_mut().unwrap().remove("data_directory"); + assert!( + serde_json::from_value::(value.clone()) + .unwrap() + .validate() + .is_err() + ); + value["restart_desktop_shell"] = false.into(); + value["service_managed"] = true.into(); assert!( serde_json::from_value::(value) .unwrap() @@ -434,6 +456,7 @@ mod tests { .unwrap() .join("desktop-runtime-v1.json"), restart_target: RestartTarget::Desktop, + restart_desktop_shell: false, data_directory, service_managed: false, status_path: status_path.to_path_buf(), diff --git a/crates/updater/src/restart.rs b/crates/updater/src/restart.rs index c0282f4a41..df5588137c 100644 --- a/crates/updater/src/restart.rs +++ b/crates/updater/src/restart.rs @@ -8,7 +8,8 @@ use std::thread; use std::time::{Duration, Instant}; use codexhost_platform::{ - ProcessIdentity, configure_background_command, process_identity, process_snapshot, + ProcessIdentity, configure_background_command, configure_detached_service_command, + process_identity, process_snapshot, }; use serde::{Deserialize, de::DeserializeOwned}; @@ -215,6 +216,23 @@ fn pass_npm_node(command: &mut Command, request: &UpdateRequest) { } } +fn apply_restart_environment(command: &mut Command, request: &UpdateRequest) { + if let Some(data) = &request.data_directory { + command.env("CODEXHOST_DATA_DIR", data); + } + if let Installation::Npm(npm) = &request.installation { + command + .env("CODEXHOST_NPM_NODE_PATH", &npm.node_path) + .env("CODEXHOST_NPM_CLI_PATH", &npm.npm_cli_path) + .env("CODEXHOST_NPM_LAUNCHER_PATH", &npm.npm_launcher_path) + .env("CODEXHOST_NPM_PACKAGE_ROOT", &npm.npm_package_root); + } + command + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); +} + fn command(request: &UpdateRequest) -> Command { let mut command = if request.restart_target == RestartTarget::Web { let mut command = Command::new(request.installation.launcher_path()); @@ -250,24 +268,25 @@ fn command(request: &UpdateRequest) -> Command { Installation::LinuxArchive(_) => Command::new(request.installation.launcher_path()), } }; - if let Some(data) = &request.data_directory { - command.env("CODEXHOST_DATA_DIR", data); - } - if let Installation::Npm(npm) = &request.installation { - command - .env("CODEXHOST_NPM_NODE_PATH", &npm.node_path) - .env("CODEXHOST_NPM_CLI_PATH", &npm.npm_cli_path) - .env("CODEXHOST_NPM_LAUNCHER_PATH", &npm.npm_launcher_path) - .env("CODEXHOST_NPM_PACKAGE_ROOT", &npm.npm_package_root); - } + apply_restart_environment(&mut command, request); configure_background_command(&mut command); command - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()); +} + +fn desktop_shell_command(request: &UpdateRequest) -> Command { + let mut command = Command::new(request.installation.launcher_path()); + command.arg("app"); + apply_restart_environment(&mut command, request); command } +pub(crate) fn relaunch_desktop_shell(request: &UpdateRequest) -> Result<(), Box> { + let mut command = desktop_shell_command(request); + configure_detached_service_command(&mut command)?; + command.spawn()?; + Ok(()) +} + pub(crate) fn restore( request: &UpdateRequest, expected_version: Option<&str>, @@ -405,6 +424,65 @@ mod tests { ); } + #[test] + fn desktop_shell_command_launches_app_with_data_and_npm_environment() { + let root = std::env::temp_dir().join("codexhost-shell-relaunch-command"); + let npm_request: UpdateRequest = serde_json::from_value(serde_json::json!({ + "schema_version": 1, "version": "1.2.3", "wait_pid": 1, + "wait_executable": root.join("node"), "runtime_descriptor_path": root.join("desktop.json"), + "status_path": root.join("status.json"), "restart_target": "web", + "restart_desktop_shell": true, "data_directory": root.join("data"), + "installation": {"kind":"npm", "node_path":root.join("node"), "npm_cli_path":root.join("npm.js"), "npm_launcher_path":root.join("wrapper.js"), "npm_package_root":root.join("package")} + })).unwrap(); + let command = desktop_shell_command(&npm_request); + assert_eq!( + command.get_program(), + npm_request.installation.launcher_path() + ); + assert_eq!(command.get_args().collect::>(), ["app"]); + assert!( + command + .get_envs() + .any(|(key, value)| key == "CODEXHOST_DATA_DIR" + && value == Some(root.join("data").as_os_str())) + ); + for key in [ + "CODEXHOST_NPM_NODE_PATH", + "CODEXHOST_NPM_CLI_PATH", + "CODEXHOST_NPM_LAUNCHER_PATH", + "CODEXHOST_NPM_PACKAGE_ROOT", + ] { + assert!( + command + .get_envs() + .any(|(name, value)| name == key && value.is_some()), + "missing {key}" + ); + } + + let packaged: UpdateRequest = serde_json::from_value(serde_json::json!({ + "schema_version": 1, "version": "1.2.3", "wait_pid": 1, + "wait_executable": root.join("node"), "runtime_descriptor_path": root.join("desktop.json"), + "status_path": root.join("status.json"), "restart_target": "web", + "restart_desktop_shell": true, "data_directory": root.join("data"), + "installation": {"kind":"macos-dmg", "dmg_path":root.join("a.dmg"), "artifact_sha256":"0".repeat(64), "app_path":root.join("codexhost.app")} + })).unwrap(); + let command = desktop_shell_command(&packaged); + assert_eq!(command.get_program(), packaged.installation.launcher_path()); + assert_eq!(command.get_args().collect::>(), ["app"]); + assert!( + command + .get_envs() + .any(|(key, value)| key == "CODEXHOST_DATA_DIR" + && value == Some(root.join("data").as_os_str())) + ); + assert!( + command + .get_envs() + .all(|(key, _)| key != "CODEXHOST_NPM_NODE_PATH") + ); + } + #[test] fn web_readiness_requires_both_live_services_at_the_target_version() { let root = std::env::temp_dir().join(format!("codexhost-ready-{}", std::process::id())); diff --git a/crates/updater/tests/background_services.rs b/crates/updater/tests/background_services.rs index 003aef6adb..60b841a350 100644 --- a/crates/updater/tests/background_services.rs +++ b/crates/updater/tests/background_services.rs @@ -236,3 +236,288 @@ fn rejected_lock_handoff_does_not_stop_or_recover_services() { assert!(fixture.root.join("web-running").exists()); assert!(fixture.root.join("host-running").exists()); } + +struct LiveWebFixture { + supervisor: Child, + web_pid: u32, + _listener: std::net::TcpListener, + address: String, + supervisor_started_at_micros: u64, +} + +impl LiveWebFixture { + fn start() -> Self { + use std::io::{BufRead, BufReader}; + + let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = listener.local_addr().unwrap().port(); + let mut supervisor = Command::new("/bin/sh") + .args(["-c", "sleep 60 & echo $!; wait"]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let mut line = String::new(); + BufReader::new(supervisor.stdout.take().unwrap()) + .read_line(&mut line) + .unwrap(); + let web_pid: u32 = line.trim().parse().unwrap(); + let supervisor_started_at_micros = codexhost_platform::process_identity(supervisor.id()) + .unwrap() + .started_at_micros; + Self { + supervisor, + web_pid, + _listener: listener, + address: format!("http://127.0.0.1:{port}/"), + supervisor_started_at_micros, + } + } +} + +impl Drop for LiveWebFixture { + fn drop(&mut self) { + if let Ok(child) = codexhost_platform::process_identity(self.web_pid) { + let _ = codexhost_platform::terminate_process_identity(&child, true); + } + let _ = self.supervisor.kill(); + let _ = self.supervisor.wait(); + } +} + +fn run_service_update_relaunch_scenario(fail_install: bool, restart_desktop_shell: bool) { + let fixture = Fixture::new(fail_install); + let live = LiveWebFixture::start(); + let package_root = fixture.root.join(PACKAGE); + let app_dir = package_root.join("app"); + fs::create_dir_all(&app_dir).unwrap(); + fs::write(app_dir.join("host-runtime.mjs"), "fixture").unwrap(); + fs::write(app_dir.join("web-server.mjs"), "fixture").unwrap(); + fs::write(package_root.join("package.json"), r#"{"version":"1.2.2"}"#).unwrap(); + fs::write( + app_dir.join("codexhost-distribution.json"), + r#"{"schemaVersion":1,"version":"1.2.2","distribution":"npm","target":"fixture"}"#, + ) + .unwrap(); + let data = fixture.root.join("data"); + fs::create_dir_all(&data).unwrap(); + let status_path = fixture.root.join("update-fixture/status-v1.json"); + fs::create_dir_all(status_path.parent().unwrap()).unwrap(); + let launcher = package_root.join("bin/codexhost"); + + let host_ready = |version: &str| { + serde_json::to_string(&serde_json::json!({ + "pid": live.supervisor.id(), + "started_at_micros": live.supervisor_started_at_micros, + "executable": "/bin/sh", + "runtime": app_dir.join("host-runtime.mjs"), + "version": version, + })) + .unwrap() + }; + let web_ready = |version: &str| { + serde_json::to_string(&serde_json::json!({ + "pid": live.supervisor.id(), + "started_at_micros": live.supervisor_started_at_micros, + "executable": launcher, + "runtime": app_dir.join("web-server.mjs"), + "version": version, + "web_pid": live.web_pid, + "address": live.address, + })) + .unwrap() + }; + let templates = fixture.root.join("templates"); + fs::create_dir_all(&templates).unwrap(); + for version in ["1.2.2", "1.2.3"] { + fs::write( + templates.join(format!("host-{version}.json")), + host_ready(version), + ) + .unwrap(); + fs::write( + templates.join(format!("web-{version}.json")), + web_ready(version), + ) + .unwrap(); + } + fs::write( + fixture.root.join("install.sh"), + format!( + r#"set -eu +if [ "$1" = root ]; then echo "$HOME/node_modules"; exit 0; fi +[ ! -f "$HOME/web-running" ] +[ ! -f "$HOME/host-running" ] +printf 'install\n' >> "$HOME/order" +if [ "{fail}" = "1" ]; then exit 1; fi +printf '{{"schemaVersion":1,"version":"1.2.3","distribution":"npm","target":"fixture"}}' > "{dist}" +"#, + fail = usize::from(fail_install), + dist = app_dir.join("codexhost-distribution.json").display(), + ), + ) + .unwrap(); + fs::write( + &launcher, + format!( + r#"#!/bin/sh +set -eu +case "$1" in + stop-for-update) + printf 'stop\n' >> "$HOME/order" + rm -f "$HOME/web-running" "$HOME/host-running" "$CODEXHOST_DATA_DIR/shared-host-ready.json" "$CODEXHOST_DATA_DIR/web-service-ready.json" + ;; + web) + printf 'web\n' >> "$HOME/order" + ver=1.2.2 + if grep -q '"1.2.3"' "{dist}"; then ver=1.2.3; fi + cp "{templates}/host-$ver.json" "$CODEXHOST_DATA_DIR/shared-host-ready.json" + cp "{templates}/web-$ver.json" "$CODEXHOST_DATA_DIR/web-service-ready.json" + ;; + app) + printf 'app\n' >> "$HOME/order" + cp "{status}" "$HOME/app-observed-status.json" + printf '%s|%s|%s|%s|%s\n' "$CODEXHOST_DATA_DIR" "$CODEXHOST_NPM_NODE_PATH" "$CODEXHOST_NPM_CLI_PATH" "$CODEXHOST_NPM_LAUNCHER_PATH" "$CODEXHOST_NPM_PACKAGE_ROOT" > "$HOME/app-env.tmp" + mv "$HOME/app-env.tmp" "$HOME/app-env.txt" + ;; + *) + exit 1 + ;; +esac +"#, + dist = app_dir.join("codexhost-distribution.json").display(), + templates = templates.display(), + status = status_path.display(), + ), + ) + .unwrap(); + fs::set_permissions(&launcher, fs::Permissions::from_mode(0o755)).unwrap(); + + let path = fixture.root.join("request.json"); + let mut request: serde_json::Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap(); + request["service_managed"] = true.into(); + request["restart_target"] = "web".into(); + if restart_desktop_shell { + request["restart_desktop_shell"] = true.into(); + } + request["data_directory"] = serde_json::to_value(&data).unwrap(); + request["status_path"] = serde_json::to_value(&status_path).unwrap(); + let lock_path = fixture.root.join("active-update-v1.lock"); + fs::write( + &lock_path, + serde_json::to_vec(&serde_json::json!({ + "ownerPid": fixture.owner.id(), "statusPath": status_path, + })) + .unwrap(), + ) + .unwrap(); + fs::write(&path, serde_json::to_vec(&request).unwrap()).unwrap(); + + let mut updater = Command::new(env!("CARGO_BIN_EXE_codexhost-updater")) + .args(["apply", "--request"]) + .arg(&path) + .env_clear() + .env("PATH", "/usr/bin:/bin") + .env("HOME", &fixture.root) + .env("USERPROFILE", &fixture.root) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(15); + while !status_path.exists() { + assert!( + Instant::now() < deadline, + "updater did not acknowledge handoff" + ); + thread::sleep(Duration::from_millis(20)); + } + let transferred = fixture.root.join("transferred.lock"); + fs::write( + &transferred, + serde_json::to_vec(&serde_json::json!({ + "ownerPid": updater.id(), "statusPath": status_path, + })) + .unwrap(), + ) + .unwrap(); + fs::rename(transferred, lock_path).unwrap(); + + let exit_status = loop { + if let Some(status) = updater.try_wait().unwrap() { + break status; + } + if Instant::now() >= deadline { + let _ = updater.kill(); + let _ = updater.wait(); + panic!( + "updater did not finish; status={:?}, order={:?}", + fs::read_to_string(&status_path), + fs::read_to_string(fixture.root.join("order")), + ); + } + thread::sleep(Duration::from_millis(20)); + }; + assert_eq!(exit_status.success(), !fail_install); + + let final_status: serde_json::Value = + serde_json::from_slice(&fs::read(&status_path).unwrap()).unwrap(); + if fail_install { + assert_eq!(final_status["phase"], "failed"); + assert!( + final_status["error"] + .as_str() + .unwrap() + .contains("service recovery succeeded") + ); + } else { + assert_eq!(final_status["phase"], "succeeded"); + } + + if restart_desktop_shell { + let app_env_path = fixture.root.join("app-env.txt"); + let until = Instant::now() + Duration::from_secs(5); + while !app_env_path.exists() { + assert!(Instant::now() < until, "desktop shell relaunch did not run"); + thread::sleep(Duration::from_millis(20)); + } + let observed_status: serde_json::Value = serde_json::from_slice( + &fs::read(fixture.root.join("app-observed-status.json")).unwrap(), + ) + .unwrap(); + assert_eq!( + observed_status["phase"], + if fail_install { "failed" } else { "succeeded" }, + "app relaunch must observe the terminal update status" + ); + let env_line = fs::read_to_string(&app_env_path).unwrap(); + let parts = env_line.trim_end().split('|').collect::>(); + assert_eq!(parts[0], data.to_string_lossy()); + assert_eq!(parts[1], "/bin/sh"); + assert_eq!(parts[2], fixture.root.join("install.sh").to_string_lossy()); + assert_eq!(parts[3], fixture.root.join("launch.sh").to_string_lossy()); + assert_eq!( + PathBuf::from(parts[4]).canonicalize().unwrap(), + package_root.canonicalize().unwrap() + ); + assert_eq!( + fs::read_to_string(fixture.root.join("order")).unwrap(), + "stop\ninstall\nweb\napp\n" + ); + } else { + thread::sleep(Duration::from_millis(150)); + assert!(!fixture.root.join("app-env.txt").exists()); + assert_eq!( + fs::read_to_string(fixture.root.join("order")).unwrap(), + "stop\ninstall\nweb\n" + ); + } +} + +#[test] +fn desktop_shell_update_relaunches_app_after_success_and_rollback_without_affecting_web() { + run_service_update_relaunch_scenario(false, true); + run_service_update_relaunch_scenario(true, true); + run_service_update_relaunch_scenario(false, false); +}