aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,339 @@
use std::path::Path;
use anyhow::Result;
use app_test_support::app_server_json_shutdown_event;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home)
.env_remove("AKODE_ACCESS_TOKEN")
.env_remove("AKODE_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove("OPENAI_FEDERATION_RULE_ID")
.env_remove("OPENAI_IDENTITY_TOKEN_FILE")
.env_remove("OPENAI_WORKLOAD_IDENTITY_CONTEXT");
Ok(cmd)
}
#[test]
fn strict_config_rejects_unknown_config_fields_for_app_server() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
r#"
foo = "bar"
"#,
)?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["app-server", "--strict-config", "--listen", "off"])
.assert()
.failure()
.stderr(contains("unknown configuration field"));
Ok(())
}
#[test]
fn app_server_preserves_config_overrides_across_subcommand() -> Result<()> {
let home = TempDir::new()?;
codex_command(home.path())?
.args([
"-c",
"missing-equals",
"app-server",
"--print-startup-config",
"-c",
"model=example",
])
.assert()
.failure()
.stdout(contains("Invalid override (missing '='): missing-equals"));
Ok(())
}
#[test]
fn agents_accept_interactive_configuration_overrides() -> Result<()> {
let codex_home = TempDir::new()?;
for args in [
["-c", "features.multi_agent_mode=true", "agents"].as_slice(),
["--enable", "multi_agent_mode", "agents"].as_slice(),
["--yolo", "agents"].as_slice(),
["--no-daemon", "agents"].as_slice(),
["agents", "--no-daemon"].as_slice(),
["--search", "agents"].as_slice(),
["--model", "gpt-5", "agents"].as_slice(),
["--approve-for-me", "agents"].as_slice(),
["--cd", ".", "agents"].as_slice(),
] {
let mut cmd = codex_command(codex_home.path())?;
cmd.env("TERM", "xterm-256color").args(args);
cmd.assert()
.failure()
.stderr(contains("stdin is not a terminal"));
}
Ok(())
}
#[test]
fn agents_reject_inputs_that_cannot_be_applied() -> Result<()> {
let codex_home = TempDir::new()?;
for (args, expected_error) in [
(
["--image=image.png", "agents"].as_slice(),
"does not accept an initial prompt or images",
),
(
["--oss", "agents", "--remote", "ws://127.0.0.1:4512"].as_slice(),
"cannot apply local provider or additional-directory overrides",
),
(
[
"--add-dir",
".",
"agents",
"--remote",
"ws://127.0.0.1:4512",
]
.as_slice(),
"cannot apply local provider or additional-directory overrides",
),
(
[
"-c",
"sandbox_workspace_write.writable_roots=[\"../shared\"]",
"agents",
"--remote",
"ws://127.0.0.1:4512",
]
.as_slice(),
"cannot apply local provider or additional-directory overrides",
),
] {
let mut cmd = codex_command(codex_home.path())?;
cmd.args(args)
.assert()
.failure()
.stderr(contains(expected_error));
}
Ok(())
}
#[test]
fn app_server_emits_json_info_events() -> Result<()> {
let codex_home = TempDir::new()?;
let event = app_server_json_shutdown_event("codex", &["app-server"], codex_home.path())?;
assert_eq!(
event,
json!({
"level": "INFO",
"fields": {
"message": "processor task exited",
"exit_reason": "stdio_connection_closed",
"remaining_connection_count": 0,
"shutdown_forced": false,
},
"target": "akode_app_server",
})
);
Ok(())
}
#[test]
fn app_server_keeps_sqlite_logs_in_overridden_sqlite_home() -> Result<()> {
let home = TempDir::new()?;
let sqlite_home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
"[features]\nplugins = false\n",
)?;
codex_command(home.path())?
.env("AKODE_SQLITE_HOME", sqlite_home.path())
.env(
"AKODE_APP_SERVER_MANAGED_CONFIG_PATH",
home.path().join("managed_config.toml"),
)
.arg("app-server")
.write_stdin("")
.assert()
.success();
assert!(sqlite_home.path().join("state_5.sqlite").is_file());
assert!(std::fs::metadata(sqlite_home.path().join("logs_2.sqlite"))?.len() > 0);
assert!(!home.path().join("logs_2.sqlite").exists());
assert!(!home.path().join("log/logs_2.sqlite").exists());
Ok(())
}
#[cfg(unix)]
#[test]
fn app_server_preserves_the_existing_sqlite_logs_symlink() -> Result<()> {
let home = TempDir::new()?;
let external_logs = TempDir::new()?;
let target = external_logs.path().join("logs_2.sqlite");
let link = home.path().join("logs_2.sqlite");
std::os::unix::fs::symlink(&target, &link)?;
std::fs::write(
home.path().join("config.toml"),
"[features]\nplugins = false\n",
)?;
codex_command(home.path())?
.env_remove("AKODE_SQLITE_HOME")
.env(
"AKODE_APP_SERVER_MANAGED_CONFIG_PATH",
home.path().join("managed_config.toml"),
)
.arg("app-server")
.write_stdin("")
.assert()
.success();
assert_eq!(std::fs::read_link(&link)?, target);
assert!(std::fs::metadata(&target)?.len() > 0);
assert!(home.path().join("state_5.sqlite").is_file());
assert!(!home.path().join("log/logs_2.sqlite").exists());
Ok(())
}
#[test]
fn print_startup_config_preserves_project_login_restrictions() -> Result<()> {
let home = TempDir::new()?;
let project = TempDir::new()?;
let project_key =
serde_json::to_string(&akode_config::loader::project_trust_key(project.path()))?;
std::fs::write(
home.path().join("config.toml"),
format!("[projects.{project_key}]\ntrust_level = \"trusted\"\n"),
)?;
std::fs::create_dir(project.path().join(".git"))?;
std::fs::create_dir(project.path().join(".akode"))?;
for method in ["chatgpt", "api"] {
std::fs::write(
project.path().join(".akode/config.toml"),
format!("forced_login_method = '{method}'\n"),
)?;
for sign_out in [None, Some("--startup-sign-out")] {
let mut command = codex_command(home.path())?;
command
.current_dir(project.path())
.args(["app-server", "--print-startup-config"])
.args(sign_out);
let output = command.assert().success();
let value: serde_json::Value = serde_json::from_slice(&output.get_output().stdout)?;
assert_eq!(
value["configRequirements"]["requirements"]["allowedLoginMethods"],
json!([method])
);
}
}
Ok(())
}
#[test]
fn print_startup_config_validates_configuration() -> Result<()> {
let home = TempDir::new()?;
let config_path = home.path().join("config.toml");
for (config, strict_arg, error) in [
("[broken\n", None, Some("failed to load configuration")),
(
"unknown_future_setting = true\n",
Some("--strict-config"),
Some("unknown configuration field"),
),
("unknown_future_setting = true\n", None, None),
] {
std::fs::write(&config_path, config)?;
let output = codex_command(home.path())?
.args(["app-server", "--print-startup-config"])
.args(strict_arg)
.assert();
let value: serde_json::Value = serde_json::from_slice(&output.get_output().stdout)?;
if let Some(error) = error {
output.failure().stdout(contains(error));
assert_eq!(value["error"]["data"]["reason"], "configLoad");
assert_eq!(
Path::new(value["error"]["data"]["filePath"].as_str().unwrap()).canonicalize()?,
config_path.canonicalize()?
);
assert!(value["error"]["data"]["line"].as_u64().is_some());
assert!(value.get("configRequirements").is_none());
} else {
output.success();
assert_eq!(value["appServerVersion"], env!("CARGO_PKG_VERSION"));
assert!(value["configRequirements"].get("requirements").is_some());
assert!(value.get("config").is_none());
}
}
Ok(())
}
#[tokio::test]
async fn print_startup_config_is_independent_of_a_locked_history_database() -> Result<()> {
use sqlx::Executor;
use std::time::Duration;
use tokio::process::Command;
use tokio::time::timeout;
let home = TempDir::new()?;
let sqlite = TempDir::new()?;
let binary = akode_utils_cargo_bin::cargo_bin("akode")?;
let mut command = Command::new(&binary);
command
.env("AKODE_HOME", home.path())
.env("AKODE_SQLITE_HOME", sqlite.path())
.env_remove("AKODE_ACCESS_TOKEN")
.env_remove("AKODE_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove("OPENAI_FEDERATION_RULE_ID")
.env_remove("OPENAI_IDENTITY_TOKEN_FILE")
.env_remove("OPENAI_WORKLOAD_IDENTITY_CONTEXT")
.args(["app-server", "--print-startup-config"])
.kill_on_drop(true);
let baseline = timeout(Duration::from_secs(10), command.output()).await??;
assert!(baseline.status.success());
let path = sqlite.path().join("state_5.sqlite");
let sqlite_config = akode_state::SqliteConfig::new_for_testing(
akode_utils_absolute_path::AbsolutePathBuf::from_absolute_path(sqlite.path())?,
);
let pool = sqlite_config.open_read_write_pool(&path).await?;
let mut database = pool.acquire().await?;
database
.execute("CREATE TABLE synthetic_history (id INTEGER)")
.await?;
database.execute("PRAGMA journal_mode=DELETE").await?;
let readers = sqlite_config
.open_read_only_pool(&path, Some(Duration::ZERO))
.await?;
let mut reader = readers.acquire().await?;
database.execute("BEGIN EXCLUSIVE").await?;
assert!(
reader
.execute("SELECT * FROM synthetic_history")
.await
.is_err()
);
let before = std::fs::read(&path)?;
let output = timeout(Duration::from_secs(10), command.output()).await??;
assert!(output.status.success());
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&output.stdout)?,
serde_json::from_slice::<serde_json::Value>(&baseline.stdout)?
);
assert_eq!(std::fs::read(&path)?, before);
database.execute("ROLLBACK").await?;
Ok(())
}

View File

