aKode fase 2a: rimossi cloud tasks, chatgpt apply, responses-api-proxy, codex app, remote control, guardian decisions; realtime senza fallback OpenAI; doctor senza sonde OpenAI
This commit is contained in:
@@ -1,25 +0,0 @@
|
||||
use clap::Parser;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
pub struct AppCommand {
|
||||
/// Workspace path to open in the Desktop app.
|
||||
#[arg(value_name = "PATH", default_value = ".")]
|
||||
pub path: PathBuf,
|
||||
|
||||
/// Override the app installer download URL (advanced).
|
||||
#[arg(long = "download-url")]
|
||||
pub download_url_override: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn run_app(cmd: AppCommand) -> anyhow::Result<()> {
|
||||
let workspace = std::fs::canonicalize(&cmd.path).unwrap_or(cmd.path);
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
crate::desktop_app::run_app_open_or_install(workspace, cmd.download_url_override).await
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
crate::desktop_app::run_app_open_or_install(workspace, cmd.download_url_override).await
|
||||
}
|
||||
}
|
||||
@@ -1,513 +0,0 @@
|
||||
use anyhow::Context as _;
|
||||
use std::ffi::CString;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use tempfile::Builder;
|
||||
use tokio::process::Command;
|
||||
|
||||
const CODEX_BUNDLE_IDENTIFIER: &str = "com.openai.codex";
|
||||
const OPENAI_APPLE_TEAM_IDENTIFIER: &str = "2DC432GLL2";
|
||||
const CODEX_DMG_URL_ARM64: &str = "https://persistent.oaistatic.com/codex-app-prod/Codex.dmg";
|
||||
const CODEX_DMG_URL_X64: &str =
|
||||
"https://persistent.oaistatic.com/codex-app-prod/Codex-latest-x64.dmg";
|
||||
|
||||
pub async fn run_mac_app_open_or_install(
|
||||
workspace: PathBuf,
|
||||
download_url_override: Option<String>,
|
||||
) -> anyhow::Result<()> {
|
||||
if let Some(app_path) = find_existing_codex_app_path(&codex_app_search_dirs()) {
|
||||
eprintln!(
|
||||
"Opening Desktop app at {app_path}...",
|
||||
app_path = app_path.display()
|
||||
);
|
||||
open_codex_app(&app_path, &workspace).await?;
|
||||
return Ok(());
|
||||
}
|
||||
eprintln!("Desktop app not found; downloading installer...");
|
||||
let download_url = download_url_override.unwrap_or_else(|| {
|
||||
let default_url = if is_apple_silicon_mac() {
|
||||
CODEX_DMG_URL_ARM64
|
||||
} else {
|
||||
CODEX_DMG_URL_X64
|
||||
};
|
||||
default_url.to_string()
|
||||
});
|
||||
let installed_app = download_and_install_codex_to_user_applications(&download_url)
|
||||
.await
|
||||
.context("failed to download/install Desktop app")?;
|
||||
eprintln!(
|
||||
"Launching Desktop app from {installed_app}...",
|
||||
installed_app = installed_app.display()
|
||||
);
|
||||
open_codex_app(&installed_app, &workspace).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_apple_silicon_mac() -> bool {
|
||||
fn macos_sysctl_flag(name: &str) -> Option<bool> {
|
||||
let name = CString::new(name).ok()?;
|
||||
let mut value: libc::c_int = 0;
|
||||
let mut size = std::mem::size_of_val(&value);
|
||||
let result = unsafe {
|
||||
libc::sysctlbyname(
|
||||
name.as_ptr(),
|
||||
(&mut value as *mut libc::c_int).cast::<libc::c_void>(),
|
||||
&mut size,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
)
|
||||
};
|
||||
(result == 0).then_some(value != 0)
|
||||
}
|
||||
|
||||
std::env::consts::ARCH == "aarch64"
|
||||
|| macos_sysctl_flag("sysctl.proc_translated").unwrap_or(false)
|
||||
|| macos_sysctl_flag("hw.optional.arm64").unwrap_or(false)
|
||||
}
|
||||
|
||||
fn find_existing_codex_app_path(applications_dirs: &[PathBuf]) -> Option<PathBuf> {
|
||||
applications_dirs
|
||||
.iter()
|
||||
.flat_map(|dir| ["ChatGPT.app", "Codex.app"].map(|app_name| dir.join(app_name)))
|
||||
.find(|candidate| is_codex_app_bundle(candidate))
|
||||
}
|
||||
|
||||
fn codex_app_search_dirs() -> Vec<PathBuf> {
|
||||
let mut paths = vec![PathBuf::from("/Applications")];
|
||||
if let Some(home) = std::env::var_os("HOME") {
|
||||
paths.push(PathBuf::from(home).join("Applications"));
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
fn is_codex_app_bundle(app_path: &Path) -> bool {
|
||||
if !app_path.is_dir() {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::process::Command::new("/usr/bin/plutil")
|
||||
.arg("-extract")
|
||||
.arg("CFBundleIdentifier")
|
||||
.arg("raw")
|
||||
.arg("-o")
|
||||
.arg("-")
|
||||
.arg(app_path.join("Contents/Info.plist"))
|
||||
.output()
|
||||
.is_ok_and(|output| {
|
||||
output.status.success()
|
||||
&& String::from_utf8_lossy(&output.stdout).trim() == CODEX_BUNDLE_IDENTIFIER
|
||||
})
|
||||
}
|
||||
|
||||
async fn open_codex_app(app_path: &Path, workspace: &Path) -> anyhow::Result<()> {
|
||||
verify_codex_app_bundle(app_path).await?;
|
||||
eprintln!(
|
||||
"Opening workspace {workspace}...",
|
||||
workspace = workspace.display()
|
||||
);
|
||||
let url = codex_new_thread_url(workspace);
|
||||
let status = Command::new("open")
|
||||
.arg("-a")
|
||||
.arg(app_path)
|
||||
.arg(&url)
|
||||
.status()
|
||||
.await
|
||||
.context("failed to invoke `open`")?;
|
||||
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
anyhow::bail!(
|
||||
"`open -a {app_path} {url}` exited with {status}",
|
||||
app_path = app_path.display(),
|
||||
url = url
|
||||
);
|
||||
}
|
||||
|
||||
async fn verify_codex_app_bundle(app_path: &Path) -> anyhow::Result<()> {
|
||||
let requirement = format!(
|
||||
"identifier \"{CODEX_BUNDLE_IDENTIFIER}\" and anchor apple generic and certificate leaf[subject.OU] = \"{OPENAI_APPLE_TEAM_IDENTIFIER}\""
|
||||
);
|
||||
let output = Command::new("/usr/bin/codesign")
|
||||
.args(["--verify", "--deep", "--strict"])
|
||||
.arg(format!("-R={requirement}"))
|
||||
.arg(app_path)
|
||||
.output()
|
||||
.await
|
||||
.context("failed to verify Desktop app signature")?;
|
||||
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
anyhow::bail!(
|
||||
"Desktop app at {} failed OpenAI signature verification (team {OPENAI_APPLE_TEAM_IDENTIFIER}, bundle {CODEX_BUNDLE_IDENTIFIER}): {}",
|
||||
app_path.display(),
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
);
|
||||
}
|
||||
|
||||
fn codex_new_thread_url(workspace: &Path) -> String {
|
||||
let workspace = workspace.as_os_str().to_string_lossy();
|
||||
let mut serializer = url::form_urlencoded::Serializer::new(String::new());
|
||||
serializer.append_pair("path", workspace.as_ref());
|
||||
let query = serializer.finish();
|
||||
format!("codex://threads/new?{query}")
|
||||
}
|
||||
|
||||
async fn download_and_install_codex_to_user_applications(dmg_url: &str) -> anyhow::Result<PathBuf> {
|
||||
let temp_dir = Builder::new()
|
||||
.prefix("codex-app-installer-")
|
||||
.tempdir()
|
||||
.context("failed to create temp dir")?;
|
||||
let tmp_root = temp_dir.path().to_path_buf();
|
||||
let _temp_dir = temp_dir;
|
||||
|
||||
let dmg_path = tmp_root.join("Codex.dmg");
|
||||
download_dmg(dmg_url, &dmg_path).await?;
|
||||
|
||||
eprintln!("Mounting Desktop app installer...");
|
||||
let mount_point = mount_dmg(&dmg_path).await?;
|
||||
eprintln!(
|
||||
"Installer mounted at {mount_point}.",
|
||||
mount_point = mount_point.display()
|
||||
);
|
||||
let result = async {
|
||||
let app_in_volume = find_codex_app_in_mount(&mount_point)
|
||||
.context("failed to locate Codex.app in mounted dmg")?;
|
||||
verify_codex_app_bundle(&app_in_volume)
|
||||
.await
|
||||
.context("refusing to install an unverified Desktop app")?;
|
||||
install_codex_app_bundle(&app_in_volume).await
|
||||
}
|
||||
.await;
|
||||
|
||||
let detach_result = detach_dmg(&mount_point).await;
|
||||
if let Err(err) = detach_result {
|
||||
eprintln!(
|
||||
"warning: failed to detach dmg at {mount_point}: {err}",
|
||||
mount_point = mount_point.display()
|
||||
);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
async fn install_codex_app_bundle(app_in_volume: &Path) -> anyhow::Result<PathBuf> {
|
||||
for applications_dir in candidate_applications_dirs()? {
|
||||
eprintln!(
|
||||
"Installing Desktop app into {applications_dir}...",
|
||||
applications_dir = applications_dir.display()
|
||||
);
|
||||
std::fs::create_dir_all(&applications_dir).with_context(|| {
|
||||
format!(
|
||||
"failed to create applications dir {applications_dir}",
|
||||
applications_dir = applications_dir.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
let dest_app = applications_dir.join("Codex.app");
|
||||
if dest_app.is_dir() {
|
||||
return Ok(dest_app);
|
||||
}
|
||||
|
||||
match copy_app_bundle(app_in_volume, &dest_app).await {
|
||||
Ok(()) => return Ok(dest_app),
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"warning: failed to install Codex.app to {applications_dir}: {err}",
|
||||
applications_dir = applications_dir.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
anyhow::bail!("failed to install Codex.app to any applications directory");
|
||||
}
|
||||
|
||||
fn candidate_applications_dirs() -> anyhow::Result<Vec<PathBuf>> {
|
||||
let mut dirs = vec![PathBuf::from("/Applications")];
|
||||
dirs.push(user_applications_dir()?);
|
||||
Ok(dirs)
|
||||
}
|
||||
|
||||
async fn download_dmg(url: &str, dest: &Path) -> anyhow::Result<()> {
|
||||
eprintln!("Downloading installer...");
|
||||
let status = Command::new("curl")
|
||||
.arg("-fL")
|
||||
.arg("--retry")
|
||||
.arg("3")
|
||||
.arg("--retry-delay")
|
||||
.arg("1")
|
||||
.arg("-o")
|
||||
.arg(dest)
|
||||
.arg(url)
|
||||
.status()
|
||||
.await
|
||||
.context("failed to invoke `curl`")?;
|
||||
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
anyhow::bail!("curl download failed with {status}");
|
||||
}
|
||||
|
||||
async fn mount_dmg(dmg_path: &Path) -> anyhow::Result<PathBuf> {
|
||||
let output = Command::new("hdiutil")
|
||||
.arg("attach")
|
||||
.arg("-nobrowse")
|
||||
.arg("-readonly")
|
||||
.arg(dmg_path)
|
||||
.output()
|
||||
.await
|
||||
.context("failed to invoke `hdiutil attach`")?;
|
||||
|
||||
if !output.status.success() {
|
||||
anyhow::bail!(
|
||||
"`hdiutil attach` failed with {status}: {stderr}",
|
||||
status = output.status,
|
||||
stderr = String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
parse_hdiutil_attach_mount_point(&stdout)
|
||||
.map(PathBuf::from)
|
||||
.with_context(|| format!("failed to parse mount point from hdiutil output:\n{stdout}"))
|
||||
}
|
||||
|
||||
async fn detach_dmg(mount_point: &Path) -> anyhow::Result<()> {
|
||||
let status = Command::new("hdiutil")
|
||||
.arg("detach")
|
||||
.arg(mount_point)
|
||||
.status()
|
||||
.await
|
||||
.context("failed to invoke `hdiutil detach`")?;
|
||||
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
anyhow::bail!("hdiutil detach failed with {status}");
|
||||
}
|
||||
|
||||
fn find_codex_app_in_mount(mount_point: &Path) -> anyhow::Result<PathBuf> {
|
||||
let direct = mount_point.join("Codex.app");
|
||||
if direct.is_dir() {
|
||||
return Ok(direct);
|
||||
}
|
||||
|
||||
for entry in std::fs::read_dir(mount_point).with_context(|| {
|
||||
format!(
|
||||
"failed to read {mount_point}",
|
||||
mount_point = mount_point.display()
|
||||
)
|
||||
})? {
|
||||
let entry = entry.context("failed to read mount directory entry")?;
|
||||
let path = entry.path();
|
||||
if path.extension().is_some_and(|ext| ext == "app") && path.is_dir() {
|
||||
return Ok(path);
|
||||
}
|
||||
}
|
||||
|
||||
anyhow::bail!(
|
||||
"no .app bundle found at {mount_point}",
|
||||
mount_point = mount_point.display()
|
||||
);
|
||||
}
|
||||
|
||||
async fn copy_app_bundle(src_app: &Path, dest_app: &Path) -> anyhow::Result<()> {
|
||||
let status = Command::new("ditto")
|
||||
.arg(src_app)
|
||||
.arg(dest_app)
|
||||
.status()
|
||||
.await
|
||||
.context("failed to invoke `ditto`")?;
|
||||
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
anyhow::bail!("ditto copy failed with {status}");
|
||||
}
|
||||
|
||||
fn user_applications_dir() -> anyhow::Result<PathBuf> {
|
||||
let home = std::env::var_os("HOME").context("HOME is not set")?;
|
||||
Ok(PathBuf::from(home).join("Applications"))
|
||||
}
|
||||
|
||||
fn parse_hdiutil_attach_mount_point(output: &str) -> Option<String> {
|
||||
output.lines().find_map(|line| {
|
||||
if !line.contains("/Volumes/") {
|
||||
return None;
|
||||
}
|
||||
if let Some((_, mount)) = line.rsplit_once('\t') {
|
||||
return Some(mount.trim().to_string());
|
||||
}
|
||||
line.split_whitespace()
|
||||
.find(|field| field.starts_with("/Volumes/"))
|
||||
.map(str::to_string)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::codex_new_thread_url;
|
||||
use super::find_existing_codex_app_path;
|
||||
use super::open_codex_app;
|
||||
use super::parse_hdiutil_attach_mount_point;
|
||||
use super::verify_codex_app_bundle;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
fn write_app_bundle(app_path: &Path, bundle_identifier: &str) {
|
||||
let contents_path = app_path.join("Contents");
|
||||
fs::create_dir_all(&contents_path).expect("create app bundle");
|
||||
fs::write(
|
||||
contents_path.join("Info.plist"),
|
||||
format!(
|
||||
r#"<?xml version="1.0"?><plist version="1.0"><dict><key>CFBundleIdentifier</key><string>{bundle_identifier}</string></dict></plist>"#
|
||||
),
|
||||
)
|
||||
.expect("write Info.plist");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_chatgpt_app_with_codex_bundle_identifier() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let app_path = temp_dir.path().join("ChatGPT.app");
|
||||
write_app_bundle(&app_path, "com.openai.codex");
|
||||
|
||||
assert_eq!(
|
||||
find_existing_codex_app_path(&[temp_dir.path().to_path_buf()]),
|
||||
Some(app_path)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_classic_chatgpt_app() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
write_app_bundle(&temp_dir.path().join("ChatGPT.app"), "com.openai.chat");
|
||||
let codex_app_path = temp_dir.path().join("Codex.app");
|
||||
write_app_bundle(&codex_app_path, "com.openai.codex");
|
||||
|
||||
assert_eq!(
|
||||
find_existing_codex_app_path(&[temp_dir.path().to_path_buf()]),
|
||||
Some(codex_app_path)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_unsigned_app_with_codex_bundle_identifier() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let app_path = temp_dir.path().join("Codex.app");
|
||||
write_app_bundle(&app_path, "com.openai.codex");
|
||||
|
||||
let err = verify_codex_app_bundle(&app_path)
|
||||
.await
|
||||
.expect_err("unsigned app should not satisfy the OpenAI signing requirement");
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("failed OpenAI signature verification"),
|
||||
"unexpected verification error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_valid_signature_without_openai_signing_identity() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let app_path = temp_dir.path().join("Codex.app");
|
||||
let contents_path = app_path.join("Contents");
|
||||
let executable_path = contents_path.join("MacOS/Codex");
|
||||
fs::create_dir_all(executable_path.parent().expect("executable parent"))
|
||||
.expect("create executable directory");
|
||||
codex_utils_cargo_bin::copy_executable(Path::new("/usr/bin/true"), &executable_path)
|
||||
.expect("copy executable into app bundle");
|
||||
fs::write(
|
||||
contents_path.join("Info.plist"),
|
||||
r#"<?xml version="1.0"?><plist version="1.0"><dict><key>CFBundleIdentifier</key><string>com.openai.codex</string><key>CFBundleExecutable</key><string>Codex</string></dict></plist>"#,
|
||||
)
|
||||
.expect("write Info.plist");
|
||||
|
||||
let sign_status = std::process::Command::new("/usr/bin/codesign")
|
||||
.args(["--force", "--sign", "-"])
|
||||
.arg(&app_path)
|
||||
.status()
|
||||
.expect("sign app bundle");
|
||||
assert!(sign_status.success(), "failed to ad-hoc sign app bundle");
|
||||
|
||||
let verify_status = std::process::Command::new("/usr/bin/codesign")
|
||||
.args(["--verify", "--deep", "--strict"])
|
||||
.arg(&app_path)
|
||||
.status()
|
||||
.expect("verify app bundle signature");
|
||||
assert!(verify_status.success(), "ad-hoc signature should be valid");
|
||||
|
||||
let err = verify_codex_app_bundle(&app_path)
|
||||
.await
|
||||
.expect_err("valid signature without the OpenAI team should not be trusted");
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("failed OpenAI signature verification"),
|
||||
"unexpected verification error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refuses_to_launch_unsigned_existing_codex_app() {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let app_path = temp_dir.path().join("Codex.app");
|
||||
write_app_bundle(&app_path, "com.openai.codex");
|
||||
|
||||
let err = open_codex_app(&app_path, temp_dir.path())
|
||||
.await
|
||||
.expect_err("unsigned existing app should not be launched");
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("failed OpenAI signature verification"),
|
||||
"unexpected launch error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_mount_point_from_tab_separated_hdiutil_output() {
|
||||
let output = "/dev/disk2s1\tApple_HFS\tCodex\t/Volumes/Codex\n";
|
||||
assert_eq!(
|
||||
parse_hdiutil_attach_mount_point(output).as_deref(),
|
||||
Some("/Volumes/Codex")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_mount_point_with_spaces() {
|
||||
let output = "/dev/disk2s1\tApple_HFS\tCodex Installer\t/Volumes/Codex Installer\n";
|
||||
assert_eq!(
|
||||
parse_hdiutil_attach_mount_point(output).as_deref(),
|
||||
Some("/Volumes/Codex Installer")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_new_thread_url_encodes_workspace_path() {
|
||||
let url = url::Url::parse(&codex_new_thread_url(Path::new("/tmp/codex workspace/#1")))
|
||||
.expect("deep link should parse");
|
||||
|
||||
assert_eq!(
|
||||
(
|
||||
url.scheme().to_string(),
|
||||
url.host_str().map(str::to_string),
|
||||
url.path().to_string(),
|
||||
url.query_pairs().into_owned().collect::<Vec<_>>(),
|
||||
),
|
||||
(
|
||||
"codex".to_string(),
|
||||
Some("threads".to_string()),
|
||||
"/new".to_string(),
|
||||
vec![("path".to_string(), "/tmp/codex workspace/#1".to_string())],
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
#[cfg(target_os = "macos")]
|
||||
mod mac;
|
||||
#[cfg(target_os = "windows")]
|
||||
mod windows;
|
||||
|
||||
/// Run the app install/open logic for the current OS.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub async fn run_app_open_or_install(
|
||||
workspace: std::path::PathBuf,
|
||||
download_url_override: Option<String>,
|
||||
) -> anyhow::Result<()> {
|
||||
mac::run_mac_app_open_or_install(workspace, download_url_override).await
|
||||
}
|
||||
|
||||
/// Run the app install/open logic for the current OS.
|
||||
#[cfg(target_os = "windows")]
|
||||
pub async fn run_app_open_or_install(
|
||||
workspace: std::path::PathBuf,
|
||||
download_url_override: Option<String>,
|
||||
) -> anyhow::Result<()> {
|
||||
windows::run_windows_app_open_or_install(workspace, download_url_override).await
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
use anyhow::Context as _;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use tokio::process::Command;
|
||||
|
||||
const CODEX_WINDOWS_INSTALLER_URL: &str =
|
||||
"https://get.microsoft.com/installer/download/9PLM9XGG6VKS?cid=website_cta_psi";
|
||||
const CODEX_MICROSOFT_STORE_WEB_URL: &str = "https://apps.microsoft.com/detail/9plm9xgg6vks";
|
||||
|
||||
pub async fn run_windows_app_open_or_install(
|
||||
workspace: PathBuf,
|
||||
download_url_override: Option<String>,
|
||||
) -> anyhow::Result<()> {
|
||||
let workspace_path = workspace.display().to_string();
|
||||
let display_workspace = display_workspace_path(&workspace);
|
||||
if codex_app_is_installed().await? {
|
||||
eprintln!("Opening workspace {display_workspace} in the Desktop app...");
|
||||
open_url(&codex_new_thread_url(&workspace_path)).await?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
eprintln!("Desktop app not found; opening Windows installer...");
|
||||
let download_url = download_url_override
|
||||
.as_deref()
|
||||
.unwrap_or(CODEX_WINDOWS_INSTALLER_URL);
|
||||
if open_url(download_url).await.is_err() && download_url_override.is_none() {
|
||||
open_url(CODEX_MICROSOFT_STORE_WEB_URL).await?;
|
||||
}
|
||||
eprintln!("After installing the Desktop app, open workspace {display_workspace}.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn codex_app_is_installed() -> anyhow::Result<bool> {
|
||||
// This package identity is stable across Codex- and ChatGPT-branded builds.
|
||||
let output = Command::new("powershell.exe")
|
||||
.arg("-NoProfile")
|
||||
.arg("-Command")
|
||||
.arg(
|
||||
"Get-StartApps | Where-Object AppID -Like 'OpenAI.Codex_*!App' | Select-Object -First 1 -ExpandProperty AppID",
|
||||
)
|
||||
.output()
|
||||
.await
|
||||
.context("failed to invoke `powershell.exe`")?;
|
||||
|
||||
if !output.status.success() {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
Ok(!String::from_utf8_lossy(&output.stdout).trim().is_empty())
|
||||
}
|
||||
|
||||
async fn open_url(url: &str) -> anyhow::Result<()> {
|
||||
let status = Command::new("powershell.exe")
|
||||
.arg("-NoProfile")
|
||||
.arg("-Command")
|
||||
.arg("& { param($target) Start-Process -FilePath $target }")
|
||||
.arg(url)
|
||||
.status()
|
||||
.await
|
||||
.with_context(|| format!("failed to open {url}"))?;
|
||||
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
anyhow::bail!("failed to open {url} with {status}");
|
||||
}
|
||||
}
|
||||
|
||||
fn codex_new_thread_url(workspace: &str) -> String {
|
||||
let mut serializer = url::form_urlencoded::Serializer::new(String::new());
|
||||
serializer.append_pair("path", workspace);
|
||||
let query = serializer.finish();
|
||||
format!("codex://threads/new?{query}")
|
||||
}
|
||||
|
||||
fn display_workspace_path(workspace: &Path) -> String {
|
||||
let path = workspace.display().to_string();
|
||||
if let Some(path) = path.strip_prefix(r"\\?\UNC\") {
|
||||
format!(r"\\{path}")
|
||||
} else if let Some(path) = path.strip_prefix(r"\\?\") {
|
||||
path.to_string()
|
||||
} else {
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::codex_new_thread_url;
|
||||
use super::display_workspace_path;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn display_workspace_path_removes_windows_extended_prefix() {
|
||||
assert_eq!(
|
||||
display_workspace_path(Path::new(r"\\?\C:\Users\fcoury\code\codex")),
|
||||
r"C:\Users\fcoury\code\codex"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_workspace_path_preserves_unc_prefix() {
|
||||
assert_eq!(
|
||||
display_workspace_path(Path::new(r"\\?\UNC\server\share\codex")),
|
||||
r"\\server\share\codex"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_workspace_path_leaves_regular_paths_unchanged() {
|
||||
assert_eq!(
|
||||
display_workspace_path(Path::new(r"C:\Users\fcoury\code\codex")),
|
||||
r"C:\Users\fcoury\code\codex"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_new_thread_url_encodes_windows_workspace_path() {
|
||||
assert_eq!(
|
||||
codex_new_thread_url(r"C:\Users\akuma\repos\koba"),
|
||||
r"codex://threads/new?path=C%3A%5CUsers%5Cakuma%5Crepos%5Ckoba"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_new_thread_url_preserves_verbatim_workspace_path() {
|
||||
assert_eq!(
|
||||
codex_new_thread_url(r"\\?\C:\Users\akuma\repos\koba"),
|
||||
r"codex://threads/new?path=%5C%5C%3F%5CC%3A%5CUsers%5Cakuma%5Crepos%5Ckoba"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -44,8 +44,10 @@ use codex_features::FEATURES;
|
||||
use codex_features::Feature;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OpenAiDestination;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use codex_http_client::classify_openai_api_url;
|
||||
use codex_install_context::CodexPackageLayout;
|
||||
use codex_install_context::InstallContext;
|
||||
use codex_install_context::InstallMethod;
|
||||
@@ -569,11 +571,6 @@ async fn build_report(
|
||||
|
||||
progress.begin("desktop");
|
||||
if let Some(desktop) = desktop::collect().await {
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
if let Some(application) = desktop.application.as_ref() {
|
||||
updates::append_desktop_update(&mut checks, config_result.as_ref().ok(), application)
|
||||
.await;
|
||||
}
|
||||
progress.finish("desktop", overall_status(&desktop.checks));
|
||||
checks.extend(desktop.checks);
|
||||
}
|
||||
@@ -2339,6 +2336,21 @@ async fn websocket_reachability_check(
|
||||
.details(details);
|
||||
}
|
||||
|
||||
// aKode: never open a probe connection to OpenAI/ChatGPT, including the implicit default.
|
||||
if provider
|
||||
.base_url
|
||||
.as_deref()
|
||||
.is_none_or(|url| classify_openai_api_url(url) != OpenAiDestination::Other)
|
||||
{
|
||||
return DoctorCheck::new(
|
||||
"network.websocket_reachability",
|
||||
"websocket",
|
||||
CheckStatus::Ok,
|
||||
"Responses WebSocket probe skipped: no explicit non-OpenAI provider base URL",
|
||||
)
|
||||
.details(details);
|
||||
}
|
||||
|
||||
details.push(format!(
|
||||
"connect timeout: {} ms",
|
||||
provider.websocket_connect_timeout().as_millis()
|
||||
@@ -2670,21 +2682,20 @@ fn provider_reachability_plan(config: &Config) -> ReachabilityPlan {
|
||||
config.model_provider.base_url.as_deref(),
|
||||
query_params.as_ref(),
|
||||
config.model_provider.is_amazon_bedrock(),
|
||||
&config.chatgpt_base_url,
|
||||
);
|
||||
plan.http_client_factory = config.http_client_factory();
|
||||
plan
|
||||
}
|
||||
|
||||
/// aKode: without a loaded config there is no explicit provider endpoint, so nothing is probed.
|
||||
fn default_reachability_plan() -> ReachabilityPlan {
|
||||
provider_reachability_plan_from_parts(
|
||||
ProviderAuthReachabilityMode::Chatgpt,
|
||||
"openai",
|
||||
"OpenAI",
|
||||
ProviderAuthReachabilityMode::NotRequired,
|
||||
"unknown",
|
||||
"unknown",
|
||||
/*provider_base_url*/ None,
|
||||
/*provider_query_params*/ None,
|
||||
/*is_amazon_bedrock*/ false,
|
||||
"https://chatgpt.com/backend-api/",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2730,35 +2741,20 @@ fn provider_reachability_plan_from_parts(
|
||||
provider_base_url: Option<&str>,
|
||||
provider_query_params: Option<&HashMap<String, String>>,
|
||||
is_amazon_bedrock: bool,
|
||||
chatgpt_base_url: &str,
|
||||
) -> ReachabilityPlan {
|
||||
let provider_route_probe_url = provider_base_url
|
||||
.or_else(|| {
|
||||
(mode == ProviderAuthReachabilityMode::ApiKey).then_some("https://api.openai.com/v1")
|
||||
})
|
||||
.and_then(|url| {
|
||||
should_probe_models_route(provider_name, url, is_amazon_bedrock)
|
||||
.then(|| provider_url_for_path(url, "models", provider_query_params))
|
||||
});
|
||||
let endpoints = match (mode, provider_base_url) {
|
||||
(ProviderAuthReachabilityMode::ApiKey, _) | (_, Some(_)) => vec![ReachabilityEndpoint {
|
||||
// aKode: only an explicitly configured base URL outside OpenAI/ChatGPT is probed. The
|
||||
// implicit chatgpt.com and api.openai.com endpoints are never contacted.
|
||||
let endpoints = provider_base_url
|
||||
.filter(|url| classify_openai_api_url(url) == OpenAiDestination::Other)
|
||||
.map(|base_url| ReachabilityEndpoint {
|
||||
label: format!("{provider_id} API"),
|
||||
url: provider_url_for_path(
|
||||
provider_base_url.unwrap_or("https://api.openai.com/v1"),
|
||||
"responses",
|
||||
provider_query_params,
|
||||
),
|
||||
url: provider_url_for_path(base_url, "responses", provider_query_params),
|
||||
required: true,
|
||||
route_probe_url: provider_route_probe_url,
|
||||
}],
|
||||
(ProviderAuthReachabilityMode::Chatgpt, None) => vec![ReachabilityEndpoint {
|
||||
label: "ChatGPT".to_string(),
|
||||
url: provider_url_for_path(chatgpt_base_url, "codex/responses", provider_query_params),
|
||||
required: true,
|
||||
route_probe_url: None,
|
||||
}],
|
||||
(ProviderAuthReachabilityMode::NotRequired, None) => Vec::new(),
|
||||
};
|
||||
route_probe_url: should_probe_models_route(provider_name, base_url, is_amazon_bedrock)
|
||||
.then(|| provider_url_for_path(base_url, "models", provider_query_params)),
|
||||
})
|
||||
.into_iter()
|
||||
.collect();
|
||||
ReachabilityPlan {
|
||||
description: mode.description().to_string(),
|
||||
endpoints,
|
||||
@@ -2878,7 +2874,7 @@ async fn provider_reachability_check(plan: ReachabilityPlan) -> DoctorCheck {
|
||||
)
|
||||
.measured(format!("{route_probe_url} returned {status}"))
|
||||
.expected("GET /models returns 2xx, 401, or 403")
|
||||
.remedy("Set base_url to the provider API root, for example https://api.openai.com/v1")
|
||||
.remedy("Set base_url to the provider API root, for example http://localhost:8080/v1")
|
||||
.field("route probe"),
|
||||
);
|
||||
}
|
||||
@@ -3922,7 +3918,6 @@ mod tests {
|
||||
Some("https://example.openai.azure.com/openai/v1"),
|
||||
/*provider_query_params*/ None,
|
||||
/*is_amazon_bedrock*/ false,
|
||||
"https://chatgpt.com/backend-api/",
|
||||
),
|
||||
ReachabilityPlan {
|
||||
description: "provider auth".to_string(),
|
||||
@@ -3953,7 +3948,6 @@ mod tests {
|
||||
Some("https://example.com/openai/v1/"),
|
||||
Some(&query_params),
|
||||
/*is_amazon_bedrock*/ false,
|
||||
"https://chatgpt.com/backend-api/",
|
||||
),
|
||||
ReachabilityPlan {
|
||||
description: description.to_string(),
|
||||
@@ -3984,14 +3978,13 @@ mod tests {
|
||||
Some("https://bedrock-runtime.us-east-1.amazonaws.com/openai/v1"),
|
||||
/*provider_query_params*/ None,
|
||||
/*is_amazon_bedrock*/ true,
|
||||
"https://chatgpt.com/backend-api/",
|
||||
);
|
||||
|
||||
assert_eq!(plan.endpoints[0].route_probe_url, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_reachability_api_key_does_not_require_chatgpt() {
|
||||
fn provider_reachability_never_infers_openai_endpoints() {
|
||||
let plan = provider_reachability_plan_from_parts(
|
||||
ProviderAuthReachabilityMode::ApiKey,
|
||||
"openai",
|
||||
@@ -3999,31 +3992,28 @@ mod tests {
|
||||
/*provider_base_url*/ None,
|
||||
/*provider_query_params*/ None,
|
||||
/*is_amazon_bedrock*/ false,
|
||||
"https://chatgpt.com/backend-api/",
|
||||
);
|
||||
assert_eq!(plan.endpoints, Vec::new());
|
||||
|
||||
assert_eq!(
|
||||
plan.endpoints,
|
||||
vec![ReachabilityEndpoint {
|
||||
label: "openai API".to_string(),
|
||||
url: "https://api.openai.com/v1/responses".to_string(),
|
||||
required: true,
|
||||
route_probe_url: Some("https://api.openai.com/v1/models".to_string()),
|
||||
}]
|
||||
);
|
||||
for base_url in [
|
||||
"https://api.openai.com/v1",
|
||||
"https://chatgpt.com/backend-api/",
|
||||
] {
|
||||
let plan = provider_reachability_plan_from_parts(
|
||||
ProviderAuthReachabilityMode::Chatgpt,
|
||||
"openai",
|
||||
"OpenAI",
|
||||
Some(base_url),
|
||||
/*provider_query_params*/ None,
|
||||
/*is_amazon_bedrock*/ false,
|
||||
);
|
||||
assert_eq!(plan.endpoints, Vec::new(), "{base_url}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_reachability_chatgpt_uses_inference_endpoint() {
|
||||
assert_eq!(
|
||||
default_reachability_plan().endpoints,
|
||||
vec![ReachabilityEndpoint {
|
||||
label: "ChatGPT".to_string(),
|
||||
url: "https://chatgpt.com/backend-api/codex/responses".to_string(),
|
||||
required: true,
|
||||
route_probe_url: None,
|
||||
}]
|
||||
);
|
||||
fn provider_reachability_default_plan_probes_nothing() {
|
||||
assert_eq!(default_reachability_plan().endpoints, Vec::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -4065,7 +4055,6 @@ mod tests {
|
||||
Some(&format!("http://{addr}/xxxx")),
|
||||
/*provider_query_params*/ None,
|
||||
/*is_amazon_bedrock*/ false,
|
||||
"https://chatgpt.com/backend-api/",
|
||||
);
|
||||
|
||||
let check = provider_reachability_check(plan).await;
|
||||
@@ -4081,7 +4070,7 @@ mod tests {
|
||||
assert_eq!(check.issues.len(), 1);
|
||||
assert_eq!(
|
||||
check.issues[0].remedy.as_deref(),
|
||||
Some("Set base_url to the provider API root, for example https://api.openai.com/v1")
|
||||
Some("Set base_url to the provider API root, for example http://localhost:8080/v1")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4106,7 +4095,6 @@ mod tests {
|
||||
Some(&format!("http://{addr}/v1")),
|
||||
/*provider_query_params*/ None,
|
||||
/*is_amazon_bedrock*/ false,
|
||||
"https://chatgpt.com/backend-api/",
|
||||
);
|
||||
|
||||
let check = provider_reachability_check(plan).await;
|
||||
|
||||
@@ -28,8 +28,6 @@ const HANDSHAKE_CHECK_ID: &str = "desktop.app_server.handshake";
|
||||
|
||||
pub(super) struct DesktopDiagnostics {
|
||||
pub(super) checks: Vec<DoctorCheck>,
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
pub(super) application: Option<platform::InstalledApp>,
|
||||
}
|
||||
|
||||
struct DesktopLog {
|
||||
@@ -69,8 +67,6 @@ pub(super) async fn collect() -> Option<DesktopDiagnostics> {
|
||||
#[cfg(target_os = "windows")]
|
||||
windows_security::collect().await,
|
||||
],
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
application: None,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -104,8 +100,6 @@ pub(super) async fn collect() -> Option<DesktopDiagnostics> {
|
||||
#[cfg(target_os = "windows")]
|
||||
windows_security::collect().await,
|
||||
],
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
application: Some(application),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -52,8 +52,6 @@ pub(in crate::doctor) struct InstalledApp {
|
||||
package_family: &'static str,
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(in crate::doctor) bundle: PathBuf,
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(in crate::doctor) build: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -268,16 +266,10 @@ pub(in crate::doctor) async fn inspect_macos_bundle(
|
||||
.or_else(|| metadata.get("CFBundleVersion"))
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(DiscoveryError)?;
|
||||
let build = metadata
|
||||
.get("CFBundleVersion")
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|value| value.parse().ok())
|
||||
.ok_or(DiscoveryError)?;
|
||||
|
||||
Ok(Some(InstalledApp {
|
||||
identity: "com.openai.codex",
|
||||
version: version.to_string(),
|
||||
bundle: bundle.to_path_buf(),
|
||||
build,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -17,13 +17,12 @@ async fn provider_reachability_rejects_proxy_authentication_challenges() {
|
||||
.mount(&proxy)
|
||||
.await;
|
||||
let plan = provider_reachability_plan_from_parts(
|
||||
ProviderAuthReachabilityMode::Chatgpt,
|
||||
"openai",
|
||||
"OpenAI",
|
||||
/*provider_base_url*/ None,
|
||||
ProviderAuthReachabilityMode::NotRequired,
|
||||
"local",
|
||||
"Local",
|
||||
Some(&format!("{}/v1", proxy.uri())),
|
||||
/*provider_query_params*/ None,
|
||||
/*is_amazon_bedrock*/ false,
|
||||
&format!("{}/backend-api/", proxy.uri()),
|
||||
);
|
||||
|
||||
let check = provider_reachability_check(plan).await;
|
||||
|
||||
@@ -1,55 +1,23 @@
|
||||
//! Diagnoses whether Codex update paths target the running installation.
|
||||
//!
|
||||
//! Update diagnostics combine cached version metadata, install-channel hints,
|
||||
//! and bounded latest-version HTTP probes. It never executes package managers or
|
||||
//! other helpers selected by PATH; npm update targets are not verified.
|
||||
//! aKode: diagnostics are local only (cached version metadata and install-channel hints).
|
||||
//! There are no latest-version probes (GitHub, Homebrew) and no desktop appcast probes.
|
||||
|
||||
use std::path::Path;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_core::config::Config;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use codex_install_context::InstallContext;
|
||||
use codex_install_context::InstallMethod;
|
||||
use http::Method;
|
||||
use serde::Deserialize;
|
||||
#[cfg(target_os = "macos")]
|
||||
use url::Url;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::DoctorCheck;
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
use super::DoctorIssue;
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
use super::desktop::platform::InstalledApp;
|
||||
use super::doctor_install_context;
|
||||
use super::doctor_managed_by_npm;
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
use super::network;
|
||||
|
||||
const MAX_VERSION_RESPONSE_BYTES: usize = 1024 * 1024;
|
||||
|
||||
const VERSION_FILE_NAME: &str = "version.json";
|
||||
const GITHUB_LATEST_RELEASE_URL: &str = "https://api.github.com/repos/openai/codex/releases/latest";
|
||||
const HOMEBREW_CASK_API_URL: &str = "https://formulae.brew.sh/api/cask/codex.json";
|
||||
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
|
||||
const DESKTOP_UPDATE_URL: &str = "https://persistent.oaistatic.com/codex-app-prod/appcast-x64.xml";
|
||||
#[cfg(all(target_os = "macos", not(target_arch = "x86_64")))]
|
||||
const DESKTOP_UPDATE_URL: &str = "https://persistent.oaistatic.com/codex-app-prod/appcast.xml";
|
||||
#[cfg(target_os = "macos")]
|
||||
const BACKEND_DESKTOP_UPDATE_URL: &str = "https://chatgpt.com/backend-api/wham/app/appcast";
|
||||
#[cfg(target_os = "windows")]
|
||||
const DESKTOP_UPDATE_URL: &str =
|
||||
"https://persistent.oaistatic.com/codex-app-prod/windows-store-update.json";
|
||||
|
||||
/// Builds the update-health row for the current installation.
|
||||
///
|
||||
/// Network failures while fetching latest-version metadata degrade the row to a
|
||||
/// warning instead of failing doctor outright; update freshness is useful
|
||||
/// support context but should not mask more direct install/config failures.
|
||||
/// Builds the update-health row for the current installation from local state only.
|
||||
pub(super) async fn updates_check(config: &Config) -> DoctorCheck {
|
||||
let current_exe = std::env::current_exe().ok();
|
||||
let install_context = doctor_install_context(current_exe.as_deref());
|
||||
@@ -63,306 +31,19 @@ pub(super) async fn updates_check(config: &Config) -> DoctorCheck {
|
||||
let version_file = config.codex_home.join(VERSION_FILE_NAME);
|
||||
push_cached_version_details(&mut details, &version_file);
|
||||
|
||||
let mut status = CheckStatus::Ok;
|
||||
let summary = "update configuration is locally consistent".to_string();
|
||||
|
||||
if doctor_managed_by_npm(current_exe.as_deref()) {
|
||||
details
|
||||
.push("npm update target: not inspected (PATH helpers are not executed)".to_string());
|
||||
}
|
||||
let client = RouteAwareClientPool::new_without_request_logging(
|
||||
config.http_client_factory(),
|
||||
ClientRouteClass::Other,
|
||||
);
|
||||
details.push("latest version probe: disabled (no network update checks)".to_string());
|
||||
|
||||
match fetch_latest_version(&client, &install_context).await {
|
||||
Ok(latest_version) => {
|
||||
details.push(format!("latest version: {latest_version}"));
|
||||
if is_newer(&latest_version, env!("CARGO_PKG_VERSION")) == Some(true) {
|
||||
details.push("latest version status: newer version is available".to_string());
|
||||
} else {
|
||||
details.push("latest version status: current version is not older".to_string());
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
status = status.max(CheckStatus::Warning);
|
||||
details.push(format!("latest version probe: {err}"));
|
||||
}
|
||||
}
|
||||
|
||||
DoctorCheck::new("updates.status", "updates", status, summary).details(details)
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
pub(super) async fn append_desktop_update(
|
||||
checks: &mut [DoctorCheck],
|
||||
config: Option<&Config>,
|
||||
application: &InstalledApp,
|
||||
) {
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(home) = std::env::var_os("HOME").map(PathBuf::from)
|
||||
&& let Some(build) = latest_macos_staged_build(
|
||||
&home
|
||||
.join("Library/Caches")
|
||||
.join(application.identity)
|
||||
.join("org.sparkle-project.Sparkle/Installation"),
|
||||
application.build,
|
||||
)
|
||||
.await
|
||||
&& let Some(update) = checks.iter_mut().find(|check| check.id == "updates.status")
|
||||
{
|
||||
update.details.extend([
|
||||
"desktop update status: ready to install".to_string(),
|
||||
format!("desktop latest build: {build}"),
|
||||
format!("desktop application: {}", application.identity),
|
||||
]);
|
||||
}
|
||||
|
||||
let Some(config) = config else {
|
||||
return;
|
||||
};
|
||||
let Some(reachability_index) = checks
|
||||
.iter()
|
||||
.position(|check| check.id == "network.provider_reachability")
|
||||
else {
|
||||
return;
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
let desktop_update_url = std::env::var_os("HOME")
|
||||
.map(PathBuf::from)
|
||||
.map(|home| {
|
||||
macos_desktop_update_url(&home, application, &os_info::get().version().to_string())
|
||||
})
|
||||
.unwrap_or_else(|| DESKTOP_UPDATE_URL.to_string());
|
||||
#[cfg(target_os = "windows")]
|
||||
let desktop_update_url = DESKTOP_UPDATE_URL;
|
||||
#[cfg(target_os = "macos")]
|
||||
let desktop_update_url = desktop_update_url.as_str();
|
||||
let desktop_update_display_url = desktop_update_url
|
||||
.split_once('?')
|
||||
.map_or(desktop_update_url, |(endpoint, _)| endpoint);
|
||||
let client = RouteAwareClientPool::new_without_request_logging(
|
||||
config.http_client_factory(),
|
||||
ClientRouteClass::Other,
|
||||
);
|
||||
let outcome = match client
|
||||
.request(Method::GET, desktop_update_url)
|
||||
.timeout(deadline.saturating_duration_since(tokio::time::Instant::now()))
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
Ok(response) => {
|
||||
let status = response.status().as_u16();
|
||||
#[cfg(target_os = "windows")]
|
||||
if status == 404 && response.url().scheme() == "https" {
|
||||
checks[reachability_index].details.push(format!(
|
||||
"desktop assets CDN: {desktop_update_display_url} reachable (HTTP 404; no update available)"
|
||||
));
|
||||
return;
|
||||
}
|
||||
if cfg!(target_os = "windows") && response.url().scheme() != "https" {
|
||||
Err("update manifest redirected to a non-HTTPS URL".to_string())
|
||||
} else if status == 407 {
|
||||
Err("proxy authentication required (HTTP 407)".to_string())
|
||||
} else if !(200..=299).contains(&status) {
|
||||
Err(format!("HTTP {status}"))
|
||||
} else {
|
||||
checks[reachability_index].details.push(format!(
|
||||
"desktop assets CDN: {desktop_update_display_url} reachable (HTTP {status})"
|
||||
));
|
||||
#[cfg(target_os = "windows")]
|
||||
if let Some(update) = checks.iter_mut().find(|check| check.id == "updates.status") {
|
||||
match response.bytes().await {
|
||||
Ok(body) => match windows_store_update(&body, &application.version) {
|
||||
Ok(Some(build)) => update.details.extend([
|
||||
"desktop update status: available".to_string(),
|
||||
format!("desktop latest build: {build}"),
|
||||
format!("desktop application: {}", application.identity),
|
||||
]),
|
||||
Ok(None) => {}
|
||||
Err(error) => {
|
||||
update.status = update.status.max(CheckStatus::Warning);
|
||||
update
|
||||
.details
|
||||
.push(format!("desktop update manifest: {error}"));
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
update.status = update.status.max(CheckStatus::Warning);
|
||||
update
|
||||
.details
|
||||
.push("desktop update manifest: response could not be read".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Err(error) => Err(network::request_error(error)),
|
||||
};
|
||||
|
||||
if let Err(error) = outcome {
|
||||
let reachability = &mut checks[reachability_index];
|
||||
reachability.details.push(format!(
|
||||
"desktop assets CDN: {desktop_update_display_url} {error} (optional)"
|
||||
));
|
||||
if reachability.status == CheckStatus::Ok {
|
||||
reachability.status = CheckStatus::Warning;
|
||||
reachability.summary = "desktop update and runtime CDN is unreachable".to_string();
|
||||
}
|
||||
reachability.issues.push(
|
||||
DoctorIssue::new(
|
||||
CheckStatus::Warning,
|
||||
"desktop update and runtime CDN is unreachable",
|
||||
)
|
||||
.measured(format!("{desktop_update_display_url} {error}"))
|
||||
.expected("desktop update and runtime CDN reachable over HTTPS")
|
||||
.remedy(
|
||||
if desktop_update_display_url.starts_with("https://chatgpt.com/") {
|
||||
"check proxy, firewall, DNS, and certificate access to chatgpt.com"
|
||||
} else {
|
||||
"check proxy, firewall, DNS, and certificate access to persistent.oaistatic.com"
|
||||
},
|
||||
)
|
||||
.field("desktop assets CDN"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn macos_desktop_update_url(home: &Path, application: &InstalledApp, os_version: &str) -> String {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ProductionAppcastState {
|
||||
#[serde(default)]
|
||||
backend_appcast_enabled: bool,
|
||||
installation_id: Option<String>,
|
||||
}
|
||||
|
||||
let state_path = home
|
||||
.join("Library/Application Support")
|
||||
.join(application.identity)
|
||||
.join("production-appcast-bootstrap.json");
|
||||
let Some(state) = std::fs::read(state_path)
|
||||
.ok()
|
||||
.and_then(|contents| serde_json::from_slice::<ProductionAppcastState>(&contents).ok())
|
||||
else {
|
||||
return DESKTOP_UPDATE_URL.to_string();
|
||||
};
|
||||
let Some(installation_id) = state
|
||||
.backend_appcast_enabled
|
||||
.then_some(state.installation_id)
|
||||
.flatten()
|
||||
else {
|
||||
return DESKTOP_UPDATE_URL.to_string();
|
||||
};
|
||||
|
||||
let Ok(mut url) = Url::parse(BACKEND_DESKTOP_UPDATE_URL) else {
|
||||
return DESKTOP_UPDATE_URL.to_string();
|
||||
};
|
||||
url.query_pairs_mut().extend_pairs([
|
||||
("installation_id", installation_id.as_str()),
|
||||
(
|
||||
"arch",
|
||||
if cfg!(target_arch = "x86_64") {
|
||||
"x64"
|
||||
} else {
|
||||
"arm64"
|
||||
},
|
||||
),
|
||||
("app_version", application.version.as_str()),
|
||||
("beta", "false"),
|
||||
("os-version", os_version),
|
||||
("plan_type", "unknown"),
|
||||
]);
|
||||
url.to_string()
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
fn windows_store_update(
|
||||
manifest: &[u8],
|
||||
installed_version: &str,
|
||||
) -> Result<Option<String>, &'static str> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct StoreManifest {
|
||||
schema_version: u64,
|
||||
build_version: String,
|
||||
store_product_id: String,
|
||||
package_identity: String,
|
||||
}
|
||||
|
||||
let manifest: StoreManifest =
|
||||
serde_json::from_slice(manifest).map_err(|_| "invalid Windows Store update manifest")?;
|
||||
if manifest.schema_version == 0
|
||||
|| manifest.store_product_id != "9PLM9XGG6VKS"
|
||||
|| manifest.package_identity != "OpenAI.Codex"
|
||||
{
|
||||
return Err("Windows Store update manifest does not target the production application");
|
||||
}
|
||||
let version = |value: &str| -> Option<[u64; 4]> {
|
||||
value
|
||||
.split('.')
|
||||
.map(str::parse::<u64>)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.ok()?
|
||||
.try_into()
|
||||
.ok()
|
||||
};
|
||||
let latest = version(&manifest.build_version)
|
||||
.ok_or("Windows Store update manifest contains an invalid build version")?;
|
||||
let installed =
|
||||
version(installed_version).ok_or("installed Windows application has an invalid version")?;
|
||||
Ok((latest > installed).then_some(manifest.build_version))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
async fn latest_macos_staged_build(root: &Path, installed_build: u64) -> Option<u64> {
|
||||
const MAX_STAGED_BUNDLES: usize = 64;
|
||||
|
||||
if !std::fs::symlink_metadata(root).ok()?.is_dir() {
|
||||
return None;
|
||||
}
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
|
||||
let mut inspected = 0;
|
||||
let mut latest = None;
|
||||
for entry in std::fs::read_dir(root).ok()? {
|
||||
if inspected == MAX_STAGED_BUNDLES || tokio::time::Instant::now() >= deadline {
|
||||
break;
|
||||
}
|
||||
let Ok(entry) = entry else {
|
||||
continue;
|
||||
};
|
||||
if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
let extracted = entry.path().join("extracted");
|
||||
if !std::fs::symlink_metadata(&extracted).is_ok_and(|metadata| metadata.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
let bundle = extracted.join("ChatGPT.app");
|
||||
if !std::fs::symlink_metadata(&bundle).is_ok_and(|metadata| metadata.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
inspected += 1;
|
||||
let Ok(result) = tokio::time::timeout_at(
|
||||
deadline,
|
||||
super::desktop::platform::inspect_macos_bundle(&bundle),
|
||||
)
|
||||
.await
|
||||
else {
|
||||
break;
|
||||
};
|
||||
if let Ok(Some(application)) = result
|
||||
&& application.build > installed_build
|
||||
{
|
||||
latest = Some(latest.map_or(application.build, |latest: u64| {
|
||||
latest.max(application.build)
|
||||
}));
|
||||
}
|
||||
}
|
||||
latest
|
||||
DoctorCheck::new(
|
||||
"updates.status",
|
||||
"updates",
|
||||
CheckStatus::Ok,
|
||||
"update configuration is locally consistent",
|
||||
)
|
||||
.details(details)
|
||||
}
|
||||
|
||||
fn push_cached_version_details(details: &mut Vec<String>, version_file: &Path) {
|
||||
@@ -399,92 +80,6 @@ fn update_action_label(context: &InstallContext) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
async fn fetch_latest_version(
|
||||
client: &RouteAwareClientPool,
|
||||
context: &InstallContext,
|
||||
) -> Result<String, String> {
|
||||
match &context.method {
|
||||
InstallMethod::Brew => fetch_homebrew_cask_version(client).await,
|
||||
InstallMethod::Npm
|
||||
| InstallMethod::Bun
|
||||
| InstallMethod::VitePlus
|
||||
| InstallMethod::Pnpm
|
||||
| InstallMethod::Standalone { .. }
|
||||
| InstallMethod::Other => fetch_latest_github_release_version(client).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn fetch_latest_github_release_version(
|
||||
client: &RouteAwareClientPool,
|
||||
) -> Result<String, String> {
|
||||
#[derive(Deserialize)]
|
||||
struct ReleaseInfo {
|
||||
tag_name: String,
|
||||
}
|
||||
|
||||
let info = http_get_json::<ReleaseInfo>(client, GITHUB_LATEST_RELEASE_URL).await?;
|
||||
info.tag_name
|
||||
.strip_prefix("rust-v")
|
||||
.map(str::to_string)
|
||||
.ok_or_else(|| format!("failed to parse latest tag {}", info.tag_name))
|
||||
}
|
||||
|
||||
async fn fetch_homebrew_cask_version(client: &RouteAwareClientPool) -> Result<String, String> {
|
||||
#[derive(Deserialize)]
|
||||
struct HomebrewCaskInfo {
|
||||
version: String,
|
||||
}
|
||||
|
||||
http_get_json::<HomebrewCaskInfo>(client, HOMEBREW_CASK_API_URL)
|
||||
.await
|
||||
.map(|info| info.version)
|
||||
}
|
||||
|
||||
async fn http_get_json<T>(client: &RouteAwareClientPool, url: &str) -> Result<T, String>
|
||||
where
|
||||
T: for<'de> Deserialize<'de>,
|
||||
{
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 5), async {
|
||||
let mut response = client
|
||||
.request(Method::GET, url)
|
||||
.header(
|
||||
http::header::USER_AGENT,
|
||||
concat!("codex-doctor/", env!("CARGO_PKG_VERSION")),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|err| err.to_string())?;
|
||||
if !response.status().is_success() {
|
||||
return Err(format!("HTTP {}", response.status()));
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
while let Some(chunk) = response.chunk().await.map_err(|err| err.to_string())? {
|
||||
if chunk.len() > MAX_VERSION_RESPONSE_BYTES.saturating_sub(body.len()) {
|
||||
return Err("version response exceeds size limit".to_string());
|
||||
}
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
serde_json::from_slice(&body).map_err(|err| err.to_string())
|
||||
})
|
||||
.await
|
||||
.map_err(|_| "version request timed out".to_string())?
|
||||
}
|
||||
|
||||
fn is_newer(latest: &str, current: &str) -> Option<bool> {
|
||||
match (parse_version(latest), parse_version(current)) {
|
||||
(Some(latest), Some(current)) => Some(latest > current),
|
||||
(Some(_), None) | (None, Some(_)) | (None, None) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_version(value: &str) -> Option<(u64, u64, u64)> {
|
||||
let mut parts = value.trim().split('.');
|
||||
let major = parts.next()?.parse::<u64>().ok()?;
|
||||
let minor = parts.next()?.parse::<u64>().ok()?;
|
||||
let patch = parts.next()?.parse::<u64>().ok()?;
|
||||
Some((major, minor, patch))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct VersionInfo {
|
||||
latest_version: String,
|
||||
@@ -499,191 +94,6 @@ mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn version_http_probe_decodes_json_and_rejects_invalid_responses() {
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
let server = MockServer::start().await;
|
||||
let client = RouteAwareClientPool::new_without_request_logging(
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
ClientRouteClass::Other,
|
||||
);
|
||||
for (endpoint, response) in [
|
||||
(
|
||||
"valid",
|
||||
ResponseTemplate::new(/*s*/ 200)
|
||||
.set_body_json(serde_json::json!({"version": "1.2.3"})),
|
||||
),
|
||||
(
|
||||
"invalid",
|
||||
ResponseTemplate::new(/*s*/ 200).set_body_string("not JSON"),
|
||||
),
|
||||
("unavailable", ResponseTemplate::new(/*s*/ 503)),
|
||||
("proxy_auth_required", ResponseTemplate::new(/*s*/ 407)),
|
||||
(
|
||||
"redirect",
|
||||
ResponseTemplate::new(/*s*/ 302)
|
||||
.insert_header("Location", format!("{}/valid", server.uri())),
|
||||
),
|
||||
(
|
||||
"timeout",
|
||||
ResponseTemplate::new(/*s*/ 200).set_delay(Duration::from_secs(/*secs*/ 6)),
|
||||
),
|
||||
(
|
||||
"oversized",
|
||||
ResponseTemplate::new(/*s*/ 200)
|
||||
.set_body_bytes(vec![b' '; MAX_VERSION_RESPONSE_BYTES + 1]),
|
||||
),
|
||||
] {
|
||||
Mock::given(method("GET"))
|
||||
.and(path(format!("/{endpoint}")))
|
||||
.respond_with(response)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let result = http_get_json::<serde_json::Value>(
|
||||
&client,
|
||||
&format!("{}/{endpoint}", server.uri()),
|
||||
)
|
||||
.await;
|
||||
if matches!(endpoint, "valid" | "redirect") {
|
||||
assert_eq!(result, Ok(serde_json::json!({"version": "1.2.3"})));
|
||||
} else if endpoint == "timeout" {
|
||||
assert_eq!(result, Err("version request timed out".to_string()));
|
||||
} else if endpoint == "proxy_auth_required" {
|
||||
assert_eq!(
|
||||
result,
|
||||
Err("HTTP 407 Proxy Authentication Required".to_string())
|
||||
);
|
||||
} else {
|
||||
assert!(result.is_err(), "{endpoint} must not be accepted");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn macos_update_probe_uses_the_persisted_production_appcast_feed() {
|
||||
let home = tempfile::tempdir().expect("temporary home should be created");
|
||||
let application = InstalledApp {
|
||||
identity: "com.openai.codex",
|
||||
version: "26.623.10000".to_string(),
|
||||
bundle: PathBuf::new(),
|
||||
build: 6139,
|
||||
};
|
||||
assert_eq!(
|
||||
macos_desktop_update_url(home.path(), &application, "26.6.0"),
|
||||
DESKTOP_UPDATE_URL
|
||||
);
|
||||
|
||||
let state_directory = home
|
||||
.path()
|
||||
.join("Library/Application Support/com.openai.codex");
|
||||
std::fs::create_dir_all(&state_directory)
|
||||
.expect("production appcast state directory should be created");
|
||||
std::fs::write(
|
||||
state_directory.join("production-appcast-bootstrap.json"),
|
||||
r#"{"backendAppcastEnabled":true,"installationId":"028e90f8-5f2a-47db-a05c-6a48f548d728"}"#,
|
||||
)
|
||||
.expect("production appcast state should be created");
|
||||
|
||||
let arch = if cfg!(target_arch = "x86_64") {
|
||||
"x64"
|
||||
} else {
|
||||
"arm64"
|
||||
};
|
||||
assert_eq!(
|
||||
macos_desktop_update_url(home.path(), &application, "26.6.0"),
|
||||
format!(
|
||||
"{BACKEND_DESKTOP_UPDATE_URL}?installation_id=028e90f8-5f2a-47db-a05c-6a48f548d728&arch={arch}&app_version=26.623.10000&beta=false&os-version=26.6.0&plan_type=unknown"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[tokio::test]
|
||||
async fn macos_staged_updates_require_a_newer_matching_extracted_bundle() {
|
||||
let root = tempfile::tempdir().expect("temporary Sparkle cache should be created");
|
||||
for index in 0..320 {
|
||||
std::fs::create_dir(root.path().join(format!("unrelated-{index}")))
|
||||
.expect("unrelated Sparkle cache directory should be created");
|
||||
}
|
||||
for (name, identity, build) in [
|
||||
("newest", "com.openai.codex", "6268"),
|
||||
("newer", "com.openai.codex", "6168"),
|
||||
("older", "com.openai.codex", "6138"),
|
||||
("different", "com.example.other", "9999"),
|
||||
("invalid", "com.openai.codex", "invalid"),
|
||||
] {
|
||||
let bundle = root.path().join(name).join("extracted/ChatGPT.app");
|
||||
write_macos_bundle(&bundle, identity, build);
|
||||
}
|
||||
let outside = tempfile::tempdir().expect("external fixture should be created");
|
||||
let linked = outside.path().join("ChatGPT.app");
|
||||
write_macos_bundle(&linked, "com.openai.codex", "9999");
|
||||
std::os::unix::fs::symlink(&linked, root.path().join("ChatGPT.app"))
|
||||
.expect("symlinked staged app fixture should be created");
|
||||
|
||||
assert_eq!(
|
||||
latest_macos_staged_build(root.path(), /*installed_build*/ 6139).await,
|
||||
Some(6268)
|
||||
);
|
||||
assert_eq!(
|
||||
latest_macos_staged_build(root.path(), /*installed_build*/ 6268).await,
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_store_updates_compare_all_four_production_build_components() {
|
||||
let mut manifest = serde_json::json!({
|
||||
"schemaVersion": 1,
|
||||
"buildVersion": "26.803.5235.1",
|
||||
"storeProductId": "9PLM9XGG6VKS",
|
||||
"packageIdentity": "OpenAI.Codex",
|
||||
});
|
||||
assert_eq!(
|
||||
windows_store_update(&serde_json::to_vec(&manifest).unwrap(), "26.803.5235.0"),
|
||||
Ok(Some("26.803.5235.1".to_string()))
|
||||
);
|
||||
assert_eq!(
|
||||
windows_store_update(&serde_json::to_vec(&manifest).unwrap(), "26.803.5235.1"),
|
||||
Ok(None)
|
||||
);
|
||||
manifest["storeProductId"] = "other".into();
|
||||
assert!(
|
||||
windows_store_update(&serde_json::to_vec(&manifest).unwrap(), "26.803.5235.0").is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn write_macos_bundle(path: &Path, identity: &str, build: &str) {
|
||||
let contents = path.join("Contents");
|
||||
std::fs::create_dir_all(&contents).expect("staged app fixture should be created");
|
||||
std::fs::write(
|
||||
contents.join("Info.plist"),
|
||||
format!(
|
||||
"<?xml version=\"1.0\"?><plist version=\"1.0\"><dict>\
|
||||
<key>CFBundleIdentifier</key><string>{identity}</string>\
|
||||
<key>CFBundleVersion</key><string>{build}</string>\
|
||||
</dict></plist>"
|
||||
),
|
||||
)
|
||||
.expect("staged app metadata should be created");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_newer_compares_plain_semver() {
|
||||
assert_eq!(is_newer("1.2.4", "1.2.3"), Some(true));
|
||||
assert_eq!(is_newer("1.2.3", "1.2.4"), Some(false));
|
||||
assert_eq!(is_newer("1.2.3-beta.1", "1.2.2"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_action_labels_install_contexts() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -5,11 +5,8 @@ use clap_complete::Shell;
|
||||
use clap_complete::generate;
|
||||
use codex_app_server_daemon::BootstrapOptions as AppServerBootstrapOptions;
|
||||
use codex_app_server_daemon::LifecycleCommand as AppServerLifecycleCommand;
|
||||
use codex_app_server_daemon::RemoteControlMode as AppServerRemoteControlMode;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_arg0::arg0_dispatch_or_else;
|
||||
use codex_chatgpt::apply_command::ApplyCommand;
|
||||
use codex_chatgpt::apply_command::run_apply_command;
|
||||
use codex_cli::cloud_config;
|
||||
use codex_cli::read_access_token_from_stdin;
|
||||
use codex_cli::read_api_key_from_stdin;
|
||||
@@ -19,12 +16,10 @@ use codex_cli::run_login_with_api_key;
|
||||
use codex_cli::run_login_with_browser;
|
||||
use codex_cli::run_login_with_device_code;
|
||||
use codex_cli::run_logout;
|
||||
use codex_cloud_tasks::Cli as CloudTasksCli;
|
||||
use codex_exec::Cli as ExecCli;
|
||||
use codex_exec::Command as ExecCommand;
|
||||
use codex_exec::ReviewArgs;
|
||||
use codex_execpolicy::ExecPolicyCheckCommand;
|
||||
use codex_responses_api_proxy::Args as ResponsesApiProxyArgs;
|
||||
use codex_rollout_trace::REDUCED_STATE_FILE_NAME;
|
||||
use codex_rollout_trace::replay_bundle;
|
||||
use codex_state::StateRuntime;
|
||||
@@ -51,13 +46,9 @@ use supports_color::Stream;
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
mod app_cmd;
|
||||
mod config_override_args;
|
||||
mod daemon_install;
|
||||
mod daemon_telemetry;
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
mod desktop_app;
|
||||
mod doctor;
|
||||
#[cfg(test)]
|
||||
#[path = "exec_args_tests.rs"]
|
||||
@@ -72,7 +63,6 @@ mod migrate_nfs_db;
|
||||
mod migrate_rollouts;
|
||||
mod plugin_cmd;
|
||||
mod queue_cmd;
|
||||
mod remote_control_cmd;
|
||||
#[cfg(target_os = "windows")]
|
||||
mod sandbox_setup;
|
||||
mod sandbox_uninstall;
|
||||
@@ -84,7 +74,6 @@ use crate::mcp_cmd::McpCli;
|
||||
use crate::plugin_cmd::PluginCli;
|
||||
use crate::plugin_cmd::PluginSubcommand;
|
||||
use crate::queue_cmd::QueueCommand;
|
||||
use crate::remote_control_cmd::RemoteControlCommand;
|
||||
use codex_exec_server_cli::ExecServerCommand;
|
||||
use doctor::DoctorCommand;
|
||||
use state_db_recovery as local_state_db;
|
||||
@@ -171,13 +160,6 @@ enum Subcommand {
|
||||
/// [experimental] Run the app server or related tooling.
|
||||
AppServer(AppServerCommand),
|
||||
|
||||
/// [experimental] Manage the app-server daemon with remote control enabled.
|
||||
RemoteControl(RemoteControlCommand),
|
||||
|
||||
/// Launch the Desktop app (opens the app installer if missing).
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
App(app_cmd::AppCommand),
|
||||
|
||||
/// Generate shell completion scripts.
|
||||
Completion(CompletionCommand),
|
||||
|
||||
@@ -197,10 +179,6 @@ enum Subcommand {
|
||||
#[clap(hide = true)]
|
||||
Execpolicy(ExecpolicyCommand),
|
||||
|
||||
/// Apply the latest diff produced by Codex agent as a `git apply` to your local working tree.
|
||||
#[clap(visible_alias = "a")]
|
||||
Apply(ApplyCommand),
|
||||
|
||||
/// Resume a previous interactive session (picker by default; use --last to continue the most recent).
|
||||
Resume(ResumeCommand),
|
||||
|
||||
@@ -225,14 +203,6 @@ enum Subcommand {
|
||||
/// Fork a previous interactive session (picker by default; use --last to fork the most recent).
|
||||
Fork(ForkCommand),
|
||||
|
||||
/// [EXPERIMENTAL] Browse tasks from Codex Cloud and apply changes locally.
|
||||
#[clap(name = "cloud", alias = "cloud-tasks")]
|
||||
Cloud(CloudTasksCli),
|
||||
|
||||
/// Internal: run the responses API proxy.
|
||||
#[clap(hide = true)]
|
||||
ResponsesApiProxy(ResponsesApiProxyArgs),
|
||||
|
||||
/// Internal: relay stdio to a Unix domain socket.
|
||||
#[clap(hide = true, name = "stdio-to-uds")]
|
||||
StdioToUds(StdioToUdsCommand),
|
||||
@@ -605,10 +575,6 @@ struct AppServerCommand {
|
||||
#[arg(long = "stdio", conflicts_with = "listen")]
|
||||
stdio: bool,
|
||||
|
||||
/// Enable remote control for this app-server process without changing persistence.
|
||||
#[arg(long = "remote-control", hide = true)]
|
||||
remote_control: bool,
|
||||
|
||||
/// Save loaded threads during managed daemon shutdown.
|
||||
#[arg(long, hide = true)]
|
||||
managed_daemon: bool,
|
||||
@@ -682,12 +648,6 @@ enum AppServerDaemonSubcommand {
|
||||
yes: bool,
|
||||
},
|
||||
|
||||
/// Enable remote control for future starts and a currently running managed daemon.
|
||||
EnableRemoteControl,
|
||||
|
||||
/// Disable remote control for future starts and a currently running managed daemon.
|
||||
DisableRemoteControl,
|
||||
|
||||
/// Stop the local app server daemon.
|
||||
Stop,
|
||||
|
||||
@@ -714,11 +674,7 @@ struct AppServerProxyCommand {
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
struct AppServerBootstrapCommand {
|
||||
/// Launch the managed app-server with remote control enabled.
|
||||
#[arg(long = "remote-control")]
|
||||
remote_control: bool,
|
||||
}
|
||||
struct AppServerBootstrapCommand {}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
struct GenerateTsCommand {
|
||||
@@ -1041,10 +997,11 @@ fn stage_str(stage: Stage) -> &'static str {
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
codex_build_info::initialize!();
|
||||
let remote_control_disabled = codex_app_server::take_remote_control_disabled_env();
|
||||
// aKode: remote control is not available; still consume the daemon's internal marker.
|
||||
let _ = codex_app_server::take_remote_control_disabled_env();
|
||||
arg0_dispatch_or_else(move |arg0_paths: Arg0DispatchPaths| async move {
|
||||
// Finish polling the large subcommand dispatcher before polling interactive TUI events.
|
||||
if let Some(tui) = Box::pin(dispatch_cli(arg0_paths, remote_control_disabled)).await? {
|
||||
if let Some(tui) = Box::pin(dispatch_cli(arg0_paths)).await? {
|
||||
tui.await?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -1053,7 +1010,6 @@ fn main() -> anyhow::Result<()> {
|
||||
|
||||
async fn dispatch_cli(
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
remote_control_disabled: bool,
|
||||
) -> anyhow::Result<Option<impl Future<Output = anyhow::Result<()>>>> {
|
||||
let MultitoolCli {
|
||||
config_overrides: mut root_config_overrides,
|
||||
@@ -1250,7 +1206,6 @@ async fn dispatch_cli(
|
||||
strict_config: app_server_strict_config,
|
||||
listen,
|
||||
stdio,
|
||||
remote_control,
|
||||
managed_daemon,
|
||||
analytics_default_enabled,
|
||||
auth,
|
||||
@@ -1297,18 +1252,9 @@ async fn dispatch_cli(
|
||||
cloud_skills_snapshot,
|
||||
code_mode_host_transport: code_mode_host.into(),
|
||||
managed_daemon,
|
||||
remote_control_startup_mode: match (remote_control, remote_control_disabled)
|
||||
{
|
||||
(true, _) => {
|
||||
codex_app_server::RemoteControlStartupMode::EnabledEphemeral
|
||||
}
|
||||
(false, true) => {
|
||||
codex_app_server::RemoteControlStartupMode::DisabledEphemeral
|
||||
}
|
||||
(false, false) => {
|
||||
codex_app_server::RemoteControlStartupMode::ResolvePersisted
|
||||
}
|
||||
},
|
||||
// aKode: remote control (chatgpt.com relay) is never started.
|
||||
remote_control_startup_mode:
|
||||
codex_app_server::RemoteControlStartupMode::DisabledEphemeral,
|
||||
..Default::default()
|
||||
};
|
||||
let exit = codex_app_server::run_main_with_transport_options(
|
||||
@@ -1332,10 +1278,10 @@ async fn dispatch_cli(
|
||||
AppServerDaemonSubcommand::Start => {
|
||||
print_app_server_daemon_output(AppServerLifecycleCommand::Start).await?;
|
||||
}
|
||||
AppServerDaemonSubcommand::Bootstrap(bootstrap_cli) => {
|
||||
AppServerDaemonSubcommand::Bootstrap(AppServerBootstrapCommand {}) => {
|
||||
let output =
|
||||
codex_app_server_daemon::bootstrap(AppServerBootstrapOptions {
|
||||
remote_control_enabled: bootstrap_cli.remote_control,
|
||||
remote_control_enabled: false,
|
||||
})
|
||||
.await?;
|
||||
println!("{}", serde_json::to_string(&output)?);
|
||||
@@ -1401,16 +1347,6 @@ async fn dispatch_cli(
|
||||
println!("{}", serde_json::to_string(&output)?);
|
||||
}
|
||||
}
|
||||
AppServerDaemonSubcommand::EnableRemoteControl => {
|
||||
print_app_server_remote_control_output(AppServerRemoteControlMode::Enabled)
|
||||
.await?;
|
||||
}
|
||||
AppServerDaemonSubcommand::DisableRemoteControl => {
|
||||
print_app_server_remote_control_output(
|
||||
AppServerRemoteControlMode::Disabled,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
AppServerDaemonSubcommand::Stop => {
|
||||
print_app_server_daemon_output(AppServerLifecycleCommand::Stop).await?;
|
||||
}
|
||||
@@ -1501,30 +1437,6 @@ async fn dispatch_cli(
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Subcommand::RemoteControl(mut remote_control_cli)) => {
|
||||
remote_control_cli.no_daemon |= interactive.no_daemon;
|
||||
let subcommand_name = remote_control_cli.subcommand_name();
|
||||
reject_remote_mode_for_subcommand(
|
||||
root_remote.as_deref(),
|
||||
root_remote_auth_token_env.as_deref(),
|
||||
subcommand_name,
|
||||
)?;
|
||||
remote_control_cmd::run(
|
||||
remote_control_cli,
|
||||
arg0_paths.clone(),
|
||||
root_config_overrides,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
Some(Subcommand::App(app_cli)) => {
|
||||
reject_remote_mode_for_subcommand(
|
||||
root_remote.as_deref(),
|
||||
root_remote_auth_token_env.as_deref(),
|
||||
"app",
|
||||
)?;
|
||||
app_cmd::run_app(app_cli).await?;
|
||||
}
|
||||
Some(Subcommand::Resume(ResumeCommand {
|
||||
session_id,
|
||||
last,
|
||||
@@ -1732,19 +1644,6 @@ async fn dispatch_cli(
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Some(Subcommand::Cloud(mut cloud_cli)) => {
|
||||
reject_remote_mode_for_subcommand(
|
||||
root_remote.as_deref(),
|
||||
root_remote_auth_token_env.as_deref(),
|
||||
"cloud",
|
||||
)?;
|
||||
prepend_config_flags(
|
||||
&mut cloud_cli.config_overrides,
|
||||
root_config_overrides.clone(),
|
||||
);
|
||||
codex_cloud_tasks::run_main(cloud_cli, arg0_paths.codex_linux_sandbox_exe.clone())
|
||||
.await?;
|
||||
}
|
||||
Some(Subcommand::Sandbox(SandboxCommand {
|
||||
host: mut sandbox_cli,
|
||||
subcommand,
|
||||
@@ -1866,27 +1765,6 @@ async fn dispatch_cli(
|
||||
run_execpolicycheck(cmd)?
|
||||
}
|
||||
},
|
||||
Some(Subcommand::Apply(mut apply_cli)) => {
|
||||
reject_remote_mode_for_subcommand(
|
||||
root_remote.as_deref(),
|
||||
root_remote_auth_token_env.as_deref(),
|
||||
"apply",
|
||||
)?;
|
||||
prepend_config_flags(
|
||||
&mut apply_cli.config_overrides,
|
||||
root_config_overrides.clone(),
|
||||
);
|
||||
run_apply_command(apply_cli, /*cwd*/ None).await?;
|
||||
}
|
||||
Some(Subcommand::ResponsesApiProxy(args)) => {
|
||||
reject_remote_mode_for_subcommand(
|
||||
root_remote.as_deref(),
|
||||
root_remote_auth_token_env.as_deref(),
|
||||
"responses-api-proxy",
|
||||
)?;
|
||||
tokio::task::spawn_blocking(move || codex_responses_api_proxy::run_main(args))
|
||||
.await??;
|
||||
}
|
||||
Some(Subcommand::StdioToUds(cmd)) => {
|
||||
reject_remote_mode_for_subcommand(
|
||||
root_remote.as_deref(),
|
||||
@@ -2375,23 +2253,17 @@ fn unsupported_subcommand_name_for_strict_config(
|
||||
Some(Subcommand::AppServer(app_server)) => {
|
||||
Some(app_server_subcommand_name(app_server.subcommand.as_ref()))
|
||||
}
|
||||
Some(Subcommand::RemoteControl(remote_control)) => Some(remote_control.subcommand_name()),
|
||||
Some(Subcommand::Mcp(_)) => Some("mcp"),
|
||||
Some(Subcommand::Plugin(_)) => Some("plugin"),
|
||||
Some(Subcommand::MigrateRollouts(_)) => Some("migrate-rollouts"),
|
||||
Some(Subcommand::MigrateNfsDb(_)) => Some("migrate-nfs-db"),
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
Some(Subcommand::App(_)) => Some("app"),
|
||||
Some(Subcommand::Login(_)) => Some("login"),
|
||||
Some(Subcommand::Logout(_)) => Some("logout"),
|
||||
Some(Subcommand::Completion(_)) => Some("completion"),
|
||||
Some(Subcommand::Update) => Some("update"),
|
||||
Some(Subcommand::Cloud(_)) => Some("cloud"),
|
||||
Some(Subcommand::Sandbox(_)) => Some("sandbox"),
|
||||
Some(Subcommand::Debug(_)) => Some("debug"),
|
||||
Some(Subcommand::Execpolicy(_)) => Some("execpolicy"),
|
||||
Some(Subcommand::Apply(_)) => Some("apply"),
|
||||
Some(Subcommand::ResponsesApiProxy(_)) => Some("responses-api-proxy"),
|
||||
Some(Subcommand::StdioToUds(_)) => Some("stdio-to-uds"),
|
||||
Some(Subcommand::Features(_)) => Some("features"),
|
||||
Some(Subcommand::TcpTunnel(_)) => Some("tcp-tunnel"),
|
||||
@@ -2438,12 +2310,6 @@ fn app_server_subcommand_name(subcommand: Option<&AppServerSubcommand>) -> &'sta
|
||||
AppServerDaemonSubcommand::Start => "app-server daemon start",
|
||||
AppServerDaemonSubcommand::Restart => "app-server daemon restart",
|
||||
AppServerDaemonSubcommand::Update { .. } => "app-server daemon update",
|
||||
AppServerDaemonSubcommand::EnableRemoteControl => {
|
||||
"app-server daemon enable-remote-control"
|
||||
}
|
||||
AppServerDaemonSubcommand::DisableRemoteControl => {
|
||||
"app-server daemon disable-remote-control"
|
||||
}
|
||||
AppServerDaemonSubcommand::Stop => "app-server daemon stop",
|
||||
AppServerDaemonSubcommand::Version => "app-server daemon version",
|
||||
AppServerDaemonSubcommand::PidUpdateLoop { .. } => "app-server daemon pid-update-loop",
|
||||
@@ -2471,14 +2337,6 @@ fn updater_http_client_factory(
|
||||
Ok(config.http_client_factory())
|
||||
}
|
||||
|
||||
async fn print_app_server_remote_control_output(
|
||||
mode: AppServerRemoteControlMode,
|
||||
) -> anyhow::Result<()> {
|
||||
let output = codex_app_server_daemon::set_remote_control(mode).await?;
|
||||
println!("{}", serde_json::to_string(&output)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_remote_auth_token_from_env_var_with<F>(
|
||||
env_var_name: &str,
|
||||
get_var: F,
|
||||
@@ -4263,7 +4121,6 @@ enabled = true
|
||||
fn app_server_analytics_default_disabled_without_flag() {
|
||||
let app_server = app_server_from_args(["codex", "app-server"].as_ref());
|
||||
assert!(!app_server.analytics_default_enabled);
|
||||
assert!(!app_server.remote_control);
|
||||
assert_eq!(
|
||||
app_server.listen,
|
||||
codex_app_server::AppServerTransport::Stdio
|
||||
@@ -4271,9 +4128,13 @@ enabled = true
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_server_remote_control_startup_flag_enables_remote_control() {
|
||||
let enabled = app_server_from_args(["codex", "app-server", "--remote-control"].as_ref());
|
||||
assert!(enabled.remote_control);
|
||||
fn removed_remote_control_flags_do_not_parse() {
|
||||
for args in [
|
||||
["codex", "app-server", "--remote-control"].as_slice(),
|
||||
["codex", "app-server", "daemon", "enable-remote-control"].as_slice(),
|
||||
] {
|
||||
assert!(MultitoolCli::try_parse_from(args).is_err(), "{args:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -4394,19 +4255,6 @@ enabled = true
|
||||
err.to_string(),
|
||||
"`--strict-config` is not supported for `codex mcp`"
|
||||
);
|
||||
|
||||
let cli = MultitoolCli::try_parse_from(["codex", "--strict-config", "remote-control"])
|
||||
.expect("parse");
|
||||
let err = reject_root_strict_config_for_subcommand(
|
||||
cli.interactive.strict_config,
|
||||
&cli.subcommand,
|
||||
)
|
||||
.expect_err("remote-control should not support root --strict-config");
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"`--strict-config` is not supported for `codex remote-control`"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -4425,34 +4273,6 @@ enabled = true
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reject_remote_flag_for_remote_control() {
|
||||
let cli = MultitoolCli::try_parse_from(["codex", "--remote", "unix://", "remote-control"])
|
||||
.expect("parse");
|
||||
let Some(Subcommand::RemoteControl(remote_control)) = &cli.subcommand else {
|
||||
panic!("expected remote-control subcommand");
|
||||
};
|
||||
assert_eq!(remote_control.subcommand_name(), "remote-control");
|
||||
|
||||
let err = reject_remote_mode_for_subcommand(
|
||||
cli.remote.remote.as_deref(),
|
||||
cli.remote.remote_auth_token_env.as_deref(),
|
||||
"remote-control",
|
||||
)
|
||||
.expect_err("remote-control should reject root --remote");
|
||||
|
||||
assert!(err.to_string().contains("remote-control"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_control_pair_parses() {
|
||||
let cli = MultitoolCli::try_parse_from(["codex", "remote-control", "pair"]).expect("parse");
|
||||
let Some(Subcommand::RemoteControl(remote_control)) = &cli.subcommand else {
|
||||
panic!("expected remote-control subcommand");
|
||||
};
|
||||
assert_eq!(remote_control.subcommand_name(), "remote-control pair");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_flag_parses_for_interactive_root() {
|
||||
let cli = MultitoolCli::try_parse_from(["codex", "--remote", "unix://codex.sock"])
|
||||
@@ -4736,21 +4556,10 @@ enabled = true
|
||||
#[test]
|
||||
fn app_server_daemon_subcommands_parse() {
|
||||
assert!(matches!(
|
||||
app_server_from_args(
|
||||
[
|
||||
"codex",
|
||||
"app-server",
|
||||
"daemon",
|
||||
"bootstrap",
|
||||
"--remote-control"
|
||||
]
|
||||
.as_ref()
|
||||
)
|
||||
.subcommand,
|
||||
app_server_from_args(["codex", "app-server", "daemon", "bootstrap"].as_ref())
|
||||
.subcommand,
|
||||
Some(AppServerSubcommand::Daemon(AppServerDaemonCommand {
|
||||
subcommand: AppServerDaemonSubcommand::Bootstrap(AppServerBootstrapCommand {
|
||||
remote_control: true
|
||||
})
|
||||
subcommand: AppServerDaemonSubcommand::Bootstrap(AppServerBootstrapCommand {})
|
||||
}))
|
||||
));
|
||||
assert!(matches!(
|
||||
@@ -4765,24 +4574,6 @@ enabled = true
|
||||
subcommand: AppServerDaemonSubcommand::Restart
|
||||
}))
|
||||
));
|
||||
assert!(matches!(
|
||||
app_server_from_args(
|
||||
["codex", "app-server", "daemon", "enable-remote-control"].as_ref()
|
||||
)
|
||||
.subcommand,
|
||||
Some(AppServerSubcommand::Daemon(AppServerDaemonCommand {
|
||||
subcommand: AppServerDaemonSubcommand::EnableRemoteControl
|
||||
}))
|
||||
));
|
||||
assert!(matches!(
|
||||
app_server_from_args(
|
||||
["codex", "app-server", "daemon", "disable-remote-control"].as_ref()
|
||||
)
|
||||
.subcommand,
|
||||
Some(AppServerSubcommand::Daemon(AppServerDaemonCommand {
|
||||
subcommand: AppServerDaemonSubcommand::DisableRemoteControl
|
||||
}))
|
||||
));
|
||||
assert!(matches!(
|
||||
app_server_from_args(["codex", "app-server", "daemon", "stop"].as_ref()).subcommand,
|
||||
Some(AppServerSubcommand::Daemon(AppServerDaemonCommand {
|
||||
|
||||
@@ -1,859 +0,0 @@
|
||||
use std::io::Write;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use clap::Args;
|
||||
use codex_app_server::AppServerRuntimeOptions;
|
||||
use codex_app_server::AppServerTransport;
|
||||
use codex_app_server_daemon::LifecycleCommand as AppServerLifecycleCommand;
|
||||
use codex_app_server_daemon::LifecycleOutput as AppServerLifecycleOutput;
|
||||
use codex_app_server_daemon::LifecycleStatus as AppServerLifecycleStatus;
|
||||
use codex_app_server_daemon::RemoteControlReadyOutput as AppServerRemoteControlReadyOutput;
|
||||
use codex_app_server_daemon::RemoteControlReadyStatus as AppServerRemoteControlReadyStatus;
|
||||
use codex_app_server_daemon::RemoteControlStartOutput as AppServerRemoteControlStartOutput;
|
||||
use codex_app_server_protocol::RemoteControlConnectionStatus;
|
||||
use codex_app_server_protocol::RemoteControlPairingStartResponse;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_features::Feature;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_cli::CliConfigOverrides;
|
||||
use codex_websocket_auth::WebsocketAuthSettings;
|
||||
use serde::Serialize;
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::timeout;
|
||||
|
||||
const FOREGROUND_SOCKET_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const FOREGROUND_SOCKET_CONNECT_RETRY_DELAY: Duration = Duration::from_millis(50);
|
||||
const FOREGROUND_APP_SERVER_ABORT_TIMEOUT: Duration = Duration::from_secs(1);
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
pub(crate) struct RemoteControlCommand {
|
||||
/// Emit machine-readable JSON.
|
||||
#[arg(long = "json", global = true)]
|
||||
json: bool,
|
||||
|
||||
/// Run an embedded app-server in the foreground until Ctrl-C.
|
||||
#[arg(long = "no-daemon")]
|
||||
pub(super) no_daemon: bool,
|
||||
|
||||
#[command(subcommand)]
|
||||
pub(super) subcommand: Option<RemoteControlSubcommand>,
|
||||
}
|
||||
|
||||
impl RemoteControlCommand {
|
||||
pub(crate) fn subcommand_name(&self) -> &'static str {
|
||||
match self.subcommand {
|
||||
None => "remote-control",
|
||||
Some(RemoteControlSubcommand::Start) => "remote-control start",
|
||||
Some(RemoteControlSubcommand::Stop) => "remote-control stop",
|
||||
Some(RemoteControlSubcommand::Pair) => "remote-control pair",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, clap::Subcommand)]
|
||||
pub(super) enum RemoteControlSubcommand {
|
||||
/// Start the app-server daemon with remote control enabled.
|
||||
Start,
|
||||
|
||||
/// Stop the app-server daemon.
|
||||
Stop,
|
||||
|
||||
/// Create and print a short-lived manual pairing code.
|
||||
Pair,
|
||||
}
|
||||
|
||||
pub(crate) async fn run(
|
||||
command: RemoteControlCommand,
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
root_config_overrides: CliConfigOverrides,
|
||||
) -> anyhow::Result<()> {
|
||||
if command.no_daemon && command.subcommand.is_some() {
|
||||
anyhow::bail!("`--no-daemon` cannot be used with a remote-control subcommand");
|
||||
}
|
||||
|
||||
if command.subcommand.is_none() {
|
||||
if command.no_daemon || command.json || !daemon_eligible(&root_config_overrides).await? {
|
||||
run_foreground_remote_control(command.json, arg0_paths, root_config_overrides).await?;
|
||||
} else {
|
||||
print_remote_control_progress(
|
||||
command.json,
|
||||
"Starting app-server daemon with remote control enabled...",
|
||||
)?;
|
||||
let daemon = match codex_app_server_daemon::start_with_features(&Default::default())
|
||||
.await
|
||||
{
|
||||
Ok(daemon) => daemon,
|
||||
#[cfg(windows)]
|
||||
Err(error) if error.is::<codex_app_server_daemon::DetachedLaunchRestricted>() => {
|
||||
return run_foreground_remote_control(
|
||||
command.json,
|
||||
arg0_paths,
|
||||
root_config_overrides,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
if daemon.backend.is_none() {
|
||||
return run_foreground_remote_control(
|
||||
command.json,
|
||||
arg0_paths,
|
||||
root_config_overrides,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let remote_control = codex_app_server_daemon::enable_remote_control_on_socket(
|
||||
&daemon.socket_path,
|
||||
FOREGROUND_SOCKET_CONNECT_TIMEOUT,
|
||||
FOREGROUND_SOCKET_CONNECT_RETRY_DELAY,
|
||||
)
|
||||
.await?;
|
||||
let output = AppServerRemoteControlReadyOutput {
|
||||
daemon: AppServerRemoteControlStartOutput::Start(daemon),
|
||||
remote_control,
|
||||
};
|
||||
print_remote_control_start_output(&output, command.json)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
match command.subcommand {
|
||||
Some(RemoteControlSubcommand::Start) => {
|
||||
print_remote_control_progress(
|
||||
command.json,
|
||||
"Starting app-server daemon with remote control enabled...",
|
||||
)?;
|
||||
let output = codex_app_server_daemon::ensure_remote_control_ready().await?;
|
||||
print_remote_control_start_output(&output, command.json)?;
|
||||
}
|
||||
Some(RemoteControlSubcommand::Stop) => {
|
||||
print_remote_control_progress(command.json, "Stopping remote control...")?;
|
||||
let output = codex_app_server_daemon::run(AppServerLifecycleCommand::Stop).await?;
|
||||
print_remote_control_stop_output(&output, command.json)?;
|
||||
}
|
||||
Some(RemoteControlSubcommand::Pair) => {
|
||||
let output = codex_app_server_daemon::start_remote_control_pairing().await?;
|
||||
print_remote_control_pairing_output(&output, command.json)?;
|
||||
}
|
||||
None => unreachable!("bare remote-control returned before explicit subcommand dispatch"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn daemon_eligible(root_config_overrides: &CliConfigOverrides) -> anyhow::Result<bool> {
|
||||
if !root_config_overrides.raw_overrides.is_empty()
|
||||
|| codex_login::is_workload_identity_selected()
|
||||
|| std::env::var_os(codex_exec_server::CODEX_EXEC_SERVER_URL_ENV_VAR).is_some()
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
if codex_app_server_daemon::is_elevated()? {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let Ok(config) = ConfigBuilder::default().build().await else {
|
||||
return Ok(false);
|
||||
};
|
||||
Ok(config.features.enabled(Feature::DaemonAutoStart)
|
||||
&& !codex_tui::uses_wsl_drvfs(&config.codex_home))
|
||||
}
|
||||
|
||||
fn print_remote_control_progress(json: bool, message: &str) -> anyhow::Result<()> {
|
||||
if json {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
println!("{message}");
|
||||
std::io::stdout()
|
||||
.flush()
|
||||
.context("failed to flush remote-control progress message")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_foreground_remote_control(
|
||||
json: bool,
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
root_config_overrides: CliConfigOverrides,
|
||||
) -> anyhow::Result<()> {
|
||||
print_remote_control_progress(json, "Starting app-server with remote control enabled...")?;
|
||||
#[cfg(not(windows))]
|
||||
let socket_dir = tempfile::Builder::new()
|
||||
.prefix("codex-rc-")
|
||||
.tempdir_in("/tmp")
|
||||
.or_else(|_| tempfile::tempdir())
|
||||
.context("failed to create private app-server socket directory")?;
|
||||
#[cfg(not(windows))]
|
||||
let socket_path = socket_dir.path().join("rc.sock");
|
||||
// Let the transport create this parent with a protected DACL instead of
|
||||
// inheriting the broader ACL from a directory created under `%TEMP%`.
|
||||
#[cfg(windows)]
|
||||
let socket_path = std::env::temp_dir()
|
||||
.join("codex-remote-control")
|
||||
.join(format!("rc-{}.sock", std::process::id()));
|
||||
let socket_path = AbsolutePathBuf::from_absolute_path(&socket_path)
|
||||
.context("private app-server socket path was not absolute")?;
|
||||
let transport = AppServerTransport::UnixSocket {
|
||||
socket_path: socket_path.clone(),
|
||||
};
|
||||
let runtime_options = AppServerRuntimeOptions {
|
||||
remote_control_startup_mode: codex_app_server::RemoteControlStartupMode::EnabledEphemeral,
|
||||
install_shutdown_signal_handler: false,
|
||||
..Default::default()
|
||||
};
|
||||
let (stop_rx, stop_signal_task) = foreground_stop_signal();
|
||||
let app_server = codex_app_server::run_main_with_transport_options(
|
||||
arg0_paths,
|
||||
root_config_overrides,
|
||||
LoaderOverrides::default(),
|
||||
/*strict_config*/ false,
|
||||
/*default_analytics_enabled*/ false,
|
||||
transport,
|
||||
SessionSource::VSCode,
|
||||
WebsocketAuthSettings::default(),
|
||||
runtime_options,
|
||||
);
|
||||
let mut app_server_task = tokio::spawn(async move { app_server.await.map(|_| ()) });
|
||||
|
||||
let summary = match wait_for_foreground_remote_control_start(
|
||||
&mut app_server_task,
|
||||
wait_for_foreground_remote_control_ready(socket_path),
|
||||
stop_rx.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
ForegroundStartupResult::Ready(summary) => summary,
|
||||
ForegroundStartupResult::Stopped => {
|
||||
abort_foreground_app_server(app_server_task).await;
|
||||
stop_signal_task.abort();
|
||||
return Ok(());
|
||||
}
|
||||
ForegroundStartupResult::ReadyFailed(error) => {
|
||||
abort_foreground_app_server(app_server_task).await;
|
||||
stop_signal_task.abort();
|
||||
return Err(error);
|
||||
}
|
||||
ForegroundStartupResult::AppServerExited(error) => {
|
||||
stop_signal_task.abort();
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
|
||||
if *stop_rx.borrow() {
|
||||
abort_foreground_app_server(app_server_task).await;
|
||||
stop_signal_task.abort();
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let Err(error) = print_foreground_ready_output(&summary, json) {
|
||||
abort_foreground_app_server(app_server_task).await;
|
||||
stop_signal_task.abort();
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
let result = wait_for_foreground_app_server(app_server_task, stop_rx).await;
|
||||
stop_signal_task.abort();
|
||||
result
|
||||
}
|
||||
|
||||
fn foreground_stop_signal() -> (watch::Receiver<bool>, JoinHandle<()>) {
|
||||
let (stop_tx, stop_rx) = watch::channel(false);
|
||||
let task = tokio::spawn(async move {
|
||||
if let Err(err) = tokio::signal::ctrl_c().await {
|
||||
eprintln!("failed to listen for Ctrl-C: {err}");
|
||||
}
|
||||
let _ = stop_tx.send(true);
|
||||
});
|
||||
(stop_rx, task)
|
||||
}
|
||||
|
||||
enum ForegroundStartupResult {
|
||||
Ready(AppServerRemoteControlReadyStatus),
|
||||
Stopped,
|
||||
ReadyFailed(anyhow::Error),
|
||||
AppServerExited(anyhow::Error),
|
||||
}
|
||||
|
||||
async fn wait_for_foreground_remote_control_start(
|
||||
app_server_task: &mut JoinHandle<std::io::Result<()>>,
|
||||
ready: impl std::future::Future<Output = anyhow::Result<AppServerRemoteControlReadyStatus>>,
|
||||
mut stop_rx: watch::Receiver<bool>,
|
||||
) -> ForegroundStartupResult {
|
||||
tokio::pin!(ready);
|
||||
|
||||
tokio::select! {
|
||||
ready_result = &mut ready => match ready_result {
|
||||
Ok(summary) => ForegroundStartupResult::Ready(summary),
|
||||
Err(error) => ForegroundStartupResult::ReadyFailed(error),
|
||||
},
|
||||
app_server_result = app_server_task => {
|
||||
ForegroundStartupResult::AppServerExited(
|
||||
foreground_app_server_exited_before_ready(app_server_result)
|
||||
)
|
||||
}
|
||||
_ = wait_for_stop_signal(&mut stop_rx) => ForegroundStartupResult::Stopped,
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_foreground_app_server(
|
||||
mut app_server_task: JoinHandle<std::io::Result<()>>,
|
||||
mut stop_rx: watch::Receiver<bool>,
|
||||
) -> anyhow::Result<()> {
|
||||
tokio::select! {
|
||||
app_server_result = &mut app_server_task => {
|
||||
app_server_result
|
||||
.context("foreground app-server task failed to join")?
|
||||
.context("foreground app-server exited with an error")?;
|
||||
}
|
||||
_ = wait_for_stop_signal(&mut stop_rx) => {
|
||||
abort_foreground_app_server(app_server_task).await;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn wait_for_stop_signal(stop_rx: &mut watch::Receiver<bool>) {
|
||||
if *stop_rx.borrow() {
|
||||
return;
|
||||
}
|
||||
let _ = stop_rx.wait_for(|stopped| *stopped).await;
|
||||
}
|
||||
|
||||
fn foreground_app_server_exited_before_ready(
|
||||
result: Result<std::io::Result<()>, tokio::task::JoinError>,
|
||||
) -> anyhow::Error {
|
||||
match result {
|
||||
Ok(Ok(())) => {
|
||||
anyhow::anyhow!("foreground app-server exited before remote control became ready")
|
||||
}
|
||||
Ok(Err(error)) => anyhow::Error::new(error)
|
||||
.context("foreground app-server exited before remote control became ready"),
|
||||
Err(error) => anyhow::Error::new(error)
|
||||
.context("foreground app-server task failed before remote control became ready"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn abort_foreground_app_server(app_server_task: JoinHandle<std::io::Result<()>>) {
|
||||
app_server_task.abort();
|
||||
let _ = timeout(FOREGROUND_APP_SERVER_ABORT_TIMEOUT, app_server_task).await;
|
||||
}
|
||||
|
||||
async fn wait_for_foreground_remote_control_ready(
|
||||
socket_path: AbsolutePathBuf,
|
||||
) -> anyhow::Result<AppServerRemoteControlReadyStatus> {
|
||||
codex_app_server_daemon::enable_remote_control_on_socket(
|
||||
socket_path.as_path(),
|
||||
FOREGROUND_SOCKET_CONNECT_TIMEOUT,
|
||||
FOREGROUND_SOCKET_CONNECT_RETRY_DELAY,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn print_remote_control_start_output(
|
||||
output: &AppServerRemoteControlReadyOutput,
|
||||
json: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
ensure_remote_control_startable(&output.remote_control)?;
|
||||
if json {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string(&RemoteControlStartJsonOutput::daemon(output))?
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for line in remote_control_start_human_lines(
|
||||
&output.remote_control,
|
||||
RemoteControlHumanOutputMode::Daemon,
|
||||
)? {
|
||||
println!("{line}");
|
||||
}
|
||||
for line in daemon_app_server_human_lines(&output.daemon) {
|
||||
println!("{line}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_foreground_ready_output(
|
||||
summary: &AppServerRemoteControlReadyStatus,
|
||||
json: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
if json {
|
||||
ensure_remote_control_startable(summary)?;
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string(&RemoteControlStartJsonOutput::foreground(summary))?
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for line in remote_control_start_human_lines(summary, RemoteControlHumanOutputMode::Foreground)?
|
||||
{
|
||||
println!("{line}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct RemoteControlStartJsonOutput<'a> {
|
||||
mode: RemoteControlModeJson,
|
||||
status: RemoteControlConnectionStatus,
|
||||
server_name: &'a str,
|
||||
environment_id: Option<&'a str>,
|
||||
timed_out: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
daemon: Option<&'a AppServerRemoteControlStartOutput>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
enum RemoteControlModeJson {
|
||||
Foreground,
|
||||
Daemon,
|
||||
}
|
||||
|
||||
impl<'a> RemoteControlStartJsonOutput<'a> {
|
||||
fn foreground(summary: &'a AppServerRemoteControlReadyStatus) -> Self {
|
||||
Self {
|
||||
mode: RemoteControlModeJson::Foreground,
|
||||
status: summary.status,
|
||||
server_name: &summary.server_name,
|
||||
environment_id: summary.environment_id.as_deref(),
|
||||
timed_out: summary.timed_out,
|
||||
daemon: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn daemon(output: &'a AppServerRemoteControlReadyOutput) -> Self {
|
||||
let remote_control = &output.remote_control;
|
||||
Self {
|
||||
mode: RemoteControlModeJson::Daemon,
|
||||
status: remote_control.status,
|
||||
server_name: &remote_control.server_name,
|
||||
environment_id: remote_control.environment_id.as_deref(),
|
||||
timed_out: remote_control.timed_out,
|
||||
daemon: Some(&output.daemon),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remote_control_start_human_message(
|
||||
output: &AppServerRemoteControlReadyStatus,
|
||||
) -> anyhow::Result<String> {
|
||||
ensure_remote_control_startable(output)?;
|
||||
match output.status {
|
||||
RemoteControlConnectionStatus::Connected => Ok(format!(
|
||||
"This machine is available for remote control as {}.",
|
||||
output.server_name
|
||||
)),
|
||||
RemoteControlConnectionStatus::Connecting => Ok(format!(
|
||||
"Remote control is enabled on {} and still connecting.",
|
||||
output.server_name
|
||||
)),
|
||||
RemoteControlConnectionStatus::Errored | RemoteControlConnectionStatus::Disabled => {
|
||||
unreachable!("errored and disabled statuses are rejected before formatting")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_remote_control_startable(
|
||||
output: &AppServerRemoteControlReadyStatus,
|
||||
) -> anyhow::Result<()> {
|
||||
match output.status {
|
||||
RemoteControlConnectionStatus::Connected | RemoteControlConnectionStatus::Connecting => {
|
||||
Ok(())
|
||||
}
|
||||
RemoteControlConnectionStatus::Errored => {
|
||||
anyhow::bail!(
|
||||
"Remote control is enabled on {} but the connection is errored.",
|
||||
output.server_name
|
||||
);
|
||||
}
|
||||
RemoteControlConnectionStatus::Disabled => {
|
||||
anyhow::bail!("Remote control is disabled on {}.", output.server_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum RemoteControlHumanOutputMode {
|
||||
Foreground,
|
||||
Daemon,
|
||||
}
|
||||
|
||||
fn remote_control_start_human_lines(
|
||||
summary: &AppServerRemoteControlReadyStatus,
|
||||
mode: RemoteControlHumanOutputMode,
|
||||
) -> anyhow::Result<Vec<String>> {
|
||||
let mut lines = vec![remote_control_start_human_message(summary)?];
|
||||
match mode {
|
||||
RemoteControlHumanOutputMode::Foreground => {
|
||||
lines.push("Press Ctrl-C to stop.".to_string());
|
||||
}
|
||||
RemoteControlHumanOutputMode::Daemon => {}
|
||||
}
|
||||
Ok(lines)
|
||||
}
|
||||
|
||||
fn daemon_app_server_human_lines(output: &AppServerRemoteControlStartOutput) -> Vec<String> {
|
||||
let (managed_codex_path, managed_codex_version) = daemon_app_server_identity(output);
|
||||
vec![
|
||||
"Daemon used app-server:".to_string(),
|
||||
format!(" path: {}", managed_codex_path.display()),
|
||||
format!(" version: {}", managed_codex_version.unwrap_or("unknown")),
|
||||
]
|
||||
}
|
||||
|
||||
fn daemon_app_server_identity(
|
||||
output: &AppServerRemoteControlStartOutput,
|
||||
) -> (&std::path::Path, Option<&str>) {
|
||||
match output {
|
||||
AppServerRemoteControlStartOutput::Bootstrap(output) => (
|
||||
&output.managed_codex_path,
|
||||
output.managed_codex_version.as_deref(),
|
||||
),
|
||||
AppServerRemoteControlStartOutput::Start(output) => (
|
||||
&output.managed_codex_path,
|
||||
output.managed_codex_version.as_deref(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn print_remote_control_stop_output(
|
||||
output: &AppServerLifecycleOutput,
|
||||
json: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
if json {
|
||||
println!("{}", serde_json::to_string(output)?);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
println!("{}", remote_control_stop_human_message(output));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_remote_control_pairing_output(
|
||||
output: &RemoteControlPairingStartResponse,
|
||||
json: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
println!("{}", format_remote_control_pairing_output(output, json)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn format_remote_control_pairing_output(
|
||||
output: &RemoteControlPairingStartResponse,
|
||||
json: bool,
|
||||
) -> anyhow::Result<String> {
|
||||
if json {
|
||||
return Ok(serde_json::to_string(output)?);
|
||||
}
|
||||
|
||||
let manual_pairing_code = output
|
||||
.manual_pairing_code
|
||||
.as_deref()
|
||||
.context("remote-control pairing response did not include a manual pairing code")?;
|
||||
Ok(format!("Pairing code: {manual_pairing_code}"))
|
||||
}
|
||||
|
||||
fn remote_control_stop_human_message(output: &AppServerLifecycleOutput) -> String {
|
||||
match output.status {
|
||||
AppServerLifecycleStatus::Stopped => "Remote control stopped.".to_string(),
|
||||
AppServerLifecycleStatus::NotRunning => "Remote control is not running.".to_string(),
|
||||
AppServerLifecycleStatus::Started
|
||||
| AppServerLifecycleStatus::Restarted
|
||||
| AppServerLifecycleStatus::AlreadyRunning
|
||||
| AppServerLifecycleStatus::Running => {
|
||||
format!(
|
||||
"Remote control stop completed with status {:?}.",
|
||||
output.status
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn remote_control_status(
|
||||
status: RemoteControlConnectionStatus,
|
||||
) -> AppServerRemoteControlReadyStatus {
|
||||
AppServerRemoteControlReadyStatus {
|
||||
status,
|
||||
server_name: "owen-mbp".to_string(),
|
||||
environment_id: Some("env_test".to_string()),
|
||||
timed_out: status == RemoteControlConnectionStatus::Connecting,
|
||||
}
|
||||
}
|
||||
|
||||
fn daemon_ready_output(
|
||||
status: RemoteControlConnectionStatus,
|
||||
) -> AppServerRemoteControlReadyOutput {
|
||||
AppServerRemoteControlReadyOutput {
|
||||
daemon: AppServerRemoteControlStartOutput::Start(AppServerLifecycleOutput {
|
||||
status: AppServerLifecycleStatus::Started,
|
||||
backend: None,
|
||||
pid: Some(42),
|
||||
managed_codex_path: PathBuf::from("/opt/codex/bin/codex"),
|
||||
managed_codex_version: Some("1.0.0".to_string()),
|
||||
socket_path: PathBuf::from("/tmp/app-server-control.sock"),
|
||||
cli_version: Some("1.0.0".to_string()),
|
||||
app_server_version: Some("2.0.0".to_string()),
|
||||
}),
|
||||
remote_control: AppServerRemoteControlReadyStatus {
|
||||
status,
|
||||
server_name: "owen-mbp".to_string(),
|
||||
environment_id: Some("env_test".to_string()),
|
||||
timed_out: status == RemoteControlConnectionStatus::Connecting,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn pairing_response(manual_pairing_code: Option<&str>) -> RemoteControlPairingStartResponse {
|
||||
RemoteControlPairingStartResponse {
|
||||
pairing_code: "pairing-code".to_string(),
|
||||
manual_pairing_code: manual_pairing_code.map(str::to_string),
|
||||
environment_id: "env_test".to_string(),
|
||||
expires_at: 1_700_000_000,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_control_human_start_messages_use_server_name() {
|
||||
assert_eq!(
|
||||
remote_control_start_human_message(&remote_control_status(
|
||||
RemoteControlConnectionStatus::Connected
|
||||
))
|
||||
.expect("connected message"),
|
||||
"This machine is available for remote control as owen-mbp."
|
||||
);
|
||||
assert_eq!(
|
||||
remote_control_start_human_message(&remote_control_status(
|
||||
RemoteControlConnectionStatus::Connecting
|
||||
))
|
||||
.expect("connecting message"),
|
||||
"Remote control is enabled on owen-mbp and still connecting."
|
||||
);
|
||||
assert_eq!(
|
||||
remote_control_start_human_message(&remote_control_status(
|
||||
RemoteControlConnectionStatus::Errored
|
||||
))
|
||||
.expect_err("errored status should fail")
|
||||
.to_string(),
|
||||
"Remote control is enabled on owen-mbp but the connection is errored."
|
||||
);
|
||||
assert_eq!(
|
||||
remote_control_start_human_message(&remote_control_status(
|
||||
RemoteControlConnectionStatus::Disabled
|
||||
))
|
||||
.expect_err("disabled status should fail")
|
||||
.to_string(),
|
||||
"Remote control is disabled on owen-mbp."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_control_human_lines_include_foreground_stop_hint_only() {
|
||||
let summary = remote_control_status(RemoteControlConnectionStatus::Connected);
|
||||
|
||||
assert_eq!(
|
||||
remote_control_start_human_lines(&summary, RemoteControlHumanOutputMode::Foreground)
|
||||
.expect("foreground lines"),
|
||||
vec![
|
||||
"This machine is available for remote control as owen-mbp.".to_string(),
|
||||
"Press Ctrl-C to stop.".to_string(),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
remote_control_start_human_lines(&summary, RemoteControlHumanOutputMode::Daemon)
|
||||
.expect("daemon lines"),
|
||||
vec!["This machine is available for remote control as owen-mbp.".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daemon_app_server_human_lines_include_path_and_version() {
|
||||
assert_eq!(
|
||||
daemon_app_server_human_lines(
|
||||
&daemon_ready_output(RemoteControlConnectionStatus::Connected).daemon
|
||||
),
|
||||
vec![
|
||||
"Daemon used app-server:".to_string(),
|
||||
" path: /opt/codex/bin/codex".to_string(),
|
||||
" version: 1.0.0".to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_control_json_output_marks_foreground_or_daemon() {
|
||||
let foreground_summary = remote_control_status(RemoteControlConnectionStatus::Connected);
|
||||
assert_eq!(
|
||||
serde_json::to_value(RemoteControlStartJsonOutput::foreground(
|
||||
&foreground_summary
|
||||
))
|
||||
.expect("foreground JSON"),
|
||||
json!({
|
||||
"mode": "foreground",
|
||||
"status": "connected",
|
||||
"serverName": "owen-mbp",
|
||||
"environmentId": "env_test",
|
||||
"timedOut": false,
|
||||
})
|
||||
);
|
||||
|
||||
let daemon_output = daemon_ready_output(RemoteControlConnectionStatus::Connected);
|
||||
assert_eq!(
|
||||
serde_json::to_value(RemoteControlStartJsonOutput::daemon(&daemon_output))
|
||||
.expect("daemon JSON"),
|
||||
json!({
|
||||
"mode": "daemon",
|
||||
"status": "connected",
|
||||
"serverName": "owen-mbp",
|
||||
"environmentId": "env_test",
|
||||
"timedOut": false,
|
||||
"daemon": {
|
||||
"status": "started",
|
||||
"pid": 42,
|
||||
"managedCodexPath": "/opt/codex/bin/codex",
|
||||
"managedCodexVersion": "1.0.0",
|
||||
"socketPath": "/tmp/app-server-control.sock",
|
||||
"cliVersion": "1.0.0",
|
||||
"appServerVersion": "2.0.0",
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_control_daemon_json_rejects_unstartable_status() {
|
||||
assert_eq!(
|
||||
print_remote_control_start_output(
|
||||
&daemon_ready_output(RemoteControlConnectionStatus::Errored),
|
||||
/*json*/ true
|
||||
)
|
||||
.expect_err("errored daemon status should fail")
|
||||
.to_string(),
|
||||
"Remote control is enabled on owen-mbp but the connection is errored."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_control_pairing_human_output_labels_the_manual_code() {
|
||||
assert_eq!(
|
||||
format_remote_control_pairing_output(
|
||||
&pairing_response(Some("ABCD-EFGH")),
|
||||
/*json*/ false,
|
||||
)
|
||||
.expect("manual pairing output"),
|
||||
"Pairing code: ABCD-EFGH"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_control_pairing_json_output_preserves_pairing_artifacts() {
|
||||
let output = format_remote_control_pairing_output(
|
||||
&pairing_response(Some("ABCD-EFGH")),
|
||||
/*json*/ true,
|
||||
)
|
||||
.expect("pairing JSON output");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&output).expect("valid JSON"),
|
||||
json!({
|
||||
"pairingCode": "pairing-code",
|
||||
"manualPairingCode": "ABCD-EFGH",
|
||||
"environmentId": "env_test",
|
||||
"expiresAt": 1_700_000_000,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_control_pairing_human_output_requires_manual_code() {
|
||||
assert_eq!(
|
||||
format_remote_control_pairing_output(
|
||||
&pairing_response(/*manual_pairing_code*/ None),
|
||||
/*json*/ false,
|
||||
)
|
||||
.expect_err("missing manual pairing code should fail")
|
||||
.to_string(),
|
||||
"remote-control pairing response did not include a manual pairing code"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn foreground_wait_aborts_app_server_on_stop_signal() {
|
||||
let app_server_task = tokio::spawn(std::future::pending::<std::io::Result<()>>());
|
||||
let (stop_tx, stop_rx) = tokio::sync::watch::channel(false);
|
||||
stop_tx.send(true).expect("send stop signal");
|
||||
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(1),
|
||||
wait_for_foreground_app_server(app_server_task, stop_rx),
|
||||
)
|
||||
.await
|
||||
.expect("foreground wait should return after stop signal")
|
||||
.expect("stop signal should shut down cleanly");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn foreground_start_wait_stops_before_ready() {
|
||||
let mut app_server_task = tokio::spawn(std::future::pending::<std::io::Result<()>>());
|
||||
let (stop_tx, stop_rx) = tokio::sync::watch::channel(false);
|
||||
stop_tx.send(true).expect("send stop signal");
|
||||
|
||||
let startup = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(1),
|
||||
wait_for_foreground_remote_control_start(
|
||||
&mut app_server_task,
|
||||
std::future::pending::<anyhow::Result<AppServerRemoteControlReadyStatus>>(),
|
||||
stop_rx,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("foreground startup wait should return after stop signal");
|
||||
|
||||
assert!(matches!(startup, ForegroundStartupResult::Stopped));
|
||||
app_server_task.abort();
|
||||
let _ = app_server_task.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn foreground_start_wait_reports_app_server_exit_before_ready() {
|
||||
let mut app_server_task =
|
||||
tokio::spawn(async { Err(std::io::Error::other("startup failed before socket bind")) });
|
||||
let (_stop_tx, stop_rx) = tokio::sync::watch::channel(false);
|
||||
|
||||
let startup = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(1),
|
||||
wait_for_foreground_remote_control_start(
|
||||
&mut app_server_task,
|
||||
std::future::pending::<anyhow::Result<AppServerRemoteControlReadyStatus>>(),
|
||||
stop_rx,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("foreground startup wait should return after app-server exits");
|
||||
|
||||
let ForegroundStartupResult::AppServerExited(error) = startup else {
|
||||
panic!("expected app-server exit before ready");
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"foreground app-server exited before remote control became ready"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user