Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 99 additions & 18 deletions crates/launcher/src/active_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ struct ActiveUpdateLock {
struct UpdateStatusProbe {
schema_version: u8,
phase: String,
#[serde(default)]
error: Option<String>,
}

#[derive(Deserialize)]
Expand Down Expand Up @@ -215,7 +217,7 @@ pub(crate) fn update_waiting_for_launcher_exit() -> io::Result<bool> {
)
}

fn read_update_phase(status_path: &Path) -> io::Result<Option<String>> {
fn read_update_status(status_path: &Path) -> io::Result<Option<UpdateStatusProbe>> {
let Some(status_bytes) = read_bounded_regular_file(status_path)? else {
return Ok(None);
};
Expand All @@ -224,28 +226,42 @@ fn read_update_phase(status_path: &Path) -> io::Result<Option<String>> {
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<UpdateStatusProbe>, service: bool) -> io::Result<bool> {
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}"
)));
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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");
}
}
22 changes: 19 additions & 3 deletions crates/launcher/src/desktop_shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,25 @@ fn read_record(path: &Path) -> std::io::Result<Option<Vec<u8>>> {
}
}

fn live_owner(bytes: &[u8]) -> Option<ProcessIdentity> {
serde_json::from_slice::<ReadyOwner>(bytes)
.ok()
.and_then(|record| process_instance(record.pid, record.started_at_micros))
}

pub fn running(data: &Path) -> std::io::Result<bool> {
Ok(read_record(&data.join(READY))?
.as_deref()
.and_then(live_owner)
.is_some())
}

pub fn stop(data: &Path) -> Result<bool, Box<dyn Error>> {
let path = data.join(READY);
let Some(bytes) = read_record(&path)? else {
return Ok(false);
};
let owner = serde_json::from_slice::<ReadyOwner>(&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)?;
}
Expand All @@ -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();
Expand All @@ -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());
Expand All @@ -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();
Expand Down Expand Up @@ -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();
}
Expand Down
101 changes: 90 additions & 11 deletions crates/launcher/src/service_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ fn invalid(message: impl Into<String>) -> 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",
Expand All @@ -26,22 +31,40 @@ 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(())
}

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(
Expand Down Expand Up @@ -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");
}
}
Expand All @@ -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();
}
}
Loading
Loading