From 7d8e2dd6c5b29e1e80709cb051b163794edf2f27 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Mon, 7 Sep 2026 17:52:31 +0000 Subject: [PATCH] Make app-server daemon automatic updates configurable (#43542) ## Why The managed daemon's updater used a fixed hourly cadence with no saved preference to disable automatic updates. ## What changed - Read `updater.autoUpdateEnabled` and `updater.updateIntervalMinutes` from `CODEX_HOME/app-server-daemon/settings.json`, defaulting to enabled with a 60-minute interval. Keep the initial five-minute delay and require a positive interval. - Apply the enabled preference during daemon lifecycle operations and re-read settings before updates and recurring waits. Preserve updater preferences and unknown fields when saving remote-control settings, using atomic file replacement. - Signal the updater's process group on Unix so stopping it also terminates installer children. Allow daemon shutdown even when settings are malformed. - Document updater configuration and remote-control preference behavior. Manual `codex update` remains unaffected. ## Testing Add tests for settings preservation, interval validation, recurring waits, enabling and disabling updates across restart and bootstrap, Unix installer termination, and shutdown with malformed settings. GitOrigin-RevId: 5dbb72c5939e9ced2390b3760a7265608c8b61a0 --- codex-rs/app-server-daemon/README.md | 38 +++-- codex-rs/app-server-daemon/src/backend/pid.rs | 18 +++ .../src/backend/pid_tests.rs | 63 ++++++++ codex-rs/app-server-daemon/src/lib.rs | 26 ++- codex-rs/app-server-daemon/src/settings.rs | 153 +++++++++++++----- .../app-server-daemon/src/settings_tests.rs | 73 +++++++++ codex-rs/app-server-daemon/src/update_loop.rs | 58 ++++++- .../src/update_loop_tests.rs | 41 +++++ codex-rs/cli/tests/app_server_daemon.rs | 34 +++- 9 files changed, 441 insertions(+), 63 deletions(-) create mode 100644 codex-rs/app-server-daemon/src/settings_tests.rs diff --git a/codex-rs/app-server-daemon/README.md b/codex-rs/app-server-daemon/README.md index 95724b0f92..68ba3169cf 100644 --- a/codex-rs/app-server-daemon/README.md +++ b/codex-rs/app-server-daemon/README.md @@ -44,6 +44,17 @@ should parse that JSON rather than relying on human-readable text. Lifecycle responses report the resolved backend, socket path, local CLI version, and running app-server version when applicable. +Standalone-managed daemons check for updates after five minutes, then hourly by +default. Edit `CODEX_HOME/app-server-daemon/settings.json` to change this: + +```json +{"remoteControlEnabled": false, + "updater": {"autoUpdateEnabled": false, "updateIntervalMinutes": 120}} +``` + +Positive minute intervals have no configured cap. `daemon restart` applies the +enabled state; the next updater wait reads a new interval. `codex update` is unaffected. + ## Bootstrap flow For a new Linux or macOS machine: @@ -63,9 +74,9 @@ $codexHome = if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $HOME '.c `bootstrap` requires the standalone managed install. It records the daemon settings under `CODEX_HOME/app-server-daemon/`, starts app-server as a -pidfile-backed detached process. It launches a detached updater loop when the -installer selected the stable `latest` channel and the managed binary supports -the updater command. +pidfile-backed detached process. It launches a detached updater loop when +automatic updates are enabled, the installer selected the stable `latest` +channel, and the managed binary supports the updater command. ## Installation and update cases @@ -75,10 +86,9 @@ on Windows) and its managed binary under `CODEX_HOME/packages/standalone/current | Situation | What starts | Does this daemon fetch new binaries? | Does a running app-server eventually move to a newer binary on its own? | | --- | --- | --- | --- | -| Latest-channel installer has run; `start` is used | Managed binary and detached updater when supported | When supported, the platform's installer runs hourly. | When supported, the running server restarts with the new binary before the updater replaces itself. | -| Latest-channel installer has run; `bootstrap` is used | Managed binary and detached updater when supported | When supported, the platform's installer runs hourly. | When supported, the running server restarts with the new binary before the updater replaces itself. | +| Latest-channel installer has run; `start` or `bootstrap` is used with automatic updates enabled | Managed binary and detached updater when supported | When supported, the platform's installer runs on the configured cadence. | When supported, the running server restarts with the new binary before the updater replaces itself. | | Installer selected an explicit release; `bootstrap` is used | Managed binary only | No; the selected release stays pinned. | No; an explicit restart uses the selected binary. | -| Another tool updates the managed binary | A fresh start or explicit restart uses it; a running server is reused. | Yes, when a latest-channel updater is running. | An updater that was running through the change compares binary contents on its next successful installer pass and refreshes the server first. | +| Another tool updates the managed binary | A fresh start or explicit restart uses it; a running server is reused. | Yes, when a latest-channel updater is running, on the configured cadence. | An updater that was running through the change compares binary contents on its next successful installer pass and refreshes the server first. | ### Standalone installs @@ -87,8 +97,8 @@ For installs created by either platform's standalone installer: - lifecycle commands always use the standalone managed binary path - `bootstrap` is supported - managed `start`, `restart`, and `bootstrap` ensure a single detached pid-backed - updater loop only for a stable latest-channel release whose managed binary - supports the updater command + updater loop only when automatic updates are enabled for a stable latest-channel + release whose managed binary supports the updater command - the installer records the latest-channel selection alongside `current`; selecting an explicit release clears it, even if that version is currently latest. The updater checks the selection again while holding the install lock @@ -126,9 +136,13 @@ JSON-RPC initialize handshake on the Unix control socket. for future starts. If a managed app-server is already running, they restart it so the new setting takes effect immediately. -Top-level `codex remote-control` bootstraps with `--remote-control` when the -updater loop is not running. Otherwise it enables remote control and starts the -daemon normally. +Top-level `codex remote-control start` enables and persists remote control for +the managed daemon, overriding a saved disabled value. It starts or bootstraps +the daemon as needed. Plain `codex remote-control` runs a separate foreground +server and does not change daemon settings; `codex remote-control stop` stops +the managed daemon without clearing its saved remote-control preference. +`daemon start` and `daemon restart` use that saved preference. `daemon bootstrap` +sets it according to `--remote-control` (disabled when omitted). `stop` sends a graceful termination request first, then sends a second termination signal after the grace window if the process is still alive. @@ -141,7 +155,7 @@ or `bootstrap` does not race another in-flight lifecycle operation. The daemon stores its local state under `CODEX_HOME/app-server-daemon/`: -- `settings.json` for persisted launch settings +- `settings.json` for remote-control launch settings and updater preferences - `app-server.pid` for the app-server process record - `app-server-updater.pid` for the pid-backed standalone updater loop - `daemon.lock` for daemon-wide lifecycle serialization diff --git a/codex-rs/app-server-daemon/src/backend/pid.rs b/codex-rs/app-server-daemon/src/backend/pid.rs index e34e170880..8da7cc68e4 100644 --- a/codex-rs/app-server-daemon/src/backend/pid.rs +++ b/codex-rs/app-server-daemon/src/backend/pid.rs @@ -361,6 +361,9 @@ impl PidBackend { fn terminate_process(&self, pid: u32) -> Result<()> { match self.command_kind { PidCommandKind::AppServer { .. } => terminate_process(pid), + #[cfg(unix)] + PidCommandKind::UpdateLoop => terminate_process_group(pid), + #[cfg(not(unix))] PidCommandKind::UpdateLoop => terminate_process(pid), } } @@ -467,6 +470,21 @@ fn force_terminate_process(pid: u32) -> Result<()> { Err(err).with_context(|| format!("failed to force terminate pid-managed app server {pid}")) } +#[cfg(unix)] +fn terminate_process_group(pid: u32) -> Result<()> { + let raw_pid = libc::pid_t::try_from(pid) + .with_context(|| format!("pid-managed updater pid {pid} is out of range"))?; + let result = unsafe { libc::kill(-raw_pid, libc::SIGTERM) }; + if result == 0 { + return Ok(()); + } + let err = std::io::Error::last_os_error(); + if err.raw_os_error() == Some(libc::ESRCH) { + return Ok(()); + } + Err(err).with_context(|| format!("failed to terminate pid-managed updater group {pid}")) +} + #[cfg(unix)] fn force_terminate_process_group(pid: u32) -> Result<()> { let raw_pid = libc::pid_t::try_from(pid) diff --git a/codex-rs/app-server-daemon/src/backend/pid_tests.rs b/codex-rs/app-server-daemon/src/backend/pid_tests.rs index ac417232cb..1474bdce1c 100644 --- a/codex-rs/app-server-daemon/src/backend/pid_tests.rs +++ b/codex-rs/app-server-daemon/src/backend/pid_tests.rs @@ -4,6 +4,8 @@ use std::time::Duration; use pretty_assertions::assert_eq; use tempfile::TempDir; +#[cfg(unix)] +use tokio::time::sleep; use codex_app_server_transport::REMOTE_CONTROL_DISABLED_ENV_VAR; @@ -226,6 +228,67 @@ async fn stop_reaps_untracked_app_server_child() { assert!(!pid_file.exists()); } +#[cfg(unix)] +#[tokio::test] +async fn stopping_updater_signals_its_installer_process_group() { + use std::os::unix::process::CommandExt; + + let temp = TempDir::new().expect("temp dir"); + let ready = temp.path().join("installer.ready"); + let stopped = temp.path().join("installer.stopped"); + let mut command = std::process::Command::new("/bin/sh"); + command + .args([ + "-c", + "sh -c 'trap \"touch $STOP_MARKER; exit 0\" TERM; touch $READY_MARKER; while :; do sleep 1; done' & wait", + ]) + .env("READY_MARKER", &ready) + .env("STOP_MARKER", &stopped) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + unsafe { + command.pre_exec(|| { + if libc::setsid() == -1 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + let mut child = command.spawn().expect("spawn updater shim"); + let pid = child.id(); + let deadline = tokio::time::Instant::now() + Duration::from_secs(2); + while !ready.exists() { + assert!( + tokio::time::Instant::now() < deadline, + "installer did not start" + ); + sleep(Duration::from_millis(10)).await; + } + let pid_file = temp.path().join("updater.pid"); + tokio::fs::write( + &pid_file, + serde_json::to_vec(&PidRecord { + pid, + process_start_time: read_process_start_time(pid).await.expect("start time"), + }) + .expect("serialize pid"), + ) + .await + .expect("write pid file"); + let backend = PidBackend::new_update_loop(temp.path().join("codex"), pid_file); + backend.stop().await.expect("stop updater"); + // The backend normally reaps the shim, so a second wait may return ECHILD. + let _ = child.wait(); + let deadline = tokio::time::Instant::now() + Duration::from_secs(2); + while !stopped.exists() { + assert!( + tokio::time::Instant::now() < deadline, + "installer was not stopped" + ); + sleep(Duration::from_millis(10)).await; + } +} + #[cfg(unix)] #[tokio::test] async fn exited_unreaped_updater_is_reaped() { diff --git a/codex-rs/app-server-daemon/src/lib.rs b/codex-rs/app-server-daemon/src/lib.rs index e5d5208897..280786d98d 100644 --- a/codex-rs/app-server-daemon/src/lib.rs +++ b/codex-rs/app-server-daemon/src/lib.rs @@ -356,6 +356,11 @@ impl Daemon { "app server is running but is not managed by codex app-server daemon" )); } + if !settings.auto_update_enabled { + backend::pid_update_loop_backend(self.backend_paths(&settings)) + .stop() + .await?; + } self.ensure_managed_codex_bin()?; if let Some(backend) = self.running_backend_instance(&settings).await? { @@ -456,7 +461,8 @@ impl Daemon { } async fn stop(&self) -> Result { - let settings = self.load_settings().await?; + // Stopping a managed process does not require readable settings. + let settings = DaemonSettings::default(); if let Some(backend) = self.running_backend_instance(&settings).await? { backend.stop().await?; return Ok(self @@ -645,9 +651,8 @@ impl Daemon { async fn bootstrap_locked(&self, options: BootstrapOptions) -> Result { self.ensure_managed_codex_bin()?; - let settings = DaemonSettings { - remote_control_enabled: options.remote_control_enabled, - }; + let mut settings = self.load_settings().await?; + settings.remote_control_enabled = options.remote_control_enabled; if client::probe(&self.socket_path).await.is_ok() && self.running_backend(&settings).await?.is_none() { @@ -657,6 +662,9 @@ impl Daemon { } settings.save(&self.settings_file).await?; + backend::pid_update_loop_backend(self.backend_paths(&settings)) + .stop() + .await?; if let Some(backend) = self.running_backend_instance(&settings).await? { backend.stop().await?; } @@ -664,9 +672,6 @@ impl Daemon { let backend = backend::pid_backend(self.backend_paths(&settings)); backend.start().await?; let info = self.wait_until_ready().await?; - backend::pid_update_loop_backend(self.backend_paths(&settings)) - .stop() - .await?; let auto_update_enabled = self.ensure_managed_updater(&settings).await?; let managed_codex_version = self.managed_codex_version_best_effort().await; Ok(BootstrapOutput { @@ -717,6 +722,10 @@ impl Daemon { async fn ensure_managed_updater(&self, settings: &DaemonSettings) -> Result { let updater = backend::pid_update_loop_backend(self.backend_paths(settings)); + if !settings.auto_update_enabled { + updater.stop().await?; + return Ok(false); + } if !self.is_stable_standalone_release()? { // An installer publishes current and the latest marker separately. // Keep its updater alive while that publication may be in progress. @@ -773,7 +782,8 @@ impl Daemon { } async fn is_bootstrapped(&self, settings: &DaemonSettings) -> Result { - if !self.is_stable_standalone_release()? + if !settings.auto_update_enabled + || !self.is_stable_standalone_release()? || !managed_install::supports_daemon_update_loop(&self.managed_codex_bin).await { return Ok(self.running_backend_instance(settings).await?.is_some()); diff --git a/codex-rs/app-server-daemon/src/settings.rs b/codex-rs/app-server-daemon/src/settings.rs index 18b9c9faf7..384b3bc709 100644 --- a/codex-rs/app-server-daemon/src/settings.rs +++ b/codex-rs/app-server-daemon/src/settings.rs @@ -1,30 +1,99 @@ use std::path::Path; +use std::time::Duration; use anyhow::Context; use anyhow::Result; +use anyhow::ensure; use serde::Deserialize; -use serde::Serialize; +use serde::de::DeserializeOwned; +use serde_json::Map; +use serde_json::Value; use tokio::fs; -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] +pub(crate) const DEFAULT_UPDATE_INTERVAL_MINUTES: u32 = 60; + +#[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct DaemonSettings { pub(crate) remote_control_enabled: bool, + pub(crate) auto_update_enabled: bool, + pub(crate) update_interval_minutes: u32, +} + +impl Default for DaemonSettings { + fn default() -> Self { + Self { + remote_control_enabled: false, + auto_update_enabled: true, + update_interval_minutes: DEFAULT_UPDATE_INTERVAL_MINUTES, + } + } +} + +#[derive(Default, Deserialize)] +#[serde(rename_all = "camelCase")] +struct StoredSettings { + #[serde(default)] + remote_control_enabled: bool, + #[serde(default)] + updater: UpdaterSettings, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct UpdaterSettings { + #[serde(default = "default_auto_update_enabled")] + pub(crate) auto_update_enabled: bool, + #[serde(default = "default_update_interval_minutes")] + pub(crate) update_interval_minutes: u32, +} + +impl Default for UpdaterSettings { + fn default() -> Self { + Self { + auto_update_enabled: default_auto_update_enabled(), + update_interval_minutes: default_update_interval_minutes(), + } + } +} + +fn default_auto_update_enabled() -> bool { + true +} + +fn default_update_interval_minutes() -> u32 { + DEFAULT_UPDATE_INTERVAL_MINUTES +} + +impl UpdaterSettings { + pub(crate) async fn load(settings_file: &Path) -> Result { + let settings: StoredSettings = read_settings(settings_file).await?; + let settings = settings.updater; + settings.validate()?; + Ok(settings) + } + + pub(crate) fn validate(&self) -> Result<()> { + ensure!( + self.update_interval_minutes > 0, + "update interval must be positive" + ); + Ok(()) + } + + pub(crate) fn update_interval(&self, minute: Duration) -> Duration { + minute * self.update_interval_minutes + } } impl DaemonSettings { pub(crate) async fn load(path: &Path) -> Result { - let contents = match fs::read_to_string(path).await { - Ok(contents) => contents, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()), - Err(err) => { - return Err(err) - .with_context(|| format!("failed to read daemon settings {}", path.display())); - } - }; - - serde_json::from_str(&contents) - .with_context(|| format!("failed to parse daemon settings {}", path.display())) + let settings: StoredSettings = read_settings(path).await?; + settings.updater.validate()?; + Ok(Self { + remote_control_enabled: settings.remote_control_enabled, + auto_update_enabled: settings.updater.auto_update_enabled, + update_interval_minutes: settings.updater.update_interval_minutes, + }) } pub(crate) async fn save(&self, path: &Path) -> Result<()> { @@ -36,28 +105,40 @@ impl DaemonSettings { ) })?; } - - let contents = serde_json::to_vec_pretty(self).context("failed to serialize settings")?; - fs::write(path, contents) - .await - .with_context(|| format!("failed to write daemon settings {}", path.display())) - } -} - -#[cfg(all(test, unix))] -mod tests { - use pretty_assertions::assert_eq; - - use super::DaemonSettings; - - #[test] - fn daemon_settings_use_camel_case_json() { - assert_eq!( - serde_json::to_string(&DaemonSettings { - remote_control_enabled: true, - }) - .expect("serialize"), - r#"{"remoteControlEnabled":true}"# + let mut settings: Map = read_settings(path).await?; + settings.insert( + "remoteControlEnabled".to_string(), + Value::Bool(self.remote_control_enabled), ); + let contents = + serde_json::to_vec_pretty(&settings).context("failed to serialize settings")?; + let temporary_path = path.with_extension("tmp"); + fs::write(&temporary_path, contents) + .await + .with_context(|| { + format!( + "failed to write daemon settings {}", + temporary_path.display() + ) + })?; + fs::rename(&temporary_path, path) + .await + .with_context(|| format!("failed to replace daemon settings {}", path.display())) } } + +async fn read_settings(path: &Path) -> Result { + let contents = match fs::read_to_string(path).await { + Ok(contents) => contents, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(T::default()), + Err(err) => { + return Err(err).with_context(|| format!("failed to read settings {}", path.display())); + } + }; + serde_json::from_str(&contents) + .with_context(|| format!("failed to parse settings {}", path.display())) +} + +#[cfg(test)] +#[path = "settings_tests.rs"] +mod tests; diff --git a/codex-rs/app-server-daemon/src/settings_tests.rs b/codex-rs/app-server-daemon/src/settings_tests.rs new file mode 100644 index 0000000000..64d2588510 --- /dev/null +++ b/codex-rs/app-server-daemon/src/settings_tests.rs @@ -0,0 +1,73 @@ +use pretty_assertions::assert_eq; +use tempfile::TempDir; + +use super::DaemonSettings; + +#[tokio::test] +async fn remote_control_save_preserves_updater_settings() { + let temp = TempDir::new().expect("temp dir"); + let path = temp.path().join("settings.json"); + tokio::fs::write(&path, r#"{"remoteControlEnabled":true}"#) + .await + .expect("write legacy settings"); + + let settings = DaemonSettings::load(&path).await.expect("load settings"); + assert_eq!( + settings, + DaemonSettings { + remote_control_enabled: true, + ..DaemonSettings::default() + } + ); + + tokio::fs::write( + &path, + r#"{"remoteControlEnabled":true,"updater":{"autoUpdateEnabled":false,"updateIntervalMinutes":17},"futureSetting":42}"#, + ) + .await + .expect("write settings"); + let updated = DaemonSettings { + remote_control_enabled: false, + ..DaemonSettings::load(&path) + .await + .expect("load updater settings") + }; + updated.save(&path).await.expect("save remote control"); + assert_eq!( + serde_json::from_slice::( + &tokio::fs::read(&path).await.expect("read settings") + ) + .expect("parse settings"), + serde_json::json!({ + "remoteControlEnabled": false, + "updater": {"autoUpdateEnabled": false, "updateIntervalMinutes": 17}, + "futureSetting": 42, + }) + ); +} + +#[tokio::test] +async fn update_interval_accepts_long_values_and_rejects_zero() { + let temp = TempDir::new().expect("temp dir"); + let path = temp.path().join("settings.json"); + for minutes in [u32::MAX, 0] { + tokio::fs::write( + &path, + serde_json::to_vec(&serde_json::json!({ + "updater": {"updateIntervalMinutes": minutes}, + })) + .expect("serialize invalid settings"), + ) + .await + .expect("write invalid settings"); + let loaded = DaemonSettings::load(&path).await; + if minutes == 0 { + assert!(loaded.is_err()); + } else { + assert_eq!( + loaded.expect("load long interval").update_interval_minutes, + minutes + ); + } + } +} diff --git a/codex-rs/app-server-daemon/src/update_loop.rs b/codex-rs/app-server-daemon/src/update_loop.rs index 60ae39c977..fd545decd3 100644 --- a/codex-rs/app-server-daemon/src/update_loop.rs +++ b/codex-rs/app-server-daemon/src/update_loop.rs @@ -31,10 +31,12 @@ use crate::UpdaterRefreshMode; use crate::managed_install::ExecutableIdentity; use crate::managed_install::executable_identity; use crate::managed_install::resolved_managed_codex_bin; +#[cfg(windows)] +use crate::settings::DaemonSettings; +use crate::settings::UpdaterSettings; const INITIAL_UPDATE_DELAY: Duration = Duration::from_secs(5 * 60); const RESTART_RETRY_INTERVAL: Duration = Duration::from_millis(50); -const UPDATE_INTERVAL: Duration = Duration::from_secs(60 * 60); #[cfg(unix)] const INSTALL_URL: &str = "https://chatgpt.com/codex/install.sh"; #[cfg(windows)] @@ -47,9 +49,8 @@ pub(crate) async fn run(http_client_factory: HttpClientFactory) -> Result<()> { #[cfg(windows)] let updater = { let daemon = Daemon::from_environment()?; - crate::backend::pid_update_loop_backend( - daemon.backend_paths(&daemon.load_settings().await?), - ) + // Updater ownership needs only paths, not settings that may be mid-edit. + crate::backend::pid_update_loop_backend(daemon.backend_paths(&DaemonSettings::default())) }; #[cfg(windows)] updater.wait_for_ownership().await?; @@ -67,7 +68,18 @@ pub(crate) async fn run(http_client_factory: HttpClientFactory) -> Result<()> { if sleep_or_terminate(INITIAL_UPDATE_DELAY, &mut terminate).await { return Ok(()); } + let daemon = Daemon::from_environment()?; loop { + match UpdaterSettings::load(&daemon.settings_file).await { + Ok(settings) if !settings.auto_update_enabled => return Ok(()), + Err(_) => { + if sleep_or_terminate(Duration::from_secs(60), &mut terminate).await { + return Ok(()); + } + continue; + } + Ok(_) => {} + } // Failed successor cleanup leaves its PID published. The predecessor // must stop instead of installing again without ownership. #[cfg(windows)] @@ -76,12 +88,34 @@ pub(crate) async fn run(http_client_factory: HttpClientFactory) -> Result<()> { Ok(UpdateLoopControl::Continue) | Err(_) => {} Ok(UpdateLoopControl::Stop) => return Ok(()), } - if sleep_or_terminate(UPDATE_INTERVAL, &mut terminate).await { - return Ok(()); + match wait_for_next_check( + &daemon.settings_file, + Duration::from_secs(60), + &mut terminate, + ) + .await + { + Ok(true) => return Ok(()), + Ok(false) => {} + Err(_) => { + if sleep_or_terminate(Duration::from_secs(60), &mut terminate).await { + return Ok(()); + } + } } } } +async fn wait_for_next_check( + settings_file: &Path, + minute: Duration, + terminate: &mut Signal, +) -> Result { + let settings = UpdaterSettings::load(settings_file).await?; + Ok(!settings.auto_update_enabled + || sleep_or_terminate(settings.update_interval(minute), terminate).await) +} + async fn sleep_or_terminate(duration: Duration, terminate: &mut Signal) -> bool { tokio::select! { _ = sleep(duration) => false, @@ -100,6 +134,12 @@ async fn update_once( terminate: &mut Signal, ) -> Result { let daemon = Daemon::from_environment()?; + if !UpdaterSettings::load(&daemon.settings_file) + .await? + .auto_update_enabled + { + return Ok(UpdateLoopControl::Stop); + } if !daemon.is_stable_standalone_release()? { // An installer can be between changing current and publishing its // latest-channel marker. Retry after the interval instead of exiting. @@ -126,6 +166,12 @@ async fn update_once( .any(|window| window == b"CODEX_INSTALL_IF_LATEST"), "standalone installer does not support guarded updates" ); + if !UpdaterSettings::load(&daemon.settings_file) + .await? + .auto_update_enabled + { + return Ok(UpdateLoopControl::Stop); + } if !daemon.is_stable_standalone_release()? { return Ok(UpdateLoopControl::Continue); } diff --git a/codex-rs/app-server-daemon/src/update_loop_tests.rs b/codex-rs/app-server-daemon/src/update_loop_tests.rs index aebe19e602..69c69cb3cb 100644 --- a/codex-rs/app-server-daemon/src/update_loop_tests.rs +++ b/codex-rs/app-server-daemon/src/update_loop_tests.rs @@ -3,12 +3,16 @@ use std::sync::Mutex; use std::time::Duration; use pretty_assertions::assert_eq; +#[cfg(unix)] +use tempfile::TempDir; use super::INSTALL_URL; use super::InstallerHttp; use super::InstallerResponse; use super::fetch_installer_script; use super::update_modes_for_identities; +#[cfg(unix)] +use super::wait_for_next_check; use crate::RestartMode; use crate::UpdaterRefreshMode; use crate::managed_install::executable_identity_from_bytes; @@ -38,6 +42,43 @@ fn changed_updater_forces_refresh_even_when_version_may_match() { ); } +#[cfg(unix)] +#[tokio::test] +async fn recurring_wait_reads_persisted_interval_and_enabled_state() { + let temp = TempDir::new().expect("temp dir"); + let settings_file = temp.path().join("settings.json"); + tokio::fs::write(&settings_file, r#"{"updater":{"updateIntervalMinutes":2}}"#) + .await + .expect("write settings"); + let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) + .expect("install signal handler"); + let started = tokio::time::Instant::now(); + assert_eq!( + tokio::time::timeout( + Duration::from_secs(1), + wait_for_next_check(&settings_file, Duration::from_millis(10), &mut terminate), + ) + .await + .expect("recurring wait should finish") + .expect("load persisted settings"), + false + ); + assert!(started.elapsed() >= Duration::from_millis(20)); + + tokio::fs::write( + &settings_file, + r#"{"updater":{"autoUpdateEnabled":false,"updateIntervalMinutes":2}}"#, + ) + .await + .expect("disable updates"); + assert_eq!( + wait_for_next_check(&settings_file, Duration::from_millis(10), &mut terminate) + .await + .expect("reload settings"), + true + ); +} + #[tokio::test] async fn installer_fetch_uses_exact_url_and_preserves_bytes() { let script = b"#!/bin/sh\nprintf 'update bytes'\n".to_vec(); diff --git a/codex-rs/cli/tests/app_server_daemon.rs b/codex-rs/cli/tests/app_server_daemon.rs index 2539e55096..08e164140e 100644 --- a/codex-rs/cli/tests/app_server_daemon.rs +++ b/codex-rs/cli/tests/app_server_daemon.rs @@ -184,7 +184,39 @@ fn managed_start_keeps_updater_on_marker_mismatch_but_stops_it_for_pin() -> Resu } #[test] -fn start_does_not_launch_updater_for_unmanaged_app_server() -> Result<()> { +fn restart_applies_saved_updater_preference() -> Result<()> { + let daemon = TestDaemon::new()?; + assert_eq!(daemon.lifecycle("start")?["status"], "started"); + let updater_pid = daemon.pid("app-server-updater.pid")?; + let settings = daemon.home.path().join("app-server-daemon/settings.json"); + std::fs::write( + &settings, + serde_json::to_vec(&serde_json::json!({ + "updater": {"autoUpdateEnabled": false, "updateIntervalMinutes": 2}, + }))?, + )?; + assert_eq!(daemon.lifecycle("restart")?["status"], "restarted"); + wait_for_exit(updater_pid)?; + assert!(daemon.pid("app-server-updater.pid").is_err()); + assert_eq!(daemon.lifecycle("bootstrap")?["autoUpdateEnabled"], false); + assert!(daemon.pid("app-server-updater.pid").is_err()); + + std::fs::write( + &settings, + serde_json::to_vec(&serde_json::json!({ + "updater": {"autoUpdateEnabled": true, "updateIntervalMinutes": 2}, + }))?, + )?; + assert_eq!(daemon.lifecycle("restart")?["status"], "restarted"); + assert_ne!(daemon.pid("app-server-updater.pid")?, updater_pid); + + std::fs::write(&settings, "{malformed")?; + assert_eq!(daemon.lifecycle("stop")?["status"], "stopped"); + Ok(()) +} + +#[test] +fn unmanaged_app_server_does_not_launch_updater() -> Result<()> { let mut daemon = TestDaemon::new()?; daemon.unmanaged = Some( daemon