@@ -0,0 +1,552 @@
//! Managed daemon lifecycle through the public CLI, using isolated standalone fixtures.
#![cfg(unix)]
#[path = "app_server_daemon/support.rs"]
mod support;
use support::TestDaemon;
use support::signal;
use support::wait_for_exit;
use std::process::Command;
use std::process::Stdio;
use std::time::Duration;
use std::time::Instant;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use pretty_assertions::assert_eq;
use serde_json::Value;
#[test]
fn managed_daemon_restarts_from_deleted_working_directory() -> Result<()> {
let daemon = TestDaemon::new()?;
let project = daemon.home.path().join("project");
std::fs::create_dir(&project)?;
let started = daemon
.command()
.current_dir(&project)
.args(["app-server", "daemon", "start"])
.output()?;
ensure!(
started.status.success(),
"{}",
String::from_utf8_lossy(&started.stderr)
);
let old_pid = daemon.pid("app-server.pid")?;
let old_updater_pid = daemon.pid("app-server-updater.pid")?;
signal(old_updater_pid, libc::SIGTERM)?;
wait_for_exit(old_updater_pid)?;
// Delete the restart caller's cwd without changing the test process's cwd.
let restarted = Command::new("/bin/sh")
.args([
"-c",
"rmdir \"$1\" && exec \"$2\" app-server daemon restart",
"restart",
])
.arg(&project)
.arg(&daemon.codex)
.current_dir(&project)
.env("AKODE_HOME", daemon.home.path())
.output()?;
ensure!(
restarted.status.success(),
"{}",
String::from_utf8_lossy(&restarted.stderr)
);
let restarted: Value = serde_json::from_slice(&restarted.stdout)?;
assert_eq!(restarted["status"], "restarted");
assert_ne!(daemon.pid("app-server.pid")?, old_pid);
assert_ne!(daemon.pid("app-server-updater.pid")?, old_updater_pid);
assert_eq!(daemon.lifecycle("version")?["status"], "running");
let updater_socket = daemon
.home
.path()
.join("app-server-daemon/app-server-updater.sock");
let deadline = Instant::now() + Duration::from_secs(30);
while std::os::unix::net::UnixStream::connect(&updater_socket).is_err() {
ensure!(
Instant::now() < deadline,
"replacement updater did not become ready"
);
std::thread::sleep(Duration::from_millis(50));
}
Ok(())
}
#[test]
fn bootstrap_updater_is_ready_in_deep_codex_home() -> Result<()> {
let mut daemon = TestDaemon::new()?;
let deep_home = tempfile::Builder::new()
.prefix(&"deep-codex-home-".repeat(8))
.tempdir_in("/tmp")?;
for name in ["packages", "app-server-daemon"] {
std::fs::rename(daemon.home.path().join(name), deep_home.path().join(name))?;
}
daemon.home = deep_home;
let state = daemon.home.path().join("app-server-daemon");
std::fs::write(
state.join("settings.json"),
br#"{"shutdownGraceSeconds":0}"#,
)?;
let socket = state.join("app-server-updater.sock");
let result = daemon.lifecycle("bootstrap")?;
assert_eq!(result["autoUpdateEnabled"], true);
assert_eq!(result["status"], "bootstrapped");
signal(daemon.pid("app-server-updater.pid")?, /*signal*/ 0)?;
let target = socket.canonicalize()?;
let _connection = std::os::unix::net::UnixStream::connect(target)?;
assert_eq!(daemon.lifecycle("version")?["status"], "running");
Ok(())
}
#[test]
fn bootstrap_reports_updater_bind_failure() -> Result<()> {
let daemon = TestDaemon::new()?;
let state = daemon.home.path().join("app-server-daemon");
std::fs::write(
state.join("settings.json"),
br#"{"shutdownGraceSeconds":0}"#,
)?;
let socket = state.join("app-server-updater.sock");
std::fs::write(&socket, b"not a socket")?;
let result = daemon
.command()
.args(["app-server", "daemon", "bootstrap"])
.output()?;
assert!(!result.status.success());
assert_eq!(std::fs::read(socket)?, b"not a socket");
assert_eq!(daemon.lifecycle("version")?["status"], "running");
Ok(())
}
#[test]
fn explicit_restart_applies_feature_overrides_and_preserves_saved_settings() -> Result<()> {
let daemon = TestDaemon::new()?;
let settings_path = daemon.home.path().join("app-server-daemon/settings.json");
std::fs::write(
&settings_path,
serde_json::to_vec(&serde_json::json!({
"shutdownGraceSeconds": 0,
"updater": { "autoUpdateEnabled": false },
"featureOverrides": {
"api_key_model_discovery": false,
"auth_elicitation": true,
"connectors": true,
"apps": true
}
}))?,
)?;
let mut previous_pid = None;
// Start from a stopped daemon, change running settings, and restart again
// with omitted flags. Every explicit restart replaces the process.
for (args, discovery) in [
(
vec![
"--enable",
"api_key_model_discovery",
"--disable",
"connectors",
"-c",
"features.network_proxy.enabled=false",
],
true,
),
(vec!["--disable", "api_key_model_discovery"], false),
(vec!["-c", "features.api_key_model_discovery=true"], true),
(vec![], true),
] {
let output = daemon
.command()
.args(["app-server", "daemon", "restart"])
.args(args)
.output()?;
ensure!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let output: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(output["status"], "restarted");
let pid = output["pid"].as_u64().context("restarted daemon PID")?;
assert_ne!(Some(pid), previous_pid);
previous_pid = Some(pid);
let settings: Value = serde_json::from_slice(&std::fs::read(&settings_path)?)?;
assert_eq!(
settings["featureOverrides"],
serde_json::json!({
"api_key_model_discovery": discovery,
"auth_elicitation": true,
"apps": false,
"network_proxy": false
})
);
assert_eq!(settings["updater"]["autoUpdateEnabled"], false);
}
// Non-toggle config keys must fail before stopping the daemon or saving settings.
let saved_settings = std::fs::read(&settings_path)?;
let output = daemon
.command()
.args([
"app-server",
"daemon",
"restart",
"--enable",
"tool_registry",
])
.output()?;
assert!(!output.status.success());
insta::assert_snapshot!(
String::from_utf8(output.stderr)?,
@"Error: daemon restart requires a boolean feature toggle: tool_registry"
);
assert_eq!(std::fs::read(&settings_path)?, saved_settings);
assert_eq!(Some(u64::from(daemon.pid("app-server.pid")?)), previous_pid);
assert_eq!(daemon.lifecycle("version")?["status"], "running");
Ok(())
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn managed_identity_survives_locale_and_timezone_changes() -> Result<()> {
let daemon = TestDaemon::new()?;
let mut original = Vec::new();
let mut updater_pid = 0;
let pid_file = daemon.home.path().join("app-server-daemon/app-server.pid");
for (action, locale, timezone, expected_status) in [
("start", "C", "UTC0", "started"),
("version", "en_AU.UTF-8", "PST8PDT", "running"),
("restart", "en_AU.UTF-8", "PST8PDT", "restarted"),
("stop", "C", "UTC0", "stopped"),
] {
let output = daemon
.command()
.args(["app-server", "daemon", action])
.env("LC_ALL", locale)
.env("TZ", timezone)
.output()?;
ensure!(
output.status.success(),
"daemon {action} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
let output: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(output["status"], expected_status);
if action == "start" {
updater_pid = daemon.pid("app-server-updater.pid")?;
original = std::fs::read(&pid_file)?;
let record: Value = serde_json::from_slice(&original)?;
assert!(record["processIdentity"].is_object());
// Older clients still receive the original, unnormalized ps value.
let legacy = Command::new("ps")
.args([
"-p",
&daemon.pid("app-server.pid")?.to_string(),
"-o",
"lstart=",
])
.env("LC_ALL", locale)
.env("TZ", timezone)
.output()?;
ensure!(legacy.status.success(), "failed to read legacy start time");
assert_eq!(
record["processStartTime"],
String::from_utf8(legacy.stdout)?.trim()
);
} else if action == "version" {
assert_eq!(output["backend"], "pid");
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
assert_eq!(std::fs::read(&pid_file)?, original);
// Finish startup promotion before deliberately restoring a legacy record.
let updater_socket = daemon
.home
.path()
.join("app-server-daemon/app-server-updater.sock");
let deadline = Instant::now() + Duration::from_secs(30);
while !updater_socket.exists() {
ensure!(Instant::now() < deadline, "updater did not become ready");
std::thread::sleep(Duration::from_millis(50));
}
let mut legacy: Value = serde_json::from_slice(&original)?;
legacy
.as_object_mut()
.context("PID record object")?
.remove("processIdentity");
let legacy_bytes = serde_json::to_vec(&legacy)?;
std::fs::write(&pid_file, &legacy_bytes)?;
let result = daemon
.command()
.args(["app-server", "daemon", "version"])
.env("LC_ALL", locale)
.env("TZ", timezone)
.output();
let preserved = std::fs::read(&pid_file);
// Restore the native identity before assertions so Drop can stop the daemon.
std::fs::write(&pid_file, &original)?;
let result = result?;
assert!(!result.status.success());
assert_eq!(preserved?, legacy_bytes);
let stderr =
String::from_utf8(result.stderr)?.replace(&legacy["pid"].to_string(), "[PID]");
insta::assert_snapshot!(stderr, @"Error: cannot verify pid-managed process [PID]: legacy start time changed; PID record retained. Retry with the locale and timezone used to start the daemon. If the system clock changed, stop the original process before restarting the daemon");
}
if action == "restart" {
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
}
}
assert!(!pid_file.exists());
Ok(())
}
#[test]
fn package_ownership_check_does_not_start_an_updater() -> Result<()> {
let daemon = TestDaemon::new()?;
let output = daemon
.command()
.args([
"app-server",
"daemon",
"pid-update-loop",
"--check-package-ownership",
])
.output()?;
ensure!(
output.status.success(),
"ownership check failed: {}",
String::from_utf8_lossy(&output.stderr)
);
let state = daemon.home.path().join("app-server-daemon");
assert!(!state.join("app-server-updater.pid").exists());
assert!(!state.join("daemon-updater.pid").exists());
Ok(())
}
#[test]
fn managed_starts_ensure_one_updater_and_recover_a_missing_one() -> Result<()> {
let daemon = TestDaemon::new()?;
assert_eq!(daemon.lifecycle("start")?["status"], "started");
let backend_pid = daemon.pid("app-server.pid")?;
let updater_pid = daemon.pid("app-server-updater.pid")?;
assert_ne!(backend_pid, updater_pid);
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.pid("app-server.pid")?, backend_pid);
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
signal(updater_pid, libc::SIGTERM)?;
wait_for_exit(updater_pid)?;
// A replacement updater also upgrades still-verifiable records left by an old CLI.
let server_record_path = daemon.home.path().join("app-server-daemon/app-server.pid");
let mut legacy: Value = serde_json::from_slice(&std::fs::read(&server_record_path)?)?;
let native = legacy.as_object_mut().unwrap().remove("processIdentity");
std::fs::write(&server_record_path, serde_json::to_vec(&legacy)?)?;
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.pid("app-server.pid")?, backend_pid);
let replacement_pid = daemon.pid("app-server-updater.pid")?;
assert_ne!(replacement_pid, updater_pid);
if let Some(native) = native {
legacy["processIdentity"] = native;
let deadline = Instant::now() + Duration::from_secs(30);
loop {
let record: Value = serde_json::from_slice(&std::fs::read(&server_record_path)?)?;
if record == legacy {
break;
}
ensure!(
Instant::now() < deadline,
"legacy record was not upgraded: {record}"
);
std::thread::sleep(Duration::from_millis(50));
}
}
assert_eq!(daemon.lifecycle("restart")?["status"], "restarted");
assert_ne!(daemon.pid("app-server.pid")?, backend_pid);
assert_eq!(daemon.pid("app-server-updater.pid")?, replacement_pid);
daemon.lifecycle("stop")?;
assert!(
!daemon
.home
.path()
.join("app-server-daemon/app-server.pid")
.exists()
);
assert_eq!(daemon.lifecycle("start")?["status"], "started");
assert!(
!daemon
.home
.path()
.join("packages/app-server-daemon")
.exists()
);
Ok(())
}
#[test]
fn managed_start_succeeds_when_updater_record_is_invalid() -> Result<()> {
let daemon = TestDaemon::new()?;
let state_dir = daemon.home.path().join("app-server-daemon");
std::fs::create_dir_all(&state_dir)?;
std::fs::write(state_dir.join("app-server-updater.pid"), "not a PID record")?;
assert_eq!(daemon.lifecycle("start")?["status"], "started");
let server_pid = daemon.pid("app-server.pid")?;
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.pid("app-server.pid")?, server_pid);
Ok(())
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn wall_clock_shift_keeps_server_and_updater_managed() -> Result<()> {
let daemon = TestDaemon::new()?;
assert_eq!(daemon.lifecycle("start")?["status"], "started");
let server_pid = daemon.pid("app-server.pid")?;
let updater_pid = daemon.pid("app-server-updater.pid")?;
for name in ["app-server.pid", "app-server-updater.pid"] {
let path = daemon.home.path().join("app-server-daemon").join(name);
let mut record: Value = serde_json::from_slice(&std::fs::read(&path)?)?;
record["processStartTime"] = "historical wall-clock start time".into();
let replacement = path.with_extension("replacement");
std::fs::write(&replacement, serde_json::to_vec(&record)?)?;
std::fs::rename(replacement, path)?;
}
let version = daemon.lifecycle("version")?;
assert_eq!(version["status"], "running");
assert_eq!(version["backend"], "pid");
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.pid("app-server.pid")?, server_pid);
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
assert_eq!(daemon.lifecycle("restart")?["status"], "restarted");
wait_for_exit(server_pid)?;
assert_ne!(daemon.pid("app-server.pid")?, server_pid);
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
Ok(())
}
#[test]
fn managed_start_keeps_updater_on_marker_mismatch_but_stops_it_for_pin() -> Result<()> {
let daemon = TestDaemon::new()?;
assert_eq!(daemon.lifecycle("start")?["status"], "started");
let updater_pid = daemon.pid("app-server-updater.pid")?;
let marker = daemon
.home
.path()
.join("packages/standalone/auto-update-version");
std::fs::write(&marker, "0.1.0-other-target")?;
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.pid("app-server-updater.pid")?, updater_pid);
std::thread::sleep(Duration::from_millis(250));
let updater_state = Command::new("/bin/ps")
.args(["-p", &updater_pid.to_string(), "-o", "stat="])
.output()?;
ensure!(
updater_state.status.success()
&& !String::from_utf8_lossy(&updater_state.stdout)
.trim()
.starts_with('Z'),
"updater exited during the latest marker transition"
);
std::fs::remove_file(marker)?;
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
wait_for_exit(updater_pid)?;
assert!(
!daemon
.home
.path()
.join("app-server-daemon/app-server-updater.pid")
.exists()
);
Ok(())
}
#[test]
fn restart_applies_saved_updater_preference() -> Result<()> {
let daemon = TestDaemon::new()?;
assert_eq!(daemon.lifecycle("start")?["status"], "started");
let updater_pid = daemon.pid("app-server-updater.pid")?;
let settings = daemon.home.path().join("app-server-daemon/settings.json");
std::fs::write(
&settings,
serde_json::to_vec(&serde_json::json!({
"updater": {"autoUpdateEnabled": false, "updateIntervalMinutes": 2},
}))?,
)?;
assert_eq!(daemon.lifecycle("restart")?["status"], "restarted");
wait_for_exit(updater_pid)?;
assert!(daemon.pid("app-server-updater.pid").is_err());
assert_eq!(daemon.lifecycle("bootstrap")?["autoUpdateEnabled"], false);
assert!(daemon.pid("app-server-updater.pid").is_err());
std::fs::write(
&settings,
serde_json::to_vec(&serde_json::json!({
"updater": {"autoUpdateEnabled": true, "updateIntervalMinutes": 2},
}))?,
)?;
assert_eq!(daemon.lifecycle("restart")?["status"], "restarted");
assert_ne!(daemon.pid("app-server-updater.pid")?, updater_pid);
std::fs::write(&settings, "{malformed")?;
assert_eq!(daemon.lifecycle("stop")?["status"], "stopped");
Ok(())
}
#[test]
fn unmanaged_app_server_does_not_launch_updater() -> Result<()> {
let mut daemon = TestDaemon::new()?;
daemon.unmanaged = Some(
daemon
.command()
.args(["app-server", "--listen", "unix://"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()?,
);
let deadline = Instant::now() + Duration::from_secs(30);
while !daemon
.command()
.args(["app-server", "daemon", "version"])
.output()?
.status
.success()
{
ensure!(Instant::now() < deadline, "app server did not become ready");
std::thread::sleep(Duration::from_millis(50));
}
let output = daemon.lifecycle("start")?;
assert_eq!(output["status"], "alreadyRunning");
assert_eq!(output["backend"], Value::Null);
assert_eq!(daemon.lifecycle("update")?["status"], "unsupported");
assert!(
!daemon
.home
.path()
.join("app-server-daemon/app-server-updater.pid")
.exists()
);
Ok(())
}
#[test]
fn manual_update_rejects_an_unowned_installation() -> Result<()> {
let daemon = TestDaemon::new()?;
std::fs::remove_file(
daemon
.home
.path()
.join("packages/standalone/current/bin/akode"),
)?;
assert_eq!(daemon.lifecycle("update")?["status"], "unsupported");
assert!(daemon.pid("app-server.pid").is_err());
assert!(daemon.pid("app-server-updater.pid").is_err());
Ok(())
}

View File

@@ -0,0 +1,223 @@
//! Real package installation and replacement through the daemon CLI.
//! Keep these I/O-heavy cases separate from ordinary lifecycle coverage.
#![cfg(unix)]
mod support;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use pretty_assertions::assert_eq;
use serde_json::Value;
use support::TestDaemon;
use support::wait_for_exit;
#[derive(Clone, Copy, PartialEq, Eq)]
enum InitialDaemon {
Missing,
Legacy,
}
fn packaged_daemon_launch(action: &str, initial: InitialDaemon) -> Result<()> {
let mut daemon = TestDaemon::new()?;
let standalone = daemon.home.path().join("packages/standalone");
let package = if action == "start" && initial == InitialDaemon::Missing {
standalone.join("releases/caller")
} else {
daemon.home.path().join("cli-package")
};
for directory in ["bin", "akode-path", "akode-resources"] {
std::fs::create_dir_all(package.join(directory))?;
}
// Both paths are in this test's temp home and therefore on the same filesystem.
// Reuse its prepared (and on Intel macOS, translated) executable. The installer
// still makes a real independent package copy; only fixture setup shares this inode.
std::fs::hard_link(
standalone.join("current/bin/akode"),
package.join("bin/akode"),
)?;
daemon.codex = package.join("bin/akode");
for helper in [
"bin/akode-code-mode-host",
"akode-path/rg",
"akode-resources/bwrap",
] {
akode_utils_cargo_bin::write_executable(&package.join(helper), "runtime fixture")?;
}
let target = format!(
"{}-{}",
std::env::consts::ARCH,
if cfg!(target_os = "macos") {
"apple-darwin"
} else if cfg!(target_env = "gnu") {
"unknown-linux-gnu"
} else {
"unknown-linux-musl"
}
);
std::fs::write(
package.join("akode-package.json"),
serde_json::to_vec(&serde_json::json!({
"version": env!("CARGO_PKG_VERSION"), "target": target, "entrypoint": "bin/akode"
}))?,
)?;
if action == "start" && initial == InitialDaemon::Missing {
std::fs::remove_file(standalone.join("current"))?;
std::os::unix::fs::symlink(&package, standalone.join("current"))?;
}
let cli_selection = standalone.join("current").canonicalize()?;
let state = daemon.home.path().join("app-server-daemon");
if initial == InitialDaemon::Missing {
std::fs::remove_file(state.join("app-server.stderr.log"))?;
}
std::fs::write(
state.join("settings.json"),
br#"{"shutdownGraceSeconds":0}"#,
)?;
let cli_before = daemon.codex.canonicalize()?;
let result = daemon
.command()
.args(["app-server", "daemon", action])
.output()
.context("failed to launch packaged daemon fixture")?;
ensure!(
result.status.success(),
"{}",
String::from_utf8_lossy(&result.stderr)
);
assert_eq!(
String::from_utf8_lossy(&result.stderr).contains("Installing daemon from CLI version"),
initial == InitialDaemon::Missing
);
let output: Value = serde_json::from_slice(&result.stdout)?;
let dedicated = daemon
.home
.path()
.canonicalize()?
.join("packages/app-server-daemon");
let (initial_root, initial_pid_file) = match initial {
InitialDaemon::Missing => (&dedicated, "daemon.pid"),
InitialDaemon::Legacy => (&standalone, "app-server.pid"),
};
assert_eq!(
output["managedCodexPath"],
initial_root
.canonicalize()?
.join("current/bin/akode")
.to_str()
.context("managed path is not UTF-8")?
);
assert_eq!(daemon.codex.canonicalize()?, cli_before);
assert_eq!(standalone.join("current").canonicalize()?, cli_selection);
assert!(state.join(initial_pid_file).exists());
let legacy_updater = match initial {
InitialDaemon::Missing => {
assert!(!state.join("app-server-updater.pid").exists());
None
}
InitialDaemon::Legacy => Some(daemon.pid("app-server-updater.pid")?),
};
if action == "start" {
let initial_current = initial_root.join("current");
let current = dedicated.join("current");
let original = initial_current.canonicalize()?;
let original_pid = daemon.pid(initial_pid_file)?;
let settings_before = std::fs::read(state.join("settings.json"))?;
let refused = daemon
.command()
.args(["app-server", "daemon", "update", "--from-cli"])
.output()?;
assert!(!refused.status.success());
assert!(String::from_utf8_lossy(&refused.stderr).contains("rerun with --yes"));
assert_eq!(daemon.pid(initial_pid_file)?, original_pid);
assert_eq!(initial_current.canonicalize()?, original);
if initial == InitialDaemon::Legacy {
assert!(!current.exists());
}
std::fs::remove_file(package.join("bin/akode-code-mode-host"))?;
let invalid = daemon
.command()
.args(["app-server", "daemon", "update", "--from-cli", "--yes"])
.output()?;
assert!(!invalid.status.success());
assert_eq!(daemon.pid(initial_pid_file)?, original_pid);
assert_eq!(initial_current.canonicalize()?, original);
if initial == InitialDaemon::Legacy {
assert!(!current.exists());
}
akode_utils_cargo_bin::write_executable(
&package.join("bin/akode-code-mode-host"),
"replacement helper",
)?;
let replaced = daemon
.command()
.args(["app-server", "daemon", "update", "--from-cli", "--yes"])
.output()?;
ensure!(
replaced.status.success(),
"{}",
String::from_utf8_lossy(&replaced.stderr)
);
let output: Value = serde_json::from_slice(&replaced.stdout)?;
assert_eq!(output["status"], "updated");
assert_ne!(daemon.pid("daemon.pid")?, original_pid);
wait_for_exit(original_pid)?;
if let Some(pid) = legacy_updater {
wait_for_exit(pid)?;
}
assert!(!state.join("app-server.pid").exists());
assert!(!state.join("app-server-updater.pid").exists());
assert_eq!(
output["managedCodexPath"],
current
.join("bin/akode")
.to_str()
.context("managed path is not UTF-8")?
);
assert_ne!(current.canonicalize()?, original);
assert!(!dedicated.join("auto-update-version").exists());
assert_eq!(std::fs::read(state.join("settings.json"))?, settings_before);
assert_eq!(
std::fs::read(current.join("bin/akode-code-mode-host"))?,
b"replacement helper"
);
if initial == InitialDaemon::Missing {
assert_eq!(
std::fs::read(original.join("bin/akode-code-mode-host"))?,
b"runtime fixture"
);
}
assert_eq!(daemon.lifecycle("start")?["status"], "alreadyRunning");
assert_eq!(daemon.lifecycle("stop")?["status"], "stopped");
assert_eq!(standalone.join("current").canonicalize()?, cli_selection);
}
if action == "bootstrap" {
// Only stable release versions follow automatic updates; local builds versioned
// 0.0.0 do not. aKode builds carry a release version (0.1.0).
let stable_build =
env!("CARGO_PKG_VERSION") != "0.0.0" && !env!("CARGO_PKG_VERSION").contains(['-', '+']);
assert_eq!(output["autoUpdateEnabled"], stable_build);
}
Ok(())
}
#[test]
fn packaged_daemon_start_and_explicit_replacement() -> Result<()> {
packaged_daemon_launch("start", InitialDaemon::Missing)
}
#[test]
fn packaged_daemon_restart_seeds_local_package() -> Result<()> {
packaged_daemon_launch("restart", InitialDaemon::Missing)
}
#[test]
fn packaged_daemon_bootstrap_seeds_local_package() -> Result<()> {
packaged_daemon_launch("bootstrap", InitialDaemon::Missing)
}
#[test]
fn packaged_daemon_explicit_replacement_migrates_running_legacy() -> Result<()> {
packaged_daemon_launch("start", InitialDaemon::Legacy)
}

View File

@@ -0,0 +1,140 @@
//! Isolated installed-CLI fixtures and PID cleanup for Unix daemon integration tests.
//! Every test owns its home and CLI selection; only immutable executable contents are shared.
use std::path::PathBuf;
use std::process::Child;
use std::process::Command;
use std::time::Duration;
use std::time::Instant;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use akode_utils_cargo_bin::copy_executable;
use serde_json::Value;
use tempfile::TempDir;
pub(super) struct TestDaemon {
pub(super) home: TempDir,
pub(super) codex: PathBuf,
pub(super) unmanaged: Option<Child>,
}
impl TestDaemon {
pub(super) fn new() -> Result<Self> {
let home = tempfile::Builder::new().tempdir_in("/tmp")?;
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
let codex_source = std::fs::canonicalize(&codex)?;
let target = if cfg!(target_os = "macos") {
format!("{}-apple-darwin", std::env::consts::ARCH)
} else {
format!("{}-unknown-linux-musl", std::env::consts::ARCH)
};
let standalone = home.path().join("packages/standalone");
let release_name = format!("0.0.0-{target}");
let managed = standalone
.join("releases")
.join(&release_name)
.join("bin/akode");
std::fs::create_dir_all(managed.parent().context("managed bin parent")?)?;
// Preserve the installed path without invalidating the shared CLI's Rosetta cache.
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
{
copy_executable(&codex_source, &managed)?;
// Translate the fixture before timed daemon capability and readiness checks.
ensure!(
Command::new(&managed)
.env("AKODE_HOME", home.path())
.arg("--version")
.output()?
.status
.success(),
"failed to prepare managed test executable"
);
}
#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
if std::fs::hard_link(&codex_source, &managed).is_err() {
copy_executable(&codex_source, &managed)?;
}
std::fs::write(standalone.join("auto-update-version"), &release_name)?;
std::os::unix::fs::symlink(
PathBuf::from("releases").join(release_name),
standalone.join("current"),
)?;
// Model a daemon that was previously launched and is currently stopped.
let state = home.path().join("app-server-daemon");
std::fs::create_dir(&state)?;
std::fs::write(state.join("app-server.stderr.log"), b"")?;
Ok(Self {
home,
codex,
unmanaged: None,
})
}
pub(super) fn command(&self) -> Command {
let mut command = Command::new(&self.codex);
command.env("AKODE_HOME", self.home.path());
command
}
pub(super) fn lifecycle(&self, action: &str) -> Result<Value> {
let output = self
.command()
.args(["app-server", "daemon", action])
.output()?;
ensure!(
output.status.success(),
"daemon {action} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
Ok(serde_json::from_slice(&output.stdout)?)
}
pub(super) fn pid(&self, name: &str) -> Result<u32> {
let record = std::fs::read(self.home.path().join("app-server-daemon").join(name))
.with_context(|| format!("failed to read {name}"))?;
Ok(serde_json::from_slice::<Value>(&record)?["pid"]
.as_u64()
.context("pid missing")? as u32)
}
}
impl Drop for TestDaemon {
fn drop(&mut self) {
if let Some(mut child) = self.unmanaged.take() {
let _ = child.kill();
let _ = child.wait();
}
let _ = self.lifecycle("stop");
if let Ok(pid) = self.pid("app-server-updater.pid") {
let _ = signal(pid, libc::SIGTERM);
}
}
}
pub(super) fn signal(pid: u32, signal: libc::c_int) -> Result<()> {
let raw_pid = libc::pid_t::try_from(pid).context("pid out of range")?;
ensure!(
unsafe { libc::kill(raw_pid, signal) } == 0,
"failed to signal pid {pid}: {}",
std::io::Error::last_os_error()
);
Ok(())
}
pub(super) fn wait_for_exit(pid: u32) -> Result<()> {
let deadline = Instant::now() + Duration::from_secs(30);
loop {
let output = Command::new("/bin/ps")
.args(["-p", &pid.to_string(), "-o", "stat="])
.output()
.context("failed to invoke ps")?;
let state = String::from_utf8_lossy(&output.stdout);
if !output.status.success() || state.trim().starts_with('Z') {
return Ok(());
}
ensure!(Instant::now() < deadline, "pid {pid} did not exit: {state}");
std::thread::sleep(Duration::from_millis(50));
}
}

View File

@@ -0,0 +1,126 @@
//! Exercises daemon installation from the Windows WinGet archive layout.
#![cfg(windows)]
use anyhow::Result;
use anyhow::ensure;
use akode_utils_cargo_bin::copy_executable;
use pretty_assertions::assert_eq;
use serde_json::Value;
use sha2::Digest;
use sha2::Sha256;
use std::process::Command;
#[test]
fn winget_package_starts_and_reselects_daemon() -> Result<()> {
if akode_app_server_daemon::is_elevated()? {
eprintln!("requires a non-elevated Windows runner");
return Ok(());
}
let temp = tempfile::tempdir()?;
let home = temp.path().join("home");
let package = temp.path().join("WinGet/Packages/OpenAI.Codex");
let target = format!("{}-pc-windows-msvc", std::env::consts::ARCH);
let entrypoint = format!("akode-{target}.exe");
let codex = package.join(&entrypoint);
for directory in ["bin", "akode-path", "akode-resources/voice"] {
std::fs::create_dir_all(package.join(directory))?;
}
copy_executable(&akode_utils_cargo_bin::cargo_bin("akode")?, &codex)?;
for helper in [
"akode-code-mode-host.exe",
"akode-path/rg.exe",
"akode-resources/codex-command-runner.exe",
"akode-resources/codex-windows-sandbox-setup.exe",
] {
std::fs::write(package.join(helper), b"runtime fixture")?;
}
let mut metadata = serde_json::json!({
"layoutVersion": 1, "version": env!("CARGO_PKG_VERSION"),
"target": target, "entrypoint": entrypoint
});
let manifest_bytes = serde_json::to_vec(&metadata)?;
std::fs::write(package.join("akode-package.json"), &manifest_bytes)?;
let checksum = format!("{:x}", Sha256::digest(std::fs::read(&codex)?));
let voice_bytes = serde_json::to_vec(&serde_json::json!({
"sha256": { &entrypoint: checksum, "akode-resources/voice/runtime": "untouched" }
}))?;
std::fs::write(
package.join("akode-resources/voice/manifest.json"),
&voice_bytes,
)?;
let current = home.join("packages/app-server-daemon/current");
// Drop before temp so assertion failures also release the managed executable.
struct StopDaemon(Command);
impl Drop for StopDaemon {
fn drop(&mut self) {
let _ = self.0.output();
}
}
let mut stop = Command::new(&codex);
stop.env("AKODE_HOME", &home)
.args(["app-server", "daemon", "stop"]);
let mut daemon = StopDaemon(stop);
for args in [
vec!["start"],
vec!["update", "--from-cli", "--yes"],
vec!["update", "--from-cli", "--yes"],
] {
let output = Command::new(&codex)
.env("AKODE_HOME", &home)
.args(["app-server", "daemon"])
.args(&args)
.output()?;
ensure!(
output.status.success(),
"daemon {args:?} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
let selected_metadata: Value =
serde_json::from_slice(&std::fs::read(current.join("akode-package.json"))?)?;
metadata["entrypoint"] = "bin/akode.exe".into();
assert_eq!(selected_metadata, metadata);
let selected_voice: Value = serde_json::from_slice(&std::fs::read(
current.join("akode-resources/voice/manifest.json"),
)?)?;
assert_eq!(
selected_voice,
serde_json::json!({
"sha256": {
"bin/akode.exe": checksum,
"akode-resources/voice/runtime": "untouched"
}
})
);
assert_eq!(
std::fs::read(current.join("bin/akode-code-mode-host.exe"))?,
b"runtime fixture"
);
let selected = current.canonicalize()?;
std::fs::remove_file(package.join("akode-code-mode-host.exe"))?;
let invalid = Command::new(&codex)
.env("AKODE_HOME", &home)
.args(["app-server", "daemon", "update", "--from-cli", "--yes"])
.output()?;
ensure!(
!invalid.status.success(),
"an incomplete WinGet package was accepted"
);
assert_eq!(current.canonicalize()?, selected);
assert_eq!(
std::fs::read(package.join("akode-package.json"))?,
manifest_bytes
);
assert_eq!(
std::fs::read(package.join("akode-resources/voice/manifest.json"))?,
voice_bytes
);
let stopped = daemon.0.output()?;
ensure!(
stopped.status.success(),
"failed to stop daemon: {}",
String::from_utf8_lossy(&stopped.stderr)
);
Ok(())
}

View File

@@ -0,0 +1,629 @@
//! Exercises daemon startup and excluded resume/fork pickers with Cargo's CLI executable.
use anyhow::Context as _;
use anyhow::Result;
use anyhow::ensure;
use std::collections::VecDeque;
use std::fs;
use std::process::Command;
use std::time::Duration;
#[tokio::test]
#[cfg(unix)]
async fn auto_daemon_start_attaches_to_shared_server() -> Result<()> {
daemon_startup("start").await
}
#[tokio::test]
#[cfg(unix)]
async fn agents_can_offer_restart_for_managed_daemon() -> Result<()> {
daemon_startup("agents").await
}
#[tokio::test]
#[cfg(unix)]
async fn agents_no_daemon_uses_embedded_even_with_a_running_daemon() -> Result<()> {
daemon_startup("agents-no-daemon").await
}
#[tokio::test]
#[cfg(unix)]
async fn agents_defers_launch_directory_trust_until_starting_a_task() -> Result<()> {
daemon_startup("agents-untrusted").await
}
#[tokio::test]
#[cfg(unix)]
async fn discovered_managed_daemon_can_restart_with_auto_start_disabled() -> Result<()> {
daemon_startup("discovered").await
}
#[tokio::test]
#[cfg(unix)]
async fn incompatible_daemon_can_cancel() -> Result<()> {
daemon_startup("mismatch-cancel").await
}
#[tokio::test]
#[cfg(unix)]
async fn incompatible_daemon_can_run_embedded() -> Result<()> {
daemon_startup("mismatch-embedded").await
}
#[tokio::test]
#[cfg(unix)]
async fn incompatible_daemon_can_restart_with_confirmed_settings() -> Result<()> {
daemon_startup("mismatch-restart").await
}
#[tokio::test]
#[cfg(unix)]
async fn fresh_daemon_requires_confirmation_to_disable_shared_features() -> Result<()> {
daemon_startup("mismatch-disable").await
}
#[tokio::test]
#[cfg(unix)]
async fn stopped_daemon_requires_confirmation_to_disable_persisted_features() -> Result<()> {
daemon_startup("mismatch-disable-persisted").await
}
#[tokio::test]
async fn daemon_exclusion_survives_resume_picker() -> Result<()> {
daemon_startup("resume").await
}
#[tokio::test]
async fn daemon_exclusion_survives_fork_picker() -> Result<()> {
daemon_startup("fork").await
}
#[tokio::test]
#[cfg(windows)]
async fn elevated_local_tui_uses_embedded_without_starting_daemon() -> Result<()> {
if !akode_app_server_daemon::is_elevated()? {
eprintln!("requires an elevated Windows runner");
return Ok(());
}
for command in ["elevated", "elevated-resume", "elevated-fork"] {
daemon_startup(command).await?;
}
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
let home = tempfile::tempdir()?;
for operation in ["start", "restart"] {
let output = Command::new(&codex)
.env("AKODE_HOME", home.path())
.args(["app-server", "daemon", operation])
.output()?;
ensure!(
!output.status.success(),
"{operation} must reject elevation"
);
ensure!(
String::from_utf8_lossy(&output.stderr).contains("non-elevated terminal"),
"{}",
String::from_utf8_lossy(&output.stderr)
);
}
ensure!(!home.path().join("app-server-daemon").exists());
Ok(())
}
#[tokio::test]
#[cfg(windows)]
async fn restrictive_launcher_uses_embedded_if_daemon_cannot_start() -> Result<()> {
const CHILD: &str = "AKODE_TEST_RESTRICTIVE_DAEMON_START";
if std::env::var_os(CHILD).is_some() {
// The PTY creates its own breakaway-permitted job. Add Cargo's
// restriction *inside* the PTY so it is the CLI's innermost job.
let job = akode_utils_pty::JobObject::create_without_breakaway()?;
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
let mut command = tokio::process::Command::new(codex);
command
.arg("--no-alt-screen")
.stdin(std::process::Stdio::inherit())
.stdout(std::process::Stdio::inherit())
.stderr(std::process::Stdio::inherit())
// This interactive CLI must inherit the PTY console rather than use
// the background helper's CREATE_NO_WINDOW launch policy.
.creation_flags(windows_sys::Win32::System::Threading::CREATE_SUSPENDED)
.kill_on_drop(true);
let mut child = command.spawn()?;
ensure!(
job.assign_and_resume_process(child.id().context("missing CLI pid")?)?
.is_some(),
"CLI job assignment failed"
);
let status = child.wait().await?;
ensure!(status.success(), "CLI exited: {status}");
return Ok(());
}
daemon_startup("restrictive-job").await
}
async fn daemon_startup(command: &str) -> Result<()> {
#[cfg(windows)]
let elevated = akode_app_server_daemon::is_elevated()?;
#[cfg(not(windows))]
let elevated = false;
let elevated_launch = command.starts_with("elevated");
let codex = akode_utils_cargo_bin::cargo_bin("akode")?.canonicalize()?;
let workspace = tempfile::tempdir()?;
let workspace_path = workspace.path().canonicalize()?;
#[cfg(unix)]
let home = tempfile::Builder::new().tempdir_in("/tmp")?;
#[cfg(not(unix))]
let home = tempfile::tempdir()?;
// Keep cold Rosetta translation outside the timed startup assertions.
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
anyhow::ensure!(
Command::new(&codex)
.env("AKODE_HOME", home.path())
.arg("--version")
.output()?
.status
.success(),
"failed to prepare CLI test executable"
);
let bedrock_onboarding = matches!(command, "bedrock" | "bedrock-running");
// aKode has no built-in catalog for providers without a catalog URL; keep the bundled one.
let catalog = home.path().join("test-models.json");
fs::write(&catalog, include_str!("../../models-manager/models.json"))?;
fs::write(
home.path().join("config.toml"),
format!(
"model = \"gpt-5.6-terra\"\n\
model_provider = \"mock\"\n\
model_catalog_json = {}\n\
cli_auth_credentials_store = \"file\"\n\
suppress_unstable_features_warning = true\n\
windows.sandbox = \"unelevated\"\n\
tui.disable_paste_burst = true\n\
{}\n\
notice.model_migrations.\"gpt-5.6-terra\" = \"gpt-6-sol\"\n\
[model_providers.mock]\nname = \"mock\"\nbase_url = \"http://127.0.0.1:9/v1\"\nrequires_openai_auth = true\n\
[projects.{}]\ntrust_level = \"{}\"\n",
serde_json::to_string(&catalog.display().to_string())?,
if command == "discovered" {
"tui.status_line=[\"model\",\"thread-id\",\"thread-name\"]\nfeatures.daemon_auto_start=false"
} else if bedrock_onboarding {
"features.gcp_setup_wizard=false"
} else {
""
},
serde_json::to_string(&workspace_path)?,
if command == "agents-untrusted" {
"untrusted"
} else {
"trusted"
},
),
)?;
let mismatch = command.starts_with("mismatch-");
let persisted = command == "mismatch-disable-persisted";
let disabling = matches!(command, "mismatch-disable" | "mismatch-disable-persisted");
let restart = command == "mismatch-restart" || disabling;
if !bedrock_onboarding {
fs::write(
home.path().join("auth.json"),
r#"{"OPENAI_API_KEY":"daemon-startup-test","tokens":null,"last_refresh":null}"#,
)?;
}
let mut env = std::env::vars().collect::<std::collections::HashMap<_, _>>();
for key in [
"AKODE_EXEC_SERVER_URL",
"AKODE_ACCESS_TOKEN",
"AKODE_API_KEY",
"AKODE_CLOUD_TASKS_MODE",
"OPENAI_API_KEY",
"OPENAI_FEDERATION_RULE_ID",
"OPENAI_IDENTITY_TOKEN_FILE",
"OPENAI_WORKLOAD_IDENTITY_CONTEXT",
] {
env.remove(key);
}
env.insert("AKODE_HOME".into(), home.path().display().to_string());
env.insert(
"AKODE_SQLITE_HOME".into(),
home.path().display().to_string(),
);
env.insert("TERM".into(), "xterm-256color".into());
let mut args = vec!["--no-alt-screen".to_string()];
let mut steps: VecDeque<(&str, &[u8])> = VecDeque::new();
if matches!(
command,
"start"
| "agents"
| "agents-no-daemon"
| "agents-untrusted"
| "discovered"
| "bedrock"
| "bedrock-running"
| "restrictive-job"
) || mismatch
{
// A selected package with a stopped daemon avoids installing a release.
let managed = home
.path()
.join("packages/app-server-daemon/current/bin")
.join(if cfg!(windows) { "akode.exe" } else { "codex" });
fs::create_dir_all(home.path().join("packages/app-server-daemon/current/bin"))?;
// Hard links change the executable's ctime and invalidate Rosetta's translation cache.
#[cfg(unix)]
std::os::unix::fs::symlink(&codex, &managed)?;
#[cfg(not(unix))]
fs::hard_link(&codex, &managed)
.or_else(|_| akode_utils_cargo_bin::copy_executable(&codex, &managed))?;
if command != "restrictive-job" {
fs::create_dir(home.path().join("app-server-daemon"))?;
fs::write(
home.path().join("app-server-daemon/settings.json"),
if persisted {
r#"{"shutdownGraceSeconds":0,"updater":{"autoUpdateEnabled":false},"featureOverrides":{"api_key_model_discovery":true}}"#
} else {
r#"{"shutdownGraceSeconds":0,"updater":{"autoUpdateEnabled":false}}"#
},
)?;
}
}
let pid_file = home.path().join("app-server-daemon/daemon.pid");
let result = async {
let mut existing_daemon = if matches!(command, "bedrock-running" | "discovered" | "agents-no-daemon")
|| (mismatch && !disabling)
{
if command == "bedrock-running" {
// This Unix-only case uses a daemon-only token and no ambient profiles.
env.insert("AWS_CONFIG_FILE".into(), "/dev/null".into());
env.insert("AWS_SHARED_CREDENTIALS_FILE".into(), "/dev/null".into());
env.remove("AWS_ACCESS_KEY_ID");
env.remove("AWS_SECRET_ACCESS_KEY");
env.insert("AWS_BEARER_TOKEN_BEDROCK".into(), "daemon-only-test-token".into());
}
let started = Command::new(&codex)
.env_clear()
.envs(&env)
.current_dir(&workspace_path)
.args(["app-server", "daemon", "start"])
.output()?;
ensure!(
started.status.success(),
"{}",
String::from_utf8_lossy(&started.stderr)
);
Some(fs::read(&pid_file)?)
} else {
None
};
let expected = if command == "start" {
// The draft header is visible before the session's command composer is ready.
steps.push_back(("GPT-5.6-Terra", b"/status\r"));
"Server:Localbackgroundserver"
} else if command == "agents-no-daemon" {
args.extend(["agents".into(), "--no-daemon".into()]);
steps.push_back(("Notasksyet", b"n"));
steps.push_back(("GPT-5.6-Terra", b"/daemon\r"));
"Notconnectedtothelocalbackgroundserver"
} else if command == "agents" {
args.push("agents".into());
steps.push_back(("Notasksyet", b"n"));
steps.push_back(("GPT-5.6-Terra", b"/daemon\r"));
steps.push_back(("Restartbackgroundserver", b"\x1b[F\r"));
"Restartbackgroundserver?"
} else if command == "agents-untrusted" {
args.push("agents".into());
steps.push_back(("Notasksyet", b"n"));
"entercontinue·escback"
} else if command == "discovered" {
args.extend(["--disable".into(), "daemon_auto_start".into()]);
// Empty drafts need not survive a daemon restart. Renaming materializes the
// thread; wait for the confirmed footer name, not the echoed command.
steps.push_back(("GPT-5.6-Terra", b"/rename daemon-restart-test\r"));
steps.push_back(("·daemon-restart-test", b"/daemon\r"));
steps.push_back(("Restartbackgroundserver", b"2"));
steps.push_back(("Restartbackgroundserver?", b"2\r"));
// Offline editing preserves text but suppresses Enter. Observe the command
// popup in a complete connected frame before submitting the retained draft.
steps.push_back(("GPT-5.6-Terra", b"/status"));
steps.push_back(("/statusshowcurrentsessionconfigurationandtokenusage", b"\r"));
"Server:Localbackgroundserver"
} else if elevated_launch || command == "restrictive-job" && elevated {
if let Some(action) = command.strip_prefix("elevated-") {
args.push(action.into());
steps.push_back(("Nosessionsyet", b"\x1b"));
}
steps.push_back(("GPT-5.6-Terra", b"\x14"));
"Runningasadministrator:sharedbackgroundserverdisabled."
} else if command == "restrictive-job" {
steps.push_back(("GPT-5.6-Terra", b"\x14"));
"Runningwithoutthesharedbackgroundserver:thisWindowslauncher"
} else if mismatch {
args.extend(if disabling && !persisted {
["--disable".into(), "auth_elicitation".into()]
} else {
["--disable".into(), "api_key_model_discovery".into()]
});
let input: &[u8] = match command {
"mismatch-cancel" => b"\x03",
"mismatch-embedded" => b"1",
"mismatch-restart" | "mismatch-disable" | "mismatch-disable-persisted" => b"2\r",
_ => unreachable!(),
};
steps.push_back(("Backgroundserverhasincompatiblefeaturesettings", input));
if command == "mismatch-cancel" {
"--no-daemon"
} else {
steps.push_back(("GPT-5.6-Terra", b"/status\r"));
if restart { "Server:Localbackgroundserver" } else { "Model:" }
}
} else if command == "bedrock-running" {
env.remove("AWS_BEARER_TOKEN_BEDROCK");
steps.push_back(("UseanAPIkeyoranotherprovider", b"3"));
steps.push_back(("UseAmazonBedrock", b"2"));
"Continuewithdetectedcredentials"
} else if bedrock_onboarding {
// With GCP disabled, only Bedrock makes the sign-in menu advertise another provider.
"UseanAPIkeyoranotherprovider"
} else {
args.extend([command.into(), "--strict-config".into()]);
if command == "resume" {
let thread_id = "00000000-0000-0000-0000-000000000001";
let sessions = home.path().join("sessions/2025/01/05");
fs::create_dir_all(&sessions)?;
let metadata = serde_json::json!({
"timestamp": "2025-01-05T12:00:00Z",
"type": "session_meta",
"payload": {
"session_id": thread_id, "id": thread_id,
"timestamp": "2025-01-05T12:00:00Z", "cwd": workspace_path,
"originator": "codex", "cli_version": "0.0.0",
"source": "cli", "model_provider": "mock"
}
});
let message = serde_json::json!({
"timestamp": "2025-01-05T12:00:00Z",
"type": "event_msg",
"payload": {"type": "user_message", "message": "Saved resume session", "kind": "plain"}
});
fs::write(
sessions.join(format!("rollout-2025-01-05T12-00-00-{thread_id}.jsonl")),
format!("{metadata}\n{message}\n"),
)?;
steps.push_back(("Savedresumesession", b"\r"));
} else {
steps.push_back(("Nosessionsyet", b"\x1b"));
}
steps.push_back(("GPT-5.6-Terra", b"\x14"));
if elevated {
"Runningasadministrator:sharedbackgroundserverdisabled."
} else {
"Runningwithoutthesharedbackgroundserver:--strict-config"
}
};
let program = if cfg!(windows) && command == "restrictive-job" {
env.insert("AKODE_TEST_RESTRICTIVE_DAEMON_START".into(), "1".into());
args = vec![
"--exact".into(),
"restrictive_launcher_uses_embedded_if_daemon_cannot_start".into(),
"--nocapture".into(),
];
std::env::current_exe()?
} else {
codex.clone()
};
let spawned = akode_utils_pty::spawn_pty_process(
&program.to_string_lossy(),
&args,
&workspace_path,
&env,
/*arg0*/ &None,
akode_utils_pty::TerminalSize {
rows: 40,
cols: 120,
},
akode_utils_pty::ChildFds::Inherited(&[]),
)
.await?;
let exit = spawned.exit_rx;
let session = spawned.session;
let writer = session.writer_sender();
let mut stdout = spawned.stdout_rx;
let mut output = String::new();
let mut initial_agents_screen = String::new();
let mut screen = vt100::Parser::new(
/*rows*/ 40, /*cols*/ 120, /*scrollback_len*/ 0,
);
let mut queries: Vec<(&str, &[u8])> = vec![
("\x1b[6n", b"\x1b[1;1R"),
("\x1b[?u", b"\x1b[?0u\x1b[?1;2c"),
("\x1b[c", b"\x1b[?1;2c"),
("\x1b]10;?", b"\x1b]10;rgb:ffff/ffff/ffff\x1b\\"),
("\x1b]11;?", b"\x1b]11;rgb:0000/0000/0000\x1b\\"),
];
// A fresh disable request includes both cold daemon startup and its confirmed restart.
let timeout = Duration::from_secs(if disabling { 90 } else { 45 });
let result = tokio::time::timeout(timeout, async {
loop {
let bytes = tokio::select! {
bytes = stdout.recv() => bytes,
// The first onboarding draw precedes its typeahead drain. Retry the
// main menu shortcut until the submenu appears (it has no option 3).
() = tokio::time::sleep(Duration::from_millis(/*millis*/ 250)),
if steps.front().is_some_and(|(ready, _)| *ready == "UseAmazonBedrock") => {
writer.send(b"3".to_vec()).await?;
continue;
}
};
let Some(bytes) = bytes else { break };
output.push_str(&String::from_utf8_lossy(&bytes));
screen.process(&bytes);
for (query, reply) in &mut queries {
if !query.is_empty() && output.contains(*query) {
writer.send(reply.to_vec()).await?;
*query = "";
}
}
// PTY reads can split a redraw after the reconnect notice is erased but
// before it is repainted. Only inspect completed synchronized updates.
if command == "discovered"
&& output
.rfind("\x1b[?2026l")
.is_none_or(|end| output[end..].contains("\x1b[?2026h"))
{
continue;
}
let text: String = screen
.screen()
.contents()
.chars()
.filter(|c| !c.is_whitespace())
.collect();
if let Some((ready, input)) = steps.front()
&& text.contains(ready)
{
if command == "agents-untrusted" && *ready == "Notasksyet" {
if !text.contains("enteropennnew") {
continue;
}
initial_agents_screen = screen.screen().contents();
}
if command == "discovered" {
if *ready == "Restartbackgroundserver?" {
existing_daemon = Some(fs::read(&pid_file)?);
} else if *ready == "GPT-5.6-Terra" {
// The header renders before thread/start completes. Wait for the
// live status line to confirm there is a session to reconnect.
if !screen.screen().contents().split_whitespace().any(|part| {
akode_protocol::ThreadId::from_string(part).is_ok()
}) {
continue;
}
}
// A replacement PID can appear before the TUI observes the disconnect.
// Wait for reconnect to clear/rebuild the transcript, so the old
// composer's command popup cannot make the status probe look ready.
if *input == b"/status" && !output.contains("\x1b[3J") {
continue;
}
// The old header can linger while the daemon stops. Check both
// the draft and its Enter against the replacement process and UI.
if (*input == b"/status" || *input == b"\r")
&& (!fs::read(&pid_file).is_ok_and(|pid| Some(pid) != existing_daemon)
|| text.contains("Reconnecting"))
{
continue;
}
}
if disabling && *ready == "Backgroundserverhasincompatiblefeaturesettings" {
existing_daemon = Some(fs::read(&pid_file)?);
let settings: serde_json::Value = serde_json::from_slice(&fs::read(home.path().join("app-server-daemon/settings.json"))?)?;
if persisted {
ensure!(settings["featureOverrides"]["api_key_model_discovery"] == true);
} else {
ensure!(settings["featureOverrides"]["auth_elicitation"].is_null());
}
}
writer.send(input.to_vec()).await?;
steps.pop_front();
output.clear();
} else if steps.is_empty() && text.contains(expected) {
if command == "agents-untrusted" {
let transition = format!(
"{initial_agents_screen}\n\n--- Start a task ---\n\n{}",
screen.screen().contents()
)
.replace(&*workspace_path.to_string_lossy(), "[WORKSPACE]")
.replace(&*home.path().to_string_lossy(), "[AKODE_HOME]")
.replace(" tab/⇧tab filter", "tab/shift+tab filter");
let transition = transition.lines().map(str::trim_end).collect::<Vec<_>>().join("\n");
let snapshot = akode_utils_cargo_bin::find_resource!(
"tests/snapshots/daemon_startup__agents_overview_before_folder_consent.snap"
)?;
insta::with_settings!({snapshot_path => snapshot.parent().context("snapshot has no parent")?}, {
insta::assert_snapshot!("agents_overview_before_folder_consent", transition);
});
}
if mismatch {
let previous_pid = existing_daemon.as_ref().context("missing original daemon PID")?;
ensure!((fs::read(&pid_file)? != *previous_pid) == restart);
if command == "mismatch-cancel" {
ensure!(text.contains("Cannotusethesharedbackgroundserver:Thissessionrequiresapi_key_model_discoverytobedisabled."));
} else {
ensure!(text.contains("Server:Localbackgroundserver") == restart);
if restart {
let settings: serde_json::Value = serde_json::from_slice(
&fs::read(home.path().join("app-server-daemon/settings.json"))?
)?;
let flag = if disabling && !persisted {
"auth_elicitation"
} else {
"api_key_model_discovery"
};
assert_eq!(settings["featureOverrides"], serde_json::json!({(flag): false}));
}
}
} else if command == "start" {
ensure!(text.contains("Server:Localbackgroundserver"));
ensure!(home.path().join("app-server-daemon/daemon.pid").exists());
} else if command == "discovered" {
let previous_pid = existing_daemon.as_ref().context("missing original daemon PID")?;
ensure!(fs::read(&pid_file)? != *previous_pid, "daemon PID did not change");
} else if let Some(existing_daemon) = &existing_daemon {
ensure!(fs::read(&pid_file)? == *existing_daemon);
} else if elevated_launch {
ensure!(!home.path().join("app-server-daemon").exists());
ensure!(!home.path().join("packages/app-server-daemon").exists());
} else if bedrock_onboarding {
ensure!(pid_file.exists() != elevated);
} else if command == "restrictive-job" {
ensure!(!pid_file.exists());
if !elevated {
let contents = screen.screen().contents();
let warning = contents.lines()
.find(|line| line.contains("Running without the shared background server:"))
.context("missing rendered fallback warning")?;
insta::assert_snapshot!("restrictive_launcher_warning", warning.trim());
}
}
return Ok::<_, anyhow::Error>(());
}
}
anyhow::bail!(
"TUI exited before {expected}: {}",
screen.screen().contents()
)
})
.await;
if command == "mismatch-cancel" && matches!(result, Ok(Ok(()))) {
let status = tokio::time::timeout(Duration::from_secs(/*secs*/ 5), exit).await??;
ensure!(status != 0, "incompatible daemon launch must fail");
}
Ok::<_, anyhow::Error>((
session,
result.with_context(|| format!("{command} timed out waiting for {}: {}", steps.front().map_or(expected, |(ready, _)| *ready), screen.screen().contents())),
))
}
.await;
// Elevated fresh Bedrock onboarding already verified that no daemon started.
if elevated
&& command == "bedrock"
&& let Ok((session, Ok(Ok(())))) = &result
{
session.terminate();
return Ok(());
}
// Stop the detached daemon, including on timeout or failed assertions.
let stopped = Command::new(&codex)
.env_clear()
.envs(&env)
.args(["app-server", "daemon", "stop"])
.output()?;
let (session, result) = result?;
session.terminate();
result??;
ensure!(
stopped.status.success(),
"{}",
String::from_utf8_lossy(&stopped.stderr)
);
Ok(())
}

View File

@@ -0,0 +1,185 @@
use std::path::Path;
use anyhow::Result;
use akode_state::StateRuntime;
use akode_utils_absolute_path::test_support::PathExt;
use predicates::str::contains;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
#[tokio::test]
async fn debug_clear_memories_resets_state_and_removes_memory_dir() -> Result<()> {
let codex_home = TempDir::new()?;
let sqlite = akode_state::SqliteConfig::new_for_testing(codex_home.path().abs());
let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string()).await?;
runtime.close().await;
let thread_id = "00000000-0000-0000-0000-000000000123";
let db_path = sqlite.state_db_path();
let pool = sqlite.open_read_write_pool(&db_path).await?;
let memories_db_path = sqlite.memories_db_path();
let memories_pool = sqlite.open_read_write_pool(&memories_db_path).await?;
sqlx::query(
r#"
INSERT INTO threads (
id,
rollout_path,
created_at,
updated_at,
source,
agent_nickname,
agent_role,
model_provider,
cwd,
cli_version,
title,
sandbox_policy,
approval_mode,
tokens_used,
first_user_message,
archived,
archived_at,
git_sha,
git_branch,
git_origin_url,
memory_mode
) VALUES (?, ?, 1, 1, 'cli', NULL, NULL, 'test-provider', ?, '', '', 'read-only', 'on-request', 0, '', 0, NULL, NULL, NULL, NULL, 'enabled')
"#,
)
.bind(thread_id)
.bind(codex_home.path().join("session.jsonl").display().to_string())
.bind(codex_home.path().display().to_string())
.execute(&pool)
.await?;
sqlx::query(
r#"
INSERT INTO stage1_outputs (
thread_id,
source_updated_at,
raw_memory,
rollout_summary,
generated_at,
rollout_slug,
usage_count,
last_usage,
selected_for_phase2,
selected_for_phase2_source_updated_at
) VALUES (?, 1, 'raw', 'summary', 1, NULL, 0, NULL, 0, NULL)
"#,
)
.bind(thread_id)
.execute(&memories_pool)
.await?;
sqlx::query(
r#"
INSERT INTO jobs (
kind,
job_key,
status,
worker_id,
ownership_token,
started_at,
finished_at,
lease_until,
retry_at,
retry_remaining,
last_error,
input_watermark,
last_success_watermark
) VALUES
('memory_stage1', ?, 'completed', NULL, NULL, NULL, NULL, NULL, NULL, 3, NULL, NULL, 1),
('memory_consolidate_global', 'global', 'completed', NULL, NULL, NULL, NULL, NULL, NULL, 3, NULL, NULL, 1)
"#,
)
.bind(thread_id)
.execute(&memories_pool)
.await?;
let memory_root = codex_home.path().join("memories");
std::fs::create_dir_all(&memory_root)?;
std::fs::write(memory_root.join("memory_summary.md"), "stale memory")?;
pool.close().await;
memories_pool.close().await;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["debug", "clear-memories"])
.assert()
.success()
.stdout(contains("Cleared memory state"));
let pool = sqlite.open_read_write_pool(&memories_db_path).await?;
let stage1_outputs_count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM stage1_outputs")
.fetch_one(&pool)
.await?;
assert_eq!(stage1_outputs_count, 0);
let memory_jobs_count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM jobs WHERE kind = 'memory_stage1' OR kind = 'memory_consolidate_global'",
)
.fetch_one(&pool)
.await?;
assert_eq!(memory_jobs_count, 0);
assert!(memory_root.exists());
assert_eq!(std::fs::read_dir(memory_root)?.count(), 0);
pool.close().await;
Ok(())
}
#[tokio::test]
async fn debug_clear_memories_resets_memories_db_without_state_db() -> Result<()> {
let codex_home = TempDir::new()?;
let sqlite = akode_state::SqliteConfig::new_for_testing(codex_home.path().abs());
let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string()).await?;
runtime.close().await;
let db_path = sqlite.state_db_path();
let memories_db_path = sqlite.memories_db_path();
let memories_pool = sqlite.open_read_write_pool(&memories_db_path).await?;
sqlx::query(
r#"
INSERT INTO stage1_outputs (
thread_id,
source_updated_at,
raw_memory,
rollout_summary,
generated_at,
rollout_slug,
usage_count,
last_usage,
selected_for_phase2,
selected_for_phase2_source_updated_at
) VALUES ('00000000-0000-0000-0000-000000000123', 1, 'raw', 'summary', 1, NULL, 0, NULL, 0, NULL)
"#,
)
.execute(&memories_pool)
.await?;
memories_pool.close().await;
std::fs::remove_file(&db_path)?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["debug", "clear-memories"])
.assert()
.success()
.stdout(contains("Cleared memory state"));
let pool = sqlite.open_read_write_pool(&memories_db_path).await?;
let stage1_outputs_count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM stage1_outputs")
.fetch_one(&pool)
.await?;
assert_eq!(stage1_outputs_count, 0);
pool.close().await;
assert!(!db_path.exists());
Ok(())
}

View File

@@ -0,0 +1,41 @@
use std::path::Path;
use anyhow::Result;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
#[test]
fn debug_models_bundled_prints_json() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
let output = cmd.args(["debug", "models", "--bundled"]).output()?;
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout)?;
let value: serde_json::Value = serde_json::from_str(&stdout)?;
assert!(value["models"].is_array());
assert!(!value["models"].as_array().unwrap_or(&Vec::new()).is_empty());
Ok(())
}
#[test]
fn debug_models_default_prints_empty_json_without_provider() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
let output = cmd.args(["debug", "models"]).output()?;
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout)?;
let value: serde_json::Value = serde_json::from_str(&stdout)?;
assert!(value["models"].is_array());
// aKode has no default provider and no built-in catalog: nothing to list, no network.
assert!(value["models"].as_array().unwrap_or(&Vec::new()).is_empty());
Ok(())
}

View File

@@ -0,0 +1,17 @@
use predicates::prelude::*;
#[test]
fn missing_session_fails_before_delete_confirmation() -> anyhow::Result<()> {
let codex_home = tempfile::tempdir()?;
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home.path())
.args(["delete", "123e4567-e89b-12d3-a456-426614174000"]);
cmd.assert()
.failure()
.stderr(predicate::str::contains(
"No active or archived session found matching",
))
.stderr(predicate::str::contains("cannot confirm").not());
Ok(())
}

View File

