mirror of
https://github.com/openai/codex.git
synced 2026-11-15 21:50:46 +00:00
Support the app-server daemon on Windows (#42405)
## Why The managed app-server daemon and automatic TUI attachment were limited to Unix, so Windows users could not share a background server across Codex sessions. ## What changed - Enable daemon lifecycle commands, `codex agents` startup, and AF_UNIX daemon discovery on Windows. - Require Windows daemons to start non-elevated and verify the discovered socket directory and peer before connecting. - Preflight detached process support, preserve path-based environment settings, and keep daemon processes out of the launching project's working directory. - Fall back to an embedded server when an implicitly discovered daemon cannot connect, while preserving errors for explicit remote endpoints and bypassing daemon reuse when `CODEX_EXEC_SERVER_URL` is set. ## Testing Add coverage for Windows launch restrictions and socket validation, implicit connection fallback, executor selection, daemon discovery, and the agents dashboard startup result. GitOrigin-RevId: e7fd63cf8690bcca8b5155266416f31f2f792aa2
This commit is contained in:
@@ -16,6 +16,8 @@ use tokio::process::Command;
|
||||
|
||||
impl PidBackend {
|
||||
pub(super) async fn start_inner(&self, replacement: Option<PidRecord>) -> Result<Option<u32>> {
|
||||
#[cfg(windows)]
|
||||
crate::backend::windows::ensure_not_elevated()?;
|
||||
if let Some(parent) = self.pid_file.parent() {
|
||||
codex_uds::prepare_private_socket_directory(parent)
|
||||
.await
|
||||
@@ -107,6 +109,61 @@ impl PidBackend {
|
||||
{
|
||||
use windows_sys::Win32::System::Threading::CREATE_BREAKAWAY_FROM_JOB;
|
||||
use windows_sys::Win32::System::Threading::DETACHED_PROCESS;
|
||||
// Preserve process-scoped paths before changing cwd; CA names match CUSTOM_CA_ENV_KEYS.
|
||||
for name in [
|
||||
"CODEX_HOME",
|
||||
"CODEX_SQLITE_HOME",
|
||||
"CODEX_CA_CERTIFICATE",
|
||||
"SSL_CERT_FILE",
|
||||
"REQUESTS_CA_BUNDLE",
|
||||
"CURL_CA_BUNDLE",
|
||||
"NODE_EXTRA_CA_CERTS",
|
||||
"GIT_SSL_CAINFO",
|
||||
"CARGO_HTTP_CAINFO",
|
||||
"PIP_CERT",
|
||||
"BUNDLE_SSL_CA_CERT",
|
||||
"npm_config_cafile",
|
||||
"AWS_CONFIG_FILE",
|
||||
"AWS_SHARED_CREDENTIALS_FILE",
|
||||
"AWS_WEB_IDENTITY_TOKEN_FILE",
|
||||
"AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE",
|
||||
] {
|
||||
let Some(mut value) = std::env::var_os(name) else {
|
||||
continue;
|
||||
};
|
||||
if matches!(name, "CODEX_SQLITE_HOME" | "npm_config_cafile") {
|
||||
value = value.to_str().unwrap_or_default().trim().into();
|
||||
}
|
||||
// These consumers expand `~` independently of the working directory.
|
||||
let expands_home = if name == "npm_config_cafile" {
|
||||
value
|
||||
.to_str()
|
||||
.is_some_and(|path| path.starts_with("~/") || path.starts_with("~\\"))
|
||||
} else {
|
||||
matches!(
|
||||
name,
|
||||
"CODEX_SQLITE_HOME" | "AWS_CONFIG_FILE" | "AWS_SHARED_CREDENTIALS_FILE"
|
||||
) && std::path::Path::new(&value).starts_with("~")
|
||||
};
|
||||
if value.is_empty() || expands_home {
|
||||
continue;
|
||||
}
|
||||
command.env(name, std::path::absolute(value)?);
|
||||
}
|
||||
if let Some(value) = std::env::var_os("SSL_CERT_DIR") {
|
||||
let paths = std::env::split_paths(&value)
|
||||
.filter(|path| !path.as_os_str().is_empty())
|
||||
.map(std::path::absolute)
|
||||
.collect::<std::io::Result<Vec<_>>>()?;
|
||||
command.env("SSL_CERT_DIR", std::env::join_paths(paths)?);
|
||||
}
|
||||
// A Windows process pins its working directory for its lifetime.
|
||||
// Keep both managed children out of the launching project's directory.
|
||||
command.current_dir(
|
||||
self.pid_file
|
||||
.parent()
|
||||
.context("daemon pid path has no parent")?,
|
||||
);
|
||||
// Never retry inside the parent's Job Object: that would report a
|
||||
// successful launch that dies when the terminal/SSH session closes.
|
||||
command.creation_flags(DETACHED_PROCESS | CREATE_BREAKAWAY_FROM_JOB);
|
||||
|
||||
@@ -18,6 +18,27 @@ use super::read_stderr_log_tail;
|
||||
use super::stderr_log_file_for_pid_file;
|
||||
use super::try_lock_file;
|
||||
|
||||
#[cfg(windows)]
|
||||
fn is_elevated_test_process() -> anyhow::Result<bool> {
|
||||
let output = std::process::Command::new("powershell.exe")
|
||||
.args([
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-Command",
|
||||
"[Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",
|
||||
])
|
||||
.output()?;
|
||||
anyhow::ensure!(
|
||||
output.status.success(),
|
||||
"administrator membership query failed"
|
||||
);
|
||||
match String::from_utf8(output.stdout)?.trim() {
|
||||
"True" => Ok(true),
|
||||
"False" => Ok(false),
|
||||
other => anyhow::bail!("unexpected administrator membership: {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn locked_empty_pid_file_is_treated_as_active_reservation() {
|
||||
let temp_dir = TempDir::new().expect("temp dir");
|
||||
@@ -116,6 +137,16 @@ async fn start_retries_stale_empty_pid_file_under_its_own_lock() {
|
||||
);
|
||||
|
||||
let err = backend.start().await.expect_err("start");
|
||||
#[cfg(windows)]
|
||||
if is_elevated_test_process().expect("query administrator membership") {
|
||||
assert!(err.to_string().contains("non-elevated terminal"));
|
||||
assert_eq!(
|
||||
tokio::fs::read(&backend.pid_file).await.unwrap(),
|
||||
Vec::<u8>::new()
|
||||
);
|
||||
assert!(!backend.lock_file.exists());
|
||||
return;
|
||||
}
|
||||
assert!(
|
||||
err.to_string()
|
||||
.starts_with("failed to spawn detached app-server process using ")
|
||||
@@ -287,6 +318,7 @@ async fn stale_creation_time_never_stops_reused_pid() {
|
||||
#[cfg(windows)]
|
||||
#[tokio::test]
|
||||
async fn failed_updater_handoff_preserves_predecessor_record() {
|
||||
let elevated = is_elevated_test_process().expect("query administrator membership");
|
||||
let temp = TempDir::new().expect("temp");
|
||||
let state_dir = temp.path().join("state");
|
||||
codex_uds::prepare_private_socket_directory(&state_dir)
|
||||
@@ -313,9 +345,13 @@ async fn failed_updater_handoff_preserves_predecessor_record() {
|
||||
.await
|
||||
.unwrap();
|
||||
let error = backend.replace_current_updater().await.unwrap_err();
|
||||
// Windows may reject breakaway before reporting the missing executable.
|
||||
// Both must reach process I/O rather than rejecting stale ownership.
|
||||
assert!(error.root_cause().is::<std::io::Error>(), "{error:#}");
|
||||
if elevated {
|
||||
assert!(error.to_string().contains("non-elevated terminal"));
|
||||
} else {
|
||||
// Windows may reject breakaway before reporting the missing executable.
|
||||
// Both must reach process I/O rather than rejecting stale ownership.
|
||||
assert!(error.root_cause().is::<std::io::Error>(), "{error:#}");
|
||||
}
|
||||
assert_eq!(
|
||||
backend.read_pid_file_state().await.unwrap(),
|
||||
PidFileState::Running(record)
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
//! Windows process identity and file locks. Keep a process handle across shutdown
|
||||
//! so PID reuse can never redirect forced termination to a different process.
|
||||
//! Managed servers must not elevate ordinary clients sharing the account's socket.
|
||||
|
||||
use std::io;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::os::windows::process::CommandExt;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::process::Stdio;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
@@ -13,6 +18,10 @@ use windows_sys::Win32::Foundation::ERROR_LOCK_VIOLATION;
|
||||
use windows_sys::Win32::Foundation::FILETIME;
|
||||
use windows_sys::Win32::Foundation::WAIT_OBJECT_0;
|
||||
use windows_sys::Win32::Foundation::WAIT_TIMEOUT;
|
||||
use windows_sys::Win32::Security::GetTokenInformation;
|
||||
use windows_sys::Win32::Security::TOKEN_ELEVATION;
|
||||
use windows_sys::Win32::Security::TOKEN_QUERY;
|
||||
use windows_sys::Win32::Security::TokenElevation;
|
||||
use windows_sys::Win32::Storage::FileSystem::LOCKFILE_EXCLUSIVE_LOCK;
|
||||
use windows_sys::Win32::Storage::FileSystem::LOCKFILE_FAIL_IMMEDIATELY;
|
||||
use windows_sys::Win32::Storage::FileSystem::LockFileEx;
|
||||
@@ -24,10 +33,14 @@ use windows_sys::Win32::System::JobObjects::JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
use windows_sys::Win32::System::JobObjects::JOBOBJECT_EXTENDED_LIMIT_INFORMATION;
|
||||
use windows_sys::Win32::System::JobObjects::JobObjectExtendedLimitInformation;
|
||||
use windows_sys::Win32::System::JobObjects::SetInformationJobObject;
|
||||
use windows_sys::Win32::System::Threading::CREATE_BREAKAWAY_FROM_JOB;
|
||||
use windows_sys::Win32::System::Threading::CREATE_SUSPENDED;
|
||||
use windows_sys::Win32::System::Threading::DETACHED_PROCESS;
|
||||
use windows_sys::Win32::System::Threading::GetCurrentProcess;
|
||||
use windows_sys::Win32::System::Threading::GetProcessId;
|
||||
use windows_sys::Win32::System::Threading::GetProcessTimes;
|
||||
use windows_sys::Win32::System::Threading::OpenProcess;
|
||||
use windows_sys::Win32::System::Threading::OpenProcessToken;
|
||||
use windows_sys::Win32::System::Threading::PROCESS_ACCESS_RIGHTS;
|
||||
use windows_sys::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION;
|
||||
use windows_sys::Win32::System::Threading::PROCESS_SYNCHRONIZE;
|
||||
@@ -35,6 +48,70 @@ use windows_sys::Win32::System::Threading::PROCESS_TERMINATE;
|
||||
use windows_sys::Win32::System::Threading::TerminateProcess;
|
||||
use windows_sys::Win32::System::Threading::WaitForSingleObject;
|
||||
|
||||
pub(crate) fn ensure_not_elevated() -> Result<()> {
|
||||
let mut token = 0;
|
||||
if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
|
||||
return Err(io::Error::last_os_error()).context("failed to query daemon launcher token");
|
||||
}
|
||||
let token = unsafe { OwnedHandle::from_raw_handle(token as _) };
|
||||
let mut elevation: TOKEN_ELEVATION = unsafe { std::mem::zeroed() };
|
||||
let mut returned = 0;
|
||||
if unsafe {
|
||||
GetTokenInformation(
|
||||
token.as_raw_handle() as _,
|
||||
TokenElevation,
|
||||
(&mut elevation as *mut TOKEN_ELEVATION).cast(),
|
||||
std::mem::size_of::<TOKEN_ELEVATION>() as u32,
|
||||
&mut returned,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error())
|
||||
.context("failed to query daemon launcher elevation");
|
||||
}
|
||||
anyhow::ensure!(
|
||||
elevation.TokenIsElevated == 0,
|
||||
"start the Windows daemon from a non-elevated terminal; shared clients must not inherit administrator privileges"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Probe the actual child association: escaping an inner job can leave an outer
|
||||
// job attached. Suspend the image so no application code runs before cleanup.
|
||||
pub(crate) fn ensure_detached_launch(executable: &Path) -> Result<()> {
|
||||
let mut child = Command::new(executable)
|
||||
.creation_flags(CREATE_SUSPENDED | DETACHED_PROCESS | CREATE_BREAKAWAY_FROM_JOB)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.context("cannot launch detached daemon; existing daemon was not stopped")?;
|
||||
let mut in_job = 0;
|
||||
let result = if unsafe {
|
||||
IsProcessInJob(
|
||||
child.as_raw_handle() as _,
|
||||
/*jobhandle*/ 0,
|
||||
&mut in_job,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
Err(io::Error::last_os_error()).context("failed to verify daemon launch capability")
|
||||
} else if in_job != 0 {
|
||||
Err(anyhow::anyhow!(
|
||||
"host Job Object prevents daemon detachment; start from a host that allows breakaway"
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
};
|
||||
child
|
||||
.kill()
|
||||
.context("failed to terminate suspended launch probe")?;
|
||||
child
|
||||
.wait()
|
||||
.context("failed to reap suspended launch probe")?;
|
||||
result
|
||||
}
|
||||
|
||||
pub(super) struct Process(OwnedHandle);
|
||||
|
||||
impl Process {
|
||||
|
||||
@@ -5,6 +5,46 @@ use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED;
|
||||
use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
|
||||
use windows_sys::Win32::System::Threading::TerminateProcess;
|
||||
|
||||
#[test]
|
||||
fn detached_launch_preflight_rejects_restrictive_job() {
|
||||
const CHILD: &str = "CODEX_TEST_RESTRICTIVE_LAUNCH_JOB";
|
||||
let executable = std::env::current_exe().expect("test executable");
|
||||
if std::env::var_os(CHILD).is_some() {
|
||||
let job = unsafe { super::CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
|
||||
assert_ne!(job, 0);
|
||||
let job = unsafe {
|
||||
<std::os::windows::io::OwnedHandle as std::os::windows::io::FromRawHandle>::from_raw_handle(job as _)
|
||||
};
|
||||
assert_ne!(
|
||||
unsafe {
|
||||
super::AssignProcessToJobObject(
|
||||
job.as_raw_handle() as _,
|
||||
super::GetCurrentProcess(),
|
||||
)
|
||||
},
|
||||
0
|
||||
);
|
||||
// A new job does not permit breakaway. Reject before any lifecycle mutation.
|
||||
assert!(super::ensure_detached_launch(&executable).is_err());
|
||||
return;
|
||||
}
|
||||
let output = std::process::Command::new(executable)
|
||||
.args([
|
||||
"--exact",
|
||||
"backend::windows::tests::detached_launch_preflight_rejects_restrictive_job",
|
||||
"--nocapture",
|
||||
])
|
||||
.env(CHILD, "1")
|
||||
.output()
|
||||
.expect("isolated job test");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn identity_queries_do_not_require_termination_access() {
|
||||
let mut child = tokio::process::Command::new("powershell.exe")
|
||||
|
||||
@@ -194,16 +194,24 @@ enum RestartDecision {
|
||||
|
||||
pub async fn run(command: LifecycleCommand) -> Result<LifecycleOutput> {
|
||||
ensure_supported_platform()?;
|
||||
#[cfg(windows)]
|
||||
if matches!(command, LifecycleCommand::Start | LifecycleCommand::Restart) {
|
||||
backend::windows::ensure_not_elevated()?;
|
||||
}
|
||||
Daemon::from_environment()?.run(command).await
|
||||
}
|
||||
|
||||
pub async fn bootstrap(options: BootstrapOptions) -> Result<BootstrapOutput> {
|
||||
ensure_supported_platform()?;
|
||||
#[cfg(windows)]
|
||||
backend::windows::ensure_not_elevated()?;
|
||||
Daemon::from_environment()?.bootstrap(options).await
|
||||
}
|
||||
|
||||
pub async fn ensure_remote_control_ready() -> Result<RemoteControlReadyOutput> {
|
||||
ensure_supported_platform()?;
|
||||
#[cfg(windows)]
|
||||
backend::windows::ensure_not_elevated()?;
|
||||
Daemon::from_environment()?
|
||||
.ensure_remote_control_ready()
|
||||
.await
|
||||
@@ -232,6 +240,8 @@ pub async fn start_remote_control_pairing() -> Result<RemoteControlPairingStartR
|
||||
|
||||
pub async fn set_remote_control(mode: RemoteControlMode) -> Result<RemoteControlOutput> {
|
||||
ensure_supported_platform()?;
|
||||
#[cfg(windows)]
|
||||
backend::windows::ensure_not_elevated()?;
|
||||
Daemon::from_environment()?.set_remote_control(mode).await
|
||||
}
|
||||
|
||||
@@ -239,18 +249,20 @@ pub async fn run_pid_update_loop(
|
||||
http_client_factory: codex_http_client::HttpClientFactory,
|
||||
) -> Result<()> {
|
||||
ensure_supported_platform()?;
|
||||
#[cfg(windows)]
|
||||
backend::windows::ensure_not_elevated()?;
|
||||
update_loop::run(http_client_factory).await
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[cfg(any(unix, windows))]
|
||||
fn ensure_supported_platform() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
fn ensure_supported_platform() -> Result<()> {
|
||||
Err(anyhow!(
|
||||
"codex app-server daemon lifecycle is only supported on Unix platforms"
|
||||
"codex app-server daemon lifecycle is only supported on Unix and Windows platforms"
|
||||
))
|
||||
}
|
||||
|
||||
@@ -386,6 +398,8 @@ impl Daemon {
|
||||
RestartDecision::NotReady => return Ok(RestartIfRunningOutcome::NotReady),
|
||||
RestartDecision::AlreadyCurrent => RestartIfRunningOutcome::AlreadyCurrent,
|
||||
RestartDecision::Restart => {
|
||||
#[cfg(windows)]
|
||||
backend::windows::ensure_detached_launch(managed_codex_bin)?;
|
||||
backend.stop().await?;
|
||||
let _ = self
|
||||
.start_managed_backend_with_bin(&settings, managed_codex_bin)
|
||||
@@ -577,11 +591,13 @@ impl Daemon {
|
||||
));
|
||||
}
|
||||
|
||||
if backend.is_some() {
|
||||
self.ensure_managed_codex_bin()?;
|
||||
}
|
||||
settings.remote_control_enabled = remote_control_enabled;
|
||||
settings.save(&self.settings_file).await?;
|
||||
|
||||
let app_server_version = if let Some(backend) = backend {
|
||||
self.ensure_managed_codex_bin()?;
|
||||
backend.stop().await?;
|
||||
let _ = self.start_managed_backend(&settings).await?;
|
||||
Some(self.wait_until_ready().await?.app_server_version)
|
||||
@@ -679,15 +695,22 @@ impl Daemon {
|
||||
|
||||
fn ensure_managed_codex_bin(&self) -> Result<()> {
|
||||
if self.managed_codex_bin.is_file() {
|
||||
#[cfg(windows)]
|
||||
backend::windows::ensure_detached_launch(&self.managed_codex_bin)?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let managed_codex_path = self.managed_codex_bin.display();
|
||||
let install_command = if cfg!(windows) {
|
||||
"irm https://chatgpt.com/codex/install.ps1 | iex"
|
||||
} else {
|
||||
"curl -fsSL https://chatgpt.com/codex/install.sh | sh"
|
||||
};
|
||||
Err(anyhow!(
|
||||
"managed standalone Codex install not found at {managed_codex_path}\n\n\
|
||||
This command requires the standalone install managed by the Codex installer, because \
|
||||
the daemon starts and updates app-server from that fixed path.\n\n\
|
||||
Install it with:\n curl -fsSL https://chatgpt.com/codex/install.sh | sh\n\n\
|
||||
Install it with:\n {install_command}\n\n\
|
||||
Then rerun the command you just tried."
|
||||
))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user