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
This commit is contained in:
Eric Traut authored and copyberry committed 2026-09-07 18:26:04 +00:00
1 parent cc737efd65
commit 7d8e2dd6c5
9 files changed
+441 -63

No files matched your search

+26 -12
View File
@@ -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 responses report the resolved backend, socket path, local CLI version, and
running app-server version when applicable. 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 ## Bootstrap flow
For a new Linux or macOS machine: 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 `bootstrap` requires the standalone managed install. It records the daemon
settings under `CODEX_HOME/app-server-daemon/`, starts app-server as a settings under `CODEX_HOME/app-server-daemon/`, starts app-server as a
pidfile-backed detached process. It launches a detached updater loop when the pidfile-backed detached process. It launches a detached updater loop when
installer selected the stable `latest` channel and the managed binary supports automatic updates are enabled, the installer selected the stable `latest`
the updater command. channel, and the managed binary supports the updater command.
## Installation and update cases ## 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? | | 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; `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. |
| 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. |
| 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. | | 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 ### Standalone installs
@@ -87,8 +97,8 @@ For installs created by either platform's standalone installer:
- lifecycle commands always use the standalone managed binary path - lifecycle commands always use the standalone managed binary path
- `bootstrap` is supported - `bootstrap` is supported
- managed `start`, `restart`, and `bootstrap` ensure a single detached pid-backed - managed `start`, `restart`, and `bootstrap` ensure a single detached pid-backed
updater loop only for a stable latest-channel release whose managed binary updater loop only when automatic updates are enabled for a stable latest-channel
supports the updater command release whose managed binary supports the updater command
- the installer records the latest-channel selection alongside `current`; - the installer records the latest-channel selection alongside `current`;
selecting an explicit release clears it, even if that version is currently selecting an explicit release clears it, even if that version is currently
latest. The updater checks the selection again while holding the install lock 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 for future starts. If a managed app-server is already running, they restart it
so the new setting takes effect immediately. so the new setting takes effect immediately.
Top-level `codex remote-control` bootstraps with `--remote-control` when the Top-level `codex remote-control start` enables and persists remote control for
updater loop is not running. Otherwise it enables remote control and starts the the managed daemon, overriding a saved disabled value. It starts or bootstraps
daemon normally. 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 `stop` sends a graceful termination request first, then sends a second
termination signal after the grace window if the process is still alive. 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/`: 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.pid` for the app-server process record
- `app-server-updater.pid` for the pid-backed standalone updater loop - `app-server-updater.pid` for the pid-backed standalone updater loop
- `daemon.lock` for daemon-wide lifecycle serialization - `daemon.lock` for daemon-wide lifecycle serialization
@@ -361,6 +361,9 @@ impl PidBackend {
fn terminate_process(&self, pid: u32) -> Result<()> { fn terminate_process(&self, pid: u32) -> Result<()> {
match self.command_kind { match self.command_kind {
PidCommandKind::AppServer { .. } => terminate_process(pid), PidCommandKind::AppServer { .. } => terminate_process(pid),
#[cfg(unix)]
PidCommandKind::UpdateLoop => terminate_process_group(pid),
#[cfg(not(unix))]
PidCommandKind::UpdateLoop => terminate_process(pid), 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}")) 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)] #[cfg(unix)]
fn force_terminate_process_group(pid: u32) -> Result<()> { fn force_terminate_process_group(pid: u32) -> Result<()> {
let raw_pid = libc::pid_t::try_from(pid) let raw_pid = libc::pid_t::try_from(pid)
@@ -4,6 +4,8 @@ use std::time::Duration;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use tempfile::TempDir; use tempfile::TempDir;
#[cfg(unix)]
use tokio::time::sleep;
use codex_app_server_transport::REMOTE_CONTROL_DISABLED_ENV_VAR; 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()); 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)] #[cfg(unix)]
#[tokio::test] #[tokio::test]
async fn exited_unreaped_updater_is_reaped() { async fn exited_unreaped_updater_is_reaped() {
+18 -8
View File
@@ -356,6 +356,11 @@ impl Daemon {
"app server is running but is not managed by codex app-server 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()?; self.ensure_managed_codex_bin()?;
if let Some(backend) = self.running_backend_instance(&settings).await? { if let Some(backend) = self.running_backend_instance(&settings).await? {
@@ -456,7 +461,8 @@ impl Daemon {
} }
async fn stop(&self) -> Result<LifecycleOutput> { async fn stop(&self) -> Result<LifecycleOutput> {
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? { if let Some(backend) = self.running_backend_instance(&settings).await? {
backend.stop().await?; backend.stop().await?;
return Ok(self return Ok(self
@@ -645,9 +651,8 @@ impl Daemon {
async fn bootstrap_locked(&self, options: BootstrapOptions) -> Result<BootstrapOutput> { async fn bootstrap_locked(&self, options: BootstrapOptions) -> Result<BootstrapOutput> {
self.ensure_managed_codex_bin()?; self.ensure_managed_codex_bin()?;
let settings = DaemonSettings { let mut settings = self.load_settings().await?;
remote_control_enabled: options.remote_control_enabled, settings.remote_control_enabled = options.remote_control_enabled;
};
if client::probe(&self.socket_path).await.is_ok() if client::probe(&self.socket_path).await.is_ok()
&& self.running_backend(&settings).await?.is_none() && self.running_backend(&settings).await?.is_none()
{ {
@@ -657,6 +662,9 @@ impl Daemon {
} }
settings.save(&self.settings_file).await?; 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? { if let Some(backend) = self.running_backend_instance(&settings).await? {
backend.stop().await?; backend.stop().await?;
} }
@@ -664,9 +672,6 @@ impl Daemon {
let backend = backend::pid_backend(self.backend_paths(&settings)); let backend = backend::pid_backend(self.backend_paths(&settings));
backend.start().await?; backend.start().await?;
let info = self.wait_until_ready().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 auto_update_enabled = self.ensure_managed_updater(&settings).await?;
let managed_codex_version = self.managed_codex_version_best_effort().await; let managed_codex_version = self.managed_codex_version_best_effort().await;
Ok(BootstrapOutput { Ok(BootstrapOutput {
@@ -717,6 +722,10 @@ impl Daemon {
async fn ensure_managed_updater(&self, settings: &DaemonSettings) -> Result<bool> { async fn ensure_managed_updater(&self, settings: &DaemonSettings) -> Result<bool> {
let updater = backend::pid_update_loop_backend(self.backend_paths(settings)); 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()? { if !self.is_stable_standalone_release()? {
// An installer publishes current and the latest marker separately. // An installer publishes current and the latest marker separately.
// Keep its updater alive while that publication may be in progress. // 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<bool> { async fn is_bootstrapped(&self, settings: &DaemonSettings) -> Result<bool> {
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 || !managed_install::supports_daemon_update_loop(&self.managed_codex_bin).await
{ {
return Ok(self.running_backend_instance(settings).await?.is_some()); return Ok(self.running_backend_instance(settings).await?.is_some());
+117 -36
View File
@@ -1,30 +1,99 @@
use std::path::Path; use std::path::Path;
use std::time::Duration;
use anyhow::Context; use anyhow::Context;
use anyhow::Result; use anyhow::Result;
use anyhow::ensure;
use serde::Deserialize; use serde::Deserialize;
use serde::Serialize; use serde::de::DeserializeOwned;
use serde_json::Map;
use serde_json::Value;
use tokio::fs; use tokio::fs;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub(crate) const DEFAULT_UPDATE_INTERVAL_MINUTES: u32 = 60;
#[serde(rename_all = "camelCase")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DaemonSettings { pub(crate) struct DaemonSettings {
pub(crate) remote_control_enabled: bool, 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<Self> {
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 { impl DaemonSettings {
pub(crate) async fn load(path: &Path) -> Result<Self> { pub(crate) async fn load(path: &Path) -> Result<Self> {
let contents = match fs::read_to_string(path).await { let settings: StoredSettings = read_settings(path).await?;
Ok(contents) => contents, settings.updater.validate()?;
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()), Ok(Self {
Err(err) => { remote_control_enabled: settings.remote_control_enabled,
return Err(err) auto_update_enabled: settings.updater.auto_update_enabled,
.with_context(|| format!("failed to read daemon settings {}", path.display())); update_interval_minutes: settings.updater.update_interval_minutes,
} })
};
serde_json::from_str(&contents)
.with_context(|| format!("failed to parse daemon settings {}", path.display()))
} }
pub(crate) async fn save(&self, path: &Path) -> Result<()> { pub(crate) async fn save(&self, path: &Path) -> Result<()> {
@@ -36,28 +105,40 @@ impl DaemonSettings {
) )
})?; })?;
} }
let mut settings: Map<String, Value> = read_settings(path).await?;
let contents = serde_json::to_vec_pretty(self).context("failed to serialize settings")?; settings.insert(
fs::write(path, contents) "remoteControlEnabled".to_string(),
.await Value::Bool(self.remote_control_enabled),
.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 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<T: DeserializeOwned + Default>(path: &Path) -> Result<T> {
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;
@@ -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::<serde_json::Value>(
&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
);
}
}
}
+52 -6
View File
@@ -31,10 +31,12 @@ use crate::UpdaterRefreshMode;
use crate::managed_install::ExecutableIdentity; use crate::managed_install::ExecutableIdentity;
use crate::managed_install::executable_identity; use crate::managed_install::executable_identity;
use crate::managed_install::resolved_managed_codex_bin; 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 INITIAL_UPDATE_DELAY: Duration = Duration::from_secs(5 * 60);
const RESTART_RETRY_INTERVAL: Duration = Duration::from_millis(50); const RESTART_RETRY_INTERVAL: Duration = Duration::from_millis(50);
const UPDATE_INTERVAL: Duration = Duration::from_secs(60 * 60);
#[cfg(unix)] #[cfg(unix)]
const INSTALL_URL: &str = "https://chatgpt.com/codex/install.sh"; const INSTALL_URL: &str = "https://chatgpt.com/codex/install.sh";
#[cfg(windows)] #[cfg(windows)]
@@ -47,9 +49,8 @@ pub(crate) async fn run(http_client_factory: HttpClientFactory) -> Result<()> {
#[cfg(windows)] #[cfg(windows)]
let updater = { let updater = {
let daemon = Daemon::from_environment()?; let daemon = Daemon::from_environment()?;
crate::backend::pid_update_loop_backend( // Updater ownership needs only paths, not settings that may be mid-edit.
daemon.backend_paths(&daemon.load_settings().await?), crate::backend::pid_update_loop_backend(daemon.backend_paths(&DaemonSettings::default()))
)
}; };
#[cfg(windows)] #[cfg(windows)]
updater.wait_for_ownership().await?; 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 { if sleep_or_terminate(INITIAL_UPDATE_DELAY, &mut terminate).await {
return Ok(()); return Ok(());
} }
let daemon = Daemon::from_environment()?;
loop { 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 // Failed successor cleanup leaves its PID published. The predecessor
// must stop instead of installing again without ownership. // must stop instead of installing again without ownership.
#[cfg(windows)] #[cfg(windows)]
@@ -76,12 +88,34 @@ pub(crate) async fn run(http_client_factory: HttpClientFactory) -> Result<()> {
Ok(UpdateLoopControl::Continue) | Err(_) => {} Ok(UpdateLoopControl::Continue) | Err(_) => {}
Ok(UpdateLoopControl::Stop) => return Ok(()), Ok(UpdateLoopControl::Stop) => return Ok(()),
} }
if sleep_or_terminate(UPDATE_INTERVAL, &mut terminate).await { match wait_for_next_check(
return Ok(()); &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<bool> {
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 { async fn sleep_or_terminate(duration: Duration, terminate: &mut Signal) -> bool {
tokio::select! { tokio::select! {
_ = sleep(duration) => false, _ = sleep(duration) => false,
@@ -100,6 +134,12 @@ async fn update_once(
terminate: &mut Signal, terminate: &mut Signal,
) -> Result<UpdateLoopControl> { ) -> Result<UpdateLoopControl> {
let daemon = Daemon::from_environment()?; 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()? { if !daemon.is_stable_standalone_release()? {
// An installer can be between changing current and publishing its // An installer can be between changing current and publishing its
// latest-channel marker. Retry after the interval instead of exiting. // 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"), .any(|window| window == b"CODEX_INSTALL_IF_LATEST"),
"standalone installer does not support guarded updates" "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()? { if !daemon.is_stable_standalone_release()? {
return Ok(UpdateLoopControl::Continue); return Ok(UpdateLoopControl::Continue);
} }
@@ -3,12 +3,16 @@ use std::sync::Mutex;
use std::time::Duration; use std::time::Duration;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
#[cfg(unix)]
use tempfile::TempDir;
use super::INSTALL_URL; use super::INSTALL_URL;
use super::InstallerHttp; use super::InstallerHttp;
use super::InstallerResponse; use super::InstallerResponse;
use super::fetch_installer_script; use super::fetch_installer_script;
use super::update_modes_for_identities; use super::update_modes_for_identities;
#[cfg(unix)]
use super::wait_for_next_check;
use crate::RestartMode; use crate::RestartMode;
use crate::UpdaterRefreshMode; use crate::UpdaterRefreshMode;
use crate::managed_install::executable_identity_from_bytes; 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] #[tokio::test]
async fn installer_fetch_uses_exact_url_and_preserves_bytes() { async fn installer_fetch_uses_exact_url_and_preserves_bytes() {
let script = b"#!/bin/sh\nprintf 'update bytes'\n".to_vec(); let script = b"#!/bin/sh\nprintf 'update bytes'\n".to_vec();
+33 -1
View File
@@ -184,7 +184,39 @@ fn managed_start_keeps_updater_on_marker_mismatch_but_stops_it_for_pin() -> Resu
} }
#[test] #[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()?; let mut daemon = TestDaemon::new()?;
daemon.unmanaged = Some( daemon.unmanaged = Some(
daemon daemon