@@ -0,0 +1,344 @@
#[cfg(target_os = "macos")]
use std::path::Path;
use std::process::Command;
use std::process::Stdio;
use anyhow::Context as _;
use anyhow::Result;
use akode_state::SqliteConfig;
use akode_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use regex_lite::Regex;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
async fn local_provider() -> Result<(MockServer, TempDir)> {
let server = MockServer::start().await;
for (request_method, request_path, status) in
[("HEAD", "/v1/responses", 200), ("GET", "/v1/models", 401)]
{
Mock::given(method(request_method))
.and(path(request_path))
.respond_with(ResponseTemplate::new(status).insert_header("x-request-id", "fixture-id"))
.mount(&server)
.await;
}
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
format!(
"cli_auth_credentials_store = \"ephemeral\"\ncheck_for_update_on_startup = false\nmodel_provider = \"local\"\n[model_providers.local]\nname = \"local\"\nbase_url = \"{}/v1\"\nwire_api = \"responses\"\n",
server.uri()
),
)?;
Ok((server, home))
}
fn local_command(home: &TempDir) -> Result<Command> {
let mut command = Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
command
.current_dir(home.path())
.env("AKODE_HOME", home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.stdin(Stdio::null());
for name in [
"HTTP_PROXY",
"HTTPS_PROXY",
"ALL_PROXY",
"http_proxy",
"https_proxy",
"all_proxy",
"AKODE_ACCESS_TOKEN",
"AKODE_API_KEY",
"OPENAI_API_KEY",
"AKODE_CA_CERTIFICATE",
"SSL_CERT_FILE",
"OPENAI_WORKLOAD_IDENTITY_CONTEXT",
"OPENAI_IDENTITY_TOKEN_FILE",
"OPENAI_FEDERATION_RULE_ID",
] {
command.env_remove(name);
}
Ok(command)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn network_only_selects_checks_without_database_or_mcp_scans() -> Result<()> {
let (server, home) = local_provider().await?;
Mock::given(path("/unrelated-mcp"))
.respond_with(ResponseTemplate::new(200))
.expect(0)
.mount(&server)
.await;
let sqlite =
SqliteConfig::new_for_testing(AbsolutePathBuf::try_from(home.path().to_path_buf())?);
let database = sqlite.logs_db_path();
std::fs::write(&database, "not a SQLite database")?;
let mcp_url = format!("{}/unrelated-mcp", server.uri());
let output = local_command(&home)?
.args(["doctor", "--network-only", "--json", "--all", "--feedback"])
.arg("-c")
.arg(format!("mcp_servers.unrelated.url={mcp_url:?}"))
.output()?;
let report: Value = serde_json::from_slice(&output.stdout)?;
assert!(output.status.success(), "{report:#}");
let checks = report["checks"].as_object().unwrap();
assert_eq!(
checks.keys().map(String::as_str).collect::<Vec<_>>(),
vec![
"config.load",
"network.env",
"network.provider_reachability",
"network.websocket_reachability",
]
);
assert_eq!(std::fs::read_to_string(database)?, "not a SQLite database");
server.verify().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn network_only_reports_recoverable_config_warnings_and_effective_config() -> Result<()> {
let (_server, home) = local_provider().await?;
let baseline_output = local_command(&home)?
.args(["doctor", "--network-only", "--json"])
.output()?;
let baseline_report: Value = serde_json::from_slice(&baseline_output.stdout)?;
assert!(baseline_output.status.success(), "{baseline_report:#}");
let baseline_warning_count =
baseline_report["checks"]["config.load"]["details"]["startup warnings"]
.as_str()
.unwrap_or("0")
.parse::<usize>()?;
let config_path = home.path().join("config.toml");
let config = std::fs::read_to_string(&config_path)?;
std::fs::write(
config_path,
// OTEL exporters were removed (otel settings are ignored without warnings); use another
// recoverable, warning-only setting.
format!("{config}\n[features.guardianv2]\nasync_classifier_mode = \"conversation\"\n"),
)?;
let output = local_command(&home)?
.args(["doctor", "--network-only", "--json"])
.output()?;
let report: Value = serde_json::from_slice(&output.stdout)?;
assert!(output.status.success(), "{report:#}");
let config_check = &report["checks"]["config.load"];
let warning_count = config_check["details"]["startup warnings"]
.as_str()
.context("missing startup-warning count")?
.parse::<usize>()?;
let warnings = &config_check["details"]["startup warning"];
let startup_warning = std::iter::once(warnings)
.chain(warnings.as_array().into_iter().flatten())
.filter_map(Value::as_str)
.find(|warning| warning.starts_with("`[features.guardianv2].async_classifier_mode`"))
.context("missing recoverable config warning")?;
let check_statuses = report["checks"]
.as_object()
.unwrap()
.iter()
.map(|(id, check)| (id.clone(), check["status"].clone()))
.collect::<serde_json::Map<_, _>>();
assert_eq!(
json!({
"overallStatus": report["overallStatus"],
"checkStatuses": check_statuses,
"config": {
"summary": config_check["summary"],
"scope": config_check["details"]["configuration scope"],
"provider": config_check["details"]["model provider"],
"startupWarnings": warning_count,
"startupWarning": startup_warning,
},
}),
json!({
"overallStatus": "warning",
"checkStatuses": {
"config.load": "warning",
"network.env": "ok",
"network.provider_reachability": "ok",
"network.websocket_reachability": "ok",
},
"config": {
"summary": "config loaded",
"scope": "invocation config, including managed policy",
"provider": "local",
"startupWarnings": baseline_warning_count + 1,
"startupWarning": "`[features.guardianv2].async_classifier_mode` is deprecated and ignored. Async classification always uses conversations; remove this setting from config.toml or profile configuration files.",
},
})
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn network_only_config_failure_does_not_guess_probe_targets() -> Result<()> {
let proxy = MockServer::start().await;
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
"model_provider = sk-config-credential-fixture\n",
)?;
let output = local_command(&home)?
.args(["doctor", "--network-only", "--json"])
.env("HTTP_PROXY", proxy.uri())
.env("HTTPS_PROXY", proxy.uri())
.output()?;
assert_eq!(output.status.code(), Some(1));
assert!(!String::from_utf8_lossy(&output.stdout).contains("sk-config-credential-fixture"));
let report: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(report["checks"].as_object().unwrap().len(), 1);
assert_eq!(report["checks"]["config.load"]["status"], "fail");
assert_eq!(
report["checks"]["config.load"]["details"]["network diagnostics"],
"effective network configuration is unavailable"
);
assert!(proxy.received_requests().await.unwrap().is_empty());
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn network_only_human_output() -> Result<()> {
let (_server, home) = local_provider().await?;
let output = local_command(&home)?
.args([
"doctor",
"--network-only",
"--summary",
"--ascii",
"--no-color",
])
.output()?;
let stdout = String::from_utf8(output.stdout)?;
assert!(output.status.success(), "{stdout}");
insta::assert_snapshot!("network_only_human_output", stdout);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn network_only_config_failure_human_output() -> Result<()> {
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
"model_provider = sk-config-credential-fixture\n",
)?;
let output = local_command(&home)?
.args(["doctor", "--network-only", "--all", "--ascii", "--no-color"])
.output()?;
let stdout = String::from_utf8(output.stdout)?;
assert_eq!(output.status.code(), Some(1));
assert!(!stdout.contains("sk-config-credential-fixture"));
// Config loading may canonicalize the directory, rendering may shorten it,
// and Windows uses backslashes.
// Normalize the rendered config-file row while retaining its label and filename.
let file_row = Regex::new(r"(?m)^( file +).+[\\/]config\.toml$")?;
assert!(file_row.is_match(&stdout), "{stdout}");
let stdout = file_row.replace_all(&stdout, "${1}<AKODE_HOME>/config.toml");
insta::assert_snapshot!("network_only_config_failure_human_output", stdout);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn invalid_custom_ca_falls_back_to_system_roots() -> Result<()> {
let server = MockServer::start().await;
for (request_method, request_path) in [("HEAD", "/v1/responses"), ("GET", "/v1/models")] {
Mock::given(method(request_method))
.and(path(request_path))
.respond_with(ResponseTemplate::new(200))
.expect(2)
.mount(&server)
.await;
}
let codex_home = TempDir::new()?;
let certificate = codex_home.path().join("invalid-ca.pem");
std::fs::write(&certificate, "not a certificate")?;
std::fs::write(
codex_home.path().join("config.toml"),
format!(
"model_provider = \"local\"\n[model_providers.local]\nname = \"local\"\nbase_url = \"{}/v1\"\nwire_api = \"responses\"\n",
server.uri()
),
)?;
for sandbox in [None, Some("seatbelt")] {
let mut command = Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
command
.args(["doctor", "--json"])
.env("AKODE_HOME", codex_home.path())
.env("AKODE_CA_CERTIFICATE", &certificate)
.stdin(Stdio::null());
if let Some(sandbox) = sandbox {
command
.env("AKODE_SANDBOX", sandbox)
.env("HTTP_PROXY", "http://127.0.0.1:1")
.env("http_proxy", "http://127.0.0.1:1")
.env("HTTPS_PROXY", "http://127.0.0.1:1")
.env("https_proxy", "http://127.0.0.1:1")
.env("NO_PROXY", "")
.env("no_proxy", "");
} else {
command
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost");
}
let output = command
.output()
.context("failed to run the doctor with an invalid custom CA")?;
let report: Value = serde_json::from_slice(&output.stdout)?;
assert!(
report["checks"]["network.provider_reachability"]["details"]["local API inference URL"]
.as_str()
.is_some_and(|detail| detail.ends_with("reachable (HTTP 200)"))
);
}
server.verify().await;
Ok(())
}
#[cfg(target_os = "macos")]
#[test]
fn doctor_reports_macos_system_proxy_configuration_and_policy() -> Result<()> {
let codex_home = TempDir::new()?;
let report = doctor_report(codex_home.path())?;
let details = &report["checks"]["network.env"]["details"];
assert_eq!(details["respect system proxy"], json!("disabled"));
assert!(matches!(
details["system proxy"].as_str(),
Some("automatic (PAC)" | "manual" | "direct" | "unavailable")
));
std::fs::write(
codex_home.path().join("config.toml"),
"[features]\nrespect_system_proxy = true\n",
)?;
let report = doctor_report(codex_home.path())?;
assert_eq!(
report["checks"]["network.env"]["details"]["respect system proxy"],
json!("enabled")
);
Ok(())
}
#[cfg(target_os = "macos")]
fn doctor_report(codex_home: &Path) -> Result<Value> {
let output = Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.args(["doctor", "--json"])
.env("AKODE_HOME", codex_home)
.stdin(Stdio::null())
.output()
.context("failed to run the doctor")?;
serde_json::from_slice(&output.stdout).context("doctor did not emit a valid json report")
}

View File

@@ -0,0 +1,693 @@
//! Black-box coverage for safe diagnostic execution and config error reporting.
use std::ffi::OsString;
use std::path::PathBuf;
use std::time::Duration;
#[cfg(unix)]
use anyhow::Context;
use anyhow::Result;
use app_test_support::TestAppServer;
use akode_app_server_protocol::RequestId;
use akode_config::loader::project_trust_key;
use akode_state::SqliteConfig;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_cargo_bin::copy_executable;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::net::TcpListener;
use tokio::time::timeout;
struct Fixture {
root: TempDir,
program: PathBuf,
workspace: PathBuf,
home: PathBuf,
marker: PathBuf,
path: OsString,
}
impl Fixture {
fn new() -> Result<Self> {
let root = TempDir::new()?;
let home = root.path().join("home");
std::fs::create_dir(&home)?;
// Cargo-built paths deliberately ignore npm provenance. Launch outside
// target/ so this fixture also exercises the packaged-install checks.
let program = root
.path()
.join(format!("codex{}", std::env::consts::EXE_SUFFIX));
let source = akode_utils_cargo_bin::cargo_bin("akode")?;
// Hard-link setup and teardown invalidate other tests' Rosetta translations.
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
{
copy_executable(&source, &program)?;
// Translate the fixture before the timed diagnostic command.
anyhow::ensure!(
std::process::Command::new(&program)
.env("AKODE_HOME", &home)
.arg("--version")
.output()?
.status
.success(),
"failed to prepare diagnostic test executable"
);
}
#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
if std::fs::hard_link(&source, &program).is_err() {
copy_executable(&source, &program)?;
}
let workspace = root.path().join("workspace");
let bin = workspace.join("node_modules/.bin");
let marker = root.path().join("helper-ran");
std::fs::create_dir_all(&bin)?;
std::fs::create_dir_all(workspace.join(".git"))?;
std::fs::write(
home.join("config.toml"),
r#"
cli_auth_credentials_store = "file"
check_for_update_on_startup = false
model_provider = "local"
[model_providers.local]
name = "local test"
base_url = "http://127.0.0.1:9/v1"
wire_api = "responses"
"#,
)?;
for name in [
"zellij", "tmux", "which", "where", "npm", "rg", "git", "curl", "cmd.exe",
] {
#[cfg(unix)]
{
let executable = bin.join(name);
akode_utils_cargo_bin::write_executable(
&executable,
"#!/bin/sh\nprintf 'helper ran\\n' >> \"$AKODE_TEST_HELPER_MARKER\"\nexit 0\n",
)?;
}
#[cfg(windows)]
std::fs::write(
bin.join(format!("{name}.cmd")),
"@echo helper ran>>\"%AKODE_TEST_HELPER_MARKER%\"\r\n@exit /b 0\r\n",
)?;
}
// Windows selects rg.exe explicitly, so rg.cmd cannot satisfy discovery.
// An invalid image still counts as found: doctor must not execute it.
#[cfg(windows)]
std::fs::write(bin.join("rg.exe"), "not an executable image")?;
let path = std::env::join_paths(std::iter::once(bin).chain(std::env::split_paths(
&std::env::var_os("PATH").unwrap_or_default(),
)))?;
Ok(Self {
root,
program,
workspace,
home,
marker,
path,
})
}
fn command(&self) -> Result<assert_cmd::Command> {
let mut command = assert_cmd::Command::new(&self.program);
command
.current_dir(&self.workspace)
.env("AKODE_HOME", &self.home)
.env("HOME", self.root.path())
.env("PATH", &self.path)
.env("AKODE_TEST_HELPER_MARKER", &self.marker)
.env("AKODE_MANAGED_BY_NPM", "1")
.env(
"AKODE_MANAGED_PACKAGE_ROOT",
self.workspace.join("node_modules/@openai/codex"),
)
.env(
"AKODE_APP_SERVER_MANAGED_CONFIG_PATH",
self.home.join("managed_config.toml"),
)
.env("HTTPS_PROXY", "http://127.0.0.1:9")
.env("HTTP_PROXY", "http://127.0.0.1:9")
.env("ALL_PROXY", "http://127.0.0.1:9")
.env("https_proxy", "http://127.0.0.1:9")
.env("http_proxy", "http://127.0.0.1:9")
.env("all_proxy", "http://127.0.0.1:9")
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("TMUX")
.env_remove("TMUX_PANE")
.env_remove("ZELLIJ_VERSION")
.env_remove("ZELLIJ_SESSION_NAME")
.env_remove("TERM_PROGRAM")
.env("TERM", "dumb")
.env("ZELLIJ", "0")
.timeout(Duration::from_secs(/*secs*/ 45));
Ok(command)
}
}
#[test]
#[cfg_attr(
windows,
ignore = "Windows doctor fixture does not discover the synthetic Git executable"
)]
fn startup_and_doctor_do_not_execute_path_helpers() -> Result<()> {
let fixture = Fixture::new()?;
// Non-TTY dumb-terminal startup exits immediately after terminal detection.
fixture.command()?.assert().failure();
assert!(!fixture.marker.exists(), "startup executed a PATH helper");
for args in [
vec!["doctor", "--json"],
vec!["doctor", "--json", "--feedback"],
] {
let mut command = fixture.command()?;
command
.args(args)
.env("TMUX", "test-tmux")
.env("TERM_PROGRAM", "tmux");
let output = command.output()?;
let report: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(
report["checks"]["installation"]["details"]["managed by npm"],
"true"
);
assert_eq!(report["checks"]["runtime.search"]["status"], "ok");
assert_eq!(
report["checks"]["runtime.search"]["details"]["search command path"],
fixture
.workspace
.join("node_modules/.bin")
.join(format!("rg{}", std::env::consts::EXE_SUFFIX))
.display()
.to_string()
);
assert_eq!(
report["checks"]["git.environment"]["summary"],
"git executable found; execution not verified"
);
assert!(!fixture.marker.exists(), "doctor executed a PATH helper");
}
Ok(())
}
#[test]
fn non_interactive_dumb_terminal_preserves_other_doctor_failures() -> Result<()> {
let fixture = Fixture::new()?;
let output = fixture
.command()?
.args(["doctor", "--json"])
// Explicit identity takes precedence over inherited terminal-specific variables.
.env("TERM_PROGRAM", "dumb")
.env_remove("TERMINFO")
.env_remove("TERMINFO_DIRS")
.output()?;
// The fixture's provider is unreachable, regardless of terminal capabilities.
assert_eq!(output.status.code(), Some(1));
let report: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(report["checks"]["terminal.env"]["status"], "warning");
assert_eq!(report["overallStatus"], "fail");
Ok(())
}
#[test]
fn doctor_reports_failed_database_paths() -> Result<()> {
let fixture = Fixture::new()?;
let sqlite_home = fixture.root.path().join("sqlite");
std::fs::create_dir(&sqlite_home)?;
let sqlite = SqliteConfig::new_for_testing(AbsolutePathBuf::try_from(sqlite_home.clone())?);
let config_file = fixture.home.join("config.toml");
let config = std::fs::read_to_string(&config_file)?;
let sqlite_home = toml::Value::String(sqlite_home.display().to_string());
std::fs::write(
&config_file,
format!("sqlite_home = {sqlite_home}\nlog_dir = {sqlite_home}\n{config}"),
)?;
for (snapshot_name, failed_paths) in [
("doctor_failed_log_database", vec![sqlite.logs_db_path()]),
(
"doctor_failed_multiple_databases",
vec![sqlite.logs_db_path(), sqlite.goals_db_path()],
),
] {
for path in &failed_paths {
std::fs::write(path, "not a SQLite database")?;
}
let paths = failed_paths
.iter()
.map(|path| path.display().to_string())
.collect::<Vec<_>>()
.join(", ");
let noun = if failed_paths.len() == 1 {
"database"
} else {
"databases"
};
let expected_cause = format!("{paths} {noun} failed integrity check");
for args in [
vec!["doctor", "--json"],
vec!["doctor", "--json", "--feedback"],
] {
let output = fixture.command()?.args(args).output()?;
assert_eq!(output.status.code(), Some(1));
let report: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(report["checks"]["state.paths"]["status"], "fail");
assert_eq!(
report["checks"]["state.paths"]["summary"],
"state database integrity check failed"
);
assert_eq!(
report["checks"]["state.paths"]["issues"][0]["cause"],
expected_cause
);
}
for summary_only in [false, true] {
let mut command = fixture.command()?;
command.args(["doctor", "--ascii", "--no-color"]);
if summary_only {
command.arg("--summary");
}
let output = command.output()?;
assert_eq!(output.status.code(), Some(1));
let stdout = String::from_utf8(output.stdout)?;
let state_row = stdout
.lines()
.filter(|line| {
line.starts_with(" [XX] state ")
|| (!summary_only
&& line.starts_with(" -> Move the damaged SQLite database aside"))
})
.collect::<Vec<_>>()
.join("\n")
.replace(&fixture.root.path().display().to_string(), "FIXTURE")
.replace('\\', "/");
if summary_only {
assert_eq!(
state_row,
format!(
" [XX] state {}",
expected_cause
.replace(&fixture.root.path().display().to_string(), "FIXTURE")
)
.replace('\\', "/")
);
} else {
insta::assert_snapshot!(snapshot_name, state_row);
}
}
for path in &failed_paths {
assert_eq!(std::fs::read_to_string(path)?, "not a SQLite database");
}
}
Ok(())
}
#[test]
fn doctor_redacts_failed_database_paths_in_json() -> Result<()> {
let fixture = Fixture::new()?;
let sqlite_home = fixture.root.path().join("doctor-secret-sqlite");
std::fs::create_dir(&sqlite_home)?;
let sqlite = SqliteConfig::new_for_testing(AbsolutePathBuf::try_from(sqlite_home.clone())?);
let config_file = fixture.home.join("config.toml");
let config = std::fs::read_to_string(&config_file)?;
let sqlite_home = toml::Value::String(sqlite_home.display().to_string());
std::fs::write(
&config_file,
format!("sqlite_home = {sqlite_home}\nlog_dir = {sqlite_home}\n{config}"),
)?;
std::fs::write(sqlite.logs_db_path(), "not a SQLite database")?;
let output = fixture
.command()?
.args(["doctor", "--json", "--feedback"])
.output()?;
assert_eq!(output.status.code(), Some(1));
let stdout = String::from_utf8(output.stdout)?;
assert!(!stdout.contains("doctor-secret-sqlite"));
let report: Value = serde_json::from_str(&stdout)?;
assert_eq!(
report["checks"]["state.paths"]["summary"],
"state database integrity check failed"
);
assert_eq!(
report["checks"]["state.paths"]["issues"][0]["cause"],
"<redacted>"
);
Ok(())
}
#[test]
fn doctor_reports_only_safe_config_error_metadata() -> Result<()> {
let fixture = Fixture::new()?;
let user_config_file = fixture.home.join("config.toml");
let original = std::fs::read_to_string(&user_config_file)?;
// macOS temp directories can use a symlinked path; trust the canonical workspace.
let project_key = toml::Value::String(project_trust_key(&fixture.workspace));
let original = format!("{original}\n[projects.{project_key}]\ntrust_level = \"trusted\"\n");
let project_config_dir = fixture.workspace.join(".akode");
std::fs::create_dir(&project_config_dir)?;
for (snapshot_name, config_file, config) in [
(
"doctor_config_error_location",
user_config_file.clone(),
"custom_header = \"doctor-test-credential\" trailing\n".to_string(),
),
(
"doctor_config_invalid_data",
project_config_dir.join("config.toml"),
"custom_header = \"doctor-test-credential\" trailing\n".to_string(),
),
(
"doctor_config_not_found",
user_config_file.clone(),
original.replace(
"model_provider = \"local\"",
"model_provider = \"doctor-test-credential\"",
),
),
// A type error in a known key reports its location (file/line/column) but never
// the offending value.
(
"doctor_config_invalid_type",
user_config_file.clone(),
original.replace(
"wire_api = \"responses\"",
"wire_api = \"responses\"\nhttp_headers = \"sk-proj-ABC123example\"",
),
),
] {
std::fs::write(&user_config_file, &original)?;
std::fs::write(&config_file, config)?;
for args in [
vec!["doctor", "--json"],
vec!["doctor", "--json", "--feedback"],
] {
let output = fixture.command()?.args(args).output()?;
assert_eq!(output.status.code(), Some(1));
let report: Value = serde_json::from_slice(&output.stdout)?;
let mut check = report["checks"]["config.load"].clone();
check
.as_object_mut()
.expect("config check")
.remove("durationMs");
if let Some(file) = check["details"]["file"].as_str() {
check["details"]["file"] = Value::String(
file.replace(
&fixture.root.path().canonicalize()?.display().to_string(),
"FIXTURE",
)
.replace(&fixture.root.path().display().to_string(), "FIXTURE")
.replace('\\', "/"),
);
}
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(!stdout.contains("doctor-test-credential"));
assert!(!stdout.contains("sk-proj-ABC123example"));
// Keep snapshots stable across serde_json feature sets in Cargo and Bazel.
check.sort_all_objects();
insta::assert_snapshot!(snapshot_name, serde_json::to_string_pretty(&check)?);
}
std::fs::remove_file(config_file)?;
}
Ok(())
}
#[test]
fn doctor_reports_configured_tui_mode() -> Result<()> {
let fixture = Fixture::new()?;
for (setting, expected) in [("true", "fullscreen"), ("false", "scrollback")] {
let output = fixture
.command()?
.args(["-c", &format!("tui.fullscreen_transcript={setting}")])
.args(["doctor", "--json"])
.output()?;
let report: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(
report["checks"]["config.load"]["details"]["configured TUI mode"],
expected
);
}
Ok(())
}
#[test]
fn doctor_reports_configured_filesystem_paths() -> Result<()> {
let fixture = Fixture::new()?;
let config_file = fixture.home.join("config.toml");
let original = std::fs::read_to_string(&config_file)?;
let existing = fixture.workspace.join("probe-existing");
let missing = fixture.workspace.join("probe-missing");
std::fs::create_dir(&existing)?;
let existing_key = toml::Value::String(existing.display().to_string());
let missing_key = toml::Value::String(missing.display().to_string());
std::fs::write(
&config_file,
format!(
r#"default_permissions = "diagnostic"
{original}
[permissions.diagnostic]
extends = ":read-only"
[permissions.diagnostic.filesystem]
{existing_key} = "read"
{missing_key} = "write"
"#
),
)?;
let output = fixture.command()?.args(["doctor", "--json"]).output()?;
let report: Value = serde_json::from_slice(&output.stdout)?;
#[cfg(windows)]
assert_eq!(report["checks"]["sandbox.filesystem_paths"]["status"], "ok");
let mut details = report["checks"]["sandbox.filesystem_paths"]["details"].clone();
// Snapshot outcomes and provenance independently of helper startup speed.
details
.as_object_mut()
.expect("path details")
.retain(|key, _| !key.ends_with(" latency"));
let canonical_root = fixture.root.path().canonicalize()?;
for value in details.as_object_mut().expect("path details").values_mut() {
let detail = value
.as_str()
.expect("scalar path detail")
.replace(&canonical_root.display().to_string(), "FIXTURE")
.replace(&fixture.root.path().display().to_string(), "FIXTURE")
.replace('\\', "/");
*value = Value::String(detail);
}
let snapshot_name = if cfg!(windows) {
"doctor_configured_filesystem_paths_windows"
} else {
"doctor_configured_filesystem_paths"
};
insta::assert_snapshot!(snapshot_name, serde_json::to_string_pretty(&details)?);
Ok(())
}
#[test]
fn filesystem_probe_does_not_load_configuration() -> Result<()> {
let fixture = Fixture::new()?;
std::fs::write(fixture.home.join("config.toml"), "invalid TOML = [")?;
for (path, expected) in [
(&fixture.workspace, 0),
(&fixture.workspace.join("missing"), 2),
] {
let output = fixture
.command()?
.args(["doctor", "--probe-filesystem-path"])
.arg(path)
.output()?;
assert_eq!(
output.status.code(),
Some(if cfg!(windows) { 5 } else { expected })
);
assert!(output.stdout.is_empty());
}
Ok(())
}
#[cfg(unix)]
#[tokio::test]
async fn interactive_tmux_startup_does_not_execute_workspace_helpers() -> Result<()> {
let fixture = Fixture::new()?;
std::fs::create_dir(fixture.workspace.join(".akode"))?;
let command = fixture.command()?;
let mut env: std::collections::HashMap<String, String> = std::env::vars().collect();
for (key, value) in command.get_envs() {
let key = key.to_string_lossy().into_owned();
if let Some(value) = value {
env.insert(key, value.to_string_lossy().into_owned());
} else {
env.remove(&key);
}
}
env.insert("TERM".to_string(), "xterm-256color".to_string());
env.insert("TERM_PROGRAM".to_string(), "tmux".to_string());
env.insert("TMUX".to_string(), "test-tmux".to_string());
env.insert(
"AKODE_TUI_DISABLE_KEYBOARD_ENHANCEMENT".to_string(),
"0".to_string(),
);
env.insert(
"GHOSTTY_RESOURCES_DIR".to_string(),
"/test/ghostty".to_string(),
);
let spawned = akode_utils_pty::spawn_pty_process(
fixture.program.to_str().unwrap(),
&["--no-daemon".to_string()],
&fixture.workspace,
&env,
/*arg0*/ &None,
akode_utils_pty::TerminalSize {
rows: 40,
cols: 120,
},
akode_utils_pty::ChildFds::Inherited(&[]),
)
.await?;
let session = spawned.session;
let mut output_rx = spawned.stdout_rx;
let writer = session.writer_sender();
let mut output = String::new();
let ansi = regex_lite::Regex::new(r"\x1b\[[0-?]*[ -/]*[@-~]")?;
let ready = timeout(Duration::from_secs(/*secs*/ 45), async {
while let Some(bytes) = output_rx.recv().await {
let chunk = String::from_utf8_lossy(&bytes);
output.push_str(&chunk);
if chunk.contains("\x1b[6n") {
writer.send(b"\x1b[1;1R".to_vec()).await?;
}
if chunk.contains("\x1b[c") {
writer.send(b"\x1b[?1;2c".to_vec()).await?;
}
// Ratatui can position over spaces instead of writing them.
let text: String = ansi
.replace_all(&output, "")
.chars()
.filter(|character| !character.is_whitespace())
.collect();
if text.contains("Trustthisfolder?") {
return Ok::<_, anyhow::Error>(());
}
}
anyhow::bail!("TUI exited before trust prompt")
})
.await;
ready.map_err(|_| {
anyhow::anyhow!(
"trust prompt timed out: {}",
output.chars().take(/*n*/ 4000).collect::<String>()
)
})??;
// The first Ctrl+C leaves the untrusted workspace for the command center.
// Keep sending Ctrl+C so the TUI exits even if the first draw discarded input.
let mut quit_retry = tokio::time::interval(Duration::from_millis(/*millis*/ 250));
let mut exit_rx = spawned.exit_rx;
timeout(Duration::from_secs(/*secs*/ 10), async {
loop {
tokio::select! {
result = &mut exit_rx => return result,
_ = quit_retry.tick() => {
let _ = writer.send(b"\x03".to_vec()).await;
}
Some(_) = output_rx.recv() => {}
}
}
})
.await
.with_context(|| {
format!(
"TUI did not exit after declining directory trust: {}",
output.chars().take(/*n*/ 4000).collect::<String>()
)
})??;
assert!(
output.contains("\x1b[>5u"),
"expected safe Ghostty/tmux keyboard flags: {output}"
);
assert!(
!fixture.marker.exists(),
"interactive startup executed a workspace helper"
);
Ok(())
}
#[tokio::test]
async fn feedback_with_logs_does_not_execute_path_helpers() -> Result<()> {
let fixture = Fixture::new()?;
let proxy = TcpListener::bind("127.0.0.1:0").await?;
let proxy_uri = format!("http://{}", proxy.local_addr()?);
// Reject all outbound traffic locally; feedback collection must not need the network.
let proxy_task = tokio::spawn(async move {
while let Ok((stream, _)) = proxy.accept().await {
let mut stream = BufReader::new(stream);
let mut request = String::new();
if stream.read_line(&mut request).await.is_ok() {
let _ = stream.get_mut().write_all(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").await;
}
}
});
let path = fixture.path.to_string_lossy();
let marker = fixture.marker.to_string_lossy();
let home = fixture.root.path().to_string_lossy();
let package_root = fixture.workspace.join("node_modules/@openai/codex");
let package_root = package_root.to_string_lossy();
let mut app_server = TestAppServer::builder()
.with_program(&fixture.program)
.with_codex_home(&fixture.home)
// The CLI does not accept the standalone app-server's test-only flag.
// Disable plugins through real config; their safety test joins a full sync.
.with_plugin_startup_tasks()
.with_args(&["-c", "features.plugins=false", "app-server"])
.with_env_overrides(&[
("PATH", Some(path.as_ref())),
("HOME", Some(home.as_ref())),
("AKODE_TEST_HELPER_MARKER", Some(marker.as_ref())),
("AKODE_MANAGED_BY_NPM", Some("1")),
("AKODE_MANAGED_PACKAGE_ROOT", Some(package_root.as_ref())),
("ZELLIJ", Some("0")),
("ZELLIJ_VERSION", None),
("TMUX", None),
("TMUX_PANE", None),
("HTTP_PROXY", Some(&proxy_uri)),
("HTTPS_PROXY", Some(&proxy_uri)),
("ALL_PROXY", Some(&proxy_uri)),
("http_proxy", Some(&proxy_uri)),
("https_proxy", Some(&proxy_uri)),
("all_proxy", Some(&proxy_uri)),
("NO_PROXY", Some("127.0.0.1,localhost")),
("no_proxy", Some("127.0.0.1,localhost")),
])
.build_initialized_with_timeout(Duration::from_secs(/*secs*/ 30))
.await?;
// Feedback is only ever saved locally; collecting its diagnostics must not run PATH helpers.
let save_path = fixture.root.path().join("feedback.zip");
let request_id = app_server
.send_raw_request(
"feedback/save",
Some(json!({
"classification": "bug",
"includeLogs": true,
"savePath": save_path.to_string_lossy(),
})),
)
.await?;
timeout(
Duration::from_secs(/*secs*/ 45),
app_server.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
assert!(save_path.exists(), "feedback must be saved locally");
assert!(!fixture.marker.exists(), "feedback executed a PATH helper");
timeout(
Duration::from_secs(/*secs*/ 10),
app_server.shutdown_gracefully(),
)
.await??;
proxy_task.abort();
Ok(())
}

View File

@@ -0,0 +1,928 @@
#[cfg(target_os = "linux")]
#[path = "exec_server/pid_namespace_tests.rs"]
mod pid_namespace_tests;
use std::collections::HashMap;
#[cfg(unix)]
use std::io::BufRead as _;
#[cfg(unix)]
use std::io::BufReader as StdBufReader;
#[cfg(unix)]
use std::io::Read as _;
#[cfg(unix)]
use std::io::Write as _;
#[cfg(unix)]
use std::net::TcpStream;
use std::path::Path;
use std::process::Stdio;
#[cfg(unix)]
use std::thread;
use std::time::Duration;
#[cfg(unix)]
use std::time::Instant;
use anyhow::Context;
use anyhow::Result;
use akode_exec_server::EnvironmentInfo;
use akode_exec_server::ExecParams;
use akode_exec_server::ExecServerClient;
use akode_exec_server::NoiseChannelIdentity;
use akode_exec_server::NoiseChannelPublicKey;
use akode_exec_server::NoiseRendezvousConnectArgs;
use akode_exec_server::NoiseRendezvousConnectBundle;
use akode_exec_server::ProcessId;
use akode_http_client::HttpClientFactory;
use akode_http_client::OutboundProxyPolicy;
use akode_utils_cargo_bin::copy_executable;
use akode_utils_path_uri::PathUri;
use futures::SinkExt;
use futures::StreamExt;
use predicates::prelude::PredicateBooleanExt;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::net::TcpListener;
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::accept_async;
use tokio_tungstenite::accept_hdr_async;
use tokio_tungstenite::tungstenite::handshake::server::Request;
use tokio_tungstenite::tungstenite::handshake::server::Response;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
#[test]
fn strict_config_rejects_unknown_config_fields_for_exec_server() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
r#"
foo = "bar"
"#,
)?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args([
"exec-server",
"--strict-config",
"--listen",
"http://127.0.0.1:0",
])
.assert()
.failure()
.stderr(contains("unknown configuration field"));
Ok(())
}
#[test]
fn local_exec_server_ignores_invalid_config_without_strict_config() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(codex_home.path().join("config.toml"), "not valid toml = [")?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["exec-server", "--listen", "stdio"])
.assert()
.success()
.stderr(contains("not valid toml").not());
Ok(())
}
/// Real global CLI flags must reach executor config reads; unrelated startup flags stay private.
#[tokio::test]
async fn local_exec_server_projects_global_mxc_preference() -> Result<()> {
let home = TempDir::new()?;
let cwd = url::Url::from_directory_path(home.path())
.map_err(|()| anyhow::anyhow!("could not convert home to file URL"))?;
let mut child = tokio::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.env("AKODE_HOME", home.path())
.args([
"-c",
"features.prefer_mxc=true",
"-c",
"model='private-startup-model'",
"exec-server",
"--listen",
"stdio",
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.kill_on_drop(true)
.spawn()?;
let mut stdin = child.stdin.take().context("exec-server stdin")?;
let mut stdout = BufReader::new(child.stdout.take().context("exec-server stdout")?);
let result = tokio::time::timeout(Duration::from_secs(30), async {
send_json_line(
&mut stdin,
&serde_json::json!({"id": 1, "method": "initialize",
"params": {"clientName": "mxc-test", "resumeSessionId": null}}),
)
.await?;
wait_for_response(&mut stdout, /*expected_id*/ 1).await?;
send_json_line(
&mut stdin,
&serde_json::json!({"method": "initialized", "params": {}}),
)
.await?;
send_json_line(
&mut stdin,
&serde_json::json!({"id": 2, "method": "environmentConfig/read", "params": {
"cwd": cwd, "configPaths": [["features", "prefer_mxc"], ["model"]],
"requirementsPaths": []
}}),
)
.await?;
wait_for_response(&mut stdout, /*expected_id*/ 2).await
})
.await
.context("executor CLI config read timed out")??;
let layers = result["result"]["config"]["layers"]
.as_array()
.context("config layers")?;
let session = layers
.iter()
.find(|l| l["source"] == "session-flags")
.context("session flags")?;
let value: toml::Value = toml::from_str(session["toml"].as_str().context("session TOML")?)?;
assert_eq!(
value,
toml::Value::Table(toml::toml! { [features] prefer_mxc = true })
);
drop(stdin);
assert!(
tokio::time::timeout(Duration::from_secs(30), child.wait())
.await??
.success()
);
Ok(())
}
/// The standalone exec-server accepts an explicit per-connection concurrency limit.
#[test]
fn local_exec_server_accepts_concurrent_requests_flag() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args([
"exec-server",
"--listen",
"stdio",
"--concurrent-requests",
"2",
])
.assert()
.success();
Ok(())
}
#[test]
fn local_exec_server_allows_disabled_parent_lifetime_environment_variable() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
cmd.env(
akode_exec_server::AKODE_EXEC_SERVER_EXIT_ON_STDIN_CLOSE_ENV_VAR,
"false",
)
.args(["exec-server", "--listen", "stdio"])
.assert()
.success();
Ok(())
}
#[tokio::test]
async fn remote_exec_server_gracefully_stops_when_parent_stdin_closes() -> Result<()> {
const ENVIRONMENT_ID: &str = "environment-parent-lifetime";
const EXECUTOR_REGISTRATION_ID: &str = "registration-parent-lifetime";
const TEST_TIMEOUT: Duration = Duration::from_secs(30);
let listener = TcpListener::bind("127.0.0.1:0").await?;
let rendezvous_url = format!("ws://{}", listener.local_addr()?);
let registry = MockServer::start().await;
Mock::given(method("POST"))
.and(path(format!(
"/cloud/environment/{ENVIRONMENT_ID}/register"
)))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"environment_id": ENVIRONMENT_ID,
"url": format!("{rendezvous_url}/relay?role=environment"),
"security_profile": "noise_hybrid_ik_v1",
"executor_registration_id": EXECUTOR_REGISTRATION_ID,
})))
.mount(&registry)
.await;
Mock::given(method("POST"))
.and(path(format!(
"/cloud/environment/{ENVIRONMENT_ID}/validate"
)))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"valid": true,
})))
.mount(&registry)
.await;
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
"cli_auth_credentials_store = \"file\"\n",
)?;
let package = TempDir::new()?;
let bin_dir = package.path().join("bin");
std::fs::create_dir(&bin_dir)?;
let executable = bin_dir.join(format!("codex{}", std::env::consts::EXE_SUFFIX));
copy_executable(&akode_utils_cargo_bin::cargo_bin("akode")?, &executable)?;
let codex_path_dir = package.path().join("akode-path");
std::fs::create_dir(&codex_path_dir)?;
let manifest = package.path().join("akode-package.json");
std::fs::write(&manifest, r#"{"version":"1.2.3-alpha.4"}"#)?;
let stderr_path = codex_home.path().join("executor-stderr.log");
let stderr = std::fs::File::create(&stderr_path)?;
let mut command = tokio::process::Command::new(executable);
command
.current_dir(codex_home.path())
.env("AKODE_HOME", codex_home.path())
.env("AKODE_API_KEY", "test-api-key")
.env_remove("AKODE_ACCESS_TOKEN")
.env(
akode_exec_server::AKODE_EXEC_SERVER_EXIT_ON_STDIN_CLOSE_ENV_VAR,
"true",
)
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env("RUST_LOG", "error,akode_exec_server::remote=info")
.args([
"exec-server",
"--remote",
&registry.uri(),
"--environment-id",
ENVIRONMENT_ID,
"--concurrent-requests",
"2",
])
.stdin(Stdio::piped())
.stderr(Stdio::from(stderr))
.kill_on_drop(true);
let mut child = command.spawn()?;
let stdin = child
.stdin
.take()
.ok_or_else(|| anyhow::anyhow!("remote exec-server stdin was not piped"))?;
// An executor that exits during startup cannot reach the rendezvous. Report that
// exit immediately instead of hiding it behind the connection timeout.
let environment_websocket = tokio::select! {
status = child.wait() => {
let status = status.context("failed to wait for remote exec-server")?;
Err(anyhow::anyhow!("remote exec-server exited before connecting: {status}"))
}
result = accept_parent_lifetime_websocket(&listener, TEST_TIMEOUT) => result,
};
let environment_websocket = match environment_websocket {
Ok(websocket) => websocket,
Err(error) => {
let registration_requests = registry.received_requests().await.map(|requests| {
requests
.iter()
.filter(|request| request.url.path().ends_with("/register"))
.count()
});
// Keep registry request headers and bodies out of the failure report.
let child_status = child.try_wait();
let stderr = std::fs::read_to_string(&stderr_path)?;
return Err(error.context(format!(
"remote executor failed to attach (registration requests: {registration_requests:?}, child status: {child_status:?}); stderr: {stderr}"
)));
}
};
// Remote startup must capture the version before registration, not on the first initialize.
std::fs::write(&manifest, r#"{"version":"9.9.9"}"#)?;
let executor_public_key = registered_parent_lifetime_executor_public_key(&registry).await?;
let harness_args = NoiseRendezvousConnectArgs {
bundle: NoiseRendezvousConnectBundle {
websocket_url: format!("{rendezvous_url}/relay?role=harness"),
environment_id: ENVIRONMENT_ID.to_string(),
executor_registration_id: EXECUTOR_REGISTRATION_ID.to_string(),
executor_public_key,
harness_key_authorization: "parent-lifetime-harness".to_string(),
},
harness_identity: NoiseChannelIdentity::generate()?,
client_name: "parent-lifetime-test".to_string(),
connect_timeout: TEST_TIMEOUT,
initialize_timeout: TEST_TIMEOUT,
resume_session_id: None,
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
};
let client_task =
tokio::spawn(async move { ExecServerClient::connect_noise_rendezvous(harness_args).await });
let harness_websocket = accept_parent_lifetime_websocket(&listener, TEST_TIMEOUT)
.await
.context("harness failed to attach")?;
let relay_task = tokio::spawn(proxy_parent_lifetime_relay(
environment_websocket,
harness_websocket,
));
let client = tokio::time::timeout(TEST_TIMEOUT, client_task)
.await
.context("remote harness did not connect")???;
let environment_info = client.environment_info().await?;
assert_eq!(
environment_info
.prepend_path_dirs
.iter()
.map(|path| std::fs::canonicalize(path.inferred_native_path_string()))
.collect::<std::io::Result<Vec<_>>>()?,
vec![codex_path_dir.canonicalize()?]
);
let expected_info = EnvironmentInfo {
executor_version: "1.2.3-alpha.4".to_string(),
cwd: Some(PathUri::from_host_native_path(
codex_home.path().canonicalize()?,
)?),
// The build identity belongs to the spawned CLI, not this test process.
provider_id: environment_info.provider_id.clone(),
prepend_path_dirs: environment_info.prepend_path_dirs.clone(),
..EnvironmentInfo::local()
};
assert_eq!(environment_info.as_ref(), &expected_info);
std::fs::remove_file(&manifest)?;
assert_eq!(client.force_environment_info().await?, expected_info);
#[cfg(windows)]
let argv = vec![
"powershell.exe",
"-NoLogo",
"-NoProfile",
"-NonInteractive",
"-Command",
"if (Test-Path Env:AKODE_EXEC_SERVER_EXIT_ON_STDIN_CLOSE) { exit 1 }; Start-Sleep -Seconds 60",
];
#[cfg(not(windows))]
let argv = vec![
"/bin/sh",
"-c",
"[ -z \"${AKODE_EXEC_SERVER_EXIT_ON_STDIN_CLOSE+present}\" ] && exec /bin/sleep 60",
];
let cwd = url::Url::from_directory_path(std::env::current_dir()?)
.map_err(|()| anyhow::anyhow!("could not convert cwd to file URL"))?;
client
.exec(ExecParams {
metadata: Default::default(),
process_id: ProcessId::from("parent-lifetime-process"),
argv: argv.into_iter().map(str::to_string).collect(),
cwd: cwd.as_str().parse()?,
shell_snapshot: None,
env_policy: Some(akode_exec_server::ExecEnvPolicy {
inherit: akode_protocol::config_types::ShellEnvironmentPolicyInherit::All,
ignore_default_excludes: false,
exclude: Vec::new(),
r#set: HashMap::new(),
include_only: Vec::new(),
}),
env: HashMap::new(),
tty: false,
pipe_stdin: false,
arg0: None,
sandbox: None,
enforce_managed_network: false,
managed_network: None,
network_proxy: None,
})
.await?;
anyhow::ensure!(
child.try_wait()?.is_none(),
"remote exec-server exited while its parent stdin remained open"
);
drop(stdin);
let status = tokio::time::timeout(TEST_TIMEOUT, child.wait())
.await
.map_err(|_| anyhow::anyhow!("remote exec-server did not exit after stdin closed"))??;
anyhow::ensure!(status.success(), "remote exec-server exited with {status}");
relay_task.abort();
let _ = relay_task.await;
Ok(())
}
#[tokio::test]
async fn forward_rejects_stdin_credentials_on_opposite_sides_of_subcommand() -> Result<()> {
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
let home = TempDir::new()?;
let remote = [
"--remote",
"https://registry.example",
"--environment-id",
"env-1",
];
let bearer = "--registration-bearer-stdin";
let rotating = "--executor-credential-stdin";
for (before, after) in [(bearer, rotating), (rotating, bearer)] {
let mut child = tokio::process::Command::new(&codex)
.env("AKODE_HOME", home.path())
.arg("exec-server")
.args(remote)
.args([before, "forward", "--connect", "ws://127.0.0.1:8765"])
.args(remote)
.arg(after)
.stdin(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()?;
// Keep the empty pipe open so either credential read would block.
let _stdin = child.stdin.take().context("credential pipe")?;
let output = tokio::time::timeout(Duration::from_secs(30), child.wait_with_output())
.await
.context("exec-server waited for a credential")??;
assert!(!output.status.success());
assert!(String::from_utf8(output.stderr)?.contains(
"--registration-bearer-stdin cannot be used with --executor-credential-stdin"
));
}
Ok(())
}
#[tokio::test]
async fn remote_exec_server_scoped_credentials_authenticate_only_register_and_validate()
-> Result<()> {
const ENVIRONMENT: &str = "environment-scoped-credentials";
const CREDENTIAL: &str = "synthetic-scoped-credential-never-log-1234";
const ROTATED_CREDENTIAL: &str = "rotated-scoped-credential";
const TIMEOUT: Duration = Duration::from_secs(30);
let listener = TcpListener::bind("127.0.0.1:0").await?;
let rendezvous = format!("ws://{}", listener.local_addr()?);
let registry = MockServer::start().await;
let (registration_tx, mut registration_rx) = tokio::sync::mpsc::unbounded_channel();
// A confirmed pre-write auth outage must retry with the same scoped credential.
Mock::given(method("POST"))
.and(path(format!("/cloud/environment/{ENVIRONMENT}/register")))
.respond_with(ResponseTemplate::new(502).set_body_json(serde_json::json!({
"detail": {"code": "authentication_service_unavailable", "message": CREDENTIAL},
})))
.with_priority(1)
.up_to_n_times(1)
.expect(1)
.mount(&registry)
.await;
let registration_response = ResponseTemplate::new(200).set_body_json(serde_json::json!({
"environment_id": ENVIRONMENT,
"url": format!("{rendezvous}/relay?role=environment"),
"security_profile": "noise_hybrid_ik_v1",
"executor_registration_id": "registration-scoped",
}));
Mock::given(method("POST"))
.and(path(format!("/cloud/environment/{ENVIRONMENT}/register")))
.respond_with(move |request: &wiremock::Request| {
let credential = request
.headers
.get("authorization")
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
.unwrap_or_default()
.to_string();
let _ = registration_tx.send(credential);
registration_response.clone()
})
.mount(&registry)
.await;
Mock::given(method("POST"))
.and(path(format!("/cloud/environment/{ENVIRONMENT}/validate")))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"valid": true})))
.mount(&registry)
.await;
let collector = MockServer::start().await;
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
format!(
r#"
[otel]
metrics_exporter = {{ otlp-http = {{ endpoint = "{}/v1/metrics", protocol = "json", headers = {{ Authorization = "general-telemetry-token" }} }} }}
"#,
collector.uri()
),
)?;
std::fs::write(
home.path().join("auth.json"),
r#"{"OPENAI_API_KEY":"general-file-token"}"#,
)?;
let mut command = tokio::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
command
.env("AKODE_HOME", home.path())
.env_remove(akode_exec_server::AKODE_EXEC_SERVER_EXIT_ON_STDIN_CLOSE_ENV_VAR)
.env("AKODE_API_KEY", "general-api-key")
.env("OPENAI_API_KEY", "general-openai-key")
.env("AKODE_ACCESS_TOKEN", "general-agent-identity")
.env(
"OPENAI_WORKLOAD_IDENTITY_CONTEXT",
"invalid-general-workload-identity",
)
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.args([
"exec-server",
"--remote",
&registry.uri(),
"--environment-id",
ENVIRONMENT,
"--executor-credential-stdin",
])
.stdin(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
let mut child = command.spawn()?;
let mut stdin = child
.stdin
.take()
.context("credential stdin was not piped")?;
send_json_line(&mut stdin, &serde_json::json!({
"version": 1, "environment_id": ENVIRONMENT, "token": CREDENTIAL,
"expires_at": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs() + 120,
})).await?;
let (socket, _) = tokio::time::timeout(TIMEOUT, listener.accept())
.await
.context("executor did not reach rendezvous")??;
let environment_websocket = tokio::time::timeout(
TIMEOUT,
accept_hdr_async(socket, |request: &Request, response: Response| {
for name in ["authorization", "chatgpt-account-id"] {
assert!(
!request.headers().contains_key(name),
"registry authentication must not be sent in the WebSocket handshake"
);
}
Ok(response)
}),
)
.await
.context("executor WebSocket handshake did not complete")??;
let executor_public_key = registered_parent_lifetime_executor_public_key(&registry).await?;
let args = NoiseRendezvousConnectArgs {
bundle: NoiseRendezvousConnectBundle {
websocket_url: format!("{rendezvous}/relay?role=harness"),
environment_id: ENVIRONMENT.to_string(),
executor_registration_id: "registration-scoped".to_string(),
executor_public_key,
harness_key_authorization: "synthetic-harness-authorization".to_string(),
},
harness_identity: NoiseChannelIdentity::generate()?,
client_name: "scoped-credential-test".to_string(),
connect_timeout: TIMEOUT,
initialize_timeout: TIMEOUT,
resume_session_id: None,
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
};
let connect =
tokio::spawn(async move { ExecServerClient::connect_noise_rendezvous(args).await });
let harness_websocket = accept_parent_lifetime_websocket(&listener, TIMEOUT).await?;
let relay = tokio::spawn(proxy_parent_lifetime_relay(
environment_websocket,
harness_websocket,
));
let client = tokio::time::timeout(TIMEOUT, connect)
.await
.context("harness timed out")???;
let before_rotation = client.environment_info().await?;
send_json_line(&mut stdin, &serde_json::json!({
"version": 1, "environment_id": ENVIRONMENT, "token": ROTATED_CREDENTIAL,
"expires_at": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs() + 120,
})).await?;
assert_eq!(
&client.force_environment_info().await?,
before_rotation.as_ref()
);
let requests = registry
.received_requests()
.await
.context("registry requests")?;
assert_eq!(
requests
.iter()
.map(|request| request.url.path())
.collect::<Vec<_>>(),
[
format!("/cloud/environment/{ENVIRONMENT}/register"),
format!("/cloud/environment/{ENVIRONMENT}/register"),
format!("/cloud/environment/{ENVIRONMENT}/validate"),
]
);
for request in requests {
assert_eq!(
request.headers["authorization"],
format!("Bearer {CREDENTIAL}")
);
assert_eq!(request.headers.get_all("authorization").iter().count(), 1);
for name in [
"chatgpt-account-id",
"x-openai-biscuit",
"biscuit",
"x-openai-access-token",
] {
assert!(
!request.headers.contains_key(name),
"unexpected registry credential header {name}"
);
}
}
assert_eq!(registration_rx.try_recv()?, CREDENTIAL);
drop(client);
relay.abort();
let _ = relay.await;
// Reject reconnects to trigger re-registration while the parent update is processed.
tokio::time::timeout(TIMEOUT, async {
loop {
let (socket, _) = listener.accept().await?;
let rejected = http::Response::builder()
.status(http::StatusCode::UNAUTHORIZED)
.body(Some("expired registration".to_string()))?;
let result = accept_hdr_async(socket, |_: &Request, _: Response| Err(rejected)).await;
assert!(result.is_err());
let credential = registration_rx
.recv()
.await
.context("missing re-registration")?;
if credential == ROTATED_CREDENTIAL {
break Ok::<(), anyhow::Error>(());
}
assert_eq!(credential, CREDENTIAL);
}
})
.await
.context("executor did not re-register with the rotated parent credential")??;
drop(stdin);
let output = tokio::time::timeout(TIMEOUT, child.wait_with_output())
.await
.context("stdin EOF did not stop executor")??;
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::ensure!(output.status.success(), "scoped executor failed: {stderr}");
assert!(!stderr.contains(CREDENTIAL));
assert!(!stderr.contains(ROTATED_CREDENTIAL));
assert!(
collector
.received_requests()
.await
.context("telemetry requests")?
.is_empty()
);
Ok(())
}
#[tokio::test]
async fn remote_exec_server_scoped_credentials_never_fall_back_for_another_environment()
-> Result<()> {
let registry = MockServer::start().await;
let home = TempDir::new()?;
std::fs::write(
home.path().join("auth.json"),
r#"{"OPENAI_API_KEY":"general-file-token"}"#,
)?;
let mut command = tokio::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
let mut child = command
.env("AKODE_HOME", home.path())
.env("AKODE_API_KEY", "general-api-key")
.env("AKODE_ACCESS_TOKEN", "general-agent-identity")
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.args([
"exec-server",
"--remote",
&registry.uri(),
"--environment-id",
"configured-environment",
"--executor-credential-stdin",
])
.stdin(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()?;
let mut stdin = child
.stdin
.take()
.context("credential stdin was not piped")?;
send_json_line(&mut stdin, &serde_json::json!({
"version": 1, "environment_id": "another-environment", "token": "never-print-this-scoped-token",
"expires_at": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs() + 120,
})).await?;
let output = tokio::time::timeout(Duration::from_secs(30), child.wait_with_output())
.await
.context("invalid scoped frame did not stop executor")??;
assert!(!output.status.success());
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("different environment"));
assert!(!stderr.contains("never-print-this-scoped-token"));
assert!(
registry
.received_requests()
.await
.context("registry requests")?
.is_empty()
);
drop(stdin);
Ok(())
}
async fn accept_parent_lifetime_websocket(
listener: &TcpListener,
timeout: Duration,
) -> Result<WebSocketStream<tokio::net::TcpStream>> {
let (socket, _) = tokio::time::timeout(timeout, listener.accept())
.await
.context("remote executor or harness did not reach rendezvous")??;
tokio::time::timeout(timeout, accept_async(socket))
.await
.context("fake rendezvous did not complete websocket handshake")?
.map_err(Into::into)
}
async fn registered_parent_lifetime_executor_public_key(
registry: &MockServer,
) -> Result<NoiseChannelPublicKey> {
let requests = registry
.received_requests()
.await
.context("failed to read remote registry requests")?;
let request = requests
.iter()
.find(|request| request.url.path().ends_with("/register"))
.context("remote executor did not register before connecting")?;
let body: serde_json::Value = serde_json::from_slice(&request.body)?;
serde_json::from_value(body["executor_public_key"].clone()).map_err(Into::into)
}
async fn proxy_parent_lifetime_relay(
mut environment: WebSocketStream<tokio::net::TcpStream>,
mut harness: WebSocketStream<tokio::net::TcpStream>,
) -> Result<()> {
loop {
tokio::select! {
message = environment.next() => {
let Some(message) = message else {
break;
};
harness.send(message?).await?;
}
message = harness.next() => {
let Some(message) = message else {
break;
};
environment.send(message?).await?;
}
}
}
Ok(())
}
async fn send_json_line(
stdin: &mut (impl tokio::io::AsyncWrite + Unpin),
message: &serde_json::Value,
) -> Result<()> {
let mut encoded = serde_json::to_vec(message)?;
encoded.push(b'\n');
stdin.write_all(&encoded).await?;
stdin.flush().await?;
Ok(())
}
#[cfg(unix)]
#[test]
fn local_exec_server_exits_successfully_on_sigterm() -> Result<()> {
let codex_home = TempDir::new()?;
let mut child = std::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.env("AKODE_HOME", codex_home.path())
.args(["exec-server", "--listen", "ws://127.0.0.1:0"])
.stdout(Stdio::piped())
.spawn()?;
let mut listen_url = String::new();
StdBufReader::new(child.stdout.take().expect("child stdout")).read_line(&mut listen_url)?;
assert!(listen_url.starts_with("ws://127.0.0.1:"), "{listen_url}");
let listen_addr = listen_url
.trim()
.strip_prefix("ws://")
.expect("listen URL should use ws://")
.parse()?;
let deadline = Instant::now() + Duration::from_secs(5);
let mut ready = false;
while let Some(remaining) = deadline.checked_duration_since(Instant::now()) {
if let Ok(mut stream) =
TcpStream::connect_timeout(&listen_addr, remaining.min(Duration::from_millis(100)))
{
let _ = stream.set_read_timeout(Some(Duration::from_secs(1)));
let request =
format!("GET /readyz HTTP/1.1\r\nHost: {listen_addr}\r\nConnection: close\r\n\r\n");
let mut response = String::new();
if stream.write_all(request.as_bytes()).is_ok()
&& stream.read_to_string(&mut response).is_ok()
&& response.starts_with("HTTP/1.1 200")
{
ready = true;
break;
}
}
thread::sleep(Duration::from_millis(10));
}
assert!(ready, "exec-server did not become ready at {listen_url}");
// SAFETY: `child.id()` is the live process spawned above.
let result = unsafe { libc::kill(child.id() as libc::pid_t, libc::SIGTERM) };
assert_eq!(result, 0);
let status = child.wait()?;
assert!(status.success(), "{status}");
Ok(())
}
async fn wait_for_response(
stdout: &mut (impl tokio::io::AsyncBufRead + Unpin),
expected_id: i64,
) -> Result<serde_json::Value> {
loop {
let mut line = String::new();
if stdout.read_line(&mut line).await? == 0 {
anyhow::bail!("exec-server stdout closed before response {expected_id}");
}
let message: serde_json::Value = serde_json::from_str(&line)?;
if message["id"].as_i64() == Some(expected_id) {
anyhow::ensure!(
message.get("error").is_none(),
"exec-server request {expected_id} failed: {message}"
);
return Ok(message);
}
}
}
/// API-key registration authenticates directly and never fetches account-managed
/// cloud configuration before registering.
#[tokio::test]
async fn remote_exec_server_api_key_registers_without_cloud_config() -> Result<()> {
const REGISTER: &str = "/cloud/environment/test/register";
const REGISTRATION_REACHED: &str = "registration reached";
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path(REGISTER))
.and(header("authorization", "Bearer test-api-key"))
.respond_with(ResponseTemplate::new(400).set_body_string(REGISTRATION_REACHED))
.mount(&server)
.await;
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
"cli_auth_credentials_store = \"file\"\n",
)?;
let output = tokio::time::timeout(
Duration::from_secs(30),
tokio::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.kill_on_drop(true)
.current_dir(home.path())
.env("AKODE_HOME", home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("OPENAI_API_KEY")
.env("AKODE_API_KEY", "test-api-key")
.args([
"exec-server",
"--remote",
&server.uri(),
"--environment-id",
"test",
])
.output(),
)
.await??;
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!output.status.success() && stderr.contains(REGISTRATION_REACHED),
"{stderr}"
);
let requests = server
.received_requests()
.await
.context("mock request log")?;
let paths: Vec<_> = requests.iter().map(|request| request.url.path()).collect();
assert_eq!(paths, vec![REGISTER]);
Ok(())
}

View File

@@ -0,0 +1,155 @@
//! End-to-end checks that only executor startup can opt into PID inheritance.
use super::*;
use akode_exec_server::FileSystemSandboxContext;
use akode_protocol::models::PermissionProfile;
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_protocol::permissions::FileSystemSpecialPath;
use akode_protocol::permissions::NetworkSandboxPolicy;
use akode_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn pid_inheritance_is_startup_only_for_process_and_filesystem_helpers() -> Result<()> {
let Some(bwrap) = akode_sandboxing::find_system_bwrap_in_path(
&PermissionProfile::read_only().file_system_sandbox_policy(),
&std::env::current_dir()?,
) else {
eprintln!("skipping PID namespace test: no system bubblewrap");
return Ok(());
};
let available = tokio::process::Command::new(&bwrap)
.args(["--unshare-user", "--ro-bind", "/", "/", "--", "/bin/true"])
.output()
.await?;
if !available.status.success() {
eprintln!(
"skipping PID namespace test: {}",
String::from_utf8_lossy(&available.stderr)
);
return Ok(());
}
tokio::time::timeout(Duration::from_secs(30), async {
let fixture = TempDir::new()?;
let wrapper = fixture.path().join("bwrap");
std::os::unix::fs::symlink(bwrap, fixture.path().join("real-bwrap"))?;
akode_utils_cargo_bin::write_executable(&wrapper, r#"#!/bin/sh
for arg in "$@"; do
[ "$arg" = "--" ] && break
if [ "$arg" = "--proc" ]; then
echo "bwrap: Can't mount proc on /newroot/proc: Operation not permitted" >&2
exit 1
fi
done
exec "${0%/*}/real-bwrap" "$@"
"#)?;
let path = format!("{}:{}", fixture.path().display(), std::env::var("PATH")?);
// System bubblewrap discovery intentionally excludes executables under the command cwd.
let workspace = TempDir::new()?;
let file = workspace.path().join("readable");
std::fs::write(&file, "ok")?;
let file_uri = url::Url::from_file_path(&file).unwrap();
let cwd = url::Url::from_directory_path(workspace.path()).unwrap();
let minimal_policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special { value: FileSystemSpecialPath::Minimal },
FileSystemAccessMode::Read,
),
FileSystemSandboxEntry::new(
AbsolutePathBuf::try_from(workspace.path())?.into(), FileSystemAccessMode::Read,
),
FileSystemSandboxEntry::new(
AbsolutePathBuf::from_absolute_path("/proc/version")?.into(), FileSystemAccessMode::Deny,
),
]);
let minimal_profile = PermissionProfile::from_runtime_permissions(
&minimal_policy, NetworkSandboxPolicy::Restricted,
);
for (inherit, profile) in [
(false, PermissionProfile::read_only()),
(true, PermissionProfile::read_only()),
(true, minimal_profile),
] {
let minimal = profile.file_system_sandbox_policy().include_platform_defaults();
let sandbox = FileSystemSandboxContext::from_permission_profile(
profile, cwd.as_str().parse()?,
);
let codex_home = TempDir::new()?;
// Neither a config key nor executor/request environment variables may opt in.
std::fs::write(codex_home.path().join("config.toml"),
"linux_sandbox_pid_namespace = 'inherit'\n")?;
let mut command = tokio::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
command.args(["exec-server", "--listen", "stdio"])
.env("AKODE_HOME", codex_home.path())
.env("PATH", &path)
.env("AKODE_LINUX_SANDBOX_PID_NAMESPACE", "inherit")
.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped())
.kill_on_drop(true);
if inherit {
command.arg("--linux-sandbox-pid-namespace=inherit");
}
let mut child = command.spawn()?;
let mut stdin = child.stdin.take().context("executor stdin")?;
let mut stdout = BufReader::new(child.stdout.take().context("executor stdout")?);
send_json_line(&mut stdin, &serde_json::json!({
"id": 1, "method": "initialize",
"params": {"clientName": "pid-namespace-test", "resumeSessionId": null}
})).await?;
wait_for_response(&mut stdout, /*expected_id*/ 1).await?;
send_json_line(&mut stdin, &serde_json::json!({"method": "initialized", "params": {}})).await?;
send_json_line(&mut stdin, &serde_json::json!({
"id": 2, "method": "process/start", "params": {
"processId": "pid-test", "cwd": cwd, "sandbox": sandbox,
"argv": ["/bin/bash", "-lc", r#"
set -e
IFS=' ' read -r pid rest < /proc/self/stat
test "$$" = "$pid"
test "$(cat <(printf shell-ok))" = shell-ok
if [ "$MINIMAL" = true ]; then
! cat /proc/version
fi
"#],
"env": {"PATH": path, "MINIMAL": minimal.to_string(), "AKODE_LINUX_SANDBOX_PID_NAMESPACE": "inherit"},
"tty": false, "pipeStdin": false, "arg0": null
}
})).await?;
// Notifications may precede the process/start response, so consume both.
let mut started = false;
let mut exit_code = None;
while !started || exit_code.is_none() {
let mut line = String::new();
anyhow::ensure!(stdout.read_line(&mut line).await? > 0, "executor closed");
let message: serde_json::Value = serde_json::from_str(&line)?;
if message["id"] == 2 {
anyhow::ensure!(message.get("error").is_none(), "start failed: {message}");
started = true;
}
if message["method"] == "process/exited" {
exit_code = message["params"]["exitCode"].as_i64();
}
}
assert_eq!(exit_code, Some(if inherit { 0 } else { 1 }));
send_json_line(&mut stdin, &serde_json::json!({
"id": 3, "method": "fs/readFile", "params": {"path": file_uri, "sandbox": sandbox}
})).await?;
loop {
let mut line = String::new();
anyhow::ensure!(stdout.read_line(&mut line).await? > 0, "executor closed");
let message: serde_json::Value = serde_json::from_str(&line)?;
if message["id"] != 3 { continue; }
assert_eq!(message["result"], serde_json::json!({"dataBase64": "b2s="}));
break;
}
drop(stdin);
// Drain notifications while the executor shuts down.
let mut remaining = String::new();
stdout.read_to_string(&mut remaining).await?;
let output = child.wait_with_output().await?;
anyhow::ensure!(output.status.success(), "executor failed: {}", String::from_utf8_lossy(&output.stderr));
}
Ok(())
}).await?
}

View File

@@ -0,0 +1,366 @@
//! Exercises listener authentication through the standalone executor CLI and real WebSockets.
use anyhow::Context;
use anyhow::Result;
use futures::SinkExt;
use futures::StreamExt;
use pretty_assertions::assert_eq;
use serde_json::json;
use sha2::Digest;
use sha2::Sha256;
use std::process::Stdio;
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use tempfile::TempDir;
use tokio::io::AsyncBufReadExt;
use tokio::io::BufReader;
use tokio::process::Command;
use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::Error as WebSocketError;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
enum AuthMode {
TokenHash,
TokenFile,
SignedBearer,
}
#[tokio::test]
async fn exec_server_websocket_auth_gates_rpc_connections() -> Result<()> {
tokio::time::timeout(Duration::from_secs(/*secs*/ 60), async {
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
for mode in [
AuthMode::TokenHash,
AuthMode::TokenFile,
AuthMode::SignedBearer,
] {
let home = TempDir::new()?;
let secret = "0123456789abcdef0123456789abcdef";
let secret_file = home.path().join("secret");
std::fs::write(&secret_file, secret)?;
let mut command = Command::new(&codex);
command
.args(["exec-server", "--listen", "ws://127.0.0.1:0", "--ws-auth"])
.env("AKODE_HOME", home.path())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true);
let token = match mode {
AuthMode::TokenHash => {
command.args([
"capability-token",
"--ws-token-sha256",
&format!("{:x}", Sha256::digest(secret.as_bytes())),
]);
secret.to_string()
}
AuthMode::TokenFile => {
command
.args(["capability-token", "--ws-token-file"])
.arg(&secret_file);
secret.to_string()
}
AuthMode::SignedBearer => {
command
.args(["signed-bearer-token", "--ws-shared-secret-file"])
.arg(&secret_file)
.args([
"--ws-issuer",
"test-issuer",
"--ws-audience",
"test-executor",
]);
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
jsonwebtoken::encode(
&jsonwebtoken::Header::new(jsonwebtoken::Algorithm::HS256),
&json!({"exp": now + 300, "iss": "test-issuer", "aud": "test-executor"}),
&jsonwebtoken::EncodingKey::from_secret(secret.as_bytes()),
)?
}
};
let mut child = command.spawn()?;
let mut lines = BufReader::new(child.stdout.take().context("stdout")?).lines();
let url = loop {
let line = lines
.next_line()
.await?
.context("listener exited before startup")?;
if line.starts_with("ws://") {
break line;
}
};
// A missing or incorrect credential must fail before any RPC session opens.
let digest_as_bearer = format!("Bearer {:x}", Sha256::digest(secret.as_bytes()));
for authorization in [
None,
Some("Bearer incorrect"),
Some("Basic incorrect"),
Some(digest_as_bearer.as_str()),
] {
let mut request = url.as_str().into_client_request()?;
if let Some(authorization) = authorization {
request
.headers_mut()
.insert("authorization", authorization.parse()?);
}
let error = connect_async(request)
.await
.expect_err("reject unauthorized upgrade");
let WebSocketError::Http(response) = error else {
anyhow::bail!("expected HTTP rejection, got {error}");
};
assert_eq!(response.status(), http::StatusCode::UNAUTHORIZED);
}
// Authentication applies to every connection, including reconnects.
for _ in 0..2 {
let mut request = url.as_str().into_client_request()?;
request
.headers_mut()
.insert("authorization", format!("Bearer {token}").parse()?);
let (mut websocket, _) = connect_async(request).await?;
websocket
.send(Message::Text(
json!({
"id": 1,
"method": "initialize",
"params": {"clientName": "auth-test"}
})
.to_string()
.into(),
))
.await?;
let response = websocket.next().await.context("initialize response")??;
let response: serde_json::Value = serde_json::from_str(response.to_text()?)?;
assert_eq!(response["id"], json!(1));
assert!(response.get("error").is_none(), "{response}");
assert!(response["result"]["sessionId"].is_string(), "{response}");
websocket.close(/*msg*/ None).await?;
}
child.kill().await?;
}
Ok(())
})
.await?
}
#[test]
fn exec_server_websocket_auth_rejects_inapplicable_transports() -> Result<()> {
let home = TempDir::new()?;
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
for (transport, expected) in [
(vec!["--listen", "stdio"], "not stdio"),
(vec!["--listen", "stdio://"], "not stdio"),
(
vec![
"--remote",
"https://registry.example",
"--environment-id",
"test",
],
"cannot be used with --remote",
),
(
vec![
"forward",
"--connect",
"ws://127.0.0.1:1234",
"--remote",
"https://registry.example",
"--environment-id",
"test",
],
"cannot be used with --remote",
),
] {
assert_cmd::Command::new(&codex)
.env("AKODE_HOME", home.path())
.args([
"exec-server",
"--ws-auth",
"capability-token",
"--ws-token-sha256",
&"ab".repeat(32),
])
.args(transport)
.assert()
.failure()
.stderr(predicates::str::contains(expected));
}
Ok(())
}
#[test]
fn exec_server_websocket_auth_rejects_invalid_configuration() -> Result<()> {
let home = TempDir::new()?;
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
for (args, expected) in [
(vec!["--ws-token-sha256", "invalid"], "require `--ws-auth"),
(
vec![
"--ws-auth",
"capability-token",
"--ws-token-sha256",
"invalid",
],
"64-character hex",
),
(vec!["--ws-auth", "capability-token"], "is required"),
] {
assert_cmd::Command::new(&codex)
.env("AKODE_HOME", home.path())
.args(["exec-server"])
.args(args)
.assert()
.failure()
.stderr(predicates::str::contains(expected));
}
Ok(())
}
#[tokio::test]
async fn app_server_executor_auth_supports_tokens_and_legacy_configuration() -> Result<()> {
use app_test_support::TestAppServer;
use app_test_support::to_response;
use akode_app_server_protocol::EnvironmentInfoResponse;
use akode_app_server_protocol::RequestId;
#[derive(Debug, PartialEq)]
enum Source {
Rpc,
Toml,
}
tokio::time::timeout(Duration::from_secs(/*secs*/ 90), async {
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
for token in [None, Some("executor-capability-for-app-server")] {
let executor_home = TempDir::new()?;
let mut command = Command::new(&codex);
command.args(["exec-server", "--listen", "ws://127.0.0.1:0"]);
if let Some(token) = token {
command.args([
"--ws-auth",
"capability-token",
"--ws-token-sha256",
&format!("{:x}", Sha256::digest(token.as_bytes())),
]);
}
let mut executor = command
.env("AKODE_HOME", executor_home.path())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true)
.spawn()?;
let mut lines =
BufReader::new(executor.stdout.take().context("executor stdout")?).lines();
let url = loop {
let line = lines.next_line().await?.context("executor exited")?;
if line.starts_with("ws://") {
break line;
}
};
for source in [Source::Rpc, Source::Toml] {
let home = TempDir::new()?;
let builder = TestAppServer::builder()
.with_program(&codex)
.with_plugin_startup_tasks()
.with_args(&["-c", "features.plugins=false", "app-server"])
.with_codex_home(home.path())
.without_auto_env()
.with_env_overrides(&[
("AKODE_EXEC_SERVER_URL", None),
("AKODE_EXEC_SERVER_NOISE_REGISTRY_URL", None),
]);
match source {
Source::Toml => {
let mut config =
format!("[[environments]]\nid = \"remote\"\nurl = {url:?}\n");
if let Some(token) = token {
config.push_str(&format!("auth_bearer_token = {token:?}\n"));
}
std::fs::write(home.path().join("environments.toml"), config)?;
}
Source::Rpc => {}
}
let mut app = builder.build().await?;
app.initialize().await?;
if source == Source::Rpc {
for credential in ["private-token\r\nInjected: true", "private-token\n"] {
let id = app
.send_raw_request(
"environment/add",
Some(json!({
"environmentId": "invalid", "execServerUrl": url,
"authBearerToken": credential,
})),
)
.await?;
let error = app
.read_stream_until_error_message(RequestId::Integer(id))
.await?;
assert!(!format!("{error:?}").contains("private-token"));
}
// Omitted and null tokens preserve old-client requests. They succeed
// with an unauthenticated executor and fail when authentication is enabled.
let credentials = match token {
Some(token) => vec![
None,
Some(serde_json::Value::Null),
Some(json!("wrong-token")),
Some(json!(token)),
],
None => vec![None, Some(serde_json::Value::Null)],
};
for credential in credentials {
let mut params = json!({
"environmentId": "remote", "execServerUrl": url,
});
if let Some(credential) = &credential {
params["authBearerToken"] = credential.clone();
}
let id = app
.send_raw_request("environment/add", Some(params))
.await?;
app.read_stream_until_response_message(RequestId::Integer(id))
.await?;
let id = app
.send_raw_request(
"environment/info",
Some(json!({"environmentId": "remote"})),
)
.await?;
if token.is_some()
&& credential.as_ref().and_then(serde_json::Value::as_str) != token
{
app.read_stream_until_error_message(RequestId::Integer(id))
.await?;
} else {
app.read_stream_until_response_message(RequestId::Integer(id))
.await?;
}
}
}
let id = app
.send_raw_request("environment/info", Some(json!({"environmentId": "remote"})))
.await?;
let response = app
.read_stream_until_response_message(RequestId::Integer(id))
.await?;
let info: EnvironmentInfoResponse = to_response(response)?;
assert!(
!info.shell.name.is_empty(),
"{source:?} should reach the executor"
);
}
executor.kill().await?;
}
Ok::<_, anyhow::Error>(())
})
.await?
}

View File

@@ -0,0 +1,119 @@
use std::fs;
use assert_cmd::Command;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
#[test]
fn execpolicy_check_matches_expected_json() -> Result<(), Box<dyn std::error::Error>> {
let codex_home = TempDir::new()?;
let policy_path = codex_home.path().join("rules").join("policy.rules");
fs::create_dir_all(
policy_path
.parent()
.expect("policy path should have a parent"),
)?;
fs::write(
&policy_path,
r#"
prefix_rule(
pattern = ["git", "push"],
decision = "forbidden",
)
"#,
)?;
let output = Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.env("AKODE_HOME", codex_home.path())
.args([
"execpolicy",
"check",
"--rules",
policy_path
.to_str()
.expect("policy path should be valid UTF-8"),
"git",
"push",
"origin",
"main",
])
.output()?;
assert!(output.status.success());
let result: serde_json::Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(
result,
json!({
"decision": "forbidden",
"matchedRules": [
{
"prefixRuleMatch": {
"matchedPrefix": ["git", "push"],
"decision": "forbidden"
}
}
]
})
);
Ok(())
}
#[test]
fn execpolicy_check_includes_justification_when_present() -> Result<(), Box<dyn std::error::Error>>
{
let codex_home = TempDir::new()?;
let policy_path = codex_home.path().join("rules").join("policy.rules");
fs::create_dir_all(
policy_path
.parent()
.expect("policy path should have a parent"),
)?;
fs::write(
&policy_path,
r#"
prefix_rule(
pattern = ["git", "push"],
decision = "forbidden",
justification = "pushing is blocked in this repo",
)
"#,
)?;
let output = Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.env("AKODE_HOME", codex_home.path())
.args([
"execpolicy",
"check",
"--rules",
policy_path
.to_str()
.expect("policy path should be valid UTF-8"),
"git",
"push",
"origin",
"main",
])
.output()?;
assert!(output.status.success());
let result: serde_json::Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(
result,
json!({
"decision": "forbidden",
"matchedRules": [
{
"prefixRuleMatch": {
"matchedPrefix": ["git", "push"],
"decision": "forbidden",
"justification": "pushing is blocked in this repo"
}
}
]
})
);
Ok(())
}

View File

@@ -0,0 +1,326 @@
use std::path::Path;
use anyhow::Result;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
#[test]
fn strict_config_rejects_unknown_config_override() -> Result<()> {
for (config_override, ignored_path) in [
("foo=bar", "foo"),
("tui.bogus_key_xyz=1", "tui.bogus_key_xyz"),
] {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["--strict-config", "-c", config_override, "exec", "hello"])
.assert()
.failure()
.stderr(contains(format!(
"unknown configuration field `{ignored_path}`"
)));
}
Ok(())
}
#[test]
fn mcp_list_reports_invalid_keybinding_reason() -> Result<()> {
for bindings in ["'backslash'", "['backslash']"] {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
format!("[tui.keymap.editor]\ninsert_newline = {bindings}\n"),
)?;
let output = codex_command(codex_home.path())?
.current_dir(codex_home.path())
.args(["mcp", "list"])
.assert()
.failure()
.get_output()
.stderr
.clone();
let output = normalize_config_location(&String::from_utf8(output)?);
insta::allow_duplicates! {
insta::assert_snapshot!(output);
}
}
Ok(())
}
#[test]
fn interactive_validates_config_before_requiring_terminal() -> Result<()> {
let cases: &[(&[&str], &str, &str, &str)] = &[
(&[], "config.toml", "model = [", "Error loading config.toml"),
(
&["--strict-config"],
"config.toml",
"unknown_key = true",
"unknown configuration field",
),
(
&["--strict-config"],
"config.toml",
"[tui]\nbogus_key_xyz = 1",
"unknown configuration field `tui.bogus_key_xyz`",
),
(
&["--strict-config", "-c", "foo=bar"],
"config.toml",
"",
"unknown configuration field",
),
(
&["--profile", "work"],
"work.config.toml",
"model = [",
"work.config.toml",
),
(
&["-c", "model_provider=\"missing\""],
"config.toml",
"",
"Model provider `missing` not found",
),
(&[], "config.toml", "", "stdin is not a terminal"),
];
for &(args, config_file, contents, expected_error) in cases {
let codex_home = TempDir::new()?;
std::fs::write(codex_home.path().join(config_file), contents)?;
let mut cmd = codex_command(codex_home.path())?;
cmd.env("TERM", "xterm-256color")
.current_dir(codex_home.path())
.args(args)
.assert()
.failure()
.stderr(contains(expected_error));
}
Ok(())
}
#[test]
fn interactive_remote_default_preserves_remote_working_directory_before_requiring_terminal()
-> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(codex_home.path().join("config.toml"), "")?;
std::fs::write(
codex_home.path().join("environments.toml"),
r#"default = "remote"
include_local = false
[[environments]]
id = "remote"
url = "ws://127.0.0.1:4512"
"#,
)?;
let remote_only_cwd = codex_home.path().join("remote-only-working-directory");
let mut cmd = codex_command(codex_home.path())?;
cmd.env("TERM", "xterm-256color")
.current_dir(codex_home.path())
.arg("--cd")
.arg(remote_only_cwd)
.assert()
.failure()
.stderr(contains("stdin is not a terminal"));
Ok(())
}
#[tokio::test]
async fn features_enable_writes_feature_flag_to_config() -> Result<()> {
let codex_home = TempDir::new()?;
for feature in ["unified_exec", "shell_tool"] {
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["features", "enable", feature])
.assert()
.success()
.stdout(contains(format!(
"Enabled feature `{feature}` in config.toml."
)));
let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?;
assert!(config.contains("[features]"));
assert!(config.contains(&format!("{feature} = true")));
}
Ok(())
}
#[tokio::test]
async fn features_disable_writes_feature_flag_to_config() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["features", "disable", "shell_tool"])
.assert()
.success()
.stdout(contains("Disabled feature `shell_tool` in config.toml."));
let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?;
assert!(config.contains("[features]"));
assert!(config.contains("shell_tool = false"));
Ok(())
}
#[tokio::test]
async fn features_enable_under_development_feature_prints_warning() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["features", "enable", "runtime_metrics"])
.assert()
.success()
.stderr(contains(
"Under-development features enabled: runtime_metrics.",
));
Ok(())
}
#[tokio::test]
async fn features_list_is_sorted_alphabetically_by_feature_name() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
let output = cmd
.args(["features", "list"])
.assert()
.success()
.get_output()
.stdout
.clone();
let stdout = String::from_utf8(output)?;
let actual_names = stdout
.lines()
.map(|line| {
line.split_once(" ")
.map(|(name, _)| name.trim_end().to_string())
.expect("feature list output should contain aligned columns")
})
.collect::<Vec<_>>();
let mut expected_names = actual_names.clone();
expected_names.sort();
assert_eq!(actual_names, expected_names);
Ok(())
}
#[test]
fn remote_start_rejects_add_dir_before_connecting() -> Result<()> {
let home = TempDir::new()?;
let output = codex_command(home.path())?
.env("TERM", "xterm-256color")
.args(["--remote", "ws://127.0.0.1:1", "--add-dir", "remote-extra"])
.assert()
.failure()
.get_output()
.stderr
.clone();
insta::assert_snapshot!(String::from_utf8(output)?);
Ok(())
}
#[test]
fn remote_start_rejects_writable_root_overrides_before_connecting() -> Result<()> {
for config_override in [
"sandbox_workspace_write.writable_roots=[\"./extra\"]",
"sandbox_workspace_write={writable_roots=[\"./extra\"],network_access=true}",
] {
let home = TempDir::new()?;
let output = codex_command(home.path())?
.env("TERM", "xterm-256color")
.args(["--remote", "ws://127.0.0.1:1", "-c", config_override])
.assert()
.failure()
.get_output()
.stderr
.clone();
let output = String::from_utf8(output)?;
insta::allow_duplicates! {
insta::assert_snapshot!(output, @"Error: sandbox_workspace_write.writable_roots overrides are not supported with --remote. Configure additional workspace roots on the server.");
}
}
Ok(())
}
#[test]
fn remote_start_allows_network_access_overrides_before_requiring_terminal() -> Result<()> {
for config_override in [
"sandbox_workspace_write.network_access=true",
"sandbox_workspace_write={network_access=true}",
] {
let home = TempDir::new()?;
codex_command(home.path())?
.env("TERM", "xterm-256color")
.args(["--remote", "ws://127.0.0.1:1", "-c", config_override])
.assert()
.failure()
.stderr(contains("stdin is not a terminal"));
}
Ok(())
}
#[test]
fn no_daemon_rejects_queue_and_explicit_remote_targets() -> Result<()> {
for args in [
"--no-daemon queue --thread example --message hello",
"--no-daemon --remote ws://localhost:9999 agents",
"--no-daemon --remote ws://localhost:9999",
"--no-daemon --remote ws://localhost:9999 archive example",
"--no-daemon --remote ws://localhost:9999 unarchive example",
"--no-daemon --remote ws://localhost:9999 delete --force 123e4567-e89b-12d3-a456-426614174000",
"--no-daemon --remote ws://localhost:9999 queue --thread example --message hello",
"--remote ws://localhost:9999 resume --no-daemon --last",
"--no-daemon fork --remote ws://localhost:9999 session-name",
] {
let args = args.split_whitespace().collect::<Vec<_>>();
let home = TempDir::new()?;
let expected = if args.contains(&"queue") && !args.contains(&"--remote") {
"--no-daemon cannot be used with codex queue."
} else {
"--no-daemon cannot be used with --remote."
};
codex_command(home.path())?
.args(args)
.assert()
.failure()
.stderr(contains(expected));
assert!(!home.path().join("app-server-daemon").exists());
}
Ok(())
}
/// Replaces `<temp home>/config.toml:<line>:<column>` with a stable placeholder.
fn normalize_config_location(output: &str) -> String {
output
.lines()
.map(|line| match line.find("/config.toml:") {
Some(index) => {
let start = line[..index].rfind(' ').map_or(0, |space| space + 1);
let rest = &line[index + "/config.toml:".len()..];
let after_location = rest.splitn(3, ':').nth(2).unwrap_or_default();
format!(
"{}[AKODE_HOME]/config.toml:<line>:<column>:{after_location}",
&line[..start]
)
}
None => line.to_string(),
})
.collect::<Vec<_>>()
.join("\n")
}

233
akode-rs/cli/tests/login.rs Normal file
View File

@@ -0,0 +1,233 @@
use std::path::Path;
use anyhow::Result;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
fn write_file_auth_config(codex_home: &Path) -> Result<()> {
std::fs::write(
codex_home.join("config.toml"),
"cli_auth_credentials_store = \"file\"\n",
)?;
Ok(())
}
fn read_auth_json(codex_home: &Path) -> Result<Value> {
let auth_json = std::fs::read_to_string(codex_home.join("auth.json"))?;
Ok(serde_json::from_str(&auth_json)?)
}
#[test]
fn login_with_api_key_reads_stdin_and_writes_auth_json() -> Result<()> {
let codex_home = TempDir::new()?;
write_file_auth_config(codex_home.path())?;
let mut cmd = codex_command(codex_home.path())?;
let login = cmd
.args([
"-c",
"forced_login_method=\"api\"",
"login",
"--with-api-key",
])
.write_stdin("sk-test\n")
.assert()
.success();
insta::assert_snapshot!(String::from_utf8_lossy(&login.get_output().stderr), @r"
Reading API key from stdin...
API key saved. Authentication is checked when you send a request.
");
let auth = read_auth_json(codex_home.path())?;
assert_eq!(auth["OPENAI_API_KEY"], "sk-test");
assert!(auth.get("tokens").is_none());
assert!(auth.get("agent_identity").is_none());
let status = codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.success();
insta::assert_snapshot!(String::from_utf8_lossy(&status.get_output().stderr), @r"
API key configured - ***
Authentication is checked when you send a request.
");
codex_command(codex_home.path())?
.args(["-c", "forced_login_method=\"api\"", "login"])
.assert()
.failure()
.stderr(contains("Only API key login is supported"));
assert_eq!(read_auth_json(codex_home.path())?, auth);
for removed_flag in ["--device-auth", "--with-access-token"] {
codex_command(codex_home.path())?
.args(["login", removed_flag])
.write_stdin("token\n")
.assert()
.failure()
.stderr(contains("unexpected argument"));
assert_eq!(read_auth_json(codex_home.path())?, auth);
}
Ok(())
}
#[test]
fn api_key_auth_commands_work_when_log_dir_is_unavailable() -> Result<()> {
let codex_home = TempDir::new()?;
let log_dir = codex_home.path().join("unavailable-logs");
std::fs::write(&log_dir, "not a directory")?;
std::fs::write(
codex_home.path().join("config.toml"),
format!("cli_auth_credentials_store = \"file\"\nlog_dir = {log_dir:?}\n"),
)?;
codex_command(codex_home.path())?
.args(["login", "--with-api-key"])
.write_stdin("sk-test\n")
.assert()
.success()
.stderr(contains("Warning: failed to create login log directory"));
assert_eq!(
read_auth_json(codex_home.path())?["OPENAI_API_KEY"],
"sk-test"
);
codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.success()
.stderr(contains("API key"));
codex_command(codex_home.path())?
.arg("logout")
.assert()
.success()
.stderr(contains("Successfully logged out"));
assert!(!codex_home.path().join("auth.json").exists());
Ok(())
}
#[test]
fn login_status_reports_auth_storage_errors() -> Result<()> {
let codex_home = TempDir::new()?;
write_file_auth_config(codex_home.path())?;
std::fs::write(codex_home.path().join("auth.json"), "{invalid json")?;
codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.failure()
.stderr(contains("Error checking login status:"));
Ok(())
}
#[test]
fn legacy_chatgpt_auth_is_reported_as_not_logged_in_and_logout_removes_it() -> Result<()> {
let codex_home = TempDir::new()?;
write_file_auth_config(codex_home.path())?;
std::fs::write(
codex_home.path().join("auth.json"),
serde_json::to_vec(&json!({
"auth_mode": "chatgpt",
"OPENAI_API_KEY": null,
"tokens": {
"id_token": "eyJhbGciOiJub25lIn0.e30.c2ln",
"access_token": "old-access",
"refresh_token": "old-refresh",
},
}))?,
)?;
codex_command(codex_home.path())?
.env_remove("AKODE_API_KEY")
.args(["login", "status"])
.assert()
.failure()
.stderr(contains("Not logged in"));
codex_command(codex_home.path())?
.arg("logout")
.assert()
.success()
.stderr(contains("Successfully logged out"));
assert!(!codex_home.path().join("auth.json").exists());
Ok(())
}
#[test]
fn provider_api_key_login_uses_private_file_store_and_never_prints_the_key() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
"provider_api_key_store = \"file\"\n\
model_provider = \"imeai\"\n\
[model_providers.imeai]\n\
name = \"imeAI\"\n\
base_url = \"http://127.0.0.1:9/v1\"\n\
api_key = \"keyring\"\n",
)?;
let secret = "sk-provider-secret-0123456789";
let login = codex_command(codex_home.path())?
.args(["login", "--provider", "imeai", "--with-api-key"])
.write_stdin(format!("{secret}\n"))
.assert()
.success();
let stderr = String::from_utf8_lossy(&login.get_output().stderr).to_string();
assert!(
stderr.contains("API key for `imeai` saved in file"),
"{stderr}"
);
assert!(!stderr.contains(secret), "{stderr}");
let path = codex_home.path().join("provider_api_keys.json");
let stored: Value = serde_json::from_str(&std::fs::read_to_string(&path)?)?;
assert_eq!(stored, json!({ "imeai": secret }));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
std::fs::metadata(&path)?.permissions().mode() & 0o777,
0o600
);
}
// The shared stored key is untouched.
assert!(!codex_home.path().join("auth.json").exists());
let status = codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.success();
let stderr = String::from_utf8_lossy(&status.get_output().stderr).to_string();
assert!(
stderr.contains("Provider `imeai`: API key stored in file"),
"{stderr}"
);
assert!(!stderr.contains(secret), "{stderr}");
codex_command(codex_home.path())?
.args(["logout", "--provider", "imeai"])
.assert()
.success()
.stderr(contains("Removed the stored API key for `imeai`"));
assert!(!path.exists());
codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.failure()
.stderr(contains(
"Provider `imeai`: no API key stored (akode login --provider imeai --with-api-key)",
));
Ok(())
}

View File

@@ -0,0 +1,253 @@
use anyhow::Result;
use akode_config::CONFIG_TOML_FILE;
use akode_core_plugins::installed_marketplaces::marketplace_install_root;
use akode_utils_absolute_path::AbsolutePathBuf;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::path::Path;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
fn write_marketplace_source(source: &Path, marker: &str) -> Result<()> {
std::fs::create_dir_all(source.join(".agents/plugins"))?;
std::fs::create_dir_all(source.join("plugins/sample/.codex-plugin"))?;
std::fs::write(
source.join(".agents/plugins/marketplace.json"),
r#"{
"name": "debug",
"plugins": [
{
"name": "sample",
"source": {
"source": "local",
"path": "./plugins/sample"
}
}
]
}"#,
)?;
std::fs::write(
source.join("plugins/sample/.codex-plugin/plugin.json"),
r#"{"name":"sample"}"#,
)?;
std::fs::write(source.join("plugins/sample/marker.txt"), marker)?;
Ok(())
}
#[tokio::test]
async fn marketplace_add_git_source_cleans_staging_after_failures() -> Result<()> {
let codex_home = TempDir::new()?;
let source = TempDir::new()?;
write_marketplace_source(source.path(), "git source")?;
for args in [
vec!["init", "--quiet"],
vec!["add", "."],
vec![
"-c",
"user.name=Codex Tests",
"-c",
"user.email=codex@example.com",
"-c",
"commit.gpgsign=false",
"commit",
"-m",
"marketplace",
],
] {
let output = std::process::Command::new("git")
.current_dir(source.path())
.args(args)
.output()?;
anyhow::ensure!(
output.status.success(),
"git fixture failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
// Exercise real Git clones without using the network or changing the process environment.
let source_url = "https://example.com/marketplace.git";
let rewrite_key = format!("url.{}.insteadOf", source.path().display());
let install_root = marketplace_install_root(codex_home.path());
let staging_root = install_root.join(".staging");
let abandoned = staging_root.join(format!("marketplace-{}-abandoned", std::env::consts::OS));
std::fs::create_dir_all(abandoned.join("checkout"))?;
std::fs::write(abandoned.join(".lock"), "")?;
std::fs::write(abandoned.join("checkout/payload"), "abandoned clone")?;
for (args, error) in [
(["--ref", "missing-ref"], "git checkout missing-ref failed"),
(
["--sparse", "plugins/sample"],
"marketplace root does not contain a supported manifest",
),
] {
for _ in 0..2 {
codex_command(codex_home.path())?
.current_dir(codex_home.path())
.env("GIT_CONFIG_COUNT", "1")
.env("GIT_CONFIG_KEY_0", &rewrite_key)
.env("GIT_CONFIG_VALUE_0", source_url)
.args(["plugin", "marketplace", "add", source_url])
.args(args)
.assert()
.failure()
.stderr(contains(error));
assert_eq!(std::fs::read_dir(&staging_root)?.count(), 0);
assert!(!install_root.join("debug").exists());
assert!(!codex_home.path().join(CONFIG_TOML_FILE).exists());
}
}
codex_command(codex_home.path())?
.current_dir(codex_home.path())
.env("GIT_CONFIG_COUNT", "1")
.env("GIT_CONFIG_KEY_0", &rewrite_key)
.env("GIT_CONFIG_VALUE_0", source_url)
.args(["plugin", "marketplace", "add", source_url])
.assert()
.success();
let config = std::fs::read_to_string(codex_home.path().join(CONFIG_TOML_FILE))?;
// A different ref bypasses the already-added shortcut and conflicts after cloning.
codex_command(codex_home.path())?
.current_dir(codex_home.path())
.env("GIT_CONFIG_COUNT", "1")
.env("GIT_CONFIG_KEY_0", &rewrite_key)
.env("GIT_CONFIG_VALUE_0", source_url)
.args(["plugin", "marketplace", "add", source_url, "--ref", "HEAD"])
.assert()
.failure()
.stderr(contains("already added from a different source"));
assert_eq!(std::fs::read_dir(&staging_root)?.count(), 0);
assert_eq!(
std::fs::read_to_string(install_root.join("debug/plugins/sample/marker.txt"))?,
"git source"
);
assert_eq!(
std::fs::read_to_string(codex_home.path().join(CONFIG_TOML_FILE))?,
config
);
Ok(())
}
#[tokio::test]
async fn marketplace_add_local_directory_source() -> Result<()> {
let codex_home = TempDir::new()?;
let source = TempDir::new()?;
write_marketplace_source(source.path(), "local ref")?;
let source_parent = source.path().parent().unwrap();
let source_arg = format!("./{}", source.path().file_name().unwrap().to_string_lossy());
codex_command(codex_home.path())?
.current_dir(source_parent)
.args(["plugin", "marketplace", "add", source_arg.as_str()])
.assert()
.success();
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
assert!(!installed_root.exists());
let config = std::fs::read_to_string(codex_home.path().join(CONFIG_TOML_FILE))?;
let config: toml::Value = toml::from_str(&config)?;
let expected_source = source.path().canonicalize()?.display().to_string();
assert_eq!(
config["marketplaces"]["debug"]["source_type"].as_str(),
Some("local")
);
assert_eq!(
config["marketplaces"]["debug"]["source"].as_str(),
Some(expected_source.as_str())
);
Ok(())
}
#[tokio::test]
async fn marketplace_add_json_prints_add_outcome() -> Result<()> {
let codex_home = TempDir::new()?;
let source = TempDir::new()?;
write_marketplace_source(source.path(), "local ref")?;
let source_parent = source.path().parent().unwrap();
let source_arg = format!("./{}", source.path().file_name().unwrap().to_string_lossy());
let assert = codex_command(codex_home.path())?
.current_dir(source_parent)
.args([
"plugin",
"marketplace",
"add",
source_arg.as_str(),
"--json",
])
.assert()
.success();
let stdout = assert.get_output().stdout.as_slice();
let actual: serde_json::Value = serde_json::from_slice(stdout)?;
let expected_installed_root = AbsolutePathBuf::try_from(source.path().canonicalize()?)?;
assert_eq!(
actual,
json!({
"marketplaceName": "debug",
"installedRoot": expected_installed_root.as_path().display().to_string(),
"alreadyAdded": false,
})
);
Ok(())
}
#[tokio::test]
async fn marketplace_add_rejects_local_manifest_file_source() -> Result<()> {
let codex_home = TempDir::new()?;
let source = TempDir::new()?;
write_marketplace_source(source.path(), "local ref")?;
let manifest_path = source.path().join(".agents/plugins/marketplace.json");
codex_command(codex_home.path())?
.args([
"plugin",
"marketplace",
"add",
manifest_path.to_str().unwrap(),
])
.assert()
.failure()
.stderr(contains(
"local marketplace source must be a directory, not a file",
));
Ok(())
}
#[tokio::test]
async fn marketplace_add_rejects_sparse_for_local_directory_source() -> Result<()> {
let codex_home = TempDir::new()?;
let source = TempDir::new()?;
write_marketplace_source(source.path(), "local ref")?;
codex_command(codex_home.path())?
.args([
"plugin",
"marketplace",
"add",
"--sparse",
".agents",
source.path().to_str().unwrap(),
])
.assert()
.failure()
.stderr(contains(
"--sparse is only supported for git marketplace sources",
));
Ok(())
}

View File

@@ -0,0 +1,127 @@
use anyhow::Result;
use akode_config::MarketplaceConfigUpdate;
use akode_config::record_user_marketplace;
use akode_core_plugins::installed_marketplaces::marketplace_install_root;
use akode_utils_absolute_path::canonicalize_existing_preserving_symlinks;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::path::Path;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
fn configured_marketplace_update() -> MarketplaceConfigUpdate<'static> {
MarketplaceConfigUpdate {
source_type: "git",
source: "https://github.com/owner/repo.git",
ref_name: Some("main"),
sparse_paths: &[],
}
}
fn write_installed_marketplace(codex_home: &Path, marketplace_name: &str) -> Result<()> {
let root = marketplace_install_root(codex_home).join(marketplace_name);
std::fs::create_dir_all(root.join(".agents/plugins"))?;
std::fs::write(root.join(".agents/plugins/marketplace.json"), "{}")?;
std::fs::write(root.join("marker.txt"), "installed")?;
Ok(())
}
#[tokio::test]
async fn marketplace_remove_deletes_config_and_installed_root() -> Result<()> {
let codex_home = TempDir::new()?;
record_user_marketplace(codex_home.path(), "debug", &configured_marketplace_update())?;
write_installed_marketplace(codex_home.path(), "debug")?;
codex_command(codex_home.path())?
.args(["plugin", "marketplace", "remove", "debug"])
.assert()
.success()
.stdout(contains("Removed marketplace `debug`."));
let config_path = codex_home.path().join("config.toml");
let config = std::fs::read_to_string(config_path)?;
assert!(!config.contains("[marketplaces.debug]"));
assert!(
!marketplace_install_root(codex_home.path())
.join("debug")
.exists()
);
Ok(())
}
#[tokio::test]
async fn marketplace_remove_json_prints_remove_outcome() -> Result<()> {
let codex_home = TempDir::new()?;
record_user_marketplace(codex_home.path(), "debug", &configured_marketplace_update())?;
write_installed_marketplace(codex_home.path(), "debug")?;
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
let normalized_installed_root = canonicalize_existing_preserving_symlinks(&installed_root)?;
let assert = codex_command(codex_home.path())?
.args(["plugin", "marketplace", "remove", "debug", "--json"])
.assert()
.success();
let stdout = assert.get_output().stdout.as_slice();
let actual: serde_json::Value = serde_json::from_slice(stdout)?;
assert_eq!(
actual,
json!({
"marketplaceName": "debug",
"installedRoot": normalized_installed_root.display().to_string(),
})
);
Ok(())
}
#[tokio::test]
async fn marketplace_remove_rejects_unknown_marketplace() -> Result<()> {
let codex_home = TempDir::new()?;
codex_command(codex_home.path())?
.args(["plugin", "marketplace", "remove", "debug"])
.assert()
.failure()
.stderr(contains(
"marketplace `debug` is not configured or installed",
));
Ok(())
}
#[tokio::test]
async fn marketplace_remove_preserves_marketplace_referenced_by_session_config() -> Result<()> {
let codex_home = TempDir::new()?;
record_user_marketplace(codex_home.path(), "debug", &configured_marketplace_update())?;
write_installed_marketplace(codex_home.path(), "debug")?;
let config_path = codex_home.path().join("config.toml");
let config = std::fs::read_to_string(&config_path)?;
codex_command(codex_home.path())?
.args([
"plugin", "marketplace",
"-c", "marketplaces.debug.source_type=\"git\"",
"remove", "debug",
])
.assert()
.failure()
.stderr(contains(
"marketplace `debug` is configured in session-flags; remove it from that configuration source instead",
));
assert_eq!(std::fs::read_to_string(config_path)?, config);
assert_eq!(
std::fs::read_to_string(
marketplace_install_root(codex_home.path()).join("debug/marker.txt")
)?,
"installed",
);
Ok(())
}

View File

@@ -0,0 +1,118 @@
use anyhow::Result;
use akode_core_plugins::installed_marketplaces::marketplace_install_root;
use akode_utils_absolute_path::AbsolutePathBuf;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::path::Path;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
#[tokio::test]
async fn marketplace_upgrade_runs_under_plugin() -> Result<()> {
let codex_home = TempDir::new()?;
let abandoned = marketplace_install_root(codex_home.path())
.join(".staging")
.join(format!("marketplace-{}-abandoned", std::env::consts::OS));
std::fs::create_dir_all(abandoned.join("checkout"))?;
std::fs::write(abandoned.join(".lock"), "")?;
std::fs::write(abandoned.join("checkout/payload"), "abandoned clone")?;
codex_command(codex_home.path())?
.args(["plugin", "marketplace", "upgrade"])
.assert()
.success()
.stdout(contains("No configured Git marketplaces to upgrade."));
assert!(!abandoned.exists());
Ok(())
}
#[tokio::test]
async fn marketplace_upgrade_json_prints_upgrade_outcome() -> Result<()> {
let codex_home = TempDir::new()?;
let source = TempDir::new()?;
let manifest = r#"{"name":"debug","plugins":[]}"#;
std::fs::create_dir_all(source.path().join(".agents/plugins"))?;
std::fs::write(
source.path().join(".agents/plugins/marketplace.json"),
manifest,
)?;
for args in [
vec!["init", "--quiet"],
vec!["add", "."],
vec![
"-c",
"user.name=Codex Tests",
"-c",
"user.email=codex@example.com",
"commit",
"-m",
"marketplace",
],
] {
let output = std::process::Command::new("git")
.current_dir(source.path())
.args(args)
.output()?;
anyhow::ensure!(
output.status.success(),
"git fixture failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
let source_arg = serde_json::to_string(&source.path().to_string_lossy())?;
let marketplace_override =
format!("marketplaces.debug={{source_type=\"git\",source={source_arg}}}");
let assert = codex_command(codex_home.path())?
.current_dir(codex_home.path())
.args(["--config", &marketplace_override])
.args(["plugin", "marketplace", "upgrade", "--json"])
.assert()
.success();
let stdout = assert.get_output().stdout.as_slice();
let actual: serde_json::Value = serde_json::from_slice(stdout)?;
let installed_root = AbsolutePathBuf::try_from(
marketplace_install_root(&codex_home.path().canonicalize()?).join("debug"),
)?;
assert_eq!(
actual,
json!({
"selectedMarketplaces": ["debug"],
"upgradedRoots": [installed_root],
"errors": [],
})
);
assert_eq!(
std::fs::read_to_string(installed_root.join(".agents/plugins/marketplace.json"))?,
manifest
);
assert!(!codex_home.path().join("config.toml").exists());
assert_eq!(
std::fs::read_dir(marketplace_install_root(codex_home.path()).join(".staging"))?.count(),
0
);
Ok(())
}
#[tokio::test]
async fn marketplace_upgrade_no_longer_runs_at_top_level() -> Result<()> {
let codex_home = TempDir::new()?;
codex_command(codex_home.path())?
.args(["marketplace", "upgrade"])
.assert()
.failure()
.stderr(contains("unrecognized subcommand 'upgrade'"));
Ok(())
}

View File

@@ -0,0 +1,582 @@
use std::collections::BTreeMap;
use std::path::Path;
use anyhow::Result;
use akode_config::types::McpServerTransportConfig;
use akode_core::config::edit::ConfigEditsBuilder;
use akode_core::config::load_global_mcp_servers;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
#[tokio::test]
async fn add_and_remove_server_updates_global_config() -> Result<()> {
let codex_home = TempDir::new()?;
let mut add_cmd = codex_command(codex_home.path())?;
add_cmd
.args(["mcp", "add", "docs", "--", "echo", "hello"])
.assert()
.success()
.stdout(contains("Added global MCP server 'docs'."));
let servers = load_global_mcp_servers(codex_home.path()).await?;
assert_eq!(servers.len(), 1);
let docs = servers.get("docs").expect("server should exist");
match &docs.transport {
McpServerTransportConfig::Stdio {
command,
args,
env,
env_vars,
cwd,
} => {
assert_eq!(command, "echo");
assert_eq!(args, &vec!["hello".to_string()]);
assert!(env.is_none());
assert!(env_vars.is_empty());
assert!(cwd.is_none());
}
other => panic!("unexpected transport: {other:?}"),
}
assert!(docs.enabled);
let mut remove_cmd = codex_command(codex_home.path())?;
remove_cmd
.args(["mcp", "remove", "docs"])
.assert()
.success()
.stdout(contains("Removed global MCP server 'docs'."));
let servers = load_global_mcp_servers(codex_home.path()).await?;
assert!(servers.is_empty());
let mut remove_again_cmd = codex_command(codex_home.path())?;
remove_again_cmd
.args(["mcp", "remove", "docs"])
.assert()
.success()
.stdout(contains("No MCP server named 'docs' found."));
let servers = load_global_mcp_servers(codex_home.path()).await?;
assert!(servers.is_empty());
Ok(())
}
#[tokio::test]
async fn npm_server_names_round_trip_through_cli() -> Result<()> {
let codex_home = TempDir::new()?;
let name = "npm:@modelcontextprotocol/server-sequential.thinking";
codex_command(codex_home.path())?
.args(["mcp", "add", name, "--", "echo", "hello"])
.assert()
.success();
let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?;
assert!(config.contains(&format!("[mcp_servers.\"{name}\"]")));
let servers = load_global_mcp_servers(codex_home.path()).await?;
assert_eq!(
servers.keys().map(String::as_str).collect::<Vec<_>>(),
vec![name]
);
let output = codex_command(codex_home.path())?
.args(["mcp", "get", name, "--json"])
.assert()
.success()
.get_output()
.stdout
.clone();
let server: serde_json::Value = serde_json::from_slice(&output)?;
assert_eq!(server["name"], name);
let output = codex_command(codex_home.path())?
.args(["mcp", "list", "--json"])
.assert()
.success()
.get_output()
.stdout
.clone();
let listed: Vec<serde_json::Value> = serde_json::from_slice(&output)?;
assert_eq!(listed.len(), 1);
assert_eq!(listed[0]["name"], name);
codex_command(codex_home.path())?
.args(["mcp", "remove", name])
.assert()
.success();
assert!(load_global_mcp_servers(codex_home.path()).await?.is_empty());
Ok(())
}
#[tokio::test]
async fn add_and_login_discover_oauth_through_configured_http_proxy() -> Result<()> {
let codex_home = TempDir::new()?;
let proxy = MockServer::start().await;
let resource_url = "http://cli-mcp.invalid";
let challenge = "Bearer resource_metadata=\"http://cli-mcp.invalid/oauth-resource\"";
Mock::given(method("GET"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(401).insert_header("WWW-Authenticate", challenge))
.mount(&proxy)
.await;
Mock::given(method("GET"))
.and(path("/oauth-resource"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"resource": format!("{resource_url}/mcp"),
"authorization_servers": [resource_url],
})))
.mount(&proxy)
.await;
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"authorization_endpoint": format!("{resource_url}/oauth/authorize"),
"token_endpoint": format!("{resource_url}/oauth/token"),
"registration_endpoint": format!("{resource_url}/oauth/register"),
"response_types_supported": ["code"],
"code_challenge_methods_supported": ["S256"],
})))
.mount(&proxy)
.await;
Mock::given(method("POST"))
.and(path("/oauth/register"))
.respond_with(ResponseTemplate::new(400))
.mount(&proxy)
.await;
let mut add = codex_command(codex_home.path())?;
add.env("HTTP_PROXY", proxy.uri())
.env("http_proxy", proxy.uri())
.env_remove("HTTPS_PROXY")
.env_remove("https_proxy")
.env_remove("ALL_PROXY")
.env_remove("all_proxy")
.env_remove("NO_PROXY")
.env_remove("no_proxy")
.args([
"-c",
"mcp_oauth_credentials_store=\"file\"",
"mcp",
"add",
"oauth",
"--url",
"http://cli-mcp.invalid/mcp",
]);
let add_output = tokio::task::spawn_blocking(move || add.output()).await??;
assert!(
!add_output.status.success(),
"mock OAuth registration should terminate the automatic login"
);
assert!(
load_global_mcp_servers(codex_home.path())
.await?
.contains_key("oauth")
);
let helper_command = if cfg!(windows) {
r#"echo {"X-Gateway":"gateway-token"}"#
} else {
r#"printf '{"X-Gateway":"gateway-token"}'"#
};
let config_path = codex_home.path().join("config.toml");
let mut config = std::fs::read_to_string(&config_path)?;
config.push_str(&format!(
"http_headers_helper = {}\n",
toml::Value::String(helper_command.to_string())
));
std::fs::write(config_path, config)?;
// Local OAuth login does not require the execution-environment registry.
std::fs::write(codex_home.path().join("environments.toml"), "invalid = [")?;
let mut login = codex_command(codex_home.path())?;
login
.env("HTTP_PROXY", proxy.uri())
.env("http_proxy", proxy.uri())
.env_remove("HTTPS_PROXY")
.env_remove("https_proxy")
.env_remove("ALL_PROXY")
.env_remove("all_proxy")
.env_remove("NO_PROXY")
.env_remove("no_proxy")
.args([
"-c",
"mcp_oauth_credentials_store=\"file\"",
"mcp",
"login",
"oauth",
]);
let login_output = tokio::task::spawn_blocking(move || login.output()).await??;
assert!(
!login_output.status.success(),
"mock OAuth registration should terminate the explicit login"
);
let requests = proxy
.received_requests()
.await
.expect("mock proxy should record OAuth requests");
let registrations: Vec<_> = requests
.iter()
.filter(|request| request.method == "POST" && request.url.path() == "/oauth/register")
.collect();
assert_eq!(registrations.len(), 2);
assert_eq!(
registrations
.iter()
.filter(|request| request.headers.get("x-gateway").is_some())
.count(),
1
);
Ok(())
}
#[tokio::test]
async fn profile_mcp_reports_legacy_profile_migration() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
r#"[profiles.work]
model = "gpt-5"
"#,
)?;
let mut list_cmd = codex_command(codex_home.path())?;
list_cmd
.args(["--profile", "work", "mcp", "list"])
.assert()
.failure()
.stderr(contains("--profile `work` cannot be used"))
.stderr(contains("[profiles.work]"))
.stderr(contains("work.config.toml"));
Ok(())
}
#[tokio::test]
async fn add_with_env_preserves_key_order_and_values() -> Result<()> {
let codex_home = TempDir::new()?;
let mut add_cmd = codex_command(codex_home.path())?;
add_cmd
.args([
"mcp",
"add",
"envy",
"--env",
"FOO=bar",
"--env",
"ALPHA=beta",
"--",
"python",
"server.py",
])
.assert()
.success();
let servers = load_global_mcp_servers(codex_home.path()).await?;
let envy = servers.get("envy").expect("server should exist");
let env = match &envy.transport {
McpServerTransportConfig::Stdio { env: Some(env), .. } => env,
other => panic!("unexpected transport: {other:?}"),
};
assert_eq!(env.len(), 2);
assert_eq!(env.get("FOO"), Some(&"bar".to_string()));
assert_eq!(env.get("ALPHA"), Some(&"beta".to_string()));
assert!(envy.enabled);
Ok(())
}
#[tokio::test]
async fn add_streamable_http_without_manual_token() -> Result<()> {
let codex_home = TempDir::new()?;
let mut add_cmd = codex_command(codex_home.path())?;
add_cmd
.args([
"mcp",
"add",
"github",
"--url",
"https://example.com/mcp",
"--oauth-client-registration",
"dcr",
])
.assert()
.success();
let servers = load_global_mcp_servers(codex_home.path()).await?;
let github = servers.get("github").expect("github server should exist");
match &github.transport {
McpServerTransportConfig::StreamableHttp {
url,
bearer_token_env_var,
http_headers,
env_http_headers,
..
} => {
assert_eq!(url, "https://example.com/mcp");
assert!(bearer_token_env_var.is_none());
assert!(http_headers.is_none());
assert!(env_http_headers.is_none());
}
other => panic!("unexpected transport: {other:?}"),
}
assert!(github.enabled);
assert_eq!(github.oauth, None);
assert!(!codex_home.path().join(".credentials.json").exists());
assert!(!codex_home.path().join(".env").exists());
let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?;
assert!(!config.contains("client_registration"));
assert!(!config.contains("[mcp_servers.github.oauth]"));
Ok(())
}
#[tokio::test]
async fn add_rejects_blank_client_credentials_before_saving() -> Result<()> {
let mut errors = Vec::new();
for (client_id, client_secret) in [("registered-client", " "), (" ", "cli-secret-marker")] {
let codex_home = TempDir::new()?;
let output = codex_command(codex_home.path())?
.args([
"mcp",
"add",
"private",
"--url",
"http://127.0.0.1:9/mcp",
"--oauth-client-id",
client_id,
"--oauth-client-secret",
client_secret,
])
.assert()
.failure()
.get_output()
.clone();
let stderr = String::from_utf8(output.stderr)?;
assert!(!stderr.contains("cli-secret-marker"));
assert!(!String::from_utf8(output.stdout)?.contains("cli-secret-marker"));
assert!(load_global_mcp_servers(codex_home.path()).await?.is_empty());
errors.push(stderr.trim().to_string());
}
insta::assert_snapshot!(errors.join("\n"), @r"
Error: --oauth-client-secret must not be empty
Error: --oauth-client-secret requires a nonempty --oauth-client-id
");
Ok(())
}
#[tokio::test]
async fn add_streamable_http_with_custom_env_var() -> Result<()> {
let codex_home = TempDir::new()?;
let mut add_cmd = codex_command(codex_home.path())?;
add_cmd
.args([
"mcp",
"add",
"issues",
"--url",
"https://example.com/issues",
"--bearer-token-env-var",
"GITHUB_TOKEN",
])
.assert()
.success();
let servers = load_global_mcp_servers(codex_home.path()).await?;
let issues = servers.get("issues").expect("issues server should exist");
match &issues.transport {
McpServerTransportConfig::StreamableHttp {
url,
bearer_token_env_var,
http_headers,
env_http_headers,
..
} => {
assert_eq!(url, "https://example.com/issues");
assert_eq!(bearer_token_env_var.as_deref(), Some("GITHUB_TOKEN"));
assert!(http_headers.is_none());
assert!(env_http_headers.is_none());
}
other => panic!("unexpected transport: {other:?}"),
}
assert!(issues.enabled);
Ok(())
}
#[tokio::test]
async fn add_streamable_http_with_oauth_options() -> Result<()> {
let codex_home = TempDir::new()?;
let expected_callback = "http://127.0.0.1/callback/w9gKTtkB7gWy";
let mut add_cmd = codex_command(codex_home.path())?;
add_cmd
.args([
"-c",
"mcp_oauth_callback_port=43123",
"mcp",
"add",
"oauth-server",
"--url",
"https://example.com/mcp",
"--oauth-client-id",
"eci-prd-pub-codex-123",
"--oauth-resource",
"https://resource.example.com",
])
.assert()
.success()
.stdout(contains(format!("OAuth callback URL: {expected_callback}")));
let servers = load_global_mcp_servers(codex_home.path()).await?;
let oauth_server = servers
.get("oauth-server")
.expect("oauth server should exist");
assert_eq!(
oauth_server.oauth_client_id(),
Some("eci-prd-pub-codex-123")
);
assert_eq!(
oauth_server
.oauth
.as_ref()
.and_then(|oauth| oauth.callback_url.as_deref()),
Some(expected_callback)
);
assert_eq!(
oauth_server.oauth_resource.as_deref(),
Some("https://resource.example.com")
);
Ok(())
}
#[tokio::test]
async fn add_persists_issuer_bound_callback_before_starting_oauth() -> Result<()> {
let codex_home = TempDir::new()?;
let oauth_server = MockServer::start().await;
let issuer = format!("{}/mcp", oauth_server.uri());
let metadata = serde_json::json!({
"issuer": issuer,
"authorization_endpoint": "not-a-valid-authorization-url",
"token_endpoint": format!("{}/token", oauth_server.uri()),
"authorization_response_iss_parameter_supported": true,
});
let concurrent_codex_home = codex_home.path().to_path_buf();
let concurrent_servers = BTreeMap::from([(
"concurrent".to_string(),
toml::from_str("command = \"echo\"\nargs = [\"concurrent\"]")?,
)]);
let concurrent_add = std::sync::Once::new();
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/mcp"))
.respond_with(move |_: &wiremock::Request| {
concurrent_add.call_once(|| {
// Edit during discovery without starting another CLI inside the HTTP timeout.
ConfigEditsBuilder::new(&concurrent_codex_home)
.replace_mcp_servers(&concurrent_servers)
.apply_blocking()
.expect("persist concurrent MCP server during discovery");
});
ResponseTemplate::new(200).set_body_json(metadata.clone())
})
.mount(&oauth_server)
.await;
let mut add_cmd = codex_command(codex_home.path())?;
add_cmd.args([
"mcp",
"add",
"issuer-bound",
"--url",
&format!("{}/mcp", oauth_server.uri()),
"--oauth-client-id",
"registered-client",
]);
let output = tokio::task::spawn_blocking(move || add_cmd.output()).await??;
assert_cmd::assert::Assert::new(output)
.failure()
.stdout(contains("OAuth callback URL: http://127.0.0.1/callback"))
.stderr(contains("OAuth authorization endpoint must be a valid URL"));
let servers = load_global_mcp_servers(codex_home.path()).await?;
assert!(servers.contains_key("concurrent"));
assert_eq!(
servers["issuer-bound"]
.oauth
.as_ref()
.and_then(|oauth| oauth.callback_url.as_deref()),
Some("http://127.0.0.1/callback")
);
Ok(())
}
#[tokio::test]
async fn add_streamable_http_rejects_removed_flag() -> Result<()> {
let codex_home = TempDir::new()?;
let mut add_cmd = codex_command(codex_home.path())?;
add_cmd
.args([
"mcp",
"add",
"github",
"--url",
"https://example.com/mcp",
"--with-bearer-token",
])
.assert()
.failure()
.stderr(contains("--with-bearer-token"));
let servers = load_global_mcp_servers(codex_home.path()).await?;
assert!(servers.is_empty());
Ok(())
}
#[tokio::test]
async fn add_cant_add_command_and_url() -> Result<()> {
let codex_home = TempDir::new()?;
let mut add_cmd = codex_command(codex_home.path())?;
add_cmd
.args([
"mcp",
"add",
"github",
"--url",
"https://example.com/mcp",
"--command",
"--",
"echo",
"hello",
])
.assert()
.failure()
.stderr(contains("unexpected argument '--command' found"));
let servers = load_global_mcp_servers(codex_home.path()).await?;
assert!(servers.is_empty());
Ok(())
}

View File

@@ -0,0 +1,511 @@
use std::collections::BTreeMap;
use std::io::Read;
use std::io::Write;
use std::net::TcpListener;
use std::path::Path;
use std::time::Duration;
use std::time::Instant;
use anyhow::Result;
use akode_config::types::McpServerTransportConfig;
use akode_core::config::edit::ConfigEditsBuilder;
use akode_core::config::load_global_mcp_servers;
use akode_login::AKODE_API_KEY_ENV_VAR;
use predicates::prelude::PredicateBooleanExt;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::Value as JsonValue;
use serde_json::json;
use tempfile::TempDir;
#[cfg(target_os = "macos")]
use wiremock::Mock;
#[cfg(target_os = "macos")]
use wiremock::MockServer;
#[cfg(target_os = "macos")]
use wiremock::ResponseTemplate;
#[cfg(target_os = "macos")]
use wiremock::matchers::method;
#[cfg(target_os = "macos")]
use wiremock::matchers::path;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
async fn configure_http_oauth_server(codex_home: &Path, url: &str) -> Result<()> {
let mut servers = load_global_mcp_servers(codex_home).await?;
servers.insert(
"oauth".to_string(),
toml::from_str(&format!("url = \"{url}\""))?,
);
ConfigEditsBuilder::new(codex_home)
.replace_mcp_servers(&servers)
.apply_blocking()?;
Ok(())
}
#[test]
fn list_shows_empty_state() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
let output = cmd.args(["mcp", "list"]).output()?;
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout)?;
assert!(stdout.contains("No MCP servers configured yet."));
Ok(())
}
#[test]
fn api_key_auth_exposes_api_curated_plugin_mcp_servers() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
r#"[features]
plugins = true
remote_plugin = false
[plugins."api-docs@openai-api-curated"]
enabled = true
"#,
)?;
let plugin_root = codex_home
.path()
.join("plugins/cache/openai-api-curated/api-docs/local");
std::fs::create_dir_all(plugin_root.join(".codex-plugin"))?;
std::fs::write(
plugin_root.join(".codex-plugin/plugin.json"),
r#"{"name":"api-docs","version":"local"}"#,
)?;
std::fs::write(
plugin_root.join(".mcp.json"),
r#"{
"mcpServers": {
"api-docs": {
"type": "stdio",
"command": "api-docs-mcp"
}
}
}"#,
)?;
let mut list_cmd = codex_command(codex_home.path())?;
list_cmd
.env(AKODE_API_KEY_ENV_VAR, "sk-test")
.args(["mcp", "list", "--json"])
.assert()
.success()
.stdout(contains(r#""name": "api-docs""#));
let mut get_cmd = codex_command(codex_home.path())?;
get_cmd
.env(AKODE_API_KEY_ENV_VAR, "sk-test")
.args(["mcp", "get", "api-docs", "--json"])
.assert()
.success()
.stdout(contains(r#""name": "api-docs""#));
Ok(())
}
#[tokio::test]
async fn list_discovers_local_oauth_server_through_environment_proxy() -> Result<()> {
let codex_home = TempDir::new()?;
configure_http_oauth_server(codex_home.path(), "http://mcp-proxy.invalid/mcp").await?;
std::fs::write(codex_home.path().join("environments.toml"), "invalid = [")?;
let listener = TcpListener::bind("127.0.0.1:0")?;
listener.set_nonblocking(true)?;
let proxy_url = format!("http://{}", listener.local_addr()?);
let proxy = std::thread::spawn(move || -> Result<Vec<String>> {
let resource_metadata = json!({
"resource": "http://mcp-proxy.invalid/mcp",
"authorization_servers": ["http://mcp-proxy.invalid"],
})
.to_string();
let authorization_metadata = json!({
"authorization_endpoint": "https://oauth.example/authorize",
"token_endpoint": "https://oauth.example/token",
})
.to_string();
let responses = [
concat!(
"HTTP/1.1 401 Unauthorized\r\n",
"www-authenticate: Bearer resource_metadata=\"http://mcp-proxy.invalid/oauth-resource\"\r\n",
"content-length: 0\r\n",
"connection: close\r\n\r\n"
)
.to_string(),
format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{resource_metadata}",
resource_metadata.len()
),
format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{authorization_metadata}",
authorization_metadata.len()
),
];
let mut requests = Vec::new();
for response in responses {
let deadline = Instant::now() + Duration::from_secs(30);
let mut stream = loop {
match listener.accept() {
Ok((stream, _)) => break stream,
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
anyhow::ensure!(
Instant::now() < deadline,
"proxy did not receive OAuth discovery request {}",
requests.len() + 1
);
std::thread::sleep(Duration::from_millis(10));
}
Err(error) => return Err(error.into()),
}
};
stream.set_nonblocking(false)?;
stream.set_read_timeout(Some(Duration::from_secs(5)))?;
let mut request = Vec::new();
let mut buffer = [0_u8; 1024];
while !request.windows(4).any(|window| window == b"\r\n\r\n") {
let bytes_read = stream.read(&mut buffer)?;
anyhow::ensure!(bytes_read > 0, "proxy request ended before its headers");
request.extend_from_slice(&buffer[..bytes_read]);
anyhow::ensure!(
request.len() <= 64 * 1024,
"proxy request headers are too large"
);
}
let request = String::from_utf8(request)?;
requests.push(request.lines().next().unwrap_or_default().to_string());
stream.write_all(response.as_bytes())?;
}
Ok(requests)
});
let mut command = codex_command(codex_home.path())?;
command
.env("HTTP_PROXY", &proxy_url)
.env("http_proxy", &proxy_url)
.env_remove("HTTPS_PROXY")
.env_remove("https_proxy")
.env_remove("ALL_PROXY")
.env_remove("all_proxy")
.env_remove("NO_PROXY")
.env_remove("no_proxy")
.args([
"-c",
"mcp_oauth_credentials_store=\"file\"",
"mcp",
"list",
"--json",
]);
let output = command.output()?;
assert!(
output.status.success(),
"mcp list failed: {}",
String::from_utf8_lossy(&output.stderr)
);
let proxy_requests = proxy
.join()
.expect("OAuth discovery proxy thread should finish")?;
assert_eq!(
proxy_requests,
vec![
"GET http://mcp-proxy.invalid/mcp HTTP/1.1",
"GET http://mcp-proxy.invalid/oauth-resource HTTP/1.1",
"GET http://mcp-proxy.invalid/.well-known/oauth-authorization-server HTTP/1.1",
]
);
let entries: JsonValue = serde_json::from_slice(&output.stdout)?;
assert_eq!(entries[0]["name"], "oauth");
assert_eq!(
entries[0]["auth_status"],
"not_logged_in",
"OAuth discovery failed after proxy requests {proxy_requests:?}; stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn list_reports_unknown_auth_status_when_oauth_discovery_is_rate_limited() -> Result<()> {
let codex_home = TempDir::new()?;
let server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("GET"))
.and(wiremock::matchers::path("/mcp"))
.respond_with(wiremock::ResponseTemplate::new(429))
.expect(1)
.mount(&server)
.await;
configure_http_oauth_server(codex_home.path(), &format!("{}/mcp", server.uri())).await?;
codex_command(codex_home.path())?
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.args([
"-c",
"mcp_oauth_credentials_store=\"file\"",
"mcp",
"list",
"--json",
])
.assert()
.success()
.stdout(contains(r#""auth_status": "unknown""#));
server.verify().await;
Ok(())
}
#[cfg(target_os = "macos")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn list_with_macos_proxy_resolution_does_not_panic() -> Result<()> {
let codex_home = TempDir::new()?;
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/mcp"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"authorization_endpoint": "https://oauth.example/authorize",
"token_endpoint": "https://oauth.example/token",
})))
.expect(2)
.mount(&server)
.await;
configure_http_oauth_server(codex_home.path(), &format!("{}/mcp", server.uri())).await?;
for respect_system_proxy in [false, true] {
let system_proxy_override = format!("features.respect_system_proxy={respect_system_proxy}");
let mut command = codex_command(codex_home.path())?;
command
.env_remove("HTTP_PROXY")
.env_remove("http_proxy")
.env_remove("HTTPS_PROXY")
.env_remove("https_proxy")
.env_remove("ALL_PROXY")
.env_remove("all_proxy")
.env_remove("NO_PROXY")
.env_remove("no_proxy")
.args([
"-c",
&system_proxy_override,
"-c",
"mcp_oauth_credentials_store=\"file\"",
"mcp",
"list",
"--json",
]);
let output = command.output()?;
assert!(
output.status.success(),
"macOS proxy resolution should not panic with respect_system_proxy={respect_system_proxy}: {}",
String::from_utf8_lossy(&output.stderr)
);
let entries: JsonValue = serde_json::from_slice(&output.stdout)?;
assert_eq!(entries[0]["auth_status"], "not_logged_in");
}
Ok(())
}
#[tokio::test]
async fn list_and_get_render_expected_output() -> Result<()> {
let codex_home = TempDir::new()?;
let mut add = codex_command(codex_home.path())?;
add.args([
"mcp",
"add",
"docs",
"--env",
"TOKEN=secret",
"--",
"docs-server",
"--port",
"4000",
])
.assert()
.success();
let mut servers = load_global_mcp_servers(codex_home.path()).await?;
let docs_entry = servers
.get_mut("docs")
.expect("docs server should exist after add");
match &mut docs_entry.transport {
McpServerTransportConfig::Stdio { env_vars, .. } => {
*env_vars = vec!["APP_TOKEN".into(), "WORKSPACE_ID".into()];
}
other => panic!("unexpected transport: {other:?}"),
}
ConfigEditsBuilder::new(codex_home.path())
.replace_mcp_servers(&servers)
.apply_blocking()?;
let mut list_cmd = codex_command(codex_home.path())?;
let list_output = list_cmd.args(["mcp", "list"]).output()?;
assert!(list_output.status.success());
let stdout = String::from_utf8(list_output.stdout)?;
assert!(stdout.contains("Name"));
assert!(stdout.contains("docs"));
assert!(stdout.contains("docs-server"));
assert!(stdout.contains("TOKEN=*****"));
assert!(stdout.contains("APP_TOKEN=*****"));
assert!(stdout.contains("WORKSPACE_ID=*****"));
assert!(stdout.contains("Status"));
assert!(stdout.contains("Auth"));
assert!(stdout.contains("enabled"));
assert!(stdout.contains("Unsupported"));
let mut list_json_cmd = codex_command(codex_home.path())?;
let json_output = list_json_cmd.args(["mcp", "list", "--json"]).output()?;
assert!(json_output.status.success());
let stdout = String::from_utf8(json_output.stdout)?;
let parsed: JsonValue = serde_json::from_str(&stdout)?;
assert_eq!(
parsed,
json!([
{
"name": "docs",
"enabled": true,
"disabled_reason": null,
"transport": {
"type": "stdio",
"command": "docs-server",
"args": [
"--port",
"4000"
],
"env": {
"TOKEN": "secret"
},
"env_vars": [
"APP_TOKEN",
"WORKSPACE_ID"
],
"cwd": null
},
"startup_timeout_sec": null,
"tool_timeout_sec": null,
"auth_status": "unsupported"
}
]
)
);
let mut get_cmd = codex_command(codex_home.path())?;
let get_output = get_cmd.args(["mcp", "get", "docs"]).output()?;
assert!(get_output.status.success());
let stdout = String::from_utf8(get_output.stdout)?;
assert!(stdout.contains("docs"));
assert!(stdout.contains("transport: stdio"));
assert!(stdout.contains("command: docs-server"));
assert!(stdout.contains("args: --port 4000"));
assert!(stdout.contains("env: TOKEN=*****"));
assert!(stdout.contains("APP_TOKEN=*****"));
assert!(stdout.contains("WORKSPACE_ID=*****"));
assert!(stdout.contains("enabled: true"));
assert!(stdout.contains("remove: akode mcp remove docs"));
let mut get_json_cmd = codex_command(codex_home.path())?;
get_json_cmd
.args(["mcp", "get", "docs", "--json"])
.assert()
.success()
.stdout(contains("\"name\": \"docs\"").and(contains("\"enabled\": true")));
Ok(())
}
#[test]
fn list_and_get_redact_http_headers_helper() -> Result<()> {
let codex_home = TempDir::new()?;
let marker = codex_home.path().join("helper-ran");
let helper = toml::Value::String(format!("echo invoked > \"{}\"", marker.display()));
std::fs::write(
codex_home.path().join("config.toml"),
format!(
"[mcp_servers.docs]\n\
url = \"https://example.com/mcp\"\n\
http_headers_helper = {helper}\n\
[mcp_servers.authenticated]\n\
url = \"https://example.com/mcp\"\n\
http_headers = {{ Authorization = \"Bearer static\" }}\n\
http_headers_helper = {helper}\n"
),
)?;
let list_output = codex_command(codex_home.path())?
.args(["mcp", "list", "--json"])
.output()?;
assert!(list_output.status.success());
let stdout = String::from_utf8(list_output.stdout)?;
assert!(stdout.contains("http_headers_helper"));
assert!(stdout.contains("<redacted>"));
let entries: Vec<JsonValue> = serde_json::from_str(&stdout)?;
let auth_statuses = entries
.into_iter()
.map(|entry| {
(
entry["name"].as_str().expect("server name").to_string(),
entry["auth_status"]
.as_str()
.expect("auth status")
.to_string(),
)
})
.collect::<BTreeMap<_, _>>();
assert_eq!(
auth_statuses,
BTreeMap::from([
("authenticated".to_string(), "bearer_token".to_string()),
("docs".to_string(), "unknown".to_string()),
])
);
assert!(!marker.exists());
for args in [
&["mcp", "get", "docs", "--json"][..],
&["mcp", "get", "docs"][..],
] {
let output = codex_command(codex_home.path())?.args(args).output()?;
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout)?;
assert!(stdout.contains("http_headers_helper"));
assert!(stdout.contains("<redacted>"));
assert!(!stdout.contains("helper-ran"));
assert!(!marker.exists());
}
Ok(())
}
#[tokio::test]
async fn get_disabled_server_shows_single_line() -> Result<()> {
let codex_home = TempDir::new()?;
let mut add = codex_command(codex_home.path())?;
add.args(["mcp", "add", "docs", "--", "docs-server"])
.assert()
.success();
let mut servers = load_global_mcp_servers(codex_home.path()).await?;
let docs = servers
.get_mut("docs")
.expect("docs server should exist after add");
docs.enabled = false;
ConfigEditsBuilder::new(codex_home.path())
.replace_mcp_servers(&servers)
.apply_blocking()?;
let mut get_cmd = codex_command(codex_home.path())?;
let get_output = get_cmd.args(["mcp", "get", "docs"]).output()?;
assert!(get_output.status.success());
let stdout = String::from_utf8(get_output.stdout)?;
assert_eq!(stdout.trim_end(), "docs (disabled)");
Ok(())
}

View File

@@ -0,0 +1,632 @@
//! Exercises terminal OAuth pasteback and its shared callback validation through the CLI.
use std::collections::BTreeMap;
use std::process::Output;
use std::process::Stdio;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use akode_core::config::load_global_mcp_servers;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::net::TcpStream;
use tokio::process::Child;
use tokio::process::ChildStdout;
use tokio::process::Command;
use tokio::time::timeout;
use url::Url;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
const TEST_TIMEOUT: Duration = Duration::from_secs(30);
struct Fixture {
server: MockServer,
home: TempDir,
issuer: String,
}
impl Fixture {
async fn new(client_secret: Option<&'static str>) -> Result<Self> {
Self::with_scopes(client_secret, &["mcp.read"]).await
}
async fn with_scopes(client_secret: Option<&'static str>, scopes: &[&str]) -> Result<Self> {
let server = MockServer::start().await;
let home = TempDir::new()?;
let issuer = format!("{}/mcp", server.uri());
let saved_client_secret = client_secret
.map(|secret| format!("client_secret = \"{secret}\"\n"))
.unwrap_or_default();
let saved_scopes = if scopes.is_empty() {
String::new()
} else {
format!("scopes = {scopes:?}\n")
};
std::fs::write(
home.path().join("config.toml"),
format!(
"mcp_oauth_credentials_store = \"file\"\n\
[mcp_servers.manual]\nurl = \"{issuer}\"\n{saved_scopes}\
[mcp_servers.manual.oauth]\nclient_id = \"registered-client\"\n\
{saved_client_secret}"
),
)?;
let fixture = Self {
server,
home,
issuer,
};
fixture.mount_oauth(client_secret).await;
Ok(fixture)
}
async fn mount_oauth(&self, client_secret: Option<&'static str>) {
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/mcp"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"issuer": self.issuer,
"authorization_endpoint": format!("{}/authorize", self.server.uri()),
"token_endpoint": format!("{}/token", self.server.uri()),
"response_types_supported": ["code"],
"code_challenge_methods_supported": ["S256"],
"scopes_supported": ["mcp.read"],
"authorization_response_iss_parameter_supported": true,
"token_endpoint_auth_methods_supported": [if client_secret.is_some() {
"client_secret_post"
} else {
"none"
}],
})))
.mount(&self.server)
.await;
Mock::given(method("POST"))
.and(path("/token"))
.and(move |request: &wiremock::Request| {
let body: BTreeMap<_, _> = url::form_urlencoded::parse(&request.body)
.into_owned()
.collect();
body.get("client_secret").map(String::as_str) == client_secret
})
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"access_token": "mock-access-token",
"token_type": "Bearer",
"refresh_token": "mock-refresh-token",
"scope": "mcp.read",
})))
.mount(&self.server)
.await;
}
async fn mount_resource_metadata(&self, scopes: &[&str], challenge_scope: Option<&str>) {
let mut challenge = format!(
"Bearer resource_metadata=\"{}/resource-metadata\"",
self.server.uri()
);
if let Some(scope) = challenge_scope {
challenge.push_str(&format!(", scope=\"{scope}\""));
}
Mock::given(method("GET"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(401).insert_header("www-authenticate", challenge))
.mount(&self.server)
.await;
Mock::given(method("GET"))
.and(path("/resource-metadata"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"resource": self.issuer,
"authorization_servers": [self.issuer],
"scopes_supported": scopes,
})))
.mount(&self.server)
.await;
}
async fn start(&self) -> Result<Login> {
let mut child = Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.kill_on_drop(true)
.current_dir(self.home.path())
.env("AKODE_HOME", self.home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.args(["mcp", "login", "manual", "--no-browser"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let mut stdout = BufReader::new(child.stdout.take().context("missing stdout")?);
let mut transcript = String::new();
let authorization_url = match read_authorization_url(&mut stdout, &mut transcript).await {
Ok(authorization_url) => authorization_url,
Err(error) => {
let mut stderr = String::new();
if let Some(stderr_pipe) = child.stderr.take() {
let _ = timeout(
Duration::from_secs(1),
stderr_pipe.take(/*limit*/ 4096).read_to_string(&mut stderr),
)
.await;
}
return Err(error.context(format!("MCP login stderr: {stderr}")));
}
};
Ok(Login {
child,
stdout,
transcript,
authorization_url,
})
}
}
async fn read_authorization_url(
stdout: &mut BufReader<ChildStdout>,
transcript: &mut String,
) -> Result<Url> {
timeout(TEST_TIMEOUT, async {
loop {
let mut line = String::new();
if stdout.read_line(&mut line).await? == 0 {
bail!("login exited before printing its authorization URL: {transcript}");
}
transcript.push_str(&line);
if line.starts_with("http://") {
return Ok(Url::parse(line.trim())?);
}
}
})
.await
.context("authorization URL timeout")?
}
struct Login {
child: Child,
stdout: BufReader<ChildStdout>,
transcript: String,
authorization_url: Url,
}
impl Login {
fn callback(&self, issuer: &str) -> Result<Url> {
let params: BTreeMap<_, _> = self.authorization_url.query_pairs().into_owned().collect();
let mut callback = Url::parse(&params["redirect_uri"])?;
callback
.query_pairs_mut()
.append_pair("code", "mock-code")
.append_pair("state", &params["state"])
.append_pair("iss", issuer);
Ok(callback)
}
async fn finish(mut self) -> Result<Output> {
let (mut output, _) = timeout(TEST_TIMEOUT, async {
tokio::try_join!(
self.child.wait_with_output(),
self.stdout.read_to_string(&mut self.transcript),
)
})
.await
.context("login completion timeout")??;
output.stdout = self.transcript.into_bytes();
Ok(output)
}
}
#[tokio::test]
async fn no_browser_exchanges_pasted_callback_and_saves_credentials() -> Result<()> {
let fixture = Fixture::new(/*client_secret*/ None).await?;
assert_no_browser_exchanges_pasted_callback_and_saves_credentials(
fixture, /*client_secret*/ None,
)
.await
}
#[tokio::test]
async fn no_browser_prefers_challenge_scopes_for_preregistered_client() -> Result<()> {
let fixture = Fixture::with_scopes(/*client_secret*/ None, &[]).await?;
fixture
.mount_resource_metadata(&["mcp.read", "mcp.write"], Some("mcp.read"))
.await;
// The authorization server advertises neither scopes nor dynamic registration.
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/mcp"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"issuer": fixture.issuer,
"authorization_endpoint": format!("{}/authorize", fixture.server.uri()),
"token_endpoint": format!("{}/token", fixture.server.uri()),
"response_types_supported": ["code"],
"code_challenge_methods_supported": ["S256"],
})))
.with_priority(/*priority*/ 1)
.mount(&fixture.server)
.await;
assert_no_browser_exchanges_pasted_callback_and_saves_credentials(
fixture, /*client_secret*/ None,
)
.await
}
#[tokio::test]
async fn no_browser_exchanges_pasted_callback_with_client_secret() -> Result<()> {
let fixture = Fixture::new(Some("headless-client-secret")).await?;
assert_no_browser_exchanges_pasted_callback_and_saves_credentials(
fixture,
Some("headless-client-secret"),
)
.await
}
#[tokio::test]
async fn add_persists_client_secret_for_subsequent_login_without_disclosure() -> Result<()> {
const CLIENT_SECRET: &str = "cli-client-secret";
let fixture = Fixture::new(Some(CLIENT_SECRET)).await?;
std::fs::write(
fixture.home.path().join("config.toml"),
"mcp_oauth_credentials_store = \"file\"\n",
)?;
// Stop automatic login before browser launch, then retry with valid metadata.
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/mcp"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"issuer": fixture.issuer,
"authorization_endpoint": "not-a-valid-authorization-url",
"token_endpoint": format!("{}/token", fixture.server.uri()),
"authorization_response_iss_parameter_supported": true,
})))
.with_priority(/*priority*/ 1)
.mount(&fixture.server)
.await;
let output = timeout(
TEST_TIMEOUT,
Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.kill_on_drop(true)
.current_dir(fixture.home.path())
.env("AKODE_HOME", fixture.home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.args([
"mcp",
"add",
"manual",
"--url",
&fixture.issuer,
"--oauth-client-id",
"registered-client",
"--oauth-client-secret",
CLIENT_SECRET,
])
.output(),
)
.await??;
assert!(!output.status.success());
let stdout = String::from_utf8(output.stdout)?;
let stderr = String::from_utf8(output.stderr)?;
assert!(stdout.contains("Detected OAuth support. Starting OAuth flow"));
assert!(!stdout.contains(CLIENT_SECRET));
assert!(!stderr.contains(CLIENT_SECRET));
let servers = load_global_mcp_servers(fixture.home.path()).await?;
assert_eq!(servers["manual"].oauth_client_secret(), Some(CLIENT_SECRET));
// Reset removes the priority override without relying on wiremock's scoped indices.
fixture.server.reset().await;
fixture.mount_oauth(Some(CLIENT_SECRET)).await;
fixture
.mount_resource_metadata(&["mcp.read"], /*challenge_scope*/ None)
.await;
assert_no_browser_exchanges_pasted_callback_and_saves_credentials(fixture, Some(CLIENT_SECRET))
.await
}
async fn assert_no_browser_exchanges_pasted_callback_and_saves_credentials(
fixture: Fixture,
client_secret: Option<&'static str>,
) -> Result<()> {
let mut login = fixture.start().await?;
let authorization_url = login.authorization_url.to_string();
let params: BTreeMap<_, _> = login.authorization_url.query_pairs().into_owned().collect();
assert_eq!(params.get("scope").map(String::as_str), Some("mcp.read"));
let callback = login.callback(&fixture.issuer)?;
login
.child
.stdin
.as_mut()
.context("missing stdin")?
.write_all(format!("{callback}\n").as_bytes())
.await?;
let output = login.finish().await?;
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let stdout = String::from_utf8(output.stdout)?;
let stderr = String::from_utf8(output.stderr)?;
if let Some(client_secret) = client_secret {
assert!(!stdout.contains(client_secret));
assert!(!stderr.contains(client_secret));
}
insta::allow_duplicates! {
insta::assert_snapshot!(stdout.replace(&authorization_url, "[AUTHORIZATION_URL]"), @r"
Authorize the MCP server by opening this URL in your browser:
[AUTHORIZATION_URL]
After signing in, copy the full URL from your browser's address bar.
If the callback page cannot load, paste that URL here anyway.
Successfully logged in to MCP server 'manual'.
");
}
assert!(stderr.contains("Callback URL (input hidden): "));
let requests = fixture
.server
.received_requests()
.await
.context("missing requests")?;
let tokens: Vec<_> = requests
.iter()
.filter(|r| r.url.path() == "/token")
.collect();
assert_eq!(tokens.len(), 1);
let mut exchange: BTreeMap<_, _> = url::form_urlencoded::parse(&tokens[0].body)
.into_owned()
.collect();
let verifier = exchange
.remove("code_verifier")
.context("missing PKCE verifier")?;
assert!((43..=128).contains(&verifier.len()));
assert_eq!(params["code_challenge_method"], "S256");
assert!(!params["code_challenge"].is_empty());
let mut expected_exchange = BTreeMap::from([
("client_id".to_string(), "registered-client".to_string()),
("code".to_string(), "mock-code".to_string()),
("grant_type".to_string(), "authorization_code".to_string()),
("redirect_uri".to_string(), params["redirect_uri"].clone()),
("resource".to_string(), fixture.issuer.clone()),
]);
if let Some(client_secret) = client_secret {
expected_exchange.insert("client_secret".to_string(), client_secret.to_string());
}
assert_eq!(exchange, expected_exchange);
let credentials: BTreeMap<String, Value> = serde_json::from_slice(&std::fs::read(
fixture.home.path().join(".credentials.json"),
)?)?;
assert_eq!(
credentials.into_values().collect::<Vec<_>>(),
vec![json!({
"server_name": "manual", "server_url": fixture.issuer, "issuer": fixture.issuer,
"client_id": "registered-client", "access_token": "mock-access-token",
"refresh_token": "mock-refresh-token", "expires_at": null, "scopes": ["mcp.read"],
})]
);
Ok(())
}
#[tokio::test]
async fn no_browser_rejects_invalid_callbacks_without_exchanging_tokens() -> Result<()> {
for (field, value) in [
("state", Some("wrong-state")),
("iss", None),
("iss", Some("https://secret-issuer-marker.example")),
("eof", None),
] {
let fixture = Fixture::new(/*client_secret*/ None).await?;
let mut login = fixture.start().await?;
let mut callback = login.callback(&fixture.issuer)?;
let mut pairs: BTreeMap<_, _> = callback.query_pairs().into_owned().collect();
pairs.remove(field);
if let Some(value) = value {
pairs.insert(field.to_string(), value.to_string());
}
callback.set_query(None);
callback.query_pairs_mut().extend_pairs(pairs);
if field == "eof" {
drop(login.child.stdin.take());
} else {
login
.child
.stdin
.as_mut()
.context("missing stdin")?
.write_all(format!("{callback}\n").as_bytes())
.await?;
}
let output = login.finish().await?;
assert!(
!output.status.success(),
"accepted invalid {field}: {value:?}"
);
let stderr = String::from_utf8(output.stderr)?;
for secret in ["mock-code", "secret-issuer-marker"] {
assert!(
!stderr.contains(secret),
"callback error leaked {secret}: {stderr}"
);
}
assert!(!fixture.home.path().join(".credentials.json").exists());
assert!(
fixture
.server
.received_requests()
.await
.context("missing requests")?
.iter()
.all(|request| request.url.path() != "/token")
);
}
Ok(())
}
#[tokio::test]
async fn no_browser_accepts_http_callback_while_terminal_input_remains_open() -> Result<()> {
let fixture = Fixture::new(/*client_secret*/ None).await?;
let mut login = fixture.start().await?;
let callback = login.callback(&fixture.issuer)?;
let stdin = login.child.stdin.take().context("missing stdin")?;
let mut stream = TcpStream::connect((
"127.0.0.1",
callback.port().context("missing callback port")?,
))
.await?;
stream
.write_all(
format!(
"GET {}?{} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
callback.path(),
callback.query().context("missing callback query")?
)
.as_bytes(),
)
.await?;
let output = login.finish().await?;
drop(stdin);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert!(fixture.home.path().join(".credentials.json").exists());
Ok(())
}
#[tokio::test]
async fn no_browser_retries_rejected_discovered_scopes_with_pasteback() -> Result<()> {
let fixture = Fixture::with_scopes(/*client_secret*/ None, &[]).await?;
fixture
.mount_resource_metadata(&["mcp.read"], /*challenge_scope*/ None)
.await;
let mut login = fixture.start().await?;
assert!(
login
.authorization_url
.query_pairs()
.any(|(key, value)| key == "scope" && value == "mcp.read")
);
let mut callback = login.callback(&fixture.issuer)?;
let mut params: BTreeMap<_, _> = callback.query_pairs().into_owned().collect();
params.remove("code");
params.insert("error".to_string(), "invalid_scope".to_string());
callback.set_query(None);
callback.query_pairs_mut().extend_pairs(params);
login
.child
.stdin
.as_mut()
.context("missing stdin")?
.write_all(format!("{callback}\n").as_bytes())
.await?;
login.authorization_url =
read_authorization_url(&mut login.stdout, &mut login.transcript).await?;
assert!(
!login
.authorization_url
.query_pairs()
.any(|(key, _)| key == "scope")
);
let callback = login.callback(&fixture.issuer)?;
login
.child
.stdin
.as_mut()
.context("missing stdin")?
.write_all(format!("{callback}\n").as_bytes())
.await?;
let output = login.finish().await?;
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert!(String::from_utf8(output.stdout)?.contains("Retrying without scopes"));
let requests = fixture
.server
.received_requests()
.await
.context("missing requests")?;
assert_eq!(
requests
.iter()
.filter(|request| request.url.path() == "/token")
.count(),
1
);
Ok(())
}
#[cfg(unix)]
#[tokio::test]
async fn no_browser_sigint_cancels_token_exchange_after_pasted_or_http_callback() -> Result<()> {
for callback_delivery in ["paste", "http"] {
let fixture = Fixture::new(/*client_secret*/ None).await?;
let request_started = std::sync::Arc::new(tokio::sync::Notify::new());
let notify = std::sync::Arc::clone(&request_started);
Mock::given(method("POST"))
.and(path("/token"))
.respond_with(move |_: &wiremock::Request| {
notify.notify_one();
ResponseTemplate::new(200)
.set_delay(Duration::from_secs(/*secs*/ 30))
.set_body_json(
json!({"access_token": "mock-access-token", "token_type": "Bearer"}),
)
})
.with_priority(/*priority*/ 1)
.expect(1)
.mount(&fixture.server)
.await;
let mut login = fixture.start().await?;
let callback = login.callback(&fixture.issuer)?;
// Keep the input pipe open after an HTTP callback, including while waiting for exit.
let mut stdin = login.child.stdin.take().context("missing stdin")?;
let mut http_callback = None;
if callback_delivery == "http" {
let mut stream = TcpStream::connect((
"127.0.0.1",
callback.port().context("missing callback port")?,
))
.await?;
stream
.write_all(
format!(
"GET {}?{} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n",
callback.path(),
callback.query().context("missing callback query")?,
)
.as_bytes(),
)
.await?;
http_callback = Some(stream);
} else {
stdin.write_all(format!("{callback}\n").as_bytes()).await?;
}
timeout(TEST_TIMEOUT, request_started.notified())
.await
.context("token exchange never started")?;
let child_pid = i32::try_from(login.child.id().context("login exited before SIGINT")?)?;
// SAFETY: this positive PID belongs to the live child process owned by this test.
assert_eq!(unsafe { libc::kill(child_pid, libc::SIGINT) }, 0);
let output = timeout(Duration::from_secs(/*secs*/ 5), login.finish())
.await
.with_context(|| {
format!("SIGINT did not cancel {callback_delivery} callback token exchange")
})??;
drop((stdin, http_callback));
assert!(
!output.status.success(),
"SIGINT login unexpectedly succeeded"
);
assert!(String::from_utf8(output.stderr)?.contains("OAuth login cancelled"));
assert!(!fixture.home.path().join(".credentials.json").exists());
}
Ok(())
}

View File

@@ -0,0 +1,132 @@
//! Exercise migration consent, permissions, and accurate partial/no-op reporting.
#![cfg(unix)]
use anyhow::Result;
use akode_state::SqliteConfig;
use predicates::prelude::PredicateBooleanExt;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use std::os::unix::fs::PermissionsExt;
#[tokio::test]
async fn migration_requires_consent_and_preserves_shared_database_mode() -> Result<()> {
let home = tempfile::tempdir()?;
let sqlite = SqliteConfig::new_for_testing(home.path().to_path_buf().try_into()?);
let mut empty = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
let empty = empty
.env("AKODE_HOME", home.path())
.env(akode_state::SQLITE_HOME_ENV, home.path())
.arg("migrate-nfs-db")
.write_stdin("y\n")
.assert()
.success()
.stdout(
contains("No databases found").and(contains("Migration completed successfully").not()),
);
insta::assert_snapshot!(
String::from_utf8_lossy(&empty.get_output().stdout)
.replace(home.path().to_str().unwrap(), "[HOME]"),
@"No databases found."
);
let path = sqlite.state_db_path();
let pool = sqlite.open_read_write_pool(&path).await?;
sqlx::raw_sql("CREATE TABLE entries (id INTEGER); INSERT INTO entries VALUES (42)")
.execute(&pool)
.await?;
pool.close().await;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(/*mode*/ 0o600))?;
let mut command = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
let declined = command
.env("AKODE_HOME", home.path())
.env(akode_state::SQLITE_HOME_ENV, home.path())
.arg("migrate-nfs-db")
.write_stdin("n\n")
.assert()
.failure()
.stderr(contains("permissions other than 0600").not())
.stderr(contains("Continue? [y/N]"));
let stderr = String::from_utf8_lossy(&declined.get_output().stderr);
let disclosure = stderr
.find("the original owner, group, and extended ACLs are not copied")
.unwrap();
let consent = stderr.find("Continue? [y/N]").unwrap();
assert!(
disclosure < consent,
"ACL loss must be disclosed before consent, including for 0600 files"
);
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(/*mode*/ 0o644))?;
let before = std::fs::read(&path)?;
let mut command = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
command
.env("AKODE_HOME", home.path())
.env(akode_state::SQLITE_HOME_ENV, home.path())
.arg("migrate-nfs-db")
.write_stdin("n\n")
.assert()
.failure()
.stderr(contains("permissions other than 0600"))
.stderr(contains("No databases were changed"));
assert_eq!(std::fs::read(&path)?, before);
// A later corrupt database must be reported without undoing a completed conversion.
std::fs::write(sqlite.logs_db_path(), b"corrupt SQLite database")?;
let mut partial = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
let partial = partial
.env("AKODE_HOME", home.path())
.env(akode_state::SQLITE_HOME_ENV, home.path())
.arg("migrate-nfs-db")
.write_stdin("y\n")
.assert()
.failure()
.stdout(
contains("Migrated database").and(contains("Migration completed successfully").not()),
)
.stderr(contains("migration failed for"));
let stderr = String::from_utf8_lossy(&partial.get_output().stderr);
insta::assert_snapshot!(
stderr
.lines()
.find(|line| line.starts_with("Error: migration failed"))
.unwrap()
.replace(home.path().to_str().unwrap(), "[HOME]"),
@"Error: migration failed for [HOME]/logs_2.sqlite. Keep all aKode instances stopped. Correct the error and rerun codex migrate-nfs-db"
);
assert_eq!(
std::fs::read(sqlite.logs_db_path())?,
b"corrupt SQLite database"
);
std::fs::remove_file(sqlite.logs_db_path())?;
let mut command = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
command
.env("AKODE_HOME", home.path())
.env(akode_state::SQLITE_HOME_ENV, home.path())
.arg("migrate-nfs-db")
.write_stdin("y\n")
.assert()
.success()
.stdout(
contains("Already in DELETE mode").and(contains("Migration completed successfully")),
);
let pool = sqlite
.open_read_only_pool(&path, /*busy_timeout*/ None)
.await?;
let mode: String = sqlx::query_scalar("PRAGMA journal_mode")
.fetch_one(&pool)
.await?;
let rows: Vec<i64> = sqlx::query_scalar("SELECT id FROM entries")
.fetch_all(&pool)
.await?;
assert_eq!(
(
mode,
rows,
std::fs::metadata(&path)?.permissions().mode() & 0o777
),
("delete".to_string(), vec![42], 0o644)
);
pool.close().await;
Ok(())
}

File diff suppressed because it is too large Load Diff

703
akode-rs/cli/tests/queue.rs Normal file
View File

@@ -0,0 +1,703 @@
use std::path::Path;
use std::process::Output;
use anyhow::Context;
use anyhow::Result;
use futures::SinkExt;
use futures::StreamExt;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use tokio::net::TcpListener;
use tokio_tungstenite::accept_async;
use tokio_tungstenite::tungstenite::Message;
const THREAD_ID: &str = "123e4567-e89b-12d3-a456-426614174000";
enum QueueResponse {
Success,
ResumeRejected,
MethodNotFound,
#[cfg(unix)]
UnknownMethodVariant,
}
#[cfg(unix)]
fn socket_test_home() -> Result<TempDir> {
// macOS temporary paths can exceed the Unix socket path limit.
#[cfg(target_os = "macos")]
let home = tempfile::tempdir_in("/tmp")?;
#[cfg(not(target_os = "macos"))]
let home = TempDir::new()?;
Ok(home)
}
async fn respond_to_queue_request<S>(
stream: S,
codex_home: &Path,
response: QueueResponse,
) -> Result<Value>
where
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
{
let mut websocket = accept_async(stream).await?;
let initialize = websocket
.next()
.await
.context("missing initialize request")??;
let initialize: Value = serde_json::from_str(initialize.to_text()?)?;
assert_eq!(initialize["method"], "initialize");
assert_eq!(
initialize["params"]["capabilities"]["experimentalApi"],
true
);
let initialized_response = json!({
"id": initialize["id"],
"result": {
"userAgent": "codex_cli_rs/0.0.0-test",
"codexHome": codex_home,
},
});
websocket
.send(Message::Text(initialized_response.to_string().into()))
.await?;
let initialized = websocket
.next()
.await
.context("missing initialized notification")??;
let initialized: Value = serde_json::from_str(initialized.to_text()?)?;
assert_eq!(initialized["method"], "initialized");
let request = websocket.next().await.context("missing queue request")??;
let request: Value = serde_json::from_str(request.to_text()?)?;
assert_eq!(request["method"], "thread/queue/add");
assert_eq!(request["params"]["threadId"], THREAD_ID);
let result = match response {
QueueResponse::Success | QueueResponse::ResumeRejected => json!({
"id": request["id"],
"result": {
"queuedSubmission": {
"id": "queued-submission-id",
"input": request["params"]["input"],
"clientUserMessageId": request["params"]["clientUserMessageId"],
},
},
}),
QueueResponse::MethodNotFound => json!({
"id": request["id"],
"error": { "code": -32601, "message": "Method not found" },
}),
#[cfg(unix)]
QueueResponse::UnknownMethodVariant => json!({
"id": request["id"],
"error": {
"code": -32600,
"message": "Invalid request: unknown variant `thread/queue/add`, expected `thread/list`",
},
}),
};
websocket
.send(Message::Text(result.to_string().into()))
.await?;
if matches!(response, QueueResponse::ResumeRejected) {
for (method, mut reply) in [
(
"thread/read",
json!({"result": {"thread": {"status": {"type": "notLoaded"}, "cwd": r"C:\workspace"}}}),
),
(
"thread/resume",
json!({"error": {"code": -32603, "message": "thread already has an active writer"}}),
),
] {
let rpc = websocket.next().await.context("missing resume request")??;
let rpc: Value = serde_json::from_str(rpc.to_text()?)?;
assert_eq!(rpc["method"], method);
assert_eq!(rpc["params"]["threadId"], THREAD_ID);
reply["id"] = rpc["id"].clone();
websocket
.send(Message::Text(reply.to_string().into()))
.await?;
}
}
Ok(request)
}
#[tokio::test]
async fn queue_submits_message_to_remote_app_server() -> Result<()> {
let (output, request) = run_remote_queue_command(QueueResponse::Success).await?;
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(request["params"]["threadId"], THREAD_ID);
assert_eq!(request["params"]["input"][0]["text"], "do the thing");
assert_eq!(
String::from_utf8(output.stdout)?,
format!("Queued message queued-submission-id for thread {THREAD_ID}.\n")
);
Ok(())
}
#[tokio::test]
async fn queue_succeeds_when_another_server_owns_the_thread() -> Result<()> {
let (output, _) = run_remote_queue_command(QueueResponse::ResumeRejected).await?;
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(
String::from_utf8(output.stdout)?,
format!("Queued message queued-submission-id for thread {THREAD_ID}.\n")
);
assert!(String::from_utf8(output.stderr)?.contains("thread already has an active writer"));
Ok(())
}
#[tokio::test]
async fn queue_does_not_fallback_from_unsupported_explicit_remote() -> Result<()> {
let (output, _) = run_remote_queue_command(QueueResponse::MethodNotFound).await?;
assert!(!output.status.success());
assert!(
String::from_utf8(output.stderr)?
.contains("remote app server does not support thread/queue/add")
);
Ok(())
}
#[test]
fn queue_rejects_empty_message() -> Result<()> {
let output = std::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.args(["queue", "--thread", THREAD_ID, "--message", ""])
.output()?;
assert!(!output.status.success());
Ok(())
}
#[test]
fn queue_rejects_unsupported_options() -> Result<()> {
let codex_home = TempDir::new()?;
for (args, expected) in [
("queue --image screenshot.png", "image attachments"),
("queue --model other-model", "`--model`"),
("--oss queue", "`--oss`"),
("queue --local-provider ollama", "`--local-provider`"),
(
"queue --dangerously-bypass-hook-trust",
"`--dangerously-bypass-hook-trust`",
),
(
"-c model=other queue -c check_for_update_on_startup=false",
"`model` config override",
),
("queue -s read-only", "`--sandbox`"),
("--approve-for-me queue", "`--approve-for-me`"),
("prompt queue", "positional prompt; use `--message`"),
("-C . queue --remote unix://", "`--cd` with `--remote`"),
("--remote unix:// queue -C .", "`--cd` with `--remote`"),
] {
let output = std::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.env("AKODE_HOME", codex_home.path())
.args(args.split_whitespace())
.args(["--thread", THREAD_ID, "--message", "do the thing"])
.output()?;
assert!(!output.status.success());
let stderr = String::from_utf8(output.stderr)?;
assert!(
stderr.contains("`akode queue`") && stderr.contains(expected),
"{args:?}: {stderr}"
);
}
Ok(())
}
async fn run_remote_queue_command(response: QueueResponse) -> Result<(Output, Value)> {
let codex_home = TempDir::new()?;
let listener = TcpListener::bind("127.0.0.1:0").await?;
let endpoint = format!("ws://{}", listener.local_addr()?);
let remote_first = matches!(response, QueueResponse::MethodNotFound);
let resume = matches!(response, QueueResponse::ResumeRejected);
let server_home = codex_home.path().to_path_buf();
let server = tokio::spawn(async move {
let (stream, _) = listener.accept().await?;
respond_to_queue_request(stream, server_home.as_path(), response).await
});
let remote_args = if remote_first {
[
"--remote",
endpoint.as_str(),
"--remote-auth-token-env",
"AKODE_REMOTE_TOKEN",
"queue",
]
} else {
[
"queue",
"--remote",
endpoint.as_str(),
"--remote-auth-token-env",
"AKODE_REMOTE_TOKEN",
]
};
let output = tokio::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.env("AKODE_HOME", codex_home.path())
.env("AKODE_REMOTE_TOKEN", "test-token")
.args(remote_args)
.args(resume.then_some("--resume"))
.args(["--thread", THREAD_ID, "--message", "do the thing"])
.output()
.await?;
Ok((output, server.await??))
}
#[cfg(unix)]
#[tokio::test]
async fn remote_session_commands_with_workload_identity_use_server_auth() -> Result<()> {
use std::time::Duration;
use app_test_support::MockResponsesConfig;
use app_test_support::TestAppServer;
use app_test_support::create_final_assistant_message_sse_response;
use akode_app_server_client::AppServerEvent;
use akode_app_server_client::DEFAULT_IN_PROCESS_CHANNEL_CAPACITY;
use akode_app_server_client::RemoteAppServerClient;
use akode_app_server_client::RemoteAppServerConnectArgs;
use akode_app_server_client::RemoteAppServerEndpoint;
use akode_app_server_protocol::ClientRequest;
use akode_app_server_protocol::RequestId;
use akode_app_server_protocol::ServerNotification;
use akode_app_server_protocol::ThreadListParams;
use akode_app_server_protocol::ThreadListResponse;
use akode_app_server_protocol::ThreadQueueListParams;
use akode_app_server_protocol::ThreadQueueListResponse;
use akode_app_server_protocol::ThreadReadParams;
use akode_app_server_protocol::ThreadReadResponse;
use akode_app_server_protocol::ThreadSetNameParams;
use akode_app_server_protocol::ThreadSetNameResponse;
use akode_app_server_protocol::ThreadStartParams;
use akode_app_server_protocol::ThreadStartResponse;
use akode_app_server_protocol::ThreadStatus;
use akode_app_server_protocol::TurnStatus;
use akode_protocol::shell_environment::OPENAI_FEDERATION_RULE_ID_ENV_VAR;
use akode_protocol::shell_environment::OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR;
use core_test_support::responses;
use tokio::process::Command;
use tokio::time::timeout;
use wiremock::Mock;
use wiremock::matchers::method;
use wiremock::matchers::path;
let codex_home = socket_test_home()?;
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
let model = responses::start_mock_server().await;
let model_requests = Mock::given(method("POST"))
.and(path("/v1/responses"))
.respond_with(responses::sse_response(
create_final_assistant_message_sse_response("queued message consumed")?,
))
.expect(2)
.mount_as_scoped(&model)
.await;
MockResponsesConfig::new(&model.uri())
.with_root_config("features.plugins = false")
.with_provider_config("env_key = \"AKODE_QUEUE_SERVER_API_KEY\"")
.write(codex_home.path())?;
let _server = TestAppServer::builder()
.with_program(&codex)
.with_codex_home(codex_home.path())
.with_plugin_startup_tasks()
.without_managed_config()
.with_args(&["app-server", "--listen", "unix://"])
.with_env_overrides(&[
("OPENAI_API_KEY", None),
("AKODE_API_KEY", None),
("AKODE_ACCESS_TOKEN", None),
(OPENAI_FEDERATION_RULE_ID_ENV_VAR, None),
(OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR, None),
("AKODE_QUEUE_SERVER_API_KEY", Some("server-only-test-key")),
])
.build()
.await?;
let socket_path = akode_app_server::app_server_control_socket_path(codex_home.path())?;
timeout(Duration::from_secs(30), async {
while !socket_path.as_path().try_exists()? {
tokio::time::sleep(Duration::from_millis(10)).await;
}
Ok::<_, anyhow::Error>(())
})
.await??;
let endpoint = format!("unix://{}", socket_path.as_path().display());
let mut app = RemoteAppServerClient::connect(RemoteAppServerConnectArgs {
required_human_approval: false,
endpoint: RemoteAppServerEndpoint::UnixSocket { socket_path },
client_name: "queue-e2e-test".to_string(),
client_version: "0.1.0".to_string(),
experimental_api: true,
mcp_server_openai_form_elicitation: false,
opt_out_notification_methods: Vec::new(),
channel_capacity: DEFAULT_IN_PROCESS_CHANNEL_CAPACITY,
})
.await?;
let started: ThreadStartResponse = app
.request_typed(ClientRequest::ThreadStart {
request_id: RequestId::Integer(1),
params: ThreadStartParams::default(),
})
.await?;
let thread_id = started.thread.id;
let message = "synthetic WIF queue end-to-end message";
let output = timeout(
Duration::from_secs(30),
Command::new(&codex)
.env("AKODE_HOME", codex_home.path())
.env(OPENAI_FEDERATION_RULE_ID_ENV_VAR, "rule-test")
.env(
OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR,
codex_home.path().join("missing-identity-token"),
)
.env_remove("AKODE_QUEUE_SERVER_API_KEY")
.kill_on_drop(true)
.args(["queue", "--resume", "--remote", "unix://"])
.args(["--thread", &thread_id, "--message", message])
.output(),
)
.await??;
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let completed = timeout(Duration::from_secs(30), async {
while let Some(event) = app.next_event().await {
if let AppServerEvent::ServerNotification(notification) = event
&& let ServerNotification::TurnCompleted(completed) = *notification
{
return Ok::<_, anyhow::Error>(completed);
}
}
anyhow::bail!("app server disconnected before the queued turn completed")
})
.await??;
assert_eq!(completed.thread_id, thread_id);
assert_eq!(completed.turn.status, TurnStatus::Completed);
let queue: ThreadQueueListResponse = app
.request_typed(ClientRequest::ThreadQueueList {
request_id: RequestId::Integer(2),
params: ThreadQueueListParams {
thread_id: thread_id.clone(),
cursor: None,
limit: None,
},
})
.await?;
assert!(queue.data.is_empty());
let requests = model_requests.received_requests().await;
let request = requests
.first()
.context("queued message did not reach the model")?;
assert!(
request.body_json::<Value>()?["input"]
.to_string()
.contains(message)
);
assert_eq!(
request.headers["authorization"].to_str()?,
"Bearer server-only-test-key"
);
let metadata: Value = serde_json::from_str(request.headers["x-codex-turn-metadata"].to_str()?)?;
assert_eq!(metadata["turn_trigger"], "queue");
let name = "remote-session-lifecycle";
let _: ThreadSetNameResponse = app
.request_typed(ClientRequest::ThreadSetName {
request_id: RequestId::Integer(3),
params: ThreadSetNameParams {
thread_id: thread_id.clone(),
name: name.to_string(),
},
})
.await?;
// A separate caller home makes name resolution rely on the selected server.
let caller_home = TempDir::new()?;
let remote_command = || {
let mut command = Command::new(&codex);
command
.env("AKODE_HOME", caller_home.path())
.current_dir(caller_home.path())
.env(OPENAI_FEDERATION_RULE_ID_ENV_VAR, "rule-test")
.env(
OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR,
caller_home.path().join("missing-identity-token"),
)
.env_remove("AKODE_QUEUE_SERVER_API_KEY")
.kill_on_drop(true)
.args(["--remote", &endpoint]);
command
};
let output = timeout(
Duration::from_secs(30),
remote_command().args(["delete", &thread_id]).output(),
)
.await??;
assert!(!output.status.success());
assert!(String::from_utf8(output.stderr)?.contains("cannot confirm session deletion"));
let cold_message = "Continue after the thread was unloaded";
let cases: &[(&[&str], Option<bool>)] = &[
(&["archive", name], Some(true)),
(&["unarchive", name], Some(false)),
(&["delete", "--force", &thread_id], None),
];
for &(args, expected_archived) in cases {
let output = timeout(
Duration::from_secs(30),
remote_command().args(args).output(),
)
.await??;
assert!(
output.status.success(),
"{args:?}: {}",
String::from_utf8_lossy(&output.stderr)
);
for archived in [false, true] {
let threads: ThreadListResponse = app
.request_typed(ClientRequest::ThreadList {
request_id: RequestId::Integer(4),
params: ThreadListParams {
current_account_only: false,
excluded_thread_ids: None,
attached_to_thread_id: None,
cursor: None,
limit: None,
sort_key: None,
sort_direction: None,
model_providers: None,
source_kinds: None,
originators: None,
archived: Some(archived),
section_id: None,
project_id: None,
cwd: None,
use_state_db_only: false,
search_term: None,
parent_thread_id: None,
ancestor_thread_id: None,
},
})
.await?;
let thread = threads.data.iter().find(|thread| thread.id == thread_id);
assert_eq!(
thread.is_some(),
expected_archived == Some(archived),
"{args:?}: archived={archived}"
);
if expected_archived == Some(false)
&& let Some(thread) = thread
{
assert_eq!(thread.status, ThreadStatus::NotLoaded);
}
}
let Some(archived) = expected_archived else {
continue;
};
// Archived threads are reachable by ID; active threads can also be targeted by name.
let (target, text) = if archived {
(thread_id.as_str(), "still archived")
} else {
(name, cold_message)
};
let output = remote_command()
.args(["queue", "--resume", "--thread", target, "--message", text])
.output()
.await?;
if archived {
assert!(!output.status.success());
assert!(
String::from_utf8(output.stderr)?
.contains(&format!("session {thread_id} is archived"))
);
} else {
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
timeout(
Duration::from_secs(30),
model_requests.wait_until_satisfied(),
)
.await?;
let requests = model_requests.received_requests().await;
assert!(
requests[1].body_json::<Value>()?["input"]
.to_string()
.contains(cold_message)
);
// The mock receives the request before the resumed turn finishes. Deletion
// requires an idle thread, and archiving removed our original subscription.
timeout(Duration::from_secs(30), async {
loop {
let read: ThreadReadResponse = app
.request_typed(ClientRequest::ThreadRead {
request_id: RequestId::Integer(5),
params: ThreadReadParams {
thread_id: thread_id.clone(),
include_turns: true,
},
})
.await?;
if let Some(last) = read.thread.turns.last()
&& last.id != completed.turn.id
&& last.status == TurnStatus::Completed
&& matches!(
read.thread.status,
ThreadStatus::Idle | ThreadStatus::NotLoaded
)
{
return anyhow::Ok(());
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
})
.await
.context("resumed queued turn did not finish before deletion")??;
}
}
Ok(())
}
#[test]
fn remote_session_commands_validate_config() -> Result<()> {
let cases: &[(&[&str], &str, &str)] = &[
(
&["--strict-config"],
"config.toml",
"unknown_queue_option = true\n",
),
(&["--profile", "queue"], "queue.config.toml", "model = 42\n"),
(
&[],
"config.toml",
"experimental_thread_store_endpoint = \"https://example.com\"\n",
),
];
let commands: &[&[&str]] = &[
&["queue", "--thread", THREAD_ID, "--message", "do the thing"],
&["archive", THREAD_ID],
&["unarchive", THREAD_ID],
&["delete", "--force", THREAD_ID],
];
for &command in commands {
for &(args, config_file, config) in cases {
let codex_home = TempDir::new()?;
std::fs::write(codex_home.path().join(config_file), config)?;
let output = std::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.env("AKODE_HOME", codex_home.path())
.current_dir(codex_home.path())
.args(args)
.args(["--remote", "ws://127.0.0.1:1"])
.args(command)
.output()?;
let stderr = String::from_utf8(output.stderr)?;
assert!(!output.status.success());
assert!(
stderr.contains("failed to load config.toml"),
"{command:?}, {config:?}: {stderr}"
);
}
}
Ok(())
}
#[cfg(unix)]
#[tokio::test]
async fn queue_rejects_local_daemon_that_does_not_support_queueing() -> Result<()> {
let codex_home = socket_test_home()?;
let socket_path = akode_app_server::app_server_control_socket_path(codex_home.path())?;
std::fs::create_dir_all(
socket_path
.as_path()
.parent()
.context("missing socket parent")?,
)?;
let listener = tokio::net::UnixListener::bind(socket_path.as_path())?;
let server_home = codex_home.path().to_path_buf();
let server = tokio::spawn(async move {
let (probe, _) = listener.accept().await?;
drop(probe);
let (stream, _) = listener.accept().await?;
respond_to_queue_request(
stream,
server_home.as_path(),
QueueResponse::UnknownMethodVariant,
)
.await
});
let output = tokio::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.env("AKODE_HOME", codex_home.path())
.args(["queue", "--thread", THREAD_ID, "--message", "do the thing"])
.output()
.await?;
server.await??;
assert!(!output.status.success());
assert!(
String::from_utf8(output.stderr)?
.contains("local app-server daemon does not support thread/queue/add")
);
assert!(!codex_home.path().join("queue_1.sqlite").exists());
Ok(())
}
#[cfg(unix)]
#[tokio::test]
async fn queue_rejects_overrides_that_bypass_local_daemon() -> Result<()> {
let codex_home = socket_test_home()?;
let socket_path = akode_app_server::app_server_control_socket_path(codex_home.path())?;
std::fs::create_dir_all(
socket_path
.as_path()
.parent()
.context("missing socket parent")?,
)?;
let listener = tokio::net::UnixListener::bind(socket_path.as_path())?;
let server = tokio::spawn(async move {
let (probe, _) = listener.accept().await?;
drop(probe);
Ok::<_, std::io::Error>(())
});
let output = tokio::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.env("AKODE_HOME", codex_home.path())
.args([
"queue",
"-C",
".",
"-c",
"check_for_update_on_startup=false",
"--thread",
THREAD_ID,
"--message",
"do the thing",
])
.output()
.await?;
assert!(!output.status.success());
assert!(
String::from_utf8(output.stderr)?
.contains("embedded app server while a local app-server daemon is running")
);
server.await??;
Ok(())
}

View File

@@ -0,0 +1,304 @@
//! Exercise trace acceptance through the CLI app-server and its offline reducer.
use anyhow::Result;
use app_test_support::MockResponsesConfig;
use app_test_support::TestAppServer;
use app_test_support::create_mock_responses_server_sequence;
use akode_app_server_protocol::AgentMessageDeltaNotification;
use akode_app_server_protocol::ClientRequest;
use akode_app_server_protocol::RequestId;
use akode_app_server_protocol::ThreadStartParams;
use akode_app_server_protocol::ThreadStartResponse;
use akode_app_server_protocol::TurnCompletedNotification;
use akode_app_server_protocol::TurnInterruptParams;
use akode_app_server_protocol::TurnInterruptResponse;
use akode_app_server_protocol::TurnStartParams;
use akode_app_server_protocol::TurnStartResponse;
use akode_app_server_protocol::TurnStatus;
use akode_app_server_protocol::UserInput;
use akode_rollout_trace::ConversationRole;
use akode_rollout_trace::ExecutionStatus;
use akode_rollout_trace::ProducerRef;
use akode_rollout_trace::RolloutTrace;
use core_test_support::responses;
use core_test_support::streaming_sse::StreamingSseChunk;
use core_test_support::streaming_sse::start_streaming_sse_server;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use tokio::sync::oneshot;
#[tokio::test]
async fn enabled_recording_cannot_silently_fail_to_start() -> Result<()> {
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
let home = TempDir::new()?;
let server = create_mock_responses_server_sequence(Vec::new()).await;
MockResponsesConfig::new(&server.uri()).write(home.path())?;
let trace_root = home.path().join("traces");
std::fs::write(&trace_root, "file")?;
let mut app = TestAppServer::builder()
.with_program(&codex)
.with_plugin_startup_tasks()
.with_args(&["app-server"])
.with_codex_home(home.path())
.with_env_overrides(&[("AKODE_ROLLOUT_TRACE_ROOT", trace_root.to_str())])
.build_initialized()
.await?;
let request_id = app
.send_thread_start_request_with_auto_env(ThreadStartParams::default())
.await?;
let error = app
.read_stream_until_error_message(RequestId::Integer(request_id))
.await?;
assert!(
error
.error
.message
.contains("failed to start rollout recording")
);
// The same app-server can start a new recording once storage is available.
std::fs::remove_file(&trace_root)?;
std::fs::create_dir(&trace_root)?;
app.start_thread(ThreadStartParams::default()).await?;
assert!(app.shutdown_gracefully().await?.success());
let mut bundles = std::fs::read_dir(trace_root)?;
let bundle = bundles.next().unwrap()?.path();
assert!(bundles.next().is_none());
assert!(akode_rollout_trace::replay_bundle(bundle)?.recording_complete);
Ok(())
}
#[tokio::test]
async fn accepted_output_survives_success_and_stream_failure() -> Result<()> {
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
for (source_id, terminal, status) in [
(
Some("msg-original"),
"response.completed",
ExecutionStatus::Completed,
),
(None, "response.completed", ExecutionStatus::Completed),
(
Some("msg-original"),
"response.failed",
ExecutionStatus::Failed,
),
(None, "response.failed", ExecutionStatus::Failed),
] {
let home = TempDir::new()?;
let traces = TempDir::new()?;
let item = json!({
"type": "message", "id": source_id, "role": "assistant",
"content": [{"type": "output_text", "text": "accepted answer"}]
});
let mut terminal_response = json!({"id": "resp-1"});
if status == ExecutionStatus::Failed {
terminal_response["error"] =
json!({"code": "server_error", "message": "stream failed"});
}
let response = [
json!({"type": "response.created", "response": {"id": "resp-1"}}),
json!({"type": "response.output_item.added", "item": item}),
json!({"type": "response.output_item.done", "item": item}),
json!({"type": terminal, "response": terminal_response}),
]
.into_iter()
.map(|event| format!("data: {event}\n\n"))
.collect();
let server = create_mock_responses_server_sequence(vec![response]).await;
MockResponsesConfig::new(&server.uri()).write(home.path())?;
let mut app = TestAppServer::builder()
.with_program(&codex)
.with_plugin_startup_tasks()
.with_args(&["app-server"])
.with_codex_home(home.path())
.with_env_overrides(&[("AKODE_ROLLOUT_TRACE_ROOT", traces.path().to_str())])
.build_initialized()
.await?;
let ThreadStartResponse { thread, .. } =
app.start_thread(ThreadStartParams::default()).await?;
let TurnStartResponse { turn } = app
.request(|request_id| ClientRequest::TurnStart {
request_id,
params: TurnStartParams {
thread_id: thread.id.clone(),
input: vec![UserInput::Text {
text: "answer once".into(),
text_elements: Vec::new(),
}],
..Default::default()
},
})
.await?;
let completed: TurnCompletedNotification = app.read_notification("turn/completed").await?;
assert_eq!(
completed.turn.status,
if status == ExecutionStatus::Completed {
TurnStatus::Completed
} else {
TurnStatus::Failed
}
);
assert!(app.shutdown_gracefully().await?.success());
// Exercise the exported artifact, not just an in-process reducer call.
// There is no following request to prove acceptance of this final item.
let bundle = std::fs::read_dir(traces.path())?.next().unwrap()?.path();
let reduced = tokio::process::Command::new(&codex)
.env("AKODE_HOME", home.path())
.args(["debug", "trace-reduce"])
.arg(&bundle)
.output()
.await?;
assert!(
reduced.status.success(),
"{}",
String::from_utf8_lossy(&reduced.stderr)
);
let rollout: RolloutTrace =
serde_json::from_reader(std::fs::File::open(bundle.join("state.json"))?)?;
assert!(rollout.recording_complete);
let call = rollout.inference_calls.values().next().unwrap();
let output_id = &call.response_item_ids[0];
let output = &rollout.conversation_items[output_id];
let mut expected = call.request_item_ids.clone();
expected.push(output_id.clone());
assert_eq!(rollout.threads[&thread.id].conversation_item_ids, expected);
assert_eq!(rollout.codex_turns[&turn.id].execution.status, status);
assert_eq!(call.execution.status, status);
assert_eq!(
output.produced_by,
vec![ProducerRef::Inference {
inference_call_id: call.inference_call_id.clone()
}]
);
assert!(
output
.responses_item_id
.as_ref()
.is_some_and(|id| !id.is_empty())
);
if let Some(source_id) = source_id {
assert_eq!(output.responses_item_id.as_deref(), Some(source_id));
}
let requests = server.received_requests().await.unwrap();
let request = requests
.iter()
.find(|request| request.url.path().ends_with("/responses"))
.unwrap();
assert_eq!(
request.headers["x-codex-inference-call-id"].to_str()?,
call.inference_call_id
);
}
Ok(())
}
#[tokio::test]
async fn accepted_output_survives_interruption_and_shutdown() -> Result<()> {
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
let home = TempDir::new()?;
let traces = TempDir::new()?;
let (release_response, response_gate) = oneshot::channel();
let (server, _) = start_streaming_sse_server(vec![vec![
StreamingSseChunk {
gate: None,
body: responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_assistant_message("accepted", "Keep this answer."),
responses::ev_message_item_added("unfinished", ""),
responses::ev_output_text_delta("Discard this unfinished text"),
]),
},
// Keep the provider stream open so only the client interrupt ends it.
StreamingSseChunk {
gate: Some(response_gate),
body: String::new(),
},
]])
.await;
MockResponsesConfig::new(server.uri()).write(home.path())?;
let mut app = TestAppServer::builder()
.with_program(&codex)
.with_plugin_startup_tasks()
.with_args(&["app-server"])
.with_codex_home(home.path())
.with_env_overrides(&[("AKODE_ROLLOUT_TRACE_ROOT", traces.path().to_str())])
.build_initialized()
.await?;
let ThreadStartResponse { thread, .. } = app.start_thread(ThreadStartParams::default()).await?;
let TurnStartResponse { turn } = app
.request(|request_id| ClientRequest::TurnStart {
request_id,
params: TurnStartParams {
thread_id: thread.id.clone(),
input: vec![UserInput::Text {
text: "answer once".into(),
text_elements: Vec::new(),
}],
..Default::default()
},
})
.await?;
// Reaching the second item proves the session processed the first one.
let delta: AgentMessageDeltaNotification =
app.read_notification("item/agentMessage/delta").await?;
assert_eq!(delta.item_id, "unfinished");
let _: TurnInterruptResponse = app
.request(|request_id| ClientRequest::TurnInterrupt {
request_id,
params: TurnInterruptParams {
thread_id: thread.id.clone(),
turn_id: turn.id.clone(),
},
})
.await?;
let completed: TurnCompletedNotification = app.read_notification("turn/completed").await?;
assert_eq!(completed.turn.status, TurnStatus::Interrupted);
assert!(app.shutdown_gracefully().await?.success());
drop(release_response);
server.shutdown().await;
// Reduce immediately after shutdown: the background stream recorder must
// have preserved the accepted output even without response.completed.
let bundle = std::fs::read_dir(traces.path())?.next().unwrap()?.path();
let reduced = tokio::process::Command::new(&codex)
.env("AKODE_HOME", home.path())
.args(["debug", "trace-reduce"])
.arg(&bundle)
.output()
.await?;
assert!(
reduced.status.success(),
"{}",
String::from_utf8_lossy(&reduced.stderr)
);
let rollout: RolloutTrace =
serde_json::from_reader(std::fs::File::open(bundle.join("state.json"))?)?;
assert!(rollout.recording_complete);
assert_eq!(rollout.inference_calls.len(), 1);
let call = rollout.inference_calls.values().next().unwrap();
assert_eq!(call.execution.status, ExecutionStatus::Cancelled);
assert_eq!(
rollout.codex_turns[&turn.id].execution.status,
ExecutionStatus::Cancelled
);
assert_eq!(call.response_item_ids.len(), 1);
let output_id = &call.response_item_ids[0];
let output = &rollout.conversation_items[output_id];
assert_eq!(output.responses_item_id.as_deref(), Some("accepted"));
assert_eq!(
output.produced_by,
vec![ProducerRef::Inference {
inference_call_id: call.inference_call_id.clone(),
}]
);
let accepted_messages: Vec<_> = rollout.threads[&thread.id]
.conversation_item_ids
.iter()
.filter(|id| rollout.conversation_items[*id].role == ConversationRole::Assistant)
.collect();
assert_eq!(accepted_messages, vec![output_id]);
Ok(())
}

View File

@@ -0,0 +1,145 @@
#![cfg(target_os = "linux")]
use std::net::TcpListener;
use anyhow::Result;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
const BWRAP_UNAVAILABLE_ERR: &str = "bubblewrap is unavailable";
#[test]
fn sandbox_with_network_proxy_blocks_direct_loopback_access() -> Result<()> {
let codex_home = TempDir::new()?;
let listener = TcpListener::bind("127.0.0.2:0")?;
let port = listener.local_addr()?.port();
std::fs::write(
codex_home.path().join("config.toml"),
r#"
default_permissions = "network-test"
[features]
network_proxy = true
use_legacy_landlock = true
[permissions.network-test]
extends = ":workspace"
[permissions.network-test.network]
enabled = true
mode = "full"
"#,
)?;
let url = format!("http://127.0.0.2:{port}/");
let output = std::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.env("AKODE_HOME", codex_home.path())
.args([
"sandbox",
"--permission-profile",
"network-test",
"--",
"curl",
"--noproxy",
"*",
"--silent",
"--show-error",
"--connect-timeout",
"1",
"--max-time",
"2",
url.as_str(),
])
.output()?;
let stderr = String::from_utf8_lossy(&output.stderr);
if stderr.contains(BWRAP_UNAVAILABLE_ERR) {
eprintln!("skipping network proxy sandbox test: bubblewrap is unavailable");
return Ok(());
}
assert_eq!(
output.status.code(),
Some(7),
"expected direct loopback access to be blocked; status={:?}; stdout={}; stderr={}",
output.status.code(),
String::from_utf8_lossy(&output.stdout),
stderr,
);
Ok(())
}
#[tokio::test]
async fn sandbox_with_network_proxy_allows_explicit_loopback_access() -> Result<()> {
let codex_home = TempDir::new()?;
let listener = TcpListener::bind("127.0.0.2:0")?;
let port = listener.local_addr()?.port();
let server = MockServer::builder().listener(listener).start().await;
Mock::given(method("GET"))
.and(path("/"))
.respond_with(ResponseTemplate::new(204))
.mount(&server)
.await;
std::fs::write(
codex_home.path().join("config.toml"),
r#"
default_permissions = "network-test"
[features]
network_proxy = true
use_legacy_landlock = true
[permissions.network-test]
extends = ":workspace"
[permissions.network-test.network]
enabled = true
mode = "full"
allow_local_binding = false
[permissions.network-test.network.domains]
"127.0.0.2" = "allow"
"#,
)?;
let url = format!("http://127.0.0.2:{port}/");
let output = tokio::process::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?)
.env("AKODE_HOME", codex_home.path())
.args([
"sandbox",
"--permission-profile",
"network-test",
"--",
"curl",
"--fail",
"--silent",
"--show-error",
"--connect-timeout",
"2",
"--max-time",
"4",
url.as_str(),
])
.output()
.await?;
let stderr = String::from_utf8_lossy(&output.stderr);
if stderr.contains(BWRAP_UNAVAILABLE_ERR) {
eprintln!("skipping network proxy sandbox test: bubblewrap is unavailable");
return Ok(());
}
assert!(
output.status.success(),
"expected allowlisted loopback access to succeed; status={:?}; stdout={}; stderr={}",
output.status.code(),
String::from_utf8_lossy(&output.stdout),
stderr,
);
Ok(())
}

View File

@@ -0,0 +1,132 @@
//! Exercises the public macOS sandbox runner with a disposable controlling terminal.
#![cfg(target_os = "macos")]
use std::collections::HashMap;
use std::path::Path;
use std::process::Command;
use std::time::Duration;
use anyhow::Context as _;
use akode_utils_pty::SpawnedProcess;
use akode_utils_pty::TerminalSize;
use akode_utils_pty::spawn_pty_process;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
const PROBE: &str = r#"
import errno, fcntl, os, select, signal, struct, sys, termios, tty
signal.alarm(15)
assert os.isatty(0)
assert os.tcgetpgrp(0) == os.getpgrp()
assert struct.unpack("HHHH", fcntl.ioctl(0, termios.TIOCGWINSZ, b"\0" * 8))[:2] == (24, 80)
original = termios.tcgetattr(0)
try:
tty.setraw(0)
print("__ready__", flush=True)
assert os.read(0, 1) == b"k"
try:
fcntl.ioctl(0, termios.TIOCSTI, b"x")
except OSError as error:
assert sys.argv[1] == "deny", error
assert error.errno == errno.EPERM, error
assert not select.select([0], [], [], 0)[0]
else:
assert os.read(0, 1) == b"x"
assert sys.argv[1] == "allow", "TIOCSTI unexpectedly succeeded"
finally:
termios.tcsetattr(0, termios.TCSANOW, original)
print("__passed__", flush=True)
"#;
#[tokio::test]
async fn sandbox_blocks_terminal_input_injection() -> anyhow::Result<()> {
let availability = Command::new("/usr/bin/sandbox-exec")
.args(["-p", "(version 1)(allow default)", "/usr/bin/true"])
.output()?;
if !availability.status.success()
&& String::from_utf8_lossy(&availability.stderr)
.contains("sandbox-exec: sandbox_apply: Operation not permitted")
{
eprintln!("skipping terminal injection test: nested Seatbelt is unavailable");
return Ok(());
}
assert!(availability.status.success(), "{availability:?}");
let codex_home = TempDir::new()?;
let mut env: HashMap<String, String> = std::env::vars().collect();
env.insert(
"AKODE_HOME".to_string(),
codex_home.path().to_string_lossy().into_owned(),
);
// The control proves this is a readable, foreground controlling terminal on
// which TIOCSTI would otherwise work. All injected input stays in this PTY.
run_probe(
"/usr/bin/python3",
vec!["-c".to_string(), PROBE.to_string(), "allow".to_string()],
codex_home.path(),
&env,
)
.await?;
let codex = akode_utils_cargo_bin::cargo_bin("akode")?;
run_probe(
&codex.to_string_lossy(),
vec![
"sandbox".to_string(),
"-P".to_string(),
":read-only".to_string(),
"--".to_string(),
"/usr/bin/python3".to_string(),
"-c".to_string(),
PROBE.to_string(),
"deny".to_string(),
],
codex_home.path(),
&env,
)
.await
}
async fn run_probe(
program: &str,
args: Vec<String>,
cwd: &Path,
env: &HashMap<String, String>,
) -> anyhow::Result<()> {
let SpawnedProcess {
session,
mut stdout_rx,
exit_rx,
..
} = spawn_pty_process(
program,
&args,
cwd,
env,
/*arg0*/ &None,
TerminalSize::default(),
akode_utils_pty::ChildFds::Inherited(&[]),
)
.await?;
let mut output = Vec::new();
let mut sent_input = false;
let code = tokio::time::timeout(Duration::from_secs(30), async {
while let Some(bytes) = stdout_rx.recv().await {
output.extend_from_slice(&bytes);
if !sent_input && String::from_utf8_lossy(&output).contains("__ready__") {
session.writer_sender().send(b"k".to_vec()).await?;
sent_input = true;
}
}
Ok::<_, anyhow::Error>(exit_rx.await?)
})
.await
.context("terminal probe timed out")??;
let output = String::from_utf8_lossy(&output);
assert_eq!(code, 0, "terminal probe failed: {output}");
assert!(output.contains("__passed__"), "{output}");
Ok(())
}

View File

@@ -0,0 +1,39 @@
//! Exercises uninstall argument handling without performing machine-wide cleanup.
use anyhow::Result;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
#[test]
fn uninstall_help_and_invalid_arguments_preserve_user_data() -> Result<()> {
let home = TempDir::new()?;
// Uninstall must work independently of configuration parsing and authentication.
std::fs::write(home.path().join("config.toml"), "invalid config [")?;
std::fs::write(home.path().join("auth.json"), "preserve credentials")?;
let mut command = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
command
.env("AKODE_HOME", home.path())
.args(["sandbox", "uninstall", "--help"])
.assert()
.success();
let mut command = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
command
.env("AKODE_HOME", home.path())
.args(["sandbox", "uninstall", "unexpected"])
.assert()
.failure()
.stderr(contains("unexpected argument"));
assert_eq!(
std::fs::read_to_string(home.path().join("config.toml"))?,
"invalid config ["
);
assert_eq!(
std::fs::read_to_string(home.path().join("auth.json"))?,
"preserve credentials"
);
Ok(())
}

View File

@@ -0,0 +1,58 @@
---
source: cli/tests/daemon_startup.rs
expression: transition
---
Agent command center Group: Project g
All 0 Needs you 0 Working 0 Ready 0 Inactive 0 tab/shift+tab filter
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
No tasks yet │
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
│
? help ↑/↓ move enter open n new
--- Start a task ---
Folder access
[WORKSPACE]
Config, hooks, and exec policies from untrusted folders stay disabled. Trusted project folders can still contribute
settings. Skills still load, and tools follow your permission settings. Opening will not change saved trust.
› 1. Open restricted
2. Back to Agent Command Center
enter continue · esc back

View File

@@ -0,0 +1,6 @@
---
source: cli/tests/daemon_startup.rs
assertion_line: 325
expression: warning.trim()
---
⚠ Running without the shared background server: this Windows launcher requires embedded mode.

View File

@@ -0,0 +1,24 @@
---
source: cli/tests/doctor_enterprise_network.rs
expression: stdout
---
aKode Doctor v0.1.0
Notes
[XX] config config could not be loaded - Fix the reported config error, then rerun akode doctor.
-------------------------------------------------------------
Configuration
[XX] config config could not be loaded - Fix the reported config error, then rerun akode doctor.
feature flags 0 enabled · 0 overridden
error invalid configuration
file <AKODE_HOME>/config.toml
line 1
column 18
network diagnostics effective network configuration is unavailable
-------------------------------------------------------------
0 ok | 1 notes | 0 warn | 1 fail failed
--summary compact output --all expand truncated lists
--json redacted report

View File

@@ -0,0 +1,19 @@
---
source: cli/tests/doctor_enterprise_network.rs
expression: stdout
---
aKode Doctor v0.1.0
Configuration
[ok] config loaded
Connectivity
[ok] network network-related environment looks readable
[ok] websocket Responses WebSocket is not enabled for the active provider
[ok] reachability active provider endpoints are reachable over HTTP
-------------------------------------------------------------
4 ok | 0 warn | 0 fail ok
Run akode doctor without --summary for detailed diagnostics.
--all expand truncated lists --json redacted report

View File

@@ -0,0 +1,17 @@
---
source: cli/tests/doctor_path_safety.rs
expression: "serde_json::to_string_pretty(&check)?"
---
{
"category": "config",
"details": {
"column": "42",
"error": "invalid configuration",
"file": "FIXTURE/home/config.toml",
"line": "1"
},
"id": "config.load",
"remediation": "Fix the reported config error, then rerun akode doctor.",
"status": "fail",
"summary": "config could not be loaded"
}

View File

@@ -0,0 +1,14 @@
---
source: cli/tests/doctor_path_safety.rs
expression: "serde_json::to_string_pretty(&check)?"
---
{
"category": "config",
"details": {
"error": "invalid data"
},
"id": "config.load",
"remediation": "Fix the reported config error, then rerun akode doctor.",
"status": "fail",
"summary": "config could not be loaded"
}

View File

@@ -0,0 +1,17 @@
---
source: cli/tests/doctor_path_safety.rs
expression: "serde_json::to_string_pretty(&check)?"
---
{
"category": "config",
"details": {
"column": "16",
"error": "invalid configuration",
"file": "FIXTURE/home/config.toml",
"line": "9"
},
"id": "config.load",
"remediation": "Fix the reported config error, then rerun akode doctor.",
"status": "fail",
"summary": "config could not be loaded"
}

View File

@@ -0,0 +1,14 @@
---
source: cli/tests/doctor_path_safety.rs
expression: "serde_json::to_string_pretty(&check)?"
---
{
"category": "config",
"details": {
"error": "entity not found"
},
"id": "config.load",
"remediation": "Fix the reported config error, then rerun akode doctor.",
"status": "fail",
"summary": "config could not be loaded"
}

View File

@@ -0,0 +1,14 @@
---
source: cli/tests/doctor_path_safety.rs
expression: "serde_json::to_string_pretty(&details)?"
---
{
"operation": "resolve paths only; read/write access is not tested",
"path 1": "FIXTURE/workspace/probe-existing (read); path resolved (read/write access not tested)",
"path 1 source": "permissions.diagnostic.filesystem.FIXTURE/workspace/probe-existing in user (FIXTURE/home/config.toml)",
"path 2": "FIXTURE/workspace/probe-missing (write); missing (may be intentional)",
"path 2 source": "permissions.diagnostic.filesystem.FIXTURE/workspace/probe-missing in user (FIXTURE/home/config.toml)",
"paths checked": "2 of 2",
"permission profile": "diagnostic",
"probe budgets": "2 seconds per path, 8 seconds total, at most 32 paths"
}

View File

@@ -0,0 +1,14 @@
---
source: cli/tests/doctor_path_safety.rs
expression: "serde_json::to_string_pretty(&details)?"
---
{
"operation": "resolve paths only; read/write access is not tested",
"path 1": "FIXTURE/workspace/probe-existing (read); not probed on Windows (network authentication risk)",
"path 1 source": "permissions.diagnostic.filesystem.FIXTURE/workspace/probe-existing in user (FIXTURE/home/config.toml)",
"path 2": "FIXTURE/workspace/probe-missing (write); not probed on Windows (network authentication risk)",
"path 2 source": "permissions.diagnostic.filesystem.FIXTURE/workspace/probe-missing in user (FIXTURE/home/config.toml)",
"paths checked": "2 of 2",
"permission profile": "diagnostic",
"probe budgets": "2 seconds per path, 8 seconds total, at most 32 paths"
}

View File

@@ -0,0 +1,6 @@
---
source: cli/tests/doctor_path_safety.rs
expression: state_row
---
[XX] state FIXTURE/sqlite/logs_2.sqlite database failed integrity check
-> Move the damaged SQLite database aside, then restart the interactive CLI or app server so it can rebuild that runtime database from saved data. Other entry points may not rebuild automatically.

View File

@@ -0,0 +1,6 @@
---
source: cli/tests/doctor_path_safety.rs
expression: state_row
---
[XX] state FIXTURE/sqlite/logs_2.sqlite, FIXTURE/sqlite/goals_1.sqlite databases failed integrity check
-> Move the damaged SQLite database aside, then restart the interactive CLI or app server so it can rebuild that runtime database from saved data. Other entry points may not rebuild automatically.

View File

@@ -0,0 +1,12 @@
---
source: cli/tests/features.rs
expression: output
---
Error: failed to load configuration
Caused by:
0: [AKODE_HOME]/config.toml:<line>:<column>: unknown key `backslash` in keybinding `backslash`. Use a printable character (for example `a`), function keys (`f1`-`f24`), or one of: enter, tab, backspace, esc, delete, arrows, home/end, page-up/page-down, space, minus.
See the Codex keymap documentation for supported actions and examples.
1: unknown key `backslash` in keybinding `backslash`. Use a printable character (for example `a`), function keys (`f1`-`f24`), or one of: enter, tab, backspace, esc, delete, arrows, home/end, page-up/page-down, space, minus.
See the Codex keymap documentation for supported actions and examples.
in `tui.keymap.editor.insert_newline`

View File

@@ -0,0 +1,5 @@
---
source: cli/tests/features.rs
expression: "String::from_utf8(output)?"
---
Error: --add-dir is not supported with --remote. Configure additional workspace roots on the server.

View File

@@ -0,0 +1,24 @@
use anyhow::Result;
use predicates::str::contains;
use std::path::Path;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
Ok(cmd)
}
#[cfg(debug_assertions)]
#[tokio::test]
async fn update_does_not_start_interactive_prompt() -> Result<()> {
let codex_home = TempDir::new()?;
codex_command(codex_home.path())?
.arg("update")
.assert()
.failure()
.stderr(contains("`akode update` is not available in debug builds"));
Ok(())
}

View File

@@ -0,0 +1,740 @@
//! Exercises interactive destination policy, startup and fork, and ownership before the first turn.
use anyhow::Context as _;
use pretty_assertions::assert_eq;
use serde_json::Value;
use std::collections::HashMap;
use std::fs;
use std::io::Write as _;
use std::path::Path;
use std::process::Command;
use std::time::Duration;
#[cfg(not(unix))]
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
fn git(cwd: &Path, args: &[&str]) -> anyhow::Result<String> {
let output = Command::new("git")
.current_dir(cwd)
.args([
"-c",
"user.name=Worktree Test",
"-c",
"user.email=test@example.invalid",
])
.args(args)
.output()?;
anyhow::ensure!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
Ok(String::from_utf8(output.stdout)?.trim().to_owned())
}
// Retain only the unfinished terminal query, never the full output stream.
#[derive(Default)]
struct TerminalQueries(Vec<u8>);
impl TerminalQueries {
fn feed(&mut self, bytes: &[u8]) -> Vec<u8> {
let mut replies = Vec::new();
for &byte in bytes {
self.0.push(byte);
if self.0 == b"\x1b[6n" {
replies.extend_from_slice(b"\x1b[1;1R");
self.0.clear();
} else if self.0 == b"\x1b[c" {
replies.extend_from_slice(b"\x1b[?1;2c");
self.0.clear();
} else {
while !b"\x1b[6n".starts_with(&self.0) && !b"\x1b[c".starts_with(&self.0) {
self.0.remove(0);
}
}
}
replies
}
}
#[test]
fn terminal_queries_reply_once_across_every_split() {
let input = b"noise\x1b[6n\x1b[c\x1b[6n";
let expected = b"\x1b[1;1R\x1b[?1;2c\x1b[1;1R";
for split in 0..=input.len() {
let mut queries = TerminalQueries::default();
let mut replies = queries.feed(&input[..split]);
replies.extend(queries.feed(&input[split..]));
assert_eq!(replies, expected);
assert_eq!(queries.feed(b"more output"), Vec::<u8>::new());
}
}
async fn rejected_start(
program: &Path,
args: &[String],
cwd: &Path,
env: &HashMap<String, String>,
expected: &str,
) -> anyhow::Result<String> {
let spawned = akode_utils_pty::spawn_pty_process(
&program.to_string_lossy(),
args,
cwd,
env,
/*arg0*/ &None,
akode_utils_pty::TerminalSize {
rows: 40,
cols: 120,
},
akode_utils_pty::ChildFds::Inherited(&[]),
)
.await?;
let mut stdout = spawned.stdout_rx;
let mut exit = spawned.exit_rx;
let mut output = String::new();
let mut queries = TerminalQueries::default();
let result = tokio::time::timeout(Duration::from_secs(/*secs*/ 45), async {
loop {
tokio::select! {
status = &mut exit, if output.contains(expected) => return Ok::<_, anyhow::Error>(status?),
bytes = stdout.recv() => {
let Some(bytes) = bytes else {
anyhow::ensure!(output.contains(expected), "TUI exited before rejection: {output}");
return Ok(exit.await?);
};
output.push_str(&String::from_utf8_lossy(&bytes));
let replies = queries.feed(&bytes);
if !replies.is_empty() { spawned.session.writer_sender().send(replies).await?; }
}
}
}
}).await;
if !matches!(&result, Ok(Ok(code)) if *code != 0) {
let _ = writeln!(
std::io::stderr(),
"worktree rejection failed (timeout={}): expected {:?}; output prefix: {:?}",
result.is_err(),
expected.chars().take(/*n*/ 200).collect::<String>(),
output.chars().take(/*n*/ 4000).collect::<String>()
);
}
if result.is_err() {
spawned.session.terminate();
}
assert_ne!(
result.with_context(|| format!("rejection timed out: {output}"))??,
0,
"{output}"
);
Ok(output)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn interactive_worktree_start_and_fork_bind_owner_before_turn() -> anyhow::Result<()> {
worktree_start_and_fork("embedded").await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(
windows,
ignore = "requires a non-elevated terminal with daemon breakaway support"
)]
async fn daemon_worktree_start_and_fork_bind_owner_before_turn() -> anyhow::Result<()> {
worktree_start_and_fork("daemon").await
}
async fn worktree_start_and_fork(backend: &str) -> anyhow::Result<()> {
// Leave room for the local control socket on Unix platforms with short sun_path limits.
#[cfg(unix)]
let root = tempfile::Builder::new().tempdir_in("/tmp")?;
#[cfg(not(unix))]
let root = TempDir::new()?;
let root = akode_utils_absolute_path::AbsolutePathBuf::from_absolute_path(root.path())?
.canonicalize()?
.into_path_buf();
let home = root.join("home");
let source = root.join("source");
let launcher = root.join("launcher");
for path in [&home, &source, &launcher, &launcher.join("extra")] {
fs::create_dir(path)?;
}
// Forking without --cd must select the daemon using the resolved project, not this launcher.
fs::create_dir(launcher.join(".akode"))?;
fs::write(
launcher.join(".akode/config.toml"),
"features.auth_elicitation = false\n",
)?;
fs::write(
source.join("AGENTS.md"),
"committed destination instructions",
)?;
let server = MockServer::start().await;
fs::create_dir(source.join(".akode"))?;
fs::write(
source.join(".akode/config.toml"),
"model = \"destination-model\"\ncli_auth_credentials_store = \"file\"\n",
)?;
git(&source, &["init", "--quiet"])?;
git(&source, &["add", "."])?;
git(
&source,
&["commit", "--quiet", "--no-gpg-sign", "-m", "initial"],
)?;
fs::write(
home.join("config.toml"),
format!(
r#"
cli_auth_credentials_store = "file"
chatgpt_base_url = "{}/source/backend-api"
check_for_update_on_startup = false
features.daemon_auto_start = {}
features.mcp_oauth_refresh_coordination = true
model_provider = "local"
model = "test-model"
sandbox_mode = "workspace-write"
windows.sandbox = "unelevated"
tui.disable_paste_burst = true
[otel]
metrics_exporter = "none"
[model_providers.local]
name = "local test"
base_url = "{}/v1"
wire_api = "responses"
[projects.{}]
trust_level = "trusted"
[projects.{}]
trust_level = "trusted"
"#,
server.uri(),
backend == "daemon",
server.uri(),
serde_json::to_string(&source)?,
serde_json::to_string(&launcher)?
),
)?;
fs::write(
source.join("AGENTS.md"),
"uncommitted launcher instructions",
)?;
fs::write(
source.join(".akode/config.toml"),
"model = \"source-model\"\n",
)?;
akode_login::login_with_api_key(
&home,
"sk-test-token",
akode_config::types::AuthCredentialsStoreMode::File,
akode_login::AuthKeyringBackendKind::default(),
)?;
let program = akode_utils_cargo_bin::cargo_bin("akode")?;
// Keep cold Rosetta translation outside the timed startup assertions.
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
anyhow::ensure!(
Command::new(&program)
.env("AKODE_HOME", &home)
.arg("--version")
.output()?
.status
.success(),
"failed to prepare CLI test executable"
);
let mut env: HashMap<String, String> = std::env::vars().collect();
env.insert("AKODE_HOME".into(), home.display().to_string());
env.insert("AKODE_SQLITE_HOME".into(), home.display().to_string());
env.insert("NO_PROXY".into(), "127.0.0.1,localhost".into());
env.insert("no_proxy".into(), "127.0.0.1,localhost".into());
env.insert("TERM".into(), "xterm-256color".into());
env.insert("TERM_PROGRAM".into(), "unrecognized-terminal".into());
for key in [
"AKODE_EXEC_SERVER_URL",
"AKODE_ACCESS_TOKEN",
"OPENAI_API_KEY",
"AKODE_API_KEY",
"TMUX",
"TMUX_PANE",
"ZELLIJ",
"ZELLIJ_SESSION_NAME",
"ZELLIJ_VERSION",
] {
env.remove(key);
}
// Keep the managed package local; no installer or updater participates in this test.
struct StopDaemon(Command);
impl Drop for StopDaemon {
fn drop(&mut self) {
let _ = self.0.output();
}
}
let _daemon = if backend == "daemon" {
let bin = home.join("packages/app-server-daemon/current/bin");
fs::create_dir_all(&bin)?;
let managed = bin.join(if cfg!(windows) { "akode.exe" } else { "codex" });
// Hard links change the executable's ctime and invalidate Rosetta's translation cache.
#[cfg(unix)]
std::os::unix::fs::symlink(program.canonicalize()?, &managed)?;
#[cfg(not(unix))]
fs::hard_link(&program, &managed)
.or_else(|_| akode_utils_cargo_bin::copy_executable(&program, &managed))?;
fs::create_dir(home.join("app-server-daemon"))?;
fs::write(
home.join("app-server-daemon/settings.json"),
r#"{"shutdownGraceSeconds":0,"updater":{"autoUpdateEnabled":false}}"#,
)?;
let mut daemon_stop = Command::new(&program);
daemon_stop
.envs(&env)
.args(["app-server", "daemon", "stop"]);
Some(StopDaemon(daemon_stop))
} else {
None
};
// Every launch, including rejection cases, exercises the same CLI feature opt-in.
let worktree_args: Vec<String> = vec![
"--worktree".into(),
"--enable".into(),
"worktrees".into(),
"--no-alt-screen".into(),
"-c".into(),
"suppress_unstable_features_warning=true".into(),
];
let mut owner = None;
let mut previous: Vec<String> = Vec::new();
let prompt = "describe checkout";
for (fork, explicit_cd, auth_failure) in [
(false, false, false),
(true, false, false),
(true, true, false),
(false, false, true),
] {
if auth_failure {
fs::write(
source.join(".akode/config.toml"),
// The stored API key satisfies `api`; require a login method it cannot satisfy.
"forced_login_method = \"chatgpt\"\n",
)?;
git(
&source,
&[
"commit",
"--quiet",
"--no-gpg-sign",
"-am",
"require API login",
],
)?;
fs::write(source.join(".akode/config.toml"), "")?;
}
Mock::given(wiremock::matchers::path("/metrics"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
.mount(&server)
.await;
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let response = app_test_support::create_final_assistant_message_sse_response("done")?;
let observed_source = source.clone();
let observed_pool = home.join("worktrees");
let observed_previous = previous.clone();
Mock::given(wiremock::matchers::method("POST"))
.and(wiremock::matchers::path("/v1/responses"))
.respond_with(move |request: &wiremock::Request| {
let observed = (|| {
let checkouts = git(&observed_source, &["worktree", "list", "--porcelain"])?;
let checkout = checkouts
.lines()
.filter_map(|line| line.strip_prefix("worktree "))
.find(|path| {
Path::new(path).starts_with(&observed_pool)
&& !observed_previous.contains(&path.to_string())
})
.context("new managed checkout")?
.to_owned();
let metadata = git(
Path::new(&checkout),
&["rev-parse", "--git-path", "codex-thread.json"],
)?;
let metadata: Value =
serde_json::from_slice(&fs::read(Path::new(&checkout).join(metadata))?)?;
Ok::<_, anyhow::Error>((request.body.clone(), checkout, metadata))
})();
let _ = tx.send(observed);
ResponseTemplate::new(200)
.insert_header("content-type", "text/event-stream")
.set_body_string(response.clone())
})
.mount(&server)
.await;
let mut args = worktree_args.clone();
if backend == "daemon" && previous.is_empty() {
args.extend(["-c".into(), "features.auth_elicitation=true".into()]);
}
if fork {
args.extend([
"--add-dir".into(),
"extra".into(),
"fork".into(),
if explicit_cd {
owner.clone().context("previous fork owner")?
} else {
"managed-source".to_owned()
},
]);
} else {
args.extend(["--cd".into(), source.display().to_string()]);
}
if explicit_cd {
args.extend(["--cd".into(), source.join(".akode").display().to_string()]);
}
args.push(prompt.into());
if previous.is_empty() {
let mut untrusted_args = args.clone();
untrusted_args.extend([
"-c".into(),
format!(
"projects={{{}={{trust_level=\"untrusted\"}}}}",
serde_json::to_string(&source)?
),
]);
rejected_start(
&program,
&untrusted_args,
&launcher,
&env,
"cannot create a checkout from an explicitly untrusted source",
)
.await?;
assert!(!home.join("worktrees").exists());
}
let spawned = akode_utils_pty::spawn_pty_process(
&program.to_string_lossy(),
&args,
&launcher,
&env,
/*arg0*/ &None,
akode_utils_pty::TerminalSize {
rows: 40,
cols: 120,
},
akode_utils_pty::ChildFds::Inherited(&[]),
)
.await?;
let session = spawned.session;
let mut stdout = spawned.stdout_rx;
let mut output = String::new();
let mut queries = TerminalQueries::default();
let observed = tokio::time::timeout(Duration::from_secs(/*secs*/ 45), async {
loop {
tokio::select! {
body = rx.recv() => {
let (body, checkout, metadata) = body.context("model request")??;
let body: Value = serde_json::from_slice(&body)?;
// Background title generation can reach the model before the user turn.
let is_user_turn = body["input"].as_array().is_some_and(|input| {
input.iter().any(|item| {
item["role"] == "user"
&& item["content"].as_array().is_some_and(|content| {
content.iter().any(|part| part["text"] == prompt)
})
})
});
if !is_user_turn {
continue;
}
return Ok::<_, anyhow::Error>((body, checkout, metadata));
}
bytes = stdout.recv() => {
let bytes = bytes.context("TUI exited before model request")?;
let text = String::from_utf8_lossy(&bytes);
output.push_str(&text);
if auth_failure && output.contains("API key login is not permitted") && output.contains("Do not use --force.") {
anyhow::bail!("observed required API login rejection");
}
let replies = queries.feed(&bytes);
if !replies.is_empty() { session.writer_sender().send(replies).await?; }
}
}
}
}).await;
if auth_failure {
assert!(observed.is_ok_and(|result| result.is_err()), "{output}");
let exit =
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), spawned.exit_rx).await??;
assert_ne!(exit, 0);
assert!(
output.contains("API key login is not permitted"),
"{output}"
);
assert!(!home.join("auth.json").exists());
assert!(output.contains("The checkout was kept"), "{output}");
continue;
}
let renamed = if !fork && let Ok(Ok((_, _, metadata))) = &observed {
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), async {
session
.writer_sender()
.send(b"/rename managed-source\r".to_vec())
.await?;
let thread_id = akode_protocol::ThreadId::from_string(
metadata["ownerThreadId"].as_str().context("owner id")?,
)?;
loop {
if akode_rollout::find_thread_name_by_id(&home, &thread_id)
.await?
.as_deref()
== Some("managed-source")
{
return Ok::<_, anyhow::Error>(());
}
tokio::select! {
bytes = stdout.recv() => {
let bytes = bytes.context("TUI exited before rename confirmation")?;
output.push_str(&String::from_utf8_lossy(&bytes));
let replies = queries.feed(&bytes);
if !replies.is_empty() { session.writer_sender().send(replies).await?; }
}
_ = tokio::time::sleep(Duration::from_millis(/*millis*/ 25)) => {}
}
}
})
.await
.context("rename timed out")
.and_then(std::convert::identity)
} else {
Ok(())
};
if backend == "daemon" && matches!(observed, Ok(Ok(_))) {
session.writer_sender().send(b"/status\r".to_vec()).await?;
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), async {
while !output.contains("Local background server") {
let bytes = stdout
.recv()
.await
.context("TUI exited before daemon status")?;
output.push_str(&String::from_utf8_lossy(&bytes));
let replies = queries.feed(&bytes);
if !replies.is_empty() {
session.writer_sender().send(replies).await?;
}
}
Ok::<_, anyhow::Error>(())
})
.await
.with_context(|| format!("daemon status timed out: {output}"))??;
}
let startup_result = observed.as_ref().map(|result| result.as_ref().map(|_| ()));
assert!(
!output.contains("Under-development features enabled:"),
"{output}"
);
if !matches!(startup_result, Ok(Ok(()))) || renamed.is_err() {
// Bypass libtest capture and report before tearing down the Windows PTY.
let _ = writeln!(
std::io::stderr(),
"worktree failure (fork={fork}, explicit_cd={explicit_cd}): startup={startup_result:?}, rename={renamed:?}\nTUI output: {:?}",
output.chars().take(/*n*/ 4000).collect::<String>()
);
}
if matches!(startup_result, Ok(Ok(()))) && renamed.is_ok() {
if !fork && backend == "embedded" {
for (input, expected) in [
("/daemon\r", "Install latest public stable"),
("\r", "Update and exit"),
("\x1b[B\r", "Updating the local background server..."),
] {
session
.writer_sender()
.send(input.as_bytes().to_vec())
.await?;
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), async {
while !output.contains(expected) {
let bytes = stdout.recv().await.context("TUI exited before handoff")?;
output.push_str(&String::from_utf8_lossy(&bytes));
}
Ok::<_, anyhow::Error>(())
})
.await
.with_context(|| format!("waiting for {expected}: {output}"))??;
}
} else {
session.writer_sender().send(b"/quit\r".to_vec()).await?;
}
} else {
session.terminate();
}
let exit =
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), spawned.exit_rx).await??;
// Include shutdown output: ConPTY can retain the channel after process exit.
let _ = tokio::time::timeout(Duration::from_secs(/*secs*/ 1), async {
while let Some(bytes) = stdout.recv().await {
output.push_str(&String::from_utf8_lossy(&bytes));
}
})
.await;
let elevated_handoff = cfg!(windows)
&& output.contains("start the Windows daemon from a non-elevated terminal");
assert_eq!(exit, i32::from(elevated_handoff), "{output}");
assert!(!output.contains("The checkout was kept"), "{output}");
let metrics = server
.received_requests()
.await
.context("requests")?
.into_iter()
.filter(|request| request.url.path() == "/metrics")
.map(|request| serde_json::from_slice::<Value>(&request.body))
.collect::<serde_json::Result<Vec<_>>>()?;
assert!(metrics.is_empty(), "no telemetry may be exported");
let (body, checkout, metadata) = observed
.with_context(|| {
format!(
"startup timed out: {}",
output.chars().take(/*n*/ 4000).collect::<String>()
)
})?
.with_context(|| {
format!(
"startup output: {}",
output.chars().take(/*n*/ 4000).collect::<String>()
)
})?;
renamed.with_context(|| {
format!(
"rename output: {}",
output.chars().take(/*n*/ 4000).collect::<String>()
)
})?;
let next_owner = metadata["ownerThreadId"]
.as_str()
.context("owner bound before request")?
.to_owned();
assert_ne!(owner.as_ref(), Some(&next_owner));
assert_eq!(
git(Path::new(&checkout), &["show", "HEAD:AGENTS.md"])?,
"committed destination instructions"
);
let context = body["input"]
.as_array()
.context("message input")?
.iter()
.filter_map(|item| item["content"].as_array())
.flatten()
.filter_map(|part| part["text"].as_str())
.collect::<Vec<_>>()
.join("\n");
if explicit_cd {
let expected = format!("{checkout}/.akode").replace('\\', "/");
assert!(context.replace('\\', "/").contains(&expected), "{context}");
}
assert!(
context.contains("committed destination instructions"),
"{context}"
);
assert!(
!context.contains("uncommitted launcher instructions"),
"{context}"
);
if fork {
assert!(
context.contains(&launcher.join("extra").display().to_string()),
"{context}"
);
}
assert_eq!(body["model"], "destination-model");
// Managed cloud configuration (ChatGPT config bundles) was removed in aKode.
if previous.is_empty() {
// A legacy summary still says launcher A, but persisted turns use checkout B.
let sqlite = akode_state::SqliteConfig::new_for_testing(
akode_utils_absolute_path::AbsolutePathBuf::from_absolute_path(&home)?,
);
let db = sqlite.open_read_write_pool(&sqlite.state_db_path()).await?;
sqlx::query("UPDATE threads SET cwd = ? WHERE id = ?")
.bind(launcher.to_string_lossy().as_ref())
.bind(&next_owner)
.execute(&db)
.await?;
db.close().await;
// B inherits trust from its primary repository; an explicit distrust entry for B
// (formerly delivered by a managed cloud bundle, now a config override) still
// rejects the fork before any checkout is created.
let before = git(&source, &["worktree", "list", "--porcelain"])?;
rejected_start(
&program,
&[
"--worktree".into(),
"--enable".into(),
"worktrees".into(),
"--no-alt-screen".into(),
"-c".into(),
format!(
"projects={{{}={{trust_level=\"untrusted\"}}}}",
serde_json::to_string(&akode_config::loader::project_trust_key(
Path::new(&checkout)
))?
),
"fork".into(),
next_owner.clone(),
],
&launcher,
&env,
"cannot create a checkout from an explicitly untrusted source",
)
.await?;
assert_eq!(git(&source, &["worktree", "list", "--porcelain"])?, before);
}
previous.push(checkout);
owner = Some(next_owner);
server.reset().await;
}
// Source loads its healthy uncommitted config, but the new checkout loads malformed HEAD.
fs::write(source.join(".akode/config.toml"), "not = [valid toml")?;
git(
&source,
&[
"commit",
"--quiet",
"--no-gpg-sign",
"-am",
"invalid destination",
],
)?;
fs::write(source.join(".akode/config.toml"), "")?;
let before = git(&source, &["worktree", "list", "--porcelain"])?;
let output = rejected_start(
&program,
&[
"--worktree".into(),
"--enable".into(),
"worktrees".into(),
"--no-alt-screen".into(),
"--cd".into(),
source.display().to_string(),
],
&launcher,
&env,
"Do not use --force.",
)
.await?;
let after = git(&source, &["worktree", "list", "--porcelain"])?;
let retained = after
.lines()
.filter_map(|line| line.strip_prefix("worktree "))
.find(|path| {
!before
.lines()
.any(|line| line.strip_prefix("worktree ") == Some(*path))
})
.context("retained failed checkout")?;
assert!(
output.contains(&format!(
"{:?}",
Path::new(&retained.replace('/', std::path::MAIN_SEPARATOR_STR))
)),
"{output}"
);
assert!(output.contains("The checkout was kept"), "{output}");
assert!(
output.contains("worktree remove <checkout-path>"),
"{output}"
);
Ok(())
}