Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

11
codex-rs/exec/BUILD.bazel Normal file
View File

@@ -0,0 +1,11 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "exec",
crate_name = "codex_exec",
integration_compile_data_extra = ["tests/fixtures/apply_patch_freeform_final.txt"],
test_shard_counts = {
"exec-all-test": 8,
},
test_tags = ["no-sandbox"],
)

86
codex-rs/exec/Cargo.toml Normal file
View File

@@ -0,0 +1,86 @@
[package]
name = "codex-exec"
version.workspace = true
edition.workspace = true
license.workspace = true
autotests = false
[[bin]]
name = "codex-exec"
path = "src/main.rs"
[lib]
name = "codex_exec"
path = "src/lib.rs"
doctest = false
[[test]]
name = "all"
path = "tests/all.rs"
[lints]
workspace = true
[dependencies]
anyhow = { workspace = true }
clap = { workspace = true, features = ["derive"] }
codex-arg0 = { workspace = true }
codex-app-server-client = { workspace = true }
codex-app-server-protocol = { workspace = true }
codex-cloud-config = { workspace = true }
codex-config = { workspace = true }
codex-core = { workspace = true }
codex-exec-server = { workspace = true }
codex-features = { workspace = true }
codex-feedback = { workspace = true }
codex-git-utils = { workspace = true }
codex-history = { workspace = true }
codex-login = { workspace = true }
codex-model-provider-info = { workspace = true }
codex-otel = { workspace = true }
codex-protocol = { workspace = true }
codex-rollout = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-cli = { workspace = true }
codex-utils-oss = { workspace = true }
codex-utils-path-uri = { workspace = true }
codex-utils-sandbox-summary = { workspace = true }
codex-worktree = { workspace = true }
owo-colors = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
supports-color = { workspace = true }
tokio = { workspace = true, features = [
"io-std",
"macros",
"process",
"rt-multi-thread",
"signal",
] }
tracing = { workspace = true, features = ["log"] }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
ts-rs = { workspace = true, features = [
"uuid-impl",
"serde-json-impl",
"no-serde-warnings",
] }
uuid = { workspace = true }
[dev-dependencies]
assert_cmd = { workspace = true }
codex-apply-patch = { workspace = true }
codex-utils-cargo-bin = { workspace = true }
core_test_support = { workspace = true }
insta = { workspace = true }
libc = { workspace = true }
opentelemetry = { workspace = true }
opentelemetry_sdk = { workspace = true }
predicates = { workspace = true }
pretty_assertions = { workspace = true }
tempfile = { workspace = true }
tracing-opentelemetry = { workspace = true }
uuid = { workspace = true }
walkdir = { workspace = true }
wiremock = { workspace = true }
zstd = { workspace = true }

347
codex-rs/exec/src/cli.rs Normal file
View File

@@ -0,0 +1,347 @@
use clap::Args;
use clap::FromArgMatches;
use clap::Parser;
use clap::ValueEnum;
use codex_protocol::protocol::ThreadSource;
use codex_utils_cli::CliConfigOverrides;
use codex_utils_cli::SharedCliOptions;
use std::path::PathBuf;
#[derive(Parser, Debug)]
#[command(
version,
override_usage = "codex exec [OPTIONS] [PROMPT]\n codex exec [OPTIONS] <COMMAND> [ARGS]"
)]
pub struct Cli {
/// Action to perform. If omitted, runs a new non-interactive session.
#[command(subcommand)]
pub command: Option<Command>,
/// Error out when config.toml contains fields that are not recognized by this version of Codex.
#[arg(long = "strict-config", global = true, default_value_t = false)]
pub strict_config: bool,
#[clap(flatten)]
pub shared: ExecSharedCliOptions,
/// Source classification for newly created or forked threads.
#[arg(long = "thread-source", value_name = "SOURCE", global = true)]
pub thread_source: Option<ThreadSource>,
/// Request an experimental Cyber access program for this turn (OpenAI provider only).
/// Omit to use server defaults. Not supported with review; fork requires a prompt.
#[arg(long, value_enum, value_name = "PROGRAM", global = true)]
pub cyber_access_program: Option<CyberAccessProgramCliArg>,
/// Allow running Codex outside a Git repository.
#[arg(long = "skip-git-repo-check", global = true, default_value_t = false)]
pub skip_git_repo_check: bool,
/// Save trust for this project and future chats, including MCP commands outside the sandbox.
/// Persists even with --ephemeral. Does not override an explicitly untrusted project.
#[arg(long, global = true)]
pub trust: bool,
/// Run without persisting session files to disk.
#[arg(long = "ephemeral", global = true, default_value_t = false)]
pub ephemeral: bool,
/// Do not load `$CODEX_HOME/config.toml`; auth still uses `CODEX_HOME`.
#[arg(long = "ignore-user-config", global = true, default_value_t = false)]
pub ignore_user_config: bool,
/// Do not load user or project execpolicy `.rules` files.
#[arg(long = "ignore-rules", global = true, default_value_t = false)]
pub ignore_rules: bool,
/// Path to a JSON Schema file describing the model's final response shape.
#[arg(long = "output-schema", value_name = "FILE", global = true)]
pub output_schema: Option<PathBuf>,
#[clap(skip)]
pub config_overrides: CliConfigOverrides,
/// Specifies color settings for use in the output.
#[arg(long = "color", value_enum, default_value_t = Color::Auto)]
pub color: Color,
/// Print events to stdout as JSONL.
#[arg(
long = "json",
alias = "experimental-json",
default_value_t = false,
global = true
)]
pub json: bool,
/// Specifies file where the last message from the agent should be written.
#[arg(
long = "output-last-message",
short = 'o',
value_name = "FILE",
global = true
)]
pub last_message_file: Option<PathBuf>,
/// Initial instructions for the agent. If not provided as an argument (or
/// if `-` is used), instructions are read from stdin. If stdin is piped and
/// a prompt is also provided, stdin is appended as a `<stdin>` block.
#[arg(value_name = "PROMPT", value_hint = clap::ValueHint::Other)]
pub prompt: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[value(rename_all = "snake_case")]
pub enum CyberAccessProgramCliArg {
Standard,
DaybreakBlue,
DaybreakRed,
}
impl From<CyberAccessProgramCliArg> for codex_app_server_protocol::CyberAccessProgram {
fn from(value: CyberAccessProgramCliArg) -> Self {
match value {
CyberAccessProgramCliArg::Standard => Self::Standard,
CyberAccessProgramCliArg::DaybreakBlue => Self::DaybreakBlue,
CyberAccessProgramCliArg::DaybreakRed => Self::DaybreakRed,
}
}
}
impl std::ops::Deref for Cli {
type Target = SharedCliOptions;
fn deref(&self) -> &Self::Target {
&self.shared.0
}
}
impl std::ops::DerefMut for Cli {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.shared.0
}
}
#[derive(Debug, Default)]
pub struct ExecSharedCliOptions(SharedCliOptions);
impl ExecSharedCliOptions {
pub fn into_inner(self) -> SharedCliOptions {
self.0
}
}
impl std::ops::Deref for ExecSharedCliOptions {
type Target = SharedCliOptions;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for ExecSharedCliOptions {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl Args for ExecSharedCliOptions {
fn augment_args(cmd: clap::Command) -> clap::Command {
mark_exec_global_args(SharedCliOptions::augment_args(cmd))
}
fn augment_args_for_update(cmd: clap::Command) -> clap::Command {
mark_exec_global_args(SharedCliOptions::augment_args_for_update(cmd))
}
}
impl FromArgMatches for ExecSharedCliOptions {
fn from_arg_matches(matches: &clap::ArgMatches) -> Result<Self, clap::Error> {
SharedCliOptions::from_arg_matches(matches).map(Self)
}
fn update_from_arg_matches(&mut self, matches: &clap::ArgMatches) -> Result<(), clap::Error> {
self.0.update_from_arg_matches(matches)
}
}
fn mark_exec_global_args(cmd: clap::Command) -> clap::Command {
cmd.mut_arg("model", |arg| arg.global(true))
.mut_arg("dangerously_bypass_approvals_and_sandbox", |arg| {
arg.global(true)
})
.mut_arg("bypass_hook_trust", |arg| arg.global(true))
.mut_arg("worktree", |arg| arg.global(true))
}
#[derive(Debug, clap::Subcommand)]
pub enum Command {
/// Resume a previous session by id or pick the most recent with --last.
Resume(ResumeArgs),
/// Fork a previous session by id into a new session.
Fork(ForkArgs),
/// Run a code review against the current repository.
Review(ReviewArgs),
}
#[derive(Args, Debug)]
pub struct ForkArgs {
/// Conversation/session id (UUID) or thread name to fork.
#[arg(value_name = "SESSION_ID")]
pub session_id: String,
/// Optional image(s) to attach to the prompt sent after forking.
#[arg(
long = "image",
short = 'i',
value_name = "FILE",
value_delimiter = ',',
num_args = 1
)]
pub images: Vec<PathBuf>,
/// Optional prompt to send after forking. If `-` is used, read from stdin.
#[arg(value_name = "PROMPT", value_hint = clap::ValueHint::Other)]
pub prompt: Option<String>,
}
#[derive(Args, Debug)]
struct ResumeArgsRaw {
// Note: This is the direct clap shape. We reinterpret the positional when --last is set
// so "codex resume --last <prompt>" treats the positional as a prompt, not a session id.
/// Conversation/session id (UUID) or thread name. UUIDs take precedence if it parses.
/// If omitted, use --last to pick the most recent recorded session.
#[arg(value_name = "SESSION_ID")]
session_id: Option<String>,
/// Resume the most recent recorded session (newest) without specifying an id.
#[arg(long = "last", default_value_t = false)]
last: bool,
/// Show all sessions (disables cwd filtering).
#[arg(long = "all", default_value_t = false)]
all: bool,
/// Optional image(s) to attach to the prompt sent after resuming.
#[arg(
long = "image",
short = 'i',
value_name = "FILE",
value_delimiter = ',',
num_args = 1
)]
images: Vec<PathBuf>,
/// Prompt to send after resuming the session. If `-` is used, read from stdin.
#[arg(value_name = "PROMPT", value_hint = clap::ValueHint::Other)]
prompt: Option<String>,
}
#[derive(Debug)]
pub struct ResumeArgs {
/// Conversation/session id (UUID) or thread name. UUIDs take precedence if it parses.
/// If omitted, use --last to pick the most recent recorded session.
pub session_id: Option<String>,
/// Resume the most recent recorded session (newest) without specifying an id.
pub last: bool,
/// Show all sessions (disables cwd filtering).
pub all: bool,
/// Optional image(s) to attach to the prompt sent after resuming.
pub images: Vec<PathBuf>,
/// Prompt to send after resuming the session. If `-` is used, read from stdin.
pub prompt: Option<String>,
}
impl From<ResumeArgsRaw> for ResumeArgs {
fn from(raw: ResumeArgsRaw) -> Self {
// When --last is used without an explicit prompt, treat the positional as the prompt
// (clap can’t express this conditional positional meaning cleanly).
let (session_id, prompt) = if raw.last && raw.prompt.is_none() {
(None, raw.session_id)
} else {
(raw.session_id, raw.prompt)
};
Self {
session_id,
last: raw.last,
all: raw.all,
images: raw.images,
prompt,
}
}
}
impl Args for ResumeArgs {
fn augment_args(cmd: clap::Command) -> clap::Command {
ResumeArgsRaw::augment_args(cmd)
}
fn augment_args_for_update(cmd: clap::Command) -> clap::Command {
ResumeArgsRaw::augment_args_for_update(cmd)
}
}
impl FromArgMatches for ResumeArgs {
fn from_arg_matches(matches: &clap::ArgMatches) -> Result<Self, clap::Error> {
ResumeArgsRaw::from_arg_matches(matches).map(Self::from)
}
fn update_from_arg_matches(&mut self, matches: &clap::ArgMatches) -> Result<(), clap::Error> {
*self = ResumeArgsRaw::from_arg_matches(matches).map(Self::from)?;
Ok(())
}
}
#[derive(Args, Debug)]
pub struct ReviewArgs {
/// Review staged, unstaged, and untracked changes.
#[arg(
long = "uncommitted",
default_value_t = false,
conflicts_with_all = ["base", "commit", "prompt"]
)]
pub uncommitted: bool,
/// Review changes against the given base branch.
#[arg(
long = "base",
value_name = "BRANCH",
conflicts_with_all = ["uncommitted", "commit", "prompt"]
)]
pub base: Option<String>,
/// Review the changes introduced by a commit.
#[arg(
long = "commit",
value_name = "SHA",
conflicts_with_all = ["uncommitted", "base", "prompt"]
)]
pub commit: Option<String>,
/// Optional commit title to display in the review summary.
#[arg(long = "title", value_name = "TITLE", requires = "commit")]
pub commit_title: Option<String>,
/// Custom review instructions. If `-` is used, read from stdin.
#[arg(value_name = "PROMPT", value_hint = clap::ValueHint::Other)]
pub prompt: Option<String>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, ValueEnum)]
#[value(rename_all = "kebab-case")]
pub enum Color {
Always,
Never,
#[default]
Auto,
}
#[cfg(test)]
#[path = "cli_tests.rs"]
mod tests;

View File

@@ -0,0 +1,153 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn resume_parses_prompt_after_global_flags() {
const PROMPT: &str = "echo resume-with-global-flags-after-subcommand";
let cli = Cli::parse_from([
"codex-exec",
"resume",
"--last",
"--json",
"--model",
"gpt-5.2-codex",
"--cyber-access-program",
"daybreak_blue",
"--dangerously-bypass-approvals-and-sandbox",
"--skip-git-repo-check",
"--ephemeral",
"--ignore-user-config",
"--ignore-rules",
PROMPT,
]);
assert!(cli.ephemeral);
assert!(cli.ignore_user_config);
assert!(cli.ignore_rules);
assert_eq!(
cli.cyber_access_program,
Some(CyberAccessProgramCliArg::DaybreakBlue)
);
let Some(Command::Resume(args)) = cli.command else {
panic!("expected resume command");
};
let effective_prompt = args.prompt.clone().or_else(|| {
if args.last {
args.session_id.clone()
} else {
None
}
});
assert_eq!(effective_prompt.as_deref(), Some(PROMPT));
}
#[test]
fn resume_accepts_output_flags_after_subcommand() {
const PROMPT: &str = "echo resume-with-output-file";
let cli = Cli::parse_from([
"codex-exec",
"resume",
"session-123",
"-o",
"/tmp/resume-output.md",
"--output-schema",
"/tmp/schema.json",
PROMPT,
]);
assert_eq!(
cli.last_message_file,
Some(PathBuf::from("/tmp/resume-output.md"))
);
assert_eq!(cli.output_schema, Some(PathBuf::from("/tmp/schema.json")));
let Some(Command::Resume(args)) = cli.command else {
panic!("expected resume command");
};
assert_eq!(args.session_id.as_deref(), Some("session-123"));
assert_eq!(args.prompt.as_deref(), Some(PROMPT));
}
#[test]
fn fork_parses_prompt_after_global_flags() {
const PROMPT: &str = "continue on the fork";
let cli = Cli::parse_from([
"codex-exec",
"fork",
"session-123",
"--json",
"--model",
"gpt-5.2-codex",
"--thread-source",
"automated_review",
"--skip-git-repo-check",
"--ephemeral",
PROMPT,
]);
assert!(cli.json);
assert!(cli.ephemeral);
assert_eq!(
cli.thread_source,
Some(ThreadSource::Feature("automated_review".to_string()))
);
let Some(Command::Fork(args)) = cli.command else {
panic!("expected fork command");
};
assert_eq!(args.session_id, "session-123");
assert_eq!(args.prompt.as_deref(), Some(PROMPT));
}
#[test]
fn parses_config_isolation_flags() {
let cli = Cli::parse_from([
"codex-exec",
"--ignore-user-config",
"--ignore-rules",
"summarize",
]);
assert!(cli.ignore_user_config);
assert!(cli.ignore_rules);
}
#[test]
fn approve_for_me_flag_applies_to_resume_when_passed_at_exec_root() {
for flag in ["--approve-for-me", "--not-so-yolo"] {
let cli = Cli::parse_from(["codex-exec", flag, "resume", "--last"]);
assert!(cli.auto_review);
}
}
#[test]
fn approve_for_me_flag_conflicts_with_other_sandbox_modes() {
for conflicting_args in [
vec!["--sandbox", "read-only"],
vec!["--dangerously-bypass-approvals-and-sandbox"],
] {
let mut args = vec!["codex-exec", "--approve-for-me"];
args.extend(conflicting_args);
args.push("summarize");
let error = Cli::try_parse_from(args).expect_err("flags should conflict");
assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict);
}
}
#[test]
fn worktree_flag_is_accepted_after_fork_subcommand() {
let cli = Cli::try_parse_from(["codex-exec", "fork", "session-id", "--worktree"])
.expect("worktree should be a global exec argument");
assert!(cli.worktree);
assert!(matches!(cli.command, Some(Command::Fork(_))));
}
#[test]
fn worktree_flag_is_accepted_before_fork_subcommand() {
let cli = Cli::try_parse_from(["codex-exec", "--worktree", "fork", "session-id"])
.expect("worktree should be accepted before the fork subcommand");
assert!(cli.worktree);
assert!(matches!(cli.command, Some(Command::Fork(_))));
}

View File

@@ -0,0 +1,112 @@
//! Resolve the cyber treatment for an exec turn from the connected server's catalog.
use crate::RequestIdSequencer;
use codex_app_server_client::InProcessAppServerClient;
use codex_app_server_protocol::Account;
use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::CyberAccessProgram;
use codex_app_server_protocol::GetAccountParams;
use codex_app_server_protocol::GetAccountResponse;
use codex_app_server_protocol::ModelListParams;
use codex_app_server_protocol::ModelListResponse;
use codex_features::Feature;
use codex_features::Features;
use codex_model_provider_info::ModelProviderInfo;
use codex_protocol::openai_models::ModelAccessPrograms;
pub(crate) async fn program_for_turn(
features: &Features,
client: &InProcessAppServerClient,
request_ids: &mut RequestIdSequencer,
model: &str,
provider_id: &str,
provider: Option<&ModelProviderInfo>,
enabled: bool,
) -> anyhow::Result<Option<CyberAccessProgram>> {
if !provider.is_some_and(|provider| provider.supports_cyber_access_programs(provider_id)) {
anyhow::ensure!(
!enabled,
"Daybreak requires a model provider with Cyber access program support"
);
return Ok(None);
}
if enabled {
anyhow::ensure!(
matches!(
read_account(client, request_ids).await?,
Some(Account::Chatgpt { .. } | Account::ApiKey { .. })
),
"Daybreak requires a signed-in ChatGPT account or an OpenAI API key"
);
}
let mut cursor = None;
loop {
let result = client
.request_typed::<ModelListResponse>(ClientRequest::ModelList {
request_id: request_ids.next(),
params: ModelListParams {
cursor,
limit: None,
include_hidden: Some(true),
model_provider: None,
},
})
.await;
let Ok(result) = result else {
return Ok(None);
};
if let Some(selected) = result.data.into_iter().find(|entry| entry.model == model) {
let programs = selected
.available_access_programs
.map(ModelAccessPrograms::from)
.filter(|programs| !programs.cyber.is_empty());
let Some(programs) = programs else {
return Ok(None);
};
if enabled {
return programs
.daybreak()
.map(|program| Some(program.into()))
.ok_or_else(|| anyhow::anyhow!("Daybreak is unavailable for model {model}; turn it off or choose a compatible model"));
}
let Some(standard) = programs.standard() else {
return Ok(None);
};
let eligible = match read_account(client, request_ids).await.unwrap_or(None) {
Some(Account::Chatgpt { .. }) => true,
Some(Account::ApiKey { .. }) => {
features.enabled(Feature::ApiKeyCyberAccessPrograms)
}
Some(Account::AmazonBedrock { .. } | Account::Gcp {}) | None => false,
};
return Ok(eligible.then_some(standard.into()));
}
match result.next_cursor {
Some(next) => cursor = Some(next),
None => {
// Preserve automatic treatment for explicit model IDs absent from the catalog.
return Ok(None);
}
}
}
}
async fn read_account(
client: &InProcessAppServerClient,
request_ids: &mut RequestIdSequencer,
) -> anyhow::Result<Option<Account>> {
let account = client
.request_typed::<GetAccountResponse>(ClientRequest::GetAccount {
request_id: request_ids.next(),
params: GetAccountParams {
refresh_token: false,
},
})
.await
.map_err(|error| {
anyhow::anyhow!("Daybreak account availability could not be determined: {error}")
})?;
Ok(account.account)
}

View File

@@ -0,0 +1,47 @@
use anyhow::Context;
use std::path::Path;
use codex_app_server_protocol::ServerNotification;
use codex_core::config::Config;
use codex_exec_server::BoundOutput;
use codex_protocol::protocol::SessionConfiguredEvent;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodexStatus {
Running,
InitiateShutdown,
}
pub(crate) trait EventProcessor {
/// Print summary of effective configuration and user prompt.
fn print_config_summary(
&mut self,
config: &Config,
prompt: &str,
session_configured: &SessionConfiguredEvent,
);
/// Handle a single typed app-server notification emitted by the agent.
fn process_server_notification(&mut self, notification: ServerNotification) -> CodexStatus;
/// Handle a local exec warning that is not represented as an app-server notification.
fn process_warning(&mut self, message: String) -> CodexStatus;
fn print_final_output(&mut self, output: Option<BoundOutput>) -> anyhow::Result<()>;
}
pub(crate) fn handle_last_message(
last_agent_message: Option<&str>,
path: &Path,
file: BoundOutput,
) -> anyhow::Result<()> {
file.write(last_agent_message.unwrap_or_default().as_bytes())
.with_context(|| format!("Failed to write last message file {path:?}"))?;
if last_agent_message.is_none() {
eprintln!(
"Warning: no last agent message; wrote empty content to {}",
path.display()
);
}
Ok(())
}

View File

@@ -0,0 +1,550 @@
use std::io::IsTerminal;
use std::path::PathBuf;
use codex_app_server_protocol::CommandExecutionStatus;
use codex_app_server_protocol::McpToolCallStatus;
use codex_app_server_protocol::PatchApplyStatus;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::ThreadItemPayload;
use codex_app_server_protocol::ThreadTokenUsage;
use codex_app_server_protocol::TurnStatus;
use codex_core::config::Config;
use codex_exec_server::BoundOutput;
use codex_model_provider_info::WireApi;
use codex_protocol::num_format::format_with_separators;
use codex_protocol::protocol::SessionConfiguredEvent;
use codex_utils_path_uri::PathUri;
use codex_utils_sandbox_summary::summarize_permission_profile;
use owo_colors::OwoColorize;
use owo_colors::Style;
use crate::event_processor::CodexStatus;
use crate::event_processor::EventProcessor;
use crate::event_processor::handle_last_message;
pub(crate) struct EventProcessorWithHumanOutput {
bold: Style,
cyan: Style,
dimmed: Style,
green: Style,
italic: Style,
magenta: Style,
red: Style,
yellow: Style,
show_agent_reasoning: bool,
show_raw_agent_reasoning: bool,
last_message_path: Option<PathBuf>,
final_message: Option<String>,
final_message_rendered: bool,
emit_final_message_on_shutdown: bool,
last_total_token_usage: Option<ThreadTokenUsage>,
last_turn_diff: String,
}
impl EventProcessorWithHumanOutput {
pub(crate) fn create_with_ansi(
with_ansi: bool,
config: &Config,
last_message_path: Option<PathBuf>,
) -> Self {
let style = |styled: Style, plain: Style| if with_ansi { styled } else { plain };
Self {
bold: style(Style::new().bold(), Style::new()),
cyan: style(Style::new().cyan(), Style::new()),
dimmed: style(Style::new().dimmed(), Style::new()),
green: style(Style::new().green(), Style::new()),
italic: style(Style::new().italic(), Style::new()),
magenta: style(Style::new().magenta(), Style::new()),
red: style(Style::new().red(), Style::new()),
yellow: style(Style::new().yellow(), Style::new()),
show_agent_reasoning: !config.hide_agent_reasoning,
show_raw_agent_reasoning: config.show_raw_agent_reasoning,
last_message_path,
final_message: None,
final_message_rendered: false,
emit_final_message_on_shutdown: false,
last_total_token_usage: None,
last_turn_diff: String::new(),
}
}
fn render_item_started(&self, item: &ThreadItemPayload) {
match item {
ThreadItemPayload::CommandExecution { command, cwd, .. } => {
eprintln!(
"{}\n{} in {cwd}",
"exec".style(self.italic).style(self.magenta),
command.style(self.bold),
);
}
ThreadItemPayload::McpToolCall { server, tool, .. } => {
eprintln!(
"{} {} {}",
"mcp:".style(self.bold),
format!("{server}/{tool}").style(self.cyan),
"started".style(self.dimmed)
);
}
ThreadItemPayload::WebSearch(item) => {
eprintln!("{} {}", "web search:".style(self.bold), item.query);
}
ThreadItemPayload::FileChange { .. } => {
eprintln!("{}", "apply patch".style(self.bold));
}
ThreadItemPayload::CollabAgentToolCall { tool, .. } => {
eprintln!("{} {:?}", "collab:".style(self.bold), tool);
}
_ => {}
}
}
fn render_item_completed(&mut self, item: ThreadItemPayload) {
match item {
ThreadItemPayload::AgentMessage { text, .. } => {
eprintln!(
"{}\n{}",
"codex".style(self.italic).style(self.magenta),
text
);
self.final_message = Some(text);
self.final_message_rendered = true;
}
ThreadItemPayload::Reasoning {
summary, content, ..
} => {
if self.show_agent_reasoning
&& let Some(text) =
reasoning_text(&summary, &content, self.show_raw_agent_reasoning)
&& !text.trim().is_empty()
{
eprintln!("{}", text.style(self.dimmed));
}
}
ThreadItemPayload::CommandExecution {
command: _,
aggregated_output,
exit_code,
status,
duration_ms,
..
} => {
let duration_suffix = duration_ms
.map(|duration_ms| format!(" in {duration_ms}ms"))
.unwrap_or_default();
match status {
CommandExecutionStatus::Completed => {
eprintln!(
"{}",
format!(" succeeded{duration_suffix}:").style(self.green)
);
}
CommandExecutionStatus::Failed => {
let exit_code = exit_code.unwrap_or(1);
eprintln!(
"{}",
format!(" exited {exit_code}{duration_suffix}:").style(self.red)
);
}
CommandExecutionStatus::Declined => {
eprintln!(
"{}",
format!(" declined{duration_suffix}:").style(self.yellow)
);
}
CommandExecutionStatus::InProgress => {
eprintln!(
"{}",
format!(" in progress{duration_suffix}:").style(self.dimmed)
);
}
}
if let Some(output) = aggregated_output
&& !output.trim().is_empty()
{
eprintln!("{output}");
}
}
ThreadItemPayload::FileChange {
changes, status, ..
} => {
let status_text = match status {
PatchApplyStatus::Completed => "completed",
PatchApplyStatus::Failed => "failed",
PatchApplyStatus::Declined => "declined",
PatchApplyStatus::InProgress => "in_progress",
};
eprintln!("{} {}", "patch:".style(self.bold), status_text);
for change in changes {
eprintln!("{}", change.path.style(self.dimmed));
}
}
ThreadItemPayload::McpToolCall {
server,
tool,
status,
error,
..
} => {
let status_text = match status {
McpToolCallStatus::Completed => "completed".style(self.green),
McpToolCallStatus::Failed => "failed".style(self.red),
McpToolCallStatus::InProgress => "in_progress".style(self.dimmed),
};
eprintln!(
"{} {} {}",
"mcp:".style(self.bold),
format!("{server}/{tool}").style(self.cyan),
format!("({status_text})").style(self.dimmed)
);
if let Some(error) = error {
eprintln!("{}", error.message.style(self.red));
}
}
ThreadItemPayload::WebSearch(item) => {
eprintln!("{} {}", "web search:".style(self.bold), item.query);
}
ThreadItemPayload::ContextCompaction { .. } => {
eprintln!("{}", "context compacted".style(self.dimmed));
}
_ => {}
}
}
}
impl EventProcessor for EventProcessorWithHumanOutput {
fn print_config_summary(
&mut self,
config: &Config,
prompt: &str,
session_configured_event: &SessionConfiguredEvent,
) {
const VERSION: &str = env!("CARGO_PKG_VERSION");
eprintln!("OpenAI Codex v{VERSION}\n--------");
for (key, value) in config_summary_entries(config, session_configured_event) {
eprintln!("{} {}", format!("{key}:").style(self.bold), value);
}
eprintln!("--------");
eprintln!("{}\n{}", "user".style(self.cyan), prompt);
}
fn process_server_notification(&mut self, notification: ServerNotification) -> CodexStatus {
match notification {
ServerNotification::ConfigWarning(notification) => {
let details = notification
.details
.map(|details| format!(" ({details})"))
.unwrap_or_default();
eprintln!(
"{} {}{}",
"warning:".style(self.yellow).style(self.bold),
notification.summary,
details
);
CodexStatus::Running
}
ServerNotification::Warning(notification) => self.process_warning(notification.message),
ServerNotification::AuthRecoveryStarted(notification) => {
eprintln!("{}", notification.message);
CodexStatus::Running
}
ServerNotification::AuthRecoveryCompleted(notification) => {
eprintln!("{}", notification.message.style(self.green));
CodexStatus::Running
}
ServerNotification::Error(notification) => {
eprintln!(
"{} {}",
"ERROR:".style(self.red).style(self.bold),
notification.error
);
CodexStatus::Running
}
ServerNotification::DeprecationNotice(notification) => {
eprintln!(
"{} {}",
"deprecated:".style(self.yellow).style(self.bold),
notification.summary
);
if let Some(details) = notification.details {
eprintln!("{}", details.style(self.dimmed));
}
CodexStatus::Running
}
ServerNotification::HookStarted(notification) => {
eprintln!(
"{} {}",
"hook:".style(self.bold),
format!("{:?}", notification.run.event_name).style(self.dimmed)
);
CodexStatus::Running
}
ServerNotification::HookCompleted(notification) => {
eprintln!(
"{} {} {:?}",
"hook:".style(self.bold),
format!("{:?}", notification.run.event_name).style(self.dimmed),
notification.run.status
);
CodexStatus::Running
}
ServerNotification::ItemStarted(notification) => {
self.render_item_started(&notification.item.payload);
CodexStatus::Running
}
ServerNotification::ItemCompleted(notification) => {
self.render_item_completed(notification.item.payload);
CodexStatus::Running
}
ServerNotification::ModelRerouted(notification) => {
eprintln!(
"{} {} -> {}",
"model rerouted:".style(self.yellow).style(self.bold),
notification.from_model,
notification.to_model
);
CodexStatus::Running
}
ServerNotification::ModelVerification(_) => CodexStatus::Running,
ServerNotification::ThreadTokenUsageUpdated(notification) => {
self.last_total_token_usage = Some(notification.token_usage);
CodexStatus::Running
}
ServerNotification::TurnCompleted(notification) => match notification.turn.status {
TurnStatus::Completed => {
let rendered_message = self
.final_message_rendered
.then(|| self.final_message.clone())
.flatten();
if let Some(final_message) =
final_message_from_turn_items(notification.turn.items.as_slice())
{
self.final_message_rendered =
rendered_message.as_deref() == Some(final_message.as_str());
self.final_message = Some(final_message);
}
self.emit_final_message_on_shutdown = true;
CodexStatus::InitiateShutdown
}
TurnStatus::Failed => {
self.final_message = None;
self.final_message_rendered = false;
self.emit_final_message_on_shutdown = false;
if let Some(error) = notification.turn.error {
eprintln!("{} {}", "ERROR:".style(self.red).style(self.bold), error);
}
CodexStatus::InitiateShutdown
}
TurnStatus::Interrupted => {
self.final_message = None;
self.final_message_rendered = false;
self.emit_final_message_on_shutdown = false;
eprintln!("{}", "turn interrupted".style(self.dimmed));
CodexStatus::InitiateShutdown
}
TurnStatus::InProgress => CodexStatus::Running,
},
ServerNotification::TurnDiffUpdated(notification) => {
if notification.diff != self.last_turn_diff && !notification.diff.trim().is_empty()
{
eprintln!("{}", notification.diff);
}
// Remember empty updates too, so a restored diff is rendered again.
self.last_turn_diff = notification.diff;
CodexStatus::Running
}
ServerNotification::TurnPlanUpdated(notification) => {
if let Some(explanation) = notification.explanation {
eprintln!("{}", explanation.style(self.italic));
}
for step in notification.plan {
match step.status {
codex_app_server_protocol::TurnPlanStepStatus::Completed => {
eprintln!(" {} {}", "✓".style(self.green), step.step);
}
codex_app_server_protocol::TurnPlanStepStatus::InProgress => {
eprintln!(" {} {}", "→".style(self.cyan), step.step);
}
codex_app_server_protocol::TurnPlanStepStatus::Pending => {
eprintln!(
" {} {}",
"•".style(self.dimmed),
step.step.style(self.dimmed)
);
}
}
}
CodexStatus::Running
}
ServerNotification::TurnStarted(_) => {
self.last_turn_diff.clear();
CodexStatus::Running
}
_ => CodexStatus::Running,
}
}
fn process_warning(&mut self, message: String) -> CodexStatus {
eprintln!(
"{} {message}",
"warning:".style(self.yellow).style(self.bold)
);
CodexStatus::Running
}
fn print_final_output(&mut self, output: Option<BoundOutput>) -> anyhow::Result<()> {
let print_to_stdout = should_print_final_message_to_stdout(
self.emit_final_message_on_shutdown
.then_some(self.final_message.as_deref())
.flatten(),
std::io::stdout().is_terminal(),
std::io::stderr().is_terminal(),
);
let output_result = if self.emit_final_message_on_shutdown
&& let (Some(path), Some(file)) = (self.last_message_path.as_deref(), output)
&& !(print_to_stdout && file.is_stdout())
{
handle_last_message(self.final_message.as_deref(), path, file)
} else {
Ok(())
};
if let Some(usage) = &self.last_total_token_usage {
eprintln!(
"{}\n{}",
"tokens used".style(self.dimmed),
format_with_separators(blended_total(usage))
);
}
#[allow(clippy::print_stdout)]
if print_to_stdout && let Some(message) = self.final_message.as_deref() {
println!("{message}");
} else if should_print_final_message_to_tty(
self.emit_final_message_on_shutdown
.then_some(self.final_message.as_deref())
.flatten(),
self.final_message_rendered,
std::io::stdout().is_terminal(),
std::io::stderr().is_terminal(),
) && let Some(message) = self.final_message.as_deref()
{
eprintln!(
"{}\n{}",
"codex".style(self.italic).style(self.magenta),
message
);
}
output_result
}
}
fn config_summary_entries(
config: &Config,
session_configured_event: &SessionConfiguredEvent,
) -> Vec<(&'static str, String)> {
let permission_profile = config.permissions.effective_permission_profile();
let mut entries = vec![
("workdir", config.cwd.display().to_string()),
("model", session_configured_event.model.clone()),
(
"provider",
session_configured_event.model_provider_id.clone(),
),
(
"approval",
config.permissions.approval_policy.value().to_string(),
),
(
"sandbox",
summarize_permission_profile(
&permission_profile,
&PathUri::from_abs_path(&config.cwd),
&config.effective_workspace_roots(),
),
),
];
if config.model_provider.wire_api == WireApi::Responses {
entries.push((
"reasoning effort",
config
.model_reasoning_effort
.as_ref()
.map(std::string::ToString::to_string)
.unwrap_or_else(|| "none".to_string()),
));
entries.push((
"reasoning summaries",
config
.model_reasoning_summary
.map(|summary| summary.to_string())
.unwrap_or_else(|| "none".to_string()),
));
}
entries.push((
"session id",
session_configured_event.session_id.to_string(),
));
entries
}
fn reasoning_text(
summary: &[String],
content: &[String],
show_raw_agent_reasoning: bool,
) -> Option<String> {
let entries = if show_raw_agent_reasoning && !content.is_empty() {
content
} else {
summary
};
if entries.is_empty() {
None
} else {
Some(entries.join("\n"))
}
}
fn final_message_from_turn_items(
items: &[impl std::borrow::Borrow<ThreadItemPayload>],
) -> Option<String> {
items
.iter()
.rev()
.find_map(|item| match item.borrow() {
ThreadItemPayload::AgentMessage { text, .. } => Some(text.clone()),
_ => None,
})
.or_else(|| {
items.iter().rev().find_map(|item| match item.borrow() {
ThreadItemPayload::Plan { text, .. } => Some(text.clone()),
_ => None,
})
})
}
fn blended_total(usage: &ThreadTokenUsage) -> i64 {
let cached_input = usage.total.cached_input_tokens.max(0);
let non_cached_input = (usage.total.input_tokens - cached_input).max(0);
(non_cached_input + usage.total.output_tokens.max(0)).max(0)
}
fn should_print_final_message_to_stdout(
final_message: Option<&str>,
stdout_is_terminal: bool,
stderr_is_terminal: bool,
) -> bool {
final_message.is_some() && !(stdout_is_terminal && stderr_is_terminal)
}
fn should_print_final_message_to_tty(
final_message: Option<&str>,
final_message_rendered: bool,
stdout_is_terminal: bool,
stderr_is_terminal: bool,
) -> bool {
final_message.is_some() && !final_message_rendered && stdout_is_terminal && stderr_is_terminal
}
#[cfg(test)]
#[path = "event_processor_with_human_output_tests.rs"]
mod tests;

View File

@@ -0,0 +1,649 @@
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::ThreadItem;
use codex_app_server_protocol::ThreadItemPayload;
use codex_app_server_protocol::Turn;
use codex_app_server_protocol::TurnStatus;
use codex_core::config::ConfigBuilder;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::SessionConfiguredEvent;
use codex_utils_absolute_path::test_support::PathBufExt;
use codex_utils_absolute_path::test_support::test_path_buf;
use codex_utils_path_uri::PathUri;
use codex_utils_sandbox_summary::summarize_permission_profile;
use owo_colors::Style;
use pretty_assertions::assert_eq;
use super::EventProcessorWithHumanOutput;
use super::config_summary_entries;
use super::final_message_from_turn_items;
use super::reasoning_text;
use super::should_print_final_message_to_stdout;
use super::should_print_final_message_to_tty;
use crate::event_processor::EventProcessor;
#[test]
fn turn_diff_notifications_render_only_changes() -> anyhow::Result<()> {
const CHILD: &str = "CODEX_EXEC_TURN_DIFF_TEST_CHILD";
if std::env::var_os(CHILD).is_none() {
// Capture stderr in a child so other tests cannot interfere with rendering.
let output = std::process::Command::new(std::env::current_exe()?)
.args([
"--exact",
"event_processor_with_human_output::tests::turn_diff_notifications_render_only_changes",
"--nocapture",
])
.env(CHILD, "1")
.output()?;
assert!(output.status.success(), "{output:?}");
assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));
insta::assert_snapshot!(String::from_utf8(output.stderr)?, @r"
turn-1
@@ -1 +1 @@
-value=1
+value=2
@@ -1 +1 @@
-value=1
+value=3
@@ -1 +1 @@
-value=1
+value=2
@@ -1 +1 @@
-value=1
+value=2
@@ -1 +1 @@
-value=1
+value=2
turn-2
@@ -1 +1 @@
-value=1
+value=2
");
return Ok(());
}
let mut processor = EventProcessorWithHumanOutput {
bold: Style::new(),
cyan: Style::new(),
dimmed: Style::new(),
green: Style::new(),
italic: Style::new(),
magenta: Style::new(),
red: Style::new(),
yellow: Style::new(),
show_agent_reasoning: true,
show_raw_agent_reasoning: false,
last_message_path: None,
final_message: None,
final_message_rendered: false,
emit_final_message_on_shutdown: false,
last_total_token_usage: None,
last_turn_diff: String::new(),
};
let first = "@@ -1 +1 @@\n-value=1\n+value=2";
let changed = "@@ -1 +1 @@\n-value=1\n+value=3";
for (turn_id, diffs) in [
// Repeated updates are quiet, but changed and restored diffs still print.
(
"turn-1",
vec![
"", " \n", first, first, changed, changed, first, "", first, " \n", first,
],
),
("turn-2", vec![first, first]),
] {
processor.process_server_notification(ServerNotification::TurnStarted(
codex_app_server_protocol::TurnStartedNotification {
thread_id: "thread-1".to_string(),
turn: Turn {
id: turn_id.to_string(),
root_turn_id: None,
items_view: codex_app_server_protocol::TurnItemsView::Full,
items: Vec::new(),
status: TurnStatus::InProgress,
error: None,
started_at: None,
completed_at: None,
duration_ms: None,
},
},
));
eprintln!("{turn_id}");
for diff in diffs {
assert_eq!(
processor.process_server_notification(ServerNotification::TurnDiffUpdated(
codex_app_server_protocol::TurnDiffUpdatedNotification {
thread_id: "thread-1".to_string(),
turn_id: turn_id.to_string(),
diff: diff.to_string(),
},
)),
crate::event_processor::CodexStatus::Running
);
}
}
Ok(())
}
#[test]
fn suppresses_final_stdout_message_when_both_streams_are_terminals() {
assert!(!should_print_final_message_to_stdout(
Some("hello"),
/*stdout_is_terminal*/ true,
/*stderr_is_terminal*/ true
));
}
#[test]
fn prints_final_stdout_message_when_stdout_is_not_terminal() {
assert!(should_print_final_message_to_stdout(
Some("hello"),
/*stdout_is_terminal*/ false,
/*stderr_is_terminal*/ true
));
}
#[test]
fn prints_final_stdout_message_when_stderr_is_not_terminal() {
assert!(should_print_final_message_to_stdout(
Some("hello"),
/*stdout_is_terminal*/ true,
/*stderr_is_terminal*/ false
));
}
#[test]
fn suppresses_final_stdout_message_when_missing() {
assert!(!should_print_final_message_to_stdout(
/*final_message*/ None, /*stdout_is_terminal*/ false,
/*stderr_is_terminal*/ false
));
}
#[test]
fn prints_final_tty_message_when_not_yet_rendered() {
assert!(should_print_final_message_to_tty(
Some("hello"),
/*final_message_rendered*/ false,
/*stdout_is_terminal*/ true,
/*stderr_is_terminal*/ true
));
}
#[test]
fn suppresses_final_tty_message_when_already_rendered() {
assert!(!should_print_final_message_to_tty(
Some("hello"),
/*final_message_rendered*/ true,
/*stdout_is_terminal*/ true,
/*stderr_is_terminal*/ true
));
}
#[test]
fn reasoning_text_prefers_summary_when_raw_reasoning_is_hidden() {
let text = reasoning_text(
&["summary".to_string()],
&["raw".to_string()],
/*show_raw_agent_reasoning*/ false,
);
assert_eq!(text.as_deref(), Some("summary"));
}
#[test]
fn reasoning_text_uses_raw_content_when_enabled() {
let text = reasoning_text(
&["summary".to_string()],
&["raw".to_string()],
/*show_raw_agent_reasoning*/ true,
);
assert_eq!(text.as_deref(), Some("raw"));
}
#[test]
fn summarizes_disabled_permission_profile_as_danger_full_access() {
let cwd = PathUri::from_abs_path(&test_path_buf("/tmp").abs());
assert_eq!(
summarize_permission_profile(
&PermissionProfile::Disabled,
&cwd,
std::slice::from_ref(&cwd),
),
"danger-full-access"
);
}
#[test]
fn summarizes_external_permission_profile() {
let cwd = PathUri::from_abs_path(&test_path_buf("/tmp").abs());
assert_eq!(
summarize_permission_profile(
&PermissionProfile::External {
network: NetworkSandboxPolicy::Enabled,
},
&cwd,
std::slice::from_ref(&cwd),
),
"external-sandbox (network access enabled)"
);
}
#[test]
fn summarizes_managed_workspace_write_permission_profile() {
let cwd = test_path_buf("/tmp/project").abs();
let cache_root = test_path_buf("/tmp/cache").abs();
let profile = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry {
path: cwd.clone().into(),
access: FileSystemAccessMode::Write,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: FileSystemPath::Path {
path: cache_root.clone().into(),
},
access: FileSystemAccessMode::Write,
missing_path_behavior: None,
},
]),
NetworkSandboxPolicy::Restricted,
);
assert_eq!(
summarize_permission_profile(
&profile,
&PathUri::from_abs_path(&cwd),
&[cwd.clone().into(), cache_root.clone().into()],
),
format!("workspace-write [workdir, {}]", cache_root.display())
);
}
#[test]
fn summarizes_managed_read_only_permission_profile() {
let cwd = PathUri::from_abs_path(&test_path_buf("/tmp/project").abs());
let profile = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::restricted(Vec::new()),
NetworkSandboxPolicy::Restricted,
);
assert_eq!(
summarize_permission_profile(&profile, &cwd, std::slice::from_ref(&cwd)),
"read-only"
);
}
#[tokio::test]
async fn config_summary_entries_include_runtime_workspace_roots() {
let codex_home = tempfile::tempdir().expect("create codex home");
let cwd = tempfile::tempdir().expect("create cwd");
let extra_root = tempfile::tempdir().expect("create extra root");
let mut config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(cwd.path().to_path_buf()))
.build()
.await
.expect("build default config");
let cwd = cwd.path().to_path_buf().abs();
let extra_root = extra_root.path().to_path_buf().abs();
let expected_extra_root_name = extra_root
.file_name()
.expect("extra root should have file name")
.to_string_lossy()
.to_string();
config.cwd = cwd.clone();
config.workspace_roots = vec![cwd.clone(), extra_root];
config
.permissions
.set_workspace_roots(config.workspace_roots.clone());
config
.permissions
.set_permission_profile(PermissionProfile::workspace_write_with(
&[],
NetworkSandboxPolicy::Restricted,
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ true,
))
.expect("set permission profile");
let session_configured_event = SessionConfiguredEvent {
session_id: SessionId::new(),
thread_id: ThreadId::new(),
forked_from_id: None,
parent_thread_id: None,
thread_source: None,
thread_name: None,
model: "gpt-5.4".to_string(),
model_provider_id: config.model_provider_id.clone(),
service_tier: None,
approval_policy: AskForApproval::Never,
approvals_reviewer: config.approvals_reviewer,
permission_profile: config.permissions.effective_permission_profile(),
active_permission_profile: None,
cwd,
reasoning_effort: None,
network_proxy: None,
rollout_path: None,
};
let summary_entries = config_summary_entries(&config, &session_configured_event);
let sandbox_summary = summary_entries
.iter()
.find_map(|(key, value)| (*key == "sandbox").then_some(value))
.expect("sandbox summary entry");
assert!(
sandbox_summary.starts_with("workspace-write [workdir, ")
&& sandbox_summary.contains(&expected_extra_root_name),
"expected runtime workspace root in sandbox summary: {summary_entries:?}"
);
}
#[test]
fn final_message_from_turn_items_uses_latest_agent_message() {
let message = final_message_from_turn_items(&[
ThreadItemPayload::AgentMessage {
moderation: None,
id: "msg-1".to_string(),
text: "first".to_string(),
phase: None,
memory_citation: None,
delivery: None,
questions: None,
},
ThreadItemPayload::Plan {
id: "plan-1".to_string(),
text: "plan".to_string(),
},
ThreadItemPayload::AgentMessage {
moderation: None,
id: "msg-2".to_string(),
text: "second".to_string(),
phase: None,
memory_citation: None,
delivery: None,
questions: None,
},
]);
assert_eq!(message.as_deref(), Some("second"));
}
#[test]
fn final_message_from_turn_items_falls_back_to_latest_plan() {
let message = final_message_from_turn_items(&[
ThreadItemPayload::Reasoning {
id: "reasoning-1".to_string(),
summary: vec!["inspect".to_string()],
content: Vec::new(),
},
ThreadItemPayload::Plan {
id: "plan-1".to_string(),
text: "first plan".to_string(),
},
ThreadItemPayload::Plan {
id: "plan-2".to_string(),
text: "final plan".to_string(),
},
]);
assert_eq!(message.as_deref(), Some("final plan"));
}
#[test]
fn turn_completed_recovers_final_message_from_turn_items() {
let mut processor = EventProcessorWithHumanOutput {
bold: Style::new(),
cyan: Style::new(),
dimmed: Style::new(),
green: Style::new(),
italic: Style::new(),
magenta: Style::new(),
red: Style::new(),
yellow: Style::new(),
show_agent_reasoning: true,
show_raw_agent_reasoning: false,
last_message_path: None,
final_message: None,
final_message_rendered: false,
emit_final_message_on_shutdown: false,
last_total_token_usage: None,
last_turn_diff: String::new(),
};
let status = processor.process_server_notification(ServerNotification::TurnCompleted(
codex_app_server_protocol::TurnCompletedNotification {
thread_id: "thread-1".to_string(),
turn: Turn {
id: "turn-1".to_string(),
root_turn_id: None,
items_view: codex_app_server_protocol::TurnItemsView::Full,
items: vec![ThreadItem::untimed(ThreadItemPayload::AgentMessage {
moderation: None,
id: "msg-1".to_string(),
text: "final answer".to_string(),
phase: None,
memory_citation: None,
delivery: None,
questions: None,
})],
status: TurnStatus::Completed,
error: None,
started_at: None,
completed_at: Some(0),
duration_ms: None,
},
},
));
assert_eq!(
status,
crate::event_processor::CodexStatus::InitiateShutdown
);
assert_eq!(processor.final_message.as_deref(), Some("final answer"));
}
#[test]
fn turn_completed_overwrites_stale_final_message_from_turn_items() {
let mut processor = EventProcessorWithHumanOutput {
bold: Style::new(),
cyan: Style::new(),
dimmed: Style::new(),
green: Style::new(),
italic: Style::new(),
magenta: Style::new(),
red: Style::new(),
yellow: Style::new(),
show_agent_reasoning: true,
show_raw_agent_reasoning: false,
last_message_path: None,
final_message: Some("stale answer".to_string()),
final_message_rendered: true,
emit_final_message_on_shutdown: false,
last_total_token_usage: None,
last_turn_diff: String::new(),
};
let status = processor.process_server_notification(ServerNotification::TurnCompleted(
codex_app_server_protocol::TurnCompletedNotification {
thread_id: "thread-1".to_string(),
turn: Turn {
id: "turn-1".to_string(),
root_turn_id: None,
items_view: codex_app_server_protocol::TurnItemsView::Full,
items: vec![ThreadItem::untimed(ThreadItemPayload::AgentMessage {
moderation: None,
id: "msg-1".to_string(),
text: "final answer".to_string(),
phase: None,
memory_citation: None,
delivery: None,
questions: None,
})],
status: TurnStatus::Completed,
error: None,
started_at: None,
completed_at: Some(0),
duration_ms: None,
},
},
));
assert_eq!(
status,
crate::event_processor::CodexStatus::InitiateShutdown
);
assert_eq!(processor.final_message.as_deref(), Some("final answer"));
assert!(!processor.final_message_rendered);
}
#[test]
fn turn_completed_preserves_streamed_final_message_when_turn_items_are_empty() {
let mut processor = EventProcessorWithHumanOutput {
bold: Style::new(),
cyan: Style::new(),
dimmed: Style::new(),
green: Style::new(),
italic: Style::new(),
magenta: Style::new(),
red: Style::new(),
yellow: Style::new(),
show_agent_reasoning: true,
show_raw_agent_reasoning: false,
last_message_path: None,
final_message: Some("streamed answer".to_string()),
final_message_rendered: false,
emit_final_message_on_shutdown: false,
last_total_token_usage: None,
last_turn_diff: String::new(),
};
let status = processor.process_server_notification(ServerNotification::TurnCompleted(
codex_app_server_protocol::TurnCompletedNotification {
thread_id: "thread-1".to_string(),
turn: Turn {
id: "turn-1".to_string(),
root_turn_id: None,
items_view: codex_app_server_protocol::TurnItemsView::Full,
items: Vec::new(),
status: TurnStatus::Completed,
error: None,
started_at: None,
completed_at: Some(0),
duration_ms: None,
},
},
));
assert_eq!(
status,
crate::event_processor::CodexStatus::InitiateShutdown
);
assert_eq!(processor.final_message.as_deref(), Some("streamed answer"));
assert!(processor.emit_final_message_on_shutdown);
}
#[test]
fn turn_failed_clears_stale_final_message() {
let mut processor = EventProcessorWithHumanOutput {
bold: Style::new(),
cyan: Style::new(),
dimmed: Style::new(),
green: Style::new(),
italic: Style::new(),
magenta: Style::new(),
red: Style::new(),
yellow: Style::new(),
show_agent_reasoning: true,
show_raw_agent_reasoning: false,
last_message_path: None,
final_message: Some("partial answer".to_string()),
final_message_rendered: true,
emit_final_message_on_shutdown: true,
last_total_token_usage: None,
last_turn_diff: String::new(),
};
let status = processor.process_server_notification(ServerNotification::TurnCompleted(
codex_app_server_protocol::TurnCompletedNotification {
thread_id: "thread-1".to_string(),
turn: Turn {
id: "turn-1".to_string(),
root_turn_id: None,
items_view: codex_app_server_protocol::TurnItemsView::Full,
items: Vec::new(),
status: TurnStatus::Failed,
error: None,
started_at: None,
completed_at: Some(0),
duration_ms: None,
},
},
));
assert_eq!(
status,
crate::event_processor::CodexStatus::InitiateShutdown
);
assert_eq!(processor.final_message, None);
assert!(!processor.final_message_rendered);
assert!(!processor.emit_final_message_on_shutdown);
}
#[test]
fn turn_interrupted_clears_stale_final_message() {
let mut processor = EventProcessorWithHumanOutput {
bold: Style::new(),
cyan: Style::new(),
dimmed: Style::new(),
green: Style::new(),
italic: Style::new(),
magenta: Style::new(),
red: Style::new(),
yellow: Style::new(),
show_agent_reasoning: true,
show_raw_agent_reasoning: false,
last_message_path: None,
final_message: Some("partial answer".to_string()),
final_message_rendered: true,
emit_final_message_on_shutdown: true,
last_total_token_usage: None,
last_turn_diff: String::new(),
};
let status = processor.process_server_notification(ServerNotification::TurnCompleted(
codex_app_server_protocol::TurnCompletedNotification {
thread_id: "thread-1".to_string(),
turn: Turn {
id: "turn-1".to_string(),
root_turn_id: None,
items_view: codex_app_server_protocol::TurnItemsView::Full,
items: Vec::new(),
status: TurnStatus::Interrupted,
error: None,
started_at: None,
completed_at: Some(0),
duration_ms: None,
},
},
));
assert_eq!(
status,
crate::event_processor::CodexStatus::InitiateShutdown
);
assert_eq!(processor.final_message, None);
assert!(!processor.final_message_rendered);
assert!(!processor.emit_final_message_on_shutdown);
}

View File

@@ -0,0 +1,646 @@
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use codex_app_server_protocol::CollabAgentTool;
use codex_app_server_protocol::CollabAgentToolCallStatus;
use codex_app_server_protocol::CommandExecutionStatus;
use codex_app_server_protocol::McpToolCallStatus;
use codex_app_server_protocol::PatchApplyStatus;
use codex_app_server_protocol::PatchChangeKind;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::ThreadItemPayload;
use codex_app_server_protocol::ThreadTokenUsage;
use codex_app_server_protocol::TurnStatus;
use codex_app_server_protocol::WebSearchAction as ApiWebSearchAction;
use codex_core::config::Config;
use codex_exec_server::BoundOutput;
use codex_protocol::models::WebSearchAction;
use codex_protocol::protocol::SessionConfiguredEvent;
use serde_json::json;
pub use crate::event_processor::CodexStatus;
use crate::event_processor::EventProcessor;
use crate::event_processor::handle_last_message;
use crate::exec_events::AgentMessageItem;
use crate::exec_events::CollabAgentState;
use crate::exec_events::CollabAgentStatus;
use crate::exec_events::CollabTool;
use crate::exec_events::CollabToolCallItem;
use crate::exec_events::CollabToolCallStatus;
use crate::exec_events::CommandExecutionItem;
use crate::exec_events::CommandExecutionStatus as ExecCommandExecutionStatus;
use crate::exec_events::ErrorItem;
use crate::exec_events::FileChangeItem;
use crate::exec_events::FileUpdateChange;
use crate::exec_events::ItemCompletedEvent;
use crate::exec_events::ItemStartedEvent;
use crate::exec_events::ItemUpdatedEvent;
use crate::exec_events::McpToolCallItem;
use crate::exec_events::McpToolCallItemError;
use crate::exec_events::McpToolCallItemResult;
use crate::exec_events::McpToolCallStatus as ExecMcpToolCallStatus;
use crate::exec_events::PatchApplyStatus as ExecPatchApplyStatus;
use crate::exec_events::PatchChangeKind as ExecPatchChangeKind;
use crate::exec_events::ReasoningItem;
use crate::exec_events::ThreadErrorEvent;
use crate::exec_events::ThreadEvent;
use crate::exec_events::ThreadItem as ExecThreadItem;
use crate::exec_events::ThreadItemDetails;
use crate::exec_events::ThreadStartedEvent;
use crate::exec_events::TodoItem;
use crate::exec_events::TodoListItem;
use crate::exec_events::TurnCompletedEvent;
use crate::exec_events::TurnFailedEvent;
use crate::exec_events::TurnStartedEvent;
use crate::exec_events::Usage;
use crate::exec_events::WebSearchItem;
pub struct EventProcessorWithJsonOutput {
last_message_path: Option<PathBuf>,
next_item_id: AtomicU64,
raw_to_exec_item_id: HashMap<String, String>,
running_todo_list: Option<RunningTodoList>,
last_total_token_usage: Option<ThreadTokenUsage>,
last_critical_error: Option<ThreadErrorEvent>,
final_message: Option<String>,
emit_final_message_on_shutdown: bool,
}
#[derive(Debug, Clone)]
struct RunningTodoList {
item_id: String,
items: Vec<TodoItem>,
}
#[derive(Debug, PartialEq)]
pub struct CollectedThreadEvents {
pub events: Vec<ThreadEvent>,
pub status: CodexStatus,
}
impl EventProcessorWithJsonOutput {
pub fn new(last_message_path: Option<PathBuf>) -> Self {
Self {
last_message_path,
next_item_id: AtomicU64::new(0),
raw_to_exec_item_id: HashMap::new(),
running_todo_list: None,
last_total_token_usage: None,
last_critical_error: None,
final_message: None,
emit_final_message_on_shutdown: false,
}
}
pub fn final_message(&self) -> Option<&str> {
self.final_message.as_deref()
}
fn next_item_id(&self) -> String {
format!("item_{}", self.next_item_id.fetch_add(1, Ordering::SeqCst))
}
#[allow(clippy::print_stdout)]
fn emit(&self, event: ThreadEvent) {
println!(
"{}",
serde_json::to_string(&event).unwrap_or_else(|err| {
json!({
"type": "error",
"message": format!("failed to serialize exec json event: {err}"),
})
.to_string()
})
);
}
fn usage_from_last_total(&self) -> Usage {
let Some(usage) = self.last_total_token_usage.as_ref() else {
return Usage::default();
};
Usage {
input_tokens: usage.total.input_tokens,
cached_input_tokens: usage.total.cached_input_tokens,
cache_write_input_tokens: usage.total.cache_write_input_tokens,
output_tokens: usage.total.output_tokens,
reasoning_output_tokens: usage.total.reasoning_output_tokens,
}
}
pub fn map_todo_items(plan: &[codex_app_server_protocol::TurnPlanStep]) -> Vec<TodoItem> {
plan.iter()
.map(|step| TodoItem {
text: step.step.clone(),
completed: matches!(
step.status,
codex_app_server_protocol::TurnPlanStepStatus::Completed
),
})
.collect()
}
fn map_item_with_id(
item: ThreadItemPayload,
make_id: impl FnOnce() -> String,
) -> Option<ExecThreadItem> {
match item {
ThreadItemPayload::AgentMessage { text, .. } => Some(ExecThreadItem {
id: make_id(),
details: ThreadItemDetails::AgentMessage(AgentMessageItem { text }),
}),
ThreadItemPayload::Reasoning { summary, .. } => {
let text = summary.join("\n");
if text.trim().is_empty() {
return None;
}
Some(ExecThreadItem {
id: make_id(),
details: ThreadItemDetails::Reasoning(ReasoningItem { text }),
})
}
ThreadItemPayload::CommandExecution {
command,
aggregated_output,
exit_code,
status,
..
} => Some(ExecThreadItem {
id: make_id(),
details: ThreadItemDetails::CommandExecution(CommandExecutionItem {
command,
aggregated_output: aggregated_output.unwrap_or_default(),
exit_code,
status: match status {
CommandExecutionStatus::InProgress => ExecCommandExecutionStatus::InProgress,
CommandExecutionStatus::Completed => ExecCommandExecutionStatus::Completed,
CommandExecutionStatus::Failed => ExecCommandExecutionStatus::Failed,
CommandExecutionStatus::Declined => ExecCommandExecutionStatus::Declined,
},
}),
}),
ThreadItemPayload::FileChange {
changes, status, ..
} => Some(ExecThreadItem {
id: make_id(),
details: ThreadItemDetails::FileChange(FileChangeItem {
changes: changes
.into_iter()
.map(|change| FileUpdateChange {
path: change.path,
kind: match change.kind {
PatchChangeKind::Add => ExecPatchChangeKind::Add,
PatchChangeKind::Delete => ExecPatchChangeKind::Delete,
PatchChangeKind::Update { .. } => ExecPatchChangeKind::Update,
},
})
.collect(),
status: match status {
PatchApplyStatus::InProgress => ExecPatchApplyStatus::InProgress,
PatchApplyStatus::Completed => ExecPatchApplyStatus::Completed,
PatchApplyStatus::Failed | PatchApplyStatus::Declined => {
ExecPatchApplyStatus::Failed
}
},
}),
}),
ThreadItemPayload::McpToolCall {
server,
tool,
status,
arguments,
result,
error,
..
} => Some(ExecThreadItem {
id: make_id(),
details: ThreadItemDetails::McpToolCall(McpToolCallItem {
server,
tool,
status: match status {
McpToolCallStatus::InProgress => ExecMcpToolCallStatus::InProgress,
McpToolCallStatus::Completed => ExecMcpToolCallStatus::Completed,
McpToolCallStatus::Failed => ExecMcpToolCallStatus::Failed,
},
arguments,
result: result.map(|result| McpToolCallItemResult {
content: result.content,
meta: result.meta,
structured_content: result.structured_content,
}),
error: error.map(|error| McpToolCallItemError {
message: error.message,
}),
}),
}),
ThreadItemPayload::CollabAgentToolCall {
tool,
sender_thread_id,
receiver_thread_ids,
prompt,
agents_states,
status,
..
} => Some(ExecThreadItem {
id: make_id(),
details: ThreadItemDetails::CollabToolCall(CollabToolCallItem {
tool: match tool {
CollabAgentTool::SendMessage
| CollabAgentTool::FollowupTask
| CollabAgentTool::InterruptAgent
| CollabAgentTool::ListAgents => return None,
CollabAgentTool::SpawnAgent => CollabTool::SpawnAgent,
CollabAgentTool::SendInput => CollabTool::SendInput,
CollabAgentTool::ResumeAgent => CollabTool::Wait,
CollabAgentTool::Wait => CollabTool::Wait,
CollabAgentTool::CloseAgent => CollabTool::CloseAgent,
},
sender_thread_id,
receiver_thread_ids,
prompt,
agents_states: agents_states
.into_iter()
.map(|(thread_id, state)| {
(
thread_id,
CollabAgentState {
status: match state.status {
codex_app_server_protocol::CollabAgentStatus::PendingInit => {
CollabAgentStatus::PendingInit
}
codex_app_server_protocol::CollabAgentStatus::Running => {
CollabAgentStatus::Running
}
codex_app_server_protocol::CollabAgentStatus::Interrupted => {
CollabAgentStatus::Interrupted
}
codex_app_server_protocol::CollabAgentStatus::Completed => {
CollabAgentStatus::Completed
}
codex_app_server_protocol::CollabAgentStatus::Errored => {
CollabAgentStatus::Errored
}
codex_app_server_protocol::CollabAgentStatus::Shutdown => {
CollabAgentStatus::Shutdown
}
codex_app_server_protocol::CollabAgentStatus::NotFound => {
CollabAgentStatus::NotFound
}
},
message: state.message,
},
)
})
.collect(),
status: match status {
CollabAgentToolCallStatus::InProgress => CollabToolCallStatus::InProgress,
CollabAgentToolCallStatus::Completed => CollabToolCallStatus::Completed,
CollabAgentToolCallStatus::Failed => CollabToolCallStatus::Failed,
CollabAgentToolCallStatus::Interrupted => return None,
},
}),
}),
ThreadItemPayload::WebSearch(item) => Some(ExecThreadItem {
id: make_id(),
details: ThreadItemDetails::WebSearch(WebSearchItem {
id: item.id,
query: item.query,
action: match item.action {
Some(ApiWebSearchAction::Search { query, queries }) => {
WebSearchAction::Search { query, queries }
}
Some(ApiWebSearchAction::OpenPage { url }) => {
WebSearchAction::OpenPage { url }
}
Some(ApiWebSearchAction::FindInPage { url, pattern }) => {
WebSearchAction::FindInPage { url, pattern }
}
Some(ApiWebSearchAction::Other) | None => WebSearchAction::Other,
},
results: item.results,
}),
}),
_ => None,
}
}
fn started_item_id(&mut self, raw_id: &str) -> String {
if let Some(existing) = self.raw_to_exec_item_id.get(raw_id) {
return existing.clone();
}
let exec_id = self.next_item_id();
self.raw_to_exec_item_id
.insert(raw_id.to_string(), exec_id.clone());
exec_id
}
fn completed_item_id(&mut self, raw_id: &str) -> String {
self.raw_to_exec_item_id
.remove(raw_id)
.unwrap_or_else(|| self.next_item_id())
}
fn map_started_item(&mut self, item: ThreadItemPayload) -> Option<ExecThreadItem> {
match item {
ThreadItemPayload::AgentMessage { .. } | ThreadItemPayload::Reasoning { .. } => None,
other => {
let raw_id = other.id().to_string();
Self::map_item_with_id(other, || self.started_item_id(&raw_id))
}
}
}
fn map_completed_item_mut(&mut self, item: ThreadItemPayload) -> Option<ExecThreadItem> {
if let ThreadItemPayload::Reasoning { summary, .. } = &item
&& summary.join("\n").trim().is_empty()
{
return None;
}
match &item {
ThreadItemPayload::AgentMessage { .. } | ThreadItemPayload::Reasoning { .. } => {
Self::map_item_with_id(item, || self.next_item_id())
}
other => {
let raw_id = other.id().to_string();
Self::map_item_with_id(item, || self.completed_item_id(&raw_id))
}
}
}
fn reconcile_unfinished_started_items(
&mut self,
turn_items: &[codex_app_server_protocol::ThreadItem],
) -> Vec<ThreadEvent> {
turn_items
.iter()
.filter_map(|item| {
let raw_id = item.id().to_string();
if !self.raw_to_exec_item_id.contains_key(&raw_id) {
return None;
}
self.map_completed_item_mut(item.payload.clone())
.map(|item| ThreadEvent::ItemCompleted(ItemCompletedEvent { item }))
})
.collect()
}
fn final_message_from_turn_items(
items: &[impl std::borrow::Borrow<ThreadItemPayload>],
) -> Option<String> {
items
.iter()
.rev()
.find_map(|item| match item.borrow() {
ThreadItemPayload::AgentMessage { text, .. } => Some(text.clone()),
_ => None,
})
.or_else(|| {
items.iter().rev().find_map(|item| match item.borrow() {
ThreadItemPayload::Plan { text, .. } => Some(text.clone()),
_ => None,
})
})
}
pub fn thread_started_event(session_configured: &SessionConfiguredEvent) -> ThreadEvent {
ThreadEvent::ThreadStarted(ThreadStartedEvent {
thread_id: session_configured.thread_id.to_string(),
})
}
pub fn collect_warning(&mut self, message: String) -> CollectedThreadEvents {
CollectedThreadEvents {
events: vec![ThreadEvent::ItemCompleted(ItemCompletedEvent {
item: ExecThreadItem {
id: self.next_item_id(),
details: ThreadItemDetails::Error(ErrorItem { message }),
},
})],
status: CodexStatus::Running,
}
}
pub fn collect_thread_events(
&mut self,
notification: ServerNotification,
) -> CollectedThreadEvents {
let mut events = Vec::new();
let status = match notification {
ServerNotification::ConfigWarning(notification) => {
let message = match notification.details {
Some(details) if !details.is_empty() => {
format!("{} ({details})", notification.summary)
}
_ => notification.summary,
};
events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent {
item: ExecThreadItem {
id: self.next_item_id(),
details: ThreadItemDetails::Error(ErrorItem { message }),
},
}));
CodexStatus::Running
}
ServerNotification::Warning(notification) => {
let warning = self.collect_warning(notification.message);
events.extend(warning.events);
warning.status
}
ServerNotification::Error(notification) => {
let message = match notification.error.additional_details {
Some(details) if !details.is_empty() => {
format!("{} ({details})", notification.error.message)
}
_ => notification.error.message,
};
let error = ThreadErrorEvent { message };
self.last_critical_error = Some(error.clone());
events.push(ThreadEvent::Error(error));
CodexStatus::Running
}
ServerNotification::DeprecationNotice(notification) => {
let message = match notification.details {
Some(details) if !details.is_empty() => {
format!("{} ({details})", notification.summary)
}
_ => notification.summary,
};
events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent {
item: ExecThreadItem {
id: self.next_item_id(),
details: ThreadItemDetails::Error(ErrorItem { message }),
},
}));
CodexStatus::Running
}
ServerNotification::HookStarted(_) | ServerNotification::HookCompleted(_) => {
CodexStatus::Running
}
ServerNotification::ItemStarted(notification) => {
if let Some(item) = self.map_started_item(notification.item.payload) {
events.push(ThreadEvent::ItemStarted(ItemStartedEvent { item }));
}
CodexStatus::Running
}
ServerNotification::ItemCompleted(notification) => {
if let Some(item) = self.map_completed_item_mut(notification.item.payload) {
if let ThreadItemDetails::AgentMessage(AgentMessageItem { text }) =
&item.details
{
self.final_message = Some(text.clone());
}
events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent { item }));
}
CodexStatus::Running
}
ServerNotification::ModelRerouted(notification) => {
events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent {
item: ExecThreadItem {
id: self.next_item_id(),
details: ThreadItemDetails::Error(ErrorItem {
message: format!(
"model rerouted: {} -> {} ({:?})",
notification.from_model, notification.to_model, notification.reason
),
}),
},
}));
CodexStatus::Running
}
ServerNotification::ModelVerification(_) => CodexStatus::Running,
ServerNotification::ThreadTokenUsageUpdated(notification) => {
self.last_total_token_usage = Some(notification.token_usage);
CodexStatus::Running
}
ServerNotification::TurnCompleted(notification) => {
if let Some(running) = self.running_todo_list.take() {
events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent {
item: ExecThreadItem {
id: running.item_id,
details: ThreadItemDetails::TodoList(TodoListItem {
items: running.items,
}),
},
}));
}
events.extend(self.reconcile_unfinished_started_items(&notification.turn.items));
match notification.turn.status {
TurnStatus::Completed => {
if let Some(final_message) =
Self::final_message_from_turn_items(notification.turn.items.as_slice())
{
self.final_message = Some(final_message);
}
self.emit_final_message_on_shutdown = true;
events.push(ThreadEvent::TurnCompleted(TurnCompletedEvent {
usage: self.usage_from_last_total(),
}));
CodexStatus::InitiateShutdown
}
TurnStatus::Failed => {
self.final_message = None;
self.emit_final_message_on_shutdown = false;
let error = notification
.turn
.error
.map(|error| ThreadErrorEvent {
message: match error.additional_details {
Some(details) if !details.is_empty() => {
format!("{} ({details})", error.message)
}
_ => error.message,
},
})
.or_else(|| self.last_critical_error.clone())
.unwrap_or_else(|| ThreadErrorEvent {
message: "turn failed".to_string(),
});
events.push(ThreadEvent::TurnFailed(TurnFailedEvent { error }));
CodexStatus::InitiateShutdown
}
TurnStatus::Interrupted => {
self.final_message = None;
self.emit_final_message_on_shutdown = false;
CodexStatus::InitiateShutdown
}
TurnStatus::InProgress => CodexStatus::Running,
}
}
ServerNotification::TurnDiffUpdated(_) => CodexStatus::Running,
ServerNotification::TurnPlanUpdated(notification) => {
let items = Self::map_todo_items(&notification.plan);
if let Some(running) = self.running_todo_list.as_mut() {
running.items = items.clone();
let item_id = running.item_id.clone();
events.push(ThreadEvent::ItemUpdated(ItemUpdatedEvent {
item: ExecThreadItem {
id: item_id,
details: ThreadItemDetails::TodoList(TodoListItem { items }),
},
}));
} else {
let item_id = self.next_item_id();
self.running_todo_list = Some(RunningTodoList {
item_id: item_id.clone(),
items: items.clone(),
});
events.push(ThreadEvent::ItemStarted(ItemStartedEvent {
item: ExecThreadItem {
id: item_id,
details: ThreadItemDetails::TodoList(TodoListItem { items }),
},
}));
}
CodexStatus::Running
}
ServerNotification::TurnStarted(_) => {
events.push(ThreadEvent::TurnStarted(TurnStartedEvent {}));
CodexStatus::Running
}
_ => CodexStatus::Running,
};
CollectedThreadEvents { events, status }
}
}
impl EventProcessor for EventProcessorWithJsonOutput {
fn print_config_summary(
&mut self,
_: &Config,
_: &str,
session_configured: &SessionConfiguredEvent,
) {
self.emit(Self::thread_started_event(session_configured));
}
fn process_server_notification(&mut self, notification: ServerNotification) -> CodexStatus {
let collected = self.collect_thread_events(notification);
for event in collected.events {
self.emit(event);
}
collected.status
}
fn process_warning(&mut self, message: String) -> CodexStatus {
let collected = self.collect_warning(message);
for event in collected.events {
self.emit(event);
}
collected.status
}
fn print_final_output(&mut self, output: Option<BoundOutput>) -> anyhow::Result<()> {
if self.emit_final_message_on_shutdown
&& let (Some(path), Some(file)) = (self.last_message_path.as_deref(), output)
{
handle_last_message(self.final_message.as_deref(), path, file)?;
}
Ok(())
}
}
#[cfg(test)]
#[path = "event_processor_with_jsonl_output_tests.rs"]
mod tests;

View File

@@ -0,0 +1,149 @@
use super::*;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::tempdir;
#[test]
fn failed_turn_does_not_overwrite_output_last_message_file() {
let tempdir = tempdir().expect("create tempdir");
let output_path = tempdir.path().join("last-message.txt");
std::fs::write(&output_path, "keep existing contents").expect("seed output file");
let mut processor = EventProcessorWithJsonOutput::new(Some(output_path.clone()));
let collected = processor.collect_thread_events(ServerNotification::ItemCompleted(
codex_app_server_protocol::ItemCompletedNotification::new(
"thread-1".to_string(),
"turn-1".to_string(),
ThreadItemPayload::AgentMessage {
moderation: None,
id: "msg-1".to_string(),
text: "partial answer".to_string(),
phase: None,
memory_citation: None,
delivery: None,
questions: None,
},
/*started_at_ms*/ None,
/*completed_at_ms*/ 0,
),
));
assert_eq!(collected.status, CodexStatus::Running);
assert_eq!(processor.final_message(), Some("partial answer"));
let status = processor.process_server_notification(ServerNotification::TurnCompleted(
codex_app_server_protocol::TurnCompletedNotification {
thread_id: "thread-1".to_string(),
turn: codex_app_server_protocol::Turn {
id: "turn-1".to_string(),
root_turn_id: None,
items_view: codex_app_server_protocol::TurnItemsView::Full,
items: Vec::new(),
status: TurnStatus::Failed,
error: Some(codex_app_server_protocol::TurnError {
misalignment: None,
message: "turn failed".to_string(),
additional_details: None,
codex_error_info: None,
}),
started_at: None,
completed_at: Some(0),
duration_ms: None,
},
},
));
assert_eq!(status, CodexStatus::InitiateShutdown);
assert_eq!(processor.final_message(), None);
let output = BoundOutput::open(&output_path).expect("bind output");
EventProcessor::print_final_output(&mut processor, Some(output)).expect("print final output");
assert_eq!(
std::fs::read_to_string(&output_path).expect("read output file"),
"keep existing contents"
);
}
#[test]
fn runtime_warning_emits_a_non_fatal_error_item() {
let mut processor = EventProcessorWithJsonOutput::new(/*last_message_path*/ None);
let collected = processor.collect_thread_events(ServerNotification::Warning(
codex_app_server_protocol::WarningNotification {
thread_id: Some("thread-1".to_string()),
message: "invalid global instructions".to_string(),
},
));
assert_eq!(
collected,
CollectedThreadEvents {
events: vec![ThreadEvent::ItemCompleted(ItemCompletedEvent {
item: ExecThreadItem {
id: "item_0".to_string(),
details: ThreadItemDetails::Error(ErrorItem {
message: "invalid global instructions".to_string(),
}),
},
})],
status: CodexStatus::Running,
}
);
}
#[test]
fn mcp_tool_call_result_preserves_meta_in_jsonl_event() {
let mut processor = EventProcessorWithJsonOutput::new(/*last_message_path*/ None);
let collected = processor.collect_thread_events(ServerNotification::ItemCompleted(
codex_app_server_protocol::ItemCompletedNotification::new(
"thread-1".to_string(),
"turn-1".to_string(),
ThreadItemPayload::McpToolCall {
id: "mcp-1".to_string(),
server: "search service".to_string(),
tool: "web_run".to_string(),
status: McpToolCallStatus::Completed,
arguments: json!({"search_query": [{"q": "OpenAI Codex CLI documentation"}]}),
app_context: None,
mcp_app_resource_uri: None,
mcp_app_ui: None,
plugin_id: None,
read_only_hint: None,
result: Some(Box::new(codex_app_server_protocol::McpToolCallResult {
content: vec![json!({"type": "text", "text": "search result"})],
structured_content: None,
meta: Some(json!({"raw_messages": [{"ref_id": "turn0search0"}]})),
})),
error: None,
duration_ms: Some(42),
},
/*started_at_ms*/ None,
/*completed_at_ms*/ 0,
),
));
assert_eq!(collected.status, CodexStatus::Running);
assert_eq!(collected.events.len(), 1);
let ThreadEvent::ItemCompleted(ItemCompletedEvent { item }) = &collected.events[0] else {
panic!("expected item.completed event");
};
let ThreadItemDetails::McpToolCall(item) = &item.details else {
panic!("expected MCP tool call item");
};
let result = item.result.as_ref().expect("expected MCP tool result");
assert_eq!(
result.meta,
Some(json!({"raw_messages": [{"ref_id": "turn0search0"}]}))
);
let serialized = serde_json::to_value(&collected.events[0]).expect("serialize event");
assert_eq!(
serialized["item"]["result"]["_meta"],
json!({"raw_messages": [{"ref_id": "turn0search0"}]})
);
assert!(serialized["item"]["result"].get("meta").is_none());
}

View File

@@ -0,0 +1,324 @@
use codex_protocol::models::WebSearchAction;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use ts_rs::TS;
/// Top-level JSONL events emitted by codex exec
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
#[serde(tag = "type")]
pub enum ThreadEvent {
/// Emitted when a new thread is started as the first event.
#[serde(rename = "thread.started")]
ThreadStarted(ThreadStartedEvent),
/// Emitted when a turn is started by sending a new prompt to the model.
/// A turn encompasses all events that happen while agent is processing the prompt.
#[serde(rename = "turn.started")]
TurnStarted(TurnStartedEvent),
/// Emitted when a turn is completed. Typically right after the assistant's response.
#[serde(rename = "turn.completed")]
TurnCompleted(TurnCompletedEvent),
/// Indicates that a turn failed with an error.
#[serde(rename = "turn.failed")]
TurnFailed(TurnFailedEvent),
/// Emitted when a new item is added to the thread. Typically the item will be in an "in progress" state.
#[serde(rename = "item.started")]
ItemStarted(ItemStartedEvent),
/// Emitted when an item is updated.
#[serde(rename = "item.updated")]
ItemUpdated(ItemUpdatedEvent),
/// Signals that an item has reached a terminal state—either success or failure.
#[serde(rename = "item.completed")]
ItemCompleted(ItemCompletedEvent),
/// Represents an unrecoverable error emitted directly by the event stream.
#[serde(rename = "error")]
Error(ThreadErrorEvent),
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct ThreadStartedEvent {
/// The identified of the new thread. Can be used to resume the thread later.
pub thread_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS, Default)]
pub struct TurnStartedEvent {}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct TurnCompletedEvent {
pub usage: Usage,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct TurnFailedEvent {
pub error: ThreadErrorEvent,
}
/// Describes the usage of tokens during a turn.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS, Default)]
pub struct Usage {
/// The number of input tokens used during the turn.
pub input_tokens: i64,
/// The number of cached input tokens used during the turn.
pub cached_input_tokens: i64,
/// The number of input tokens written to the prompt cache during the turn.
#[serde(default)]
pub cache_write_input_tokens: i64,
/// The number of output tokens used during the turn.
pub output_tokens: i64,
/// The number of reasoning output tokens used during the turn.
pub reasoning_output_tokens: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct ItemStartedEvent {
pub item: ThreadItem,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct ItemCompletedEvent {
pub item: ThreadItem,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct ItemUpdatedEvent {
pub item: ThreadItem,
}
/// Fatal error emitted by the stream.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct ThreadErrorEvent {
pub message: String,
}
/// Canonical representation of a thread item and its domain-specific payload.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct ThreadItem {
pub id: String,
#[serde(flatten)]
pub details: ThreadItemDetails,
}
/// Typed payloads for each supported thread item type.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ThreadItemDetails {
/// Response from the agent.
/// Either a natural-language response or a JSON string when structured output is requested.
AgentMessage(AgentMessageItem),
/// Agent's reasoning summary.
Reasoning(ReasoningItem),
/// Tracks a command executed by the agent. The item starts when the command is
/// spawned, and completes when the process exits with an exit code.
CommandExecution(CommandExecutionItem),
/// Represents a set of file changes by the agent. The item is emitted only as a
/// completed event once the patch succeeds or fails.
FileChange(FileChangeItem),
/// Represents a call to an MCP tool. The item starts when the invocation is
/// dispatched and completes when the MCP server reports success or failure.
McpToolCall(McpToolCallItem),
/// Represents a call to a collab tool. The item starts when the collab tool is
/// invoked and completes when the collab tool reports success or failure.
CollabToolCall(CollabToolCallItem),
/// Captures a web search request. It starts when the search is kicked off
/// and completes when results are returned to the agent.
WebSearch(WebSearchItem),
/// Tracks the agent's running to-do list. It starts when the plan is first
/// issued, updates as steps change state, and completes when the turn ends.
TodoList(TodoListItem),
/// Describes a non-fatal error surfaced as an item.
Error(ErrorItem),
}
/// Response from the agent.
/// Either a natural-language response or a JSON string when structured output is requested.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct AgentMessageItem {
pub text: String,
}
/// Agent's reasoning summary.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct ReasoningItem {
pub text: String,
}
/// The status of a command execution.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, TS)]
#[serde(rename_all = "snake_case")]
pub enum CommandExecutionStatus {
#[default]
InProgress,
Completed,
Failed,
Declined,
}
/// A command executed by the agent.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct CommandExecutionItem {
pub command: String,
pub aggregated_output: String,
pub exit_code: Option<i32>,
pub status: CommandExecutionStatus,
}
/// A set of file changes by the agent.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct FileUpdateChange {
pub path: String,
pub kind: PatchChangeKind,
}
/// The status of a file change.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
#[serde(rename_all = "snake_case")]
pub enum PatchApplyStatus {
InProgress,
Completed,
Failed,
}
/// A set of file changes by the agent.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct FileChangeItem {
pub changes: Vec<FileUpdateChange>,
pub status: PatchApplyStatus,
}
/// Indicates the type of the file change.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
#[serde(rename_all = "snake_case")]
pub enum PatchChangeKind {
Add,
Delete,
Update,
}
/// The status of an MCP tool call.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, TS)]
#[serde(rename_all = "snake_case")]
pub enum McpToolCallStatus {
#[default]
InProgress,
Completed,
Failed,
}
/// The status of a collab tool call.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, TS)]
#[serde(rename_all = "snake_case")]
pub enum CollabToolCallStatus {
#[default]
InProgress,
Completed,
Failed,
}
/// Supported collab tools.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]
#[serde(rename_all = "snake_case")]
pub enum CollabTool {
SpawnAgent,
SendInput,
Wait,
CloseAgent,
}
/// The status of a collab agent.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]
#[serde(rename_all = "snake_case")]
pub enum CollabAgentStatus {
PendingInit,
Running,
Interrupted,
Completed,
Errored,
Shutdown,
NotFound,
}
/// Last known state of a collab agent.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]
pub struct CollabAgentState {
pub status: CollabAgentStatus,
pub message: Option<String>,
}
/// A call to a collab tool.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct CollabToolCallItem {
pub tool: CollabTool,
pub sender_thread_id: String,
pub receiver_thread_ids: Vec<String>,
pub prompt: Option<String>,
pub agents_states: HashMap<String, CollabAgentState>,
pub status: CollabToolCallStatus,
}
/// Result payload produced by an MCP tool invocation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct McpToolCallItemResult {
// NOTE: `rmcp::model::Content` (and its `RawContent` variants) would be a
// more precise Rust representation of MCP content blocks. We intentionally
// use `serde_json::Value` here because this crate exports JSON schema + TS
// types (`schemars`/`ts-rs`), and the rmcp model types aren't set up to be
// schema/TS friendly (and would introduce heavier coupling to rmcp's Rust
// representations). Using `JsonValue` keeps the payload wire-shaped and
// easy to export.
pub content: Vec<JsonValue>,
#[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub meta: Option<JsonValue>,
pub structured_content: Option<JsonValue>,
}
/// Error details reported by a failed MCP tool invocation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct McpToolCallItemError {
pub message: String,
}
/// A call to an MCP tool.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct McpToolCallItem {
pub server: String,
pub tool: String,
#[serde(default)]
pub arguments: JsonValue,
pub result: Option<McpToolCallItemResult>,
pub error: Option<McpToolCallItemError>,
pub status: McpToolCallStatus,
}
/// A web search request.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct WebSearchItem {
pub id: String,
pub query: String,
pub action: WebSearchAction,
/// Structured results returned by web search, when available.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub results: Option<Vec<JsonValue>>,
}
/// An error notification.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct ErrorItem {
pub message: String,
}
/// An item in agent's to-do list.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct TodoItem {
pub text: String,
pub completed: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
pub struct TodoListItem {
pub items: Vec<TodoItem>,
}

2586
codex-rs/exec/src/lib.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,919 @@
use super::*;
use codex_app_server_protocol::AuthRecoveryNotification;
use codex_app_server_protocol::ThreadItem;
use codex_app_server_protocol::ThreadItemPayload as AppServerThreadItemPayload;
use codex_otel::set_parent_from_w3c_trace_context;
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::models::ActivePermissionProfile;
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE;
use codex_utils_absolute_path::test_support::PathBufExt;
use codex_utils_absolute_path::test_support::test_path_buf;
use opentelemetry::trace::TraceContextExt;
use opentelemetry::trace::TraceId;
use opentelemetry::trace::TracerProvider as _;
use opentelemetry_sdk::trace::SdkTracerProvider;
use pretty_assertions::assert_eq;
use std::io;
use std::io::Write;
use std::sync::Arc;
use std::sync::Mutex;
use tempfile::tempdir;
use tracing_opentelemetry::OpenTelemetrySpanExt;
fn test_tracing_subscriber() -> impl tracing::Subscriber + Send + Sync {
let provider = SdkTracerProvider::builder().build();
let tracer = provider.tracer("codex-exec-tests");
tracing_subscriber::registry().with(tracing_opentelemetry::layer().with_tracer(tracer))
}
#[derive(Clone)]
struct TestLogWriter {
buffer: Arc<Mutex<Vec<u8>>>,
}
struct TestLogSink {
buffer: Arc<Mutex<Vec<u8>>>,
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for TestLogWriter {
type Writer = TestLogSink;
fn make_writer(&'a self) -> Self::Writer {
TestLogSink {
buffer: Arc::clone(&self.buffer),
}
}
}
impl Write for TestLogSink {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.buffer.lock().expect("log buffer lock").extend(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[test]
fn exec_default_stderr_filter_suppresses_otel_self_diagnostics() {
let buffer = Arc::new(Mutex::new(Vec::new()));
let writer = TestLogWriter {
buffer: Arc::clone(&buffer),
};
let subscriber = tracing_subscriber::registry().with(
tracing_subscriber::fmt::layer()
.with_ansi(false)
.with_writer(writer)
.with_filter(EnvFilter::try_new(EXEC_DEFAULT_LOG_FILTER).expect("default filter")),
);
tracing::subscriber::with_default(subscriber, || {
tracing::error!(target: "opentelemetry_sdk", "telemetry export failed");
tracing::error!(target: "opentelemetry_otlp", "telemetry request failed");
tracing::error!(target: "codex_exec_test", "real exec error");
});
let logs = String::from_utf8(buffer.lock().expect("log buffer lock").clone()).expect("utf8");
assert!(!logs.contains("telemetry export failed"));
assert!(!logs.contains("telemetry request failed"));
assert!(logs.contains("real exec error"));
}
#[test]
fn exec_root_span_can_be_parented_from_trace_context() {
let subscriber = test_tracing_subscriber();
let _guard = tracing::subscriber::set_default(subscriber);
let parent = codex_protocol::protocol::W3cTraceContext {
traceparent: Some("00-00000000000000000000000000000077-0000000000000088-01".into()),
tracestate: Some("vendor=value".into()),
};
let exec_span = exec_root_span();
assert!(set_parent_from_w3c_trace_context(&exec_span, &parent));
let trace_id = exec_span.context().span().span_context().trace_id();
assert_eq!(
trace_id,
TraceId::from_hex("00000000000000000000000000000077").expect("trace id")
);
}
#[test]
fn builds_uncommitted_review_request() {
let args = ReviewArgs {
uncommitted: true,
base: None,
commit: None,
commit_title: None,
prompt: None,
};
let request = build_review_request(&args).expect("builds uncommitted review request");
let expected = ReviewRequest {
target: ReviewTarget::UncommittedChanges,
user_facing_hint: None,
};
assert_eq!(request, expected);
}
#[test]
fn builds_commit_review_request_with_title() {
let args = ReviewArgs {
uncommitted: false,
base: None,
commit: Some("123456789".to_string()),
commit_title: Some("Add review command".to_string()),
prompt: None,
};
let request = build_review_request(&args).expect("builds commit review request");
let expected = ReviewRequest {
target: ReviewTarget::Commit {
sha: "123456789".to_string(),
title: Some("Add review command".to_string()),
},
user_facing_hint: None,
};
assert_eq!(request, expected);
}
#[test]
fn builds_custom_review_request_trims_prompt() {
let args = ReviewArgs {
uncommitted: false,
base: None,
commit: None,
commit_title: None,
prompt: Some(" custom review instructions ".to_string()),
};
let request = build_review_request(&args).expect("builds custom review request");
let expected = ReviewRequest {
target: ReviewTarget::Custom {
instructions: "custom review instructions".to_string(),
},
user_facing_hint: None,
};
assert_eq!(request, expected);
}
#[test]
fn decode_prompt_bytes_strips_utf8_bom() {
let input = [0xEF, 0xBB, 0xBF, b'h', b'i', b'\n'];
let out = decode_prompt_bytes(&input).expect("decode utf-8 with BOM");
assert_eq!(out, "hi\n");
}
#[test]
fn decode_prompt_bytes_decodes_utf16le_bom() {
// UTF-16LE BOM + "hi\n"
let input = [0xFF, 0xFE, b'h', 0x00, b'i', 0x00, b'\n', 0x00];
let out = decode_prompt_bytes(&input).expect("decode utf-16le with BOM");
assert_eq!(out, "hi\n");
}
#[test]
fn decode_prompt_bytes_decodes_utf16be_bom() {
// UTF-16BE BOM + "hi\n"
let input = [0xFE, 0xFF, 0x00, b'h', 0x00, b'i', 0x00, b'\n'];
let out = decode_prompt_bytes(&input).expect("decode utf-16be with BOM");
assert_eq!(out, "hi\n");
}
#[test]
fn decode_prompt_bytes_rejects_utf32le_bom() {
// UTF-32LE BOM + "hi\n"
let input = [
0xFF, 0xFE, 0x00, 0x00, b'h', 0x00, 0x00, 0x00, b'i', 0x00, 0x00, 0x00, b'\n', 0x00, 0x00,
0x00,
];
let err = decode_prompt_bytes(&input).expect_err("utf-32le should be rejected");
assert_eq!(
err,
PromptDecodeError::UnsupportedBom {
encoding: "UTF-32LE"
}
);
}
#[test]
fn decode_prompt_bytes_rejects_utf32be_bom() {
// UTF-32BE BOM + "hi\n"
let input = [
0x00, 0x00, 0xFE, 0xFF, 0x00, 0x00, 0x00, b'h', 0x00, 0x00, 0x00, b'i', 0x00, 0x00, 0x00,
b'\n',
];
let err = decode_prompt_bytes(&input).expect_err("utf-32be should be rejected");
assert_eq!(
err,
PromptDecodeError::UnsupportedBom {
encoding: "UTF-32BE"
}
);
}
#[test]
fn decode_prompt_bytes_rejects_invalid_utf8() {
// Invalid UTF-8 sequence: 0xC3 0x28
let input = [0xC3, 0x28];
let err = decode_prompt_bytes(&input).expect_err("invalid utf-8 should fail");
assert_eq!(err, PromptDecodeError::InvalidUtf8 { valid_up_to: 0 });
}
#[test]
fn prompt_with_stdin_context_wraps_stdin_block() {
let combined = prompt_with_stdin_context("Summarize this concisely", "my output");
assert_eq!(
combined,
"Summarize this concisely\n\n<stdin>\nmy output\n</stdin>"
);
}
#[test]
fn prompt_with_stdin_context_preserves_trailing_newline() {
let combined = prompt_with_stdin_context("Summarize this concisely", "my output\n");
assert_eq!(
combined,
"Summarize this concisely\n\n<stdin>\nmy output\n</stdin>"
);
}
#[test]
fn lagged_event_warning_message_is_explicit() {
assert_eq!(
lagged_event_warning_message(/*skipped*/ 7),
"in-process app-server event stream lagged; dropped 7 events".to_string()
);
}
#[test]
fn runtime_warnings_are_filtered_to_the_primary_thread() {
let primary_thread_id = "thread-1";
let turn_id = "turn-1";
let outcomes = [
codex_app_server_protocol::WarningNotification {
thread_id: None,
message: "global warning".to_string(),
},
codex_app_server_protocol::WarningNotification {
thread_id: Some(primary_thread_id.to_string()),
message: "primary warning".to_string(),
},
codex_app_server_protocol::WarningNotification {
thread_id: Some("thread-2".to_string()),
message: "other warning".to_string(),
},
]
.map(|warning| {
should_process_notification(
&ServerNotification::Warning(warning),
primary_thread_id,
turn_id,
)
});
assert_eq!(outcomes, [true, true, false]);
let recovery = AuthRecoveryNotification {
thread_id: primary_thread_id.to_string(),
turn_id: turn_id.to_string(),
provider: "example".to_string(),
message: "Refresh authentication".to_string(),
};
let outcomes = [
ServerNotification::AuthRecoveryStarted(recovery.clone()),
ServerNotification::AuthRecoveryCompleted(recovery.clone()),
ServerNotification::AuthRecoveryStarted(AuthRecoveryNotification {
thread_id: "thread-2".to_string(),
..recovery.clone()
}),
ServerNotification::AuthRecoveryCompleted(AuthRecoveryNotification {
turn_id: "turn-2".to_string(),
..recovery
}),
]
.map(|notification| should_process_notification(&notification, primary_thread_id, turn_id));
assert_eq!(outcomes, [true, true, false, false]);
}
#[tokio::test]
async fn resume_lookup_model_providers_filters_only_last_lookup() {
let codex_home = tempdir().expect("create temp codex home");
let cwd = tempdir().expect("create temp cwd");
let mut config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(cwd.path().to_path_buf()))
.build()
.await
.expect("build default config");
config.model_provider_id = "test-provider".to_string();
let last_args = crate::cli::ResumeArgs {
session_id: None,
last: true,
all: false,
images: vec![],
prompt: None,
};
let named_args = crate::cli::ResumeArgs {
session_id: Some("named-session".to_string()),
last: false,
all: false,
images: vec![],
prompt: None,
};
assert_eq!(
resume_lookup_model_providers(&config, &last_args),
Some(vec!["test-provider".to_string()])
);
assert_eq!(resume_lookup_model_providers(&config, &named_args), None);
}
#[test]
fn turn_items_for_thread_returns_matching_turn_items() {
let thread = AppServerThread {
environments: None,
id: "thread-1".to_string(),
extra: None,
session_id: "thread-1".to_string(),
forked_from_id: None,
parent_thread_id: None,
preview: String::new(),
ephemeral: false,
section: None,
section_entered_at: None,
project_id: None,
daybreak_enabled: None,
history_mode: Default::default(),
model_provider: "openai".to_string(),
model: None,
reasoning_effort: None,
created_at: 0,
updated_at: 0,
recency_at: Some(0),
status: codex_app_server_protocol::ThreadStatus::Idle,
path: None,
cwd: test_path_buf("/tmp/project").abs(),
cli_version: "0.0.0-test".to_string(),
originator: None,
source: codex_app_server_protocol::SessionSource::Exec,
can_accept_direct_input: None,
thread_source: None,
agent_nickname: None,
agent_role: None,
git_info: None,
name: None,
turns: vec![
codex_app_server_protocol::Turn {
id: "turn-1".to_string(),
root_turn_id: None,
items_view: codex_app_server_protocol::TurnItemsView::Full,
items: vec![ThreadItem::untimed(
AppServerThreadItemPayload::AgentMessage {
moderation: None,
id: "msg-1".to_string(),
text: "hello".to_string(),
phase: None,
memory_citation: None,
delivery: None,
questions: None,
},
)],
status: codex_app_server_protocol::TurnStatus::Completed,
error: None,
started_at: None,
completed_at: None,
duration_ms: None,
},
codex_app_server_protocol::Turn {
id: "turn-2".to_string(),
root_turn_id: None,
items_view: codex_app_server_protocol::TurnItemsView::Full,
items: vec![ThreadItem::untimed(AppServerThreadItemPayload::Plan {
id: "plan-1".to_string(),
text: "ship it".to_string(),
})],
status: codex_app_server_protocol::TurnStatus::Completed,
error: None,
started_at: None,
completed_at: None,
duration_ms: None,
},
],
};
assert_eq!(
turn_items_for_thread(&thread, "turn-1"),
Some(vec![ThreadItem::untimed(
AppServerThreadItemPayload::AgentMessage {
moderation: None,
id: "msg-1".to_string(),
text: "hello".to_string(),
phase: None,
memory_citation: None,
delivery: None,
questions: None,
}
)])
);
assert_eq!(turn_items_for_thread(&thread, "missing-turn"), None);
}
#[test]
fn should_backfill_turn_completed_items_backfills_persisted_summaries_only() {
let notification =
ServerNotification::TurnCompleted(codex_app_server_protocol::TurnCompletedNotification {
thread_id: "thread-1".to_string(),
turn: codex_app_server_protocol::Turn {
id: "turn-1".to_string(),
root_turn_id: None,
items_view: codex_app_server_protocol::TurnItemsView::Summary,
items: Vec::new(),
status: codex_app_server_protocol::TurnStatus::Completed,
error: None,
started_at: None,
completed_at: None,
duration_ms: None,
},
});
assert!(!should_backfill_turn_completed_items(
/*thread_ephemeral*/ true,
&notification
));
assert!(should_backfill_turn_completed_items(
/*thread_ephemeral*/ false,
&notification
));
}
#[test]
fn canceled_mcp_server_elicitation_response_uses_cancel_action() {
let request = serde_json::from_value(serde_json::json!({
"mode": "form",
"message": "Allow the tool call?",
"requestedSchema": { "type": "object", "properties": {} },
"_meta": { APPROVAL_KIND_KEY: APPROVAL_KIND_MCP_TOOL_CALL },
}))
.expect("valid MCP tool approval request");
let value = canceled_mcp_server_elicitation_response(&request)
.expect("mcp elicitation cancel response should serialize");
let response: McpServerElicitationRequestResponse =
serde_json::from_value(value).expect("cancel response should deserialize");
assert_eq!(
response,
McpServerElicitationRequestResponse {
action: McpServerElicitationAction::Cancel,
content: None,
meta: Some(serde_json::json!({
CANCELLATION_REASON_KEY: McpApprovalCancellationReason::NonInteractive,
})),
}
);
}
#[tokio::test]
async fn thread_start_params_include_review_policy_when_review_policy_is_manual_only() {
let codex_home = tempdir().expect("create temp codex home");
let cwd = tempdir().expect("create temp cwd");
let config = ConfigBuilder::default()
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
.codex_home(codex_home.path().to_path_buf())
.harness_overrides(ConfigOverrides {
approvals_reviewer: Some(ApprovalsReviewer::User),
..Default::default()
})
.fallback_cwd(Some(cwd.path().to_path_buf()))
.build()
.await
.expect("build config with manual-only review policy");
let params = thread_start_params_from_config(&config, &ThreadSource::User);
assert_eq!(
params.approvals_reviewer,
Some(codex_app_server_protocol::ApprovalsReviewer::User)
);
assert_eq!(params.sandbox, None);
assert_eq!(
params.permissions,
permissions_selection_from_config(&config)
);
}
#[tokio::test]
async fn thread_start_params_include_review_policy_when_auto_review_is_enabled() {
let codex_home = tempdir().expect("create temp codex home");
let cwd = tempdir().expect("create temp cwd");
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.harness_overrides(ConfigOverrides {
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
..Default::default()
})
.fallback_cwd(Some(cwd.path().to_path_buf()))
.build()
.await
.expect("build config with guardian review policy");
let params = thread_start_params_from_config(&config, &ThreadSource::User);
assert_eq!(
params.approvals_reviewer,
Some(codex_app_server_protocol::ApprovalsReviewer::AutoReview)
);
}
#[tokio::test]
async fn thread_resume_params_only_include_explicit_review_policy_override() {
let codex_home = tempdir().expect("create temp codex home");
let cwd = tempdir().expect("create temp cwd");
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.harness_overrides(ConfigOverrides {
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
..Default::default()
})
.fallback_cwd(Some(cwd.path().to_path_buf()))
.build()
.await
.expect("build config with guardian review policy");
let params_without_override = thread_resume_params_from_config(
&config,
"thread-id".to_string(),
/*approvals_reviewer_override*/ None,
);
let params_with_override = thread_resume_params_from_config(
&config,
"thread-id".to_string(),
Some(codex_app_server_protocol::ApprovalsReviewer::AutoReview),
);
assert_eq!(params_without_override.approvals_reviewer, None);
assert_eq!(
params_with_override.approvals_reviewer,
Some(codex_app_server_protocol::ApprovalsReviewer::AutoReview)
);
}
#[tokio::test]
async fn build_exec_config_retries_without_invalid_headless_policy_for_auto_review() {
let codex_home = tempdir().expect("create temp codex home");
let cwd = tempdir().expect("create temp cwd");
std::fs::write(
codex_home.path().join("config.toml"),
r#"
approval_policy = "on-request"
approvals_reviewer = "auto_review"
"#,
)
.expect("write config");
let requirements_path = codex_home.path().join("requirements.toml");
std::fs::write(
&requirements_path,
r#"
allowed_approval_policies = ["never", "on-request"]
allowed_sandbox_modes = ["read-only", "workspace-write"]
"#,
)
.expect("write requirements");
let mut loader_overrides = LoaderOverrides::without_managed_config_for_tests();
loader_overrides.system_requirements_path = Some(requirements_path);
let overrides = ConfigOverrides {
cwd: Some(cwd.path().to_path_buf()),
approval_policy: Some(AskForApproval::Never),
sandbox_mode: Some(SandboxMode::DangerFullAccess),
..Default::default()
};
let build_config = |overrides| {
ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.loader_overrides(loader_overrides.clone())
.harness_overrides(overrides)
.build()
};
let error = build_config(overrides.clone())
.await
.expect_err("synthetic headless approval policy should fail");
assert!(
error
.to_string()
.contains("`approval_policy = \"never\"` cannot be used")
);
let config = build_exec_config(
overrides,
/*preserve_headless_approval_policy*/ false,
build_config,
)
.await
.expect("auto-review config should retry without the synthetic approval policy");
assert_eq!(
config.permissions.approval_policy.value(),
AskForApproval::OnRequest
);
assert_eq!(config.approvals_reviewer, ApprovalsReviewer::AutoReview);
}
#[tokio::test]
async fn build_exec_config_preserves_headless_error_when_retry_fails() {
let overrides = ConfigOverrides {
approval_policy: Some(AskForApproval::Never),
..Default::default()
};
let error = build_exec_config(
overrides,
/*preserve_headless_approval_policy*/ false,
|overrides| async move {
let message = if overrides.approval_policy == Some(AskForApproval::Never) {
"headless error"
} else {
"retry error"
};
Err(std::io::Error::other(message))
},
)
.await
.expect_err("failed speculative retry should preserve the original error");
assert_eq!(error.to_string(), "headless error");
}
#[tokio::test]
async fn thread_start_params_match_history_to_persistence() {
let codex_home = tempdir().expect("create temp codex home");
let cwd = tempdir().expect("create temp cwd");
let mut config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(cwd.path().to_path_buf()))
.build()
.await
.expect("build config");
let params = thread_start_params_from_config(&config, &ThreadSource::User);
assert_eq!(
params.thread_source,
Some(codex_app_server_protocol::ThreadSource::User)
);
assert_eq!(params.history_mode, Some(ThreadHistoryMode::Paginated));
let thread_source = ThreadSource::Feature("automated_review".to_string());
let params = thread_start_params_from_config(&config, &thread_source);
assert_eq!(params.thread_source, Some(thread_source));
config.ephemeral = true;
let params = thread_start_params_from_config(&config, &ThreadSource::User);
assert_eq!(params.ephemeral, Some(true));
assert_eq!(params.history_mode, None);
}
#[tokio::test]
async fn thread_lifecycle_params_preserve_hook_trust_bypass() {
let codex_home = tempdir().expect("create temp codex home");
let cwd = tempdir().expect("create temp cwd");
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.harness_overrides(ConfigOverrides {
bypass_hook_trust: Some(true),
..Default::default()
})
.fallback_cwd(Some(cwd.path().to_path_buf()))
.build()
.await
.expect("build config with hook trust bypass");
let expected_config = Some(HashMap::from([(
"bypass_hook_trust".to_string(),
serde_json::Value::Bool(true),
)]));
let start_params = thread_start_params_from_config(&config, &ThreadSource::User);
let resume_params = thread_resume_params_from_config(
&config,
"thread-id".to_string(),
/*approvals_reviewer_override*/ None,
);
assert_eq!(start_params.config, expected_config);
assert_eq!(resume_params.config, expected_config);
}
#[test]
fn active_profile_selection_uses_profile_id_only() {
let selection = permission_profile_id_from_active_profile(ActivePermissionProfile::new(
BUILT_IN_PERMISSION_PROFILE_WORKSPACE,
));
assert_eq!(selection, BUILT_IN_PERMISSION_PROFILE_WORKSPACE.to_string());
}
#[tokio::test]
async fn thread_lifecycle_params_include_legacy_sandbox_when_no_active_profile() {
let codex_home = tempdir().expect("create temp codex home");
let cwd = tempdir().expect("create temp cwd");
let config = ConfigBuilder::default()
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
.codex_home(codex_home.path().to_path_buf())
.harness_overrides(ConfigOverrides {
sandbox_mode: Some(SandboxMode::DangerFullAccess),
..Default::default()
})
.fallback_cwd(Some(cwd.path().to_path_buf()))
.build()
.await
.expect("build config with legacy sandbox override");
let start_params = thread_start_params_from_config(&config, &ThreadSource::User);
let resume_params = thread_resume_params_from_config(
&config,
"thread-id".to_string(),
/*approvals_reviewer_override*/ None,
);
assert_eq!(config.permissions.active_permission_profile(), None);
assert_eq!(
start_params.sandbox,
Some(codex_app_server_protocol::SandboxMode::DangerFullAccess)
);
assert_eq!(start_params.permissions, None);
assert_eq!(
resume_params.sandbox,
Some(codex_app_server_protocol::SandboxMode::DangerFullAccess)
);
assert_eq!(resume_params.permissions, None);
}
#[tokio::test]
async fn session_configured_from_thread_response_uses_review_policy_from_response() {
let codex_home = tempdir().expect("create temp codex home");
let cwd = tempdir().expect("create temp cwd");
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(cwd.path().to_path_buf()))
.build()
.await
.expect("build config");
let response = sample_thread_start_response();
let event = session_configured_from_thread_start_response(&response, &config)
.expect("build bootstrap session configured event");
assert_eq!(
event.session_id.to_string(),
"67e55044-10b1-426f-9247-bb680e5fe0c7"
);
assert_eq!(
event.thread_id.to_string(),
"67e55044-10b1-426f-9247-bb680e5fe0c8"
);
assert_eq!(event.approvals_reviewer, ApprovalsReviewer::AutoReview);
}
#[tokio::test]
async fn session_configured_from_thread_response_uses_permission_profile_from_config() {
let codex_home = tempdir().expect("create temp codex home");
let cwd = tempdir().expect("create temp cwd");
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(cwd.path().to_path_buf()))
.build()
.await
.expect("build config");
let response = sample_thread_start_response();
let event = session_configured_from_thread_start_response(&response, &config)
.expect("build bootstrap session configured event");
assert_eq!(
event.permission_profile,
config.permissions.effective_permission_profile()
);
}
#[tokio::test]
async fn session_configured_from_thread_response_preserves_thread_source() {
let codex_home = tempdir().expect("create temp codex home");
let cwd = tempdir().expect("create temp cwd");
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(cwd.path().to_path_buf()))
.build()
.await
.expect("build config");
let response = sample_thread_start_response();
let event = session_configured_from_thread_start_response(&response, &config)
.expect("build bootstrap session configured event");
assert_eq!(
event.thread_source,
Some(codex_protocol::protocol::ThreadSource::User)
);
}
#[tokio::test]
async fn session_configured_from_thread_response_preserves_parent_thread_id() {
let codex_home = tempdir().expect("create temp codex home");
let cwd = tempdir().expect("create temp cwd");
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(cwd.path().to_path_buf()))
.build()
.await
.expect("build config");
let parent_thread_id = ThreadId::new();
let forked_from_id = ThreadId::new();
let mut response = sample_thread_start_response();
response.thread.parent_thread_id = Some(parent_thread_id.to_string());
response.thread.forked_from_id = Some(forked_from_id.to_string());
let event = session_configured_from_thread_start_response(&response, &config)
.expect("build bootstrap session configured event");
assert_eq!(event.parent_thread_id, Some(parent_thread_id));
assert_eq!(event.forked_from_id, Some(forked_from_id));
}
fn sample_thread_start_response() -> ThreadStartResponse {
ThreadStartResponse {
disabled_plugin_ids: Vec::new(),
thread: codex_app_server_protocol::Thread {
originator: None,
environments: None,
id: "67e55044-10b1-426f-9247-bb680e5fe0c8".to_string(),
extra: None,
session_id: "67e55044-10b1-426f-9247-bb680e5fe0c7".to_string(),
forked_from_id: None,
parent_thread_id: None,
preview: String::new(),
ephemeral: false,
section: None,
section_entered_at: None,
project_id: None,
daybreak_enabled: None,
history_mode: Default::default(),
model_provider: "openai".to_string(),
model: None,
reasoning_effort: None,
created_at: 0,
updated_at: 0,
recency_at: Some(0),
status: codex_app_server_protocol::ThreadStatus::Idle,
path: Some(PathBuf::from("/tmp/rollout.jsonl")),
cwd: test_path_buf("/tmp").abs(),
cli_version: "0.0.0".to_string(),
source: codex_app_server_protocol::SessionSource::Cli,
can_accept_direct_input: None,
thread_source: Some(codex_app_server_protocol::ThreadSource::User),
agent_nickname: None,
agent_role: None,
git_info: None,
name: Some("thread".to_string()),
turns: vec![],
},
model: "gpt-5.4".to_string(),
model_provider: "openai".to_string(),
service_tier: None,
cwd: test_path_buf("/tmp").abs(),
runtime_workspace_roots: Vec::new(),
instruction_sources: Vec::new(),
approval_policy: codex_app_server_protocol::AskForApproval::OnRequest,
approvals_reviewer: codex_app_server_protocol::ApprovalsReviewer::AutoReview,
sandbox: codex_app_server_protocol::SandboxPolicy::WorkspaceWrite {
writable_roots: vec![],
network_access: false,
exclude_tmpdir_env_var: false,
exclude_slash_tmp: false,
},
active_permission_profile: None,
reasoning_effort: None,
multi_agent_mode: Default::default(),
}
}

48
codex-rs/exec/src/main.rs Normal file
View File

@@ -0,0 +1,48 @@
// Release builds exceed rustc's default query depth when laying out the async
// MessageProcessor::handle_initialized_client_request future.
#![recursion_limit = "256"]
//! Entry-point for the `codex-exec` binary.
//!
//! When this CLI is invoked normally, it parses the standard `codex-exec` CLI
//! options and launches the non-interactive Codex agent. However, if it is
//! invoked with arg0 as `codex-linux-sandbox`, we instead treat the invocation
//! as a request to run the logic for the standalone `codex-linux-sandbox`
//! executable (i.e., parse any -s args and then run a *sandboxed* command under
//! Landlock + seccomp.
//!
//! This allows us to ship a completely separate set of functionality as part
//! of the `codex-exec` binary.
use clap::Parser;
use codex_arg0::Arg0DispatchPaths;
use codex_arg0::arg0_dispatch_or_else;
use codex_exec::Cli;
use codex_exec::run_main;
use codex_utils_cli::CliConfigOverrides;
#[derive(Parser, Debug)]
struct TopCli {
#[clap(flatten)]
config_overrides: CliConfigOverrides,
#[clap(flatten)]
inner: Cli,
}
fn main() -> anyhow::Result<()> {
arg0_dispatch_or_else(|arg0_paths: Arg0DispatchPaths| async move {
let top_cli = TopCli::parse();
// Merge root-level overrides into inner CLI struct so downstream logic remains unchanged.
let mut inner = top_cli.inner;
inner
.config_overrides
.prepend_root_overrides(top_cli.config_overrides);
run_main(inner, arg0_paths).await?;
Ok(())
})
}
#[cfg(test)]
#[path = "main_tests.rs"]
mod tests;

View File

@@ -0,0 +1,43 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn top_cli_parses_resume_prompt_after_config_flag() {
const PROMPT: &str = "echo resume-with-global-flags-after-subcommand";
let cli = TopCli::parse_from([
"codex-exec",
"resume",
"--strict-config",
"--last",
"--json",
"--model",
"gpt-5.2-codex",
"--config",
"reasoning_level=xhigh",
"--dangerously-bypass-approvals-and-sandbox",
"--skip-git-repo-check",
PROMPT,
]);
let mut inner = cli.inner;
inner
.config_overrides
.prepend_root_overrides(cli.config_overrides);
let Some(codex_exec::Command::Resume(args)) = inner.command.as_ref() else {
panic!("expected resume command");
};
let effective_prompt = args.prompt.clone().or_else(|| {
if args.last {
args.session_id.clone()
} else {
None
}
});
assert_eq!(effective_prompt.as_deref(), Some(PROMPT));
assert_eq!(inner.config_overrides.raw_overrides.len(), 1);
assert_eq!(
inner.config_overrides.raw_overrides[0],
"reasoning_level=xhigh"
);
assert!(inner.strict_config);
}

View File

@@ -0,0 +1,89 @@
//! Resolves managed fork sources through the existing name/ID lookup before final configuration.
//! The temporary app-server never starts a thread or executes a turn.
use super::*;
pub(super) struct ForkNetwork {
pub cloud_config_bundle: CloudConfigBundleLoader,
pub policy: codex_app_server_client::EmbeddedNetworkPolicy,
}
pub(super) async fn fork_source(
args: &mut crate::cli::ForkArgs,
config: &Config,
arg0_paths: &Arg0DispatchPaths,
cli_overrides: &[(String, codex_config::TomlValue)],
loader_overrides: &LoaderOverrides,
network: ForkNetwork,
strict_config: bool,
) -> anyhow::Result<std::path::PathBuf> {
let state_db = codex_core::init_state_db(config).await;
let environment_manager = EnvironmentManager::from_codex_home(
config.codex_home.clone(),
Some(ExecServerRuntimeOptions::from_optional_paths(
arg0_paths.codex_self_exe.clone(),
arg0_paths.codex_linux_sandbox_exe.clone(),
)?),
network.policy.bind(config.http_client_factory()),
)
.await?;
let client = InProcessAppServerClient::start(InProcessClientStartArgs {
required_human_approval: false,
arg0_paths: arg0_paths.clone(),
config: std::sync::Arc::new(config.clone()),
cli_overrides: cli_overrides.to_vec(),
loader_overrides: LoaderOverrides {
ignore_project_config: true,
..loader_overrides.clone()
},
strict_config,
cloud_config_bundle: network.cloud_config_bundle,
embedded_network_policy: network.policy,
feedback: CodexFeedback::new(),
log_db: None,
state_db: state_db.clone(),
environment_manager: std::sync::Arc::new(environment_manager),
config_warnings: Vec::new(),
session_source: SessionSource::Exec,
enable_codex_api_key_env: true,
client_name: "codex_exec".to_string(),
client_version: env!("CARGO_PKG_VERSION").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 result = async {
let lookup = crate::cli::ResumeArgs {
session_id: Some(args.session_id.clone()),
last: false,
all: true,
images: Vec::new(),
prompt: None,
};
let thread_id = resolve_resume_thread_id(&client, config, state_db.as_ref(), &lookup)
.await?
.ok_or_else(|| anyhow::anyhow!("Session not found: {}", args.session_id))?;
let source: ThreadReadResponse = send_request_with_response(
&client,
ClientRequest::ThreadRead {
request_id: RequestId::Integer(1),
params: ThreadReadParams {
thread_id: thread_id.clone(),
include_turns: false,
},
},
"thread/read",
)
.await
.map_err(anyhow::Error::msg)?;
args.session_id = thread_id;
Ok::<_, anyhow::Error>(latest_thread_cwd(&source.thread).await)
}
.await;
let shutdown = client.shutdown().await;
let source_cwd = result?;
shutdown?;
Ok(source_cwd)
}

View File

@@ -0,0 +1,7 @@
#![allow(clippy::expect_used)]
// Single integration test binary that aggregates all test modules.
// The submodules live in `tests/suite/`.
mod suite;
mod event_processor_with_json_output;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,4 @@
class BaseClass:
def method():
return True

View File

@@ -0,0 +1,72 @@
#![cfg(not(target_os = "windows"))]
#![allow(clippy::unwrap_used)]
use core_test_support::responses;
use core_test_support::test_codex_exec::test_codex_exec;
/// Verify that the --add-dir flag is accepted and the command runs successfully.
/// This test confirms the CLI argument is properly wired up.
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn accepts_add_dir_flag() -> anyhow::Result<()> {
let test = test_codex_exec();
let server = responses::start_mock_server().await;
let body = responses::sse(vec![
responses::ev_response_created("response_1"),
responses::ev_assistant_message("response_1", "Task completed"),
responses::ev_completed("response_1"),
]);
responses::mount_sse_once(&server, body).await;
// Create temporary directories to use with --add-dir
let temp_dir1 = tempfile::tempdir()?;
let temp_dir2 = tempfile::tempdir()?;
test.cmd_with_server(&server)
.arg("--skip-git-repo-check")
.arg("--sandbox")
.arg("workspace-write")
.arg("--add-dir")
.arg(temp_dir1.path())
.arg("--add-dir")
.arg(temp_dir2.path())
.arg("test with additional directories")
.assert()
.code(0);
Ok(())
}
/// Verify that multiple --add-dir flags can be specified.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn accepts_multiple_add_dir_flags() -> anyhow::Result<()> {
let test = test_codex_exec();
let server = responses::start_mock_server().await;
let body = responses::sse(vec![
responses::ev_response_created("response_1"),
responses::ev_assistant_message("response_1", "Multiple directories accepted"),
responses::ev_completed("response_1"),
]);
responses::mount_sse_once(&server, body).await;
let temp_dir1 = tempfile::tempdir()?;
let temp_dir2 = tempfile::tempdir()?;
let temp_dir3 = tempfile::tempdir()?;
test.cmd_with_server(&server)
.arg("--skip-git-repo-check")
.arg("--sandbox")
.arg("workspace-write")
.arg("--add-dir")
.arg(temp_dir1.path())
.arg("--add-dir")
.arg(temp_dir2.path())
.arg("--add-dir")
.arg(temp_dir3.path())
.arg("test with three directories")
.assert()
.code(0);
Ok(())
}

View File

@@ -0,0 +1,74 @@
#![allow(clippy::unwrap_used)]
use core_test_support::responses;
use core_test_support::test_codex_exec::test_codex_exec;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_includes_workspace_agents_md_in_request() -> anyhow::Result<()> {
let test = test_codex_exec();
std::fs::write(test.cwd_path().join("AGENTS.md"), "workspace instructions")?;
let server = responses::start_mock_server().await;
let body = responses::sse(vec![
responses::ev_response_created("resp1"),
responses::ev_assistant_message("m1", "fixture hello"),
responses::ev_completed("resp1"),
]);
let response_mock = responses::mount_sse_once(&server, body).await;
test.cmd_with_server(&server)
.arg("--skip-git-repo-check")
.arg("tell me something")
.assert()
.success();
let user_messages = response_mock.single_request().message_input_texts("user");
assert!(
user_messages
.iter()
.any(|text| text.contains("workspace instructions")),
"request should include workspace AGENTS.md instructions: {user_messages:?}"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_prefers_workspace_agents_override_md() -> anyhow::Result<()> {
let test = test_codex_exec();
std::fs::write(test.cwd_path().join("AGENTS.md"), "base instructions")?;
std::fs::write(
test.cwd_path().join("AGENTS.override.md"),
"override instructions",
)?;
let server = responses::start_mock_server().await;
let body = responses::sse(vec![
responses::ev_response_created("resp1"),
responses::ev_assistant_message("m1", "fixture hello"),
responses::ev_completed("resp1"),
]);
let response_mock = responses::mount_sse_once(&server, body).await;
test.cmd_with_server(&server)
.arg("--skip-git-repo-check")
.arg("tell me something")
.assert()
.success();
let user_messages = response_mock.single_request().message_input_texts("user");
assert!(
user_messages
.iter()
.any(|text| text.contains("override instructions")),
"request should include AGENTS.override.md instructions: {user_messages:?}"
);
assert!(
user_messages
.iter()
.all(|text| !text.contains("base instructions")),
"request should exclude shadowed AGENTS.md instructions: {user_messages:?}"
);
Ok(())
}

View File

@@ -0,0 +1,519 @@
#![allow(clippy::unwrap_used, unused_imports)]
use anyhow::Context;
use assert_cmd::prelude::*;
use codex_apply_patch::CODEX_CORE_APPLY_PATCH_ARG1;
use core_test_support::responses::ev_apply_patch_custom_tool_call;
use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_exec_command_call_with_args;
use core_test_support::responses::mount_sse_sequence;
use core_test_support::responses::sse;
use core_test_support::responses::start_mock_server;
use pretty_assertions::assert_eq;
use std::fs;
use std::process::Command;
use tempfile::tempdir;
/// While we may add an `apply-patch` subcommand to the `codex` CLI multitool
/// at some point, we must ensure that the smaller `codex-exec` CLI can still
/// emulate the `apply_patch` CLI.
#[test]
fn test_standalone_exec_cli_can_use_apply_patch() -> anyhow::Result<()> {
let tmp = tempdir()?;
let relative_path = "source.txt";
let absolute_path = tmp.path().join(relative_path);
fs::write(&absolute_path, "original content\n")?;
Command::new(codex_utils_cargo_bin::cargo_bin("codex-exec")?)
.arg(CODEX_CORE_APPLY_PATCH_ARG1)
.arg(
r#"*** Begin Patch
*** Update File: source.txt
@@
-original content
+modified by apply_patch
*** End Patch"#,
)
.current_dir(tmp.path())
.assert()
.success()
.stdout("Success. Updated the following files:\nM source.txt\n")
.stderr(predicates::str::is_empty());
assert_eq!(
fs::read_to_string(absolute_path)?,
"modified by apply_patch\n"
);
Ok(())
}
#[cfg(not(target_os = "windows"))]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_apply_patch_tool() -> anyhow::Result<()> {
use core_test_support::skip_if_no_network;
use core_test_support::test_codex_exec::test_codex_exec;
skip_if_no_network!(Ok(()));
let test = test_codex_exec();
let tmp_path = test.cwd_path().to_path_buf();
let add_patch = r#"*** Begin Patch
*** Add File: test.md
+Hello world
*** End Patch"#;
let update_patch = r#"*** Begin Patch
*** Update File: test.md
@@
-Hello world
+Final text
*** End Patch"#;
let response_streams = vec![
sse(vec![
ev_apply_patch_custom_tool_call("request_0", add_patch),
ev_completed("request_0"),
]),
sse(vec![
ev_apply_patch_custom_tool_call("request_1", update_patch),
ev_completed("request_1"),
]),
sse(vec![ev_completed("request_2")]),
];
let server = start_mock_server().await;
mount_sse_sequence(&server, response_streams).await;
test.cmd_with_server(&server)
.arg("--skip-git-repo-check")
.arg("-s")
.arg("danger-full-access")
.arg("foo")
.assert()
.success();
let final_path = tmp_path.join("test.md");
let contents = std::fs::read_to_string(&final_path).expect("final file should be readable");
assert_eq!(contents, "Final text\n");
Ok(())
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn human_output_prints_unchanged_turn_diff_once() -> anyhow::Result<()> {
use core_test_support::skip_if_no_network;
use core_test_support::test_codex_exec::test_codex_exec;
skip_if_no_network!(Ok(()));
let test = test_codex_exec();
let run_dir = test.cwd_path();
Command::new("git")
.args(["init", "--quiet"])
.current_dir(run_dir)
.assert()
.success();
fs::write(run_dir.join("probe.txt"), "value=1\n")?;
Command::new("git")
.args(["add", "probe.txt"])
.current_dir(run_dir)
.assert()
.success();
Command::new("git")
.args([
"-c",
"user.name=Reproducer",
"-c",
"user.email=reproducer@example.invalid",
"commit",
"--quiet",
"-m",
"baseline",
])
.current_dir(run_dir)
.assert()
.success();
// Replay the reported single edit, unrelated command, and final response.
let server = start_mock_server().await;
let mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_apply_patch_custom_tool_call(
"patch",
"*** Begin Patch\n*** Update File: probe.txt\n@@\n-value=1\n+value=2\n*** End Patch",
),
ev_completed("response-1"),
]),
sse(vec![
ev_exec_command_call_with_args(
"command",
&serde_json::json!({
"cmd": "printf 'DIAG_CMD_OK\\n'",
"shell": "/bin/sh",
"login": false,
"yield_time_ms": 10_000,
}),
),
ev_completed("response-2"),
]),
sse(vec![
ev_assistant_message("message", "DIAG_DONE"),
ev_completed("response-3"),
]),
],
)
.await;
let result = test
.cmd_with_server(&server)
.args([
"--ephemeral",
"--color",
"never",
"-s",
"danger-full-access",
"-c",
"features.hooks=false",
"-c",
"features.shell_snapshot=false",
"-c",
"features.shell_snapshot_v2=false",
"Replace value=1 with value=2 once, print DIAG_CMD_OK, then finish with DIAG_DONE.",
])
.assert()
.success()
.stdout("DIAG_DONE\n");
let stderr = String::from_utf8_lossy(&result.get_output().stderr);
assert_eq!(fs::read_to_string(run_dir.join("probe.txt"))?, "value=2\n");
assert_eq!(mock.requests().len(), 3);
assert_eq!(stderr.matches("patch: completed").count(), 1, "{stderr}");
assert_eq!(
stderr.lines().filter(|line| *line == "DIAG_CMD_OK").count(),
1,
"{stderr}"
);
assert_eq!(
stderr
.lines()
.filter(|line| *line == "diff --git a/probe.txt b/probe.txt")
.count(),
1,
"{stderr}"
);
Ok(())
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn nested_apply_patch_alias_works_with_restricted_reads() -> anyhow::Result<()> {
use core_test_support::skip_if_no_network;
use core_test_support::skip_if_sandbox;
use core_test_support::test_codex_exec::test_codex_exec;
skip_if_no_network!(Ok(()));
skip_if_sandbox!(Ok(()));
#[cfg(target_os = "linux")]
if super::sandbox::linux_sandbox_test_env().await.is_none() {
return Ok(());
}
let test = test_codex_exec();
let binary = codex_utils_cargo_bin::cargo_bin("codex-exec")?.canonicalize()?;
let binary_dir = serde_json::to_string(binary.parent().expect("binary directory"))?;
let codex_home = serde_json::to_string(test.home_path())?;
fs::write(
test.home_path().join("config.toml"),
format!(
r#"default_permissions = "aliases"
approval_policy = "never"
[features]
shell_snapshot = false
shell_snapshot_v2 = false
[permissions.aliases.filesystem]
":minimal" = "read"
":project_roots" = "write"
{binary_dir} = "read"
{codex_home} = "none"
"#
),
)?;
fs::write(
test.home_path().join("outside-workspace.txt"),
"must remain unreadable to the script",
)?;
fs::write(
test.cwd_path().join("patch.sh"),
"if cat \"$HOME/outside-workspace.txt\" >/dev/null 2>&1; then exit 99; fi\napply_patch <<'PATCH'\n*** Begin Patch\n*** Add File: patched.txt\n+through the nested alias\n*** End Patch\nPATCH\n",
)?;
let server = start_mock_server().await;
let mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_exec_command_call_with_args(
"nested-patch",
&serde_json::json!({
"cmd": "/bin/sh patch.sh",
"shell": "/bin/sh",
"login": false,
"yield_time_ms": 10_000,
}),
),
ev_completed("response-1"),
]),
sse(vec![ev_completed("response-2")]),
],
)
.await;
let run = test.cmd_with_server(&server)
.env("HOME", test.home_path())
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.arg("--skip-git-repo-check")
.arg("-c")
.arg("default_permissions=\"aliases\"")
.arg("-c")
.arg("approvals_reviewer=\"user\"")
.arg("-c")
.arg("model_provider=\"test\"")
.arg("-c")
.arg(format!(
"model_providers.test={{name=\"test\",base_url={:?},wire_api=\"responses\",requires_openai_auth=false,supports_websockets=false}}",
format!("{}/v1", server.uri())
))
.arg("run the patch script")
.assert()
.success();
let output = mock
.function_call_output_text("nested-patch")
.expect("tool output");
assert!(
output.contains("Process exited with code 0"),
"{output}\n{}",
String::from_utf8_lossy(&run.get_output().stderr)
);
assert_eq!(
fs::read_to_string(test.cwd_path().join("patched.txt"))?,
"through the nested alias\n"
);
Ok(())
}
#[cfg(not(target_os = "windows"))]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_apply_patch_freeform_tool() -> anyhow::Result<()> {
use core_test_support::skip_if_no_network;
use core_test_support::test_codex_exec::test_codex_exec;
skip_if_no_network!(Ok(()));
let test = test_codex_exec();
let freeform_add_patch = r#"*** Begin Patch
*** Add File: app.py
+class BaseClass:
+ def method():
+ return False
*** End Patch"#;
let freeform_update_patch = r#"*** Begin Patch
*** Update File: app.py
@@ def method():
- return False
+
+ return True
*** End Patch"#;
let response_streams = vec![
sse(vec![
ev_apply_patch_custom_tool_call("request_0", freeform_add_patch),
ev_completed("request_0"),
]),
sse(vec![
ev_apply_patch_custom_tool_call("request_1", freeform_update_patch),
ev_completed("request_1"),
]),
sse(vec![ev_completed("request_2")]),
];
let server = start_mock_server().await;
mount_sse_sequence(&server, response_streams).await;
test.cmd_with_server(&server)
.arg("--skip-git-repo-check")
.arg("-s")
.arg("danger-full-access")
.arg("foo")
.assert()
.success();
// Verify final file contents
let final_path = test.cwd_path().join("app.py");
let contents = std::fs::read_to_string(&final_path).expect("final file should be readable");
assert_eq!(
contents,
include_str!("../fixtures/apply_patch_freeform_final.txt")
);
Ok(())
}
#[cfg(not(target_os = "windows"))]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn shutdown_flushes_completed_turn_and_file_diff() -> anyhow::Result<()> {
use codex_login::AuthDotJson;
use codex_login::AuthKeyringBackendKind;
use codex_login::TokenData;
use codex_login::save_auth;
use codex_login::token_data::IdTokenInfo;
use codex_protocol::auth::AuthMode;
use core_test_support::skip_if_no_network;
use core_test_support::test_codex_exec::test_codex_exec;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use wiremock::Mock;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
skip_if_no_network!(Ok(()));
let test = test_codex_exec();
let run_dir = test.cwd_path();
assert!(
std::process::Command::new("git")
.args(["init", "--quiet"])
.current_dir(run_dir)
.status()
.context("initialize test git repository")?
.success()
);
assert!(
std::process::Command::new("git")
.args([
"remote",
"add",
"origin",
"https://github.com/test-org/turn-profile-test.git",
])
.current_dir(run_dir)
.status()
.context("add test git remote")?
.success()
);
save_auth(
test.home_path(),
&AuthDotJson {
auth_mode: Some(AuthMode::Chatgpt),
openai_api_key: None,
tokens: Some(TokenData {
id_token: IdTokenInfo {
raw_jwt: "header.eyJhbGciOiJub25lIn0.eyJzdWIiOiJ1c2VyLTEyMyJ9.".to_string(),
..Default::default()
},
access_token: "test-access-token".to_string(),
refresh_token: "test-refresh-token".to_string(),
oauth_provenance: None,
login_owner_id: None,
account_id: None,
}),
last_refresh: None,
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
},
codex_login::AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)?;
let server = start_mock_server().await;
let deliveries = Arc::new(AtomicUsize::new(0));
let completed_deliveries = Arc::clone(&deliveries);
Mock::given(method("POST"))
.and(|request: &wiremock::Request| request.url.path().ends_with("events"))
.respond_with(move |_request: &wiremock::Request| {
// A request is counted only once its delayed handler has completed.
std::thread::sleep(Duration::from_millis(750));
completed_deliveries.fetch_add(1, Ordering::Release);
ResponseTemplate::new(200)
})
.expect(3..)
.mount(&server)
.await;
mount_sse_sequence(
&server,
vec![
sse(vec![
ev_apply_patch_custom_tool_call(
"request_0",
"*** Begin Patch\n*** Add File: flushed.md\n+persist this line\n*** End Patch",
),
ev_completed("request_0"),
]),
sse(vec![ev_completed("request_1")]),
],
)
.await;
test.cmd_with_server(&server)
.env_remove("CODEX_API_KEY")
.env_remove("CODEX_ANALYTICS_EVENTS_CAPTURE_FILE")
.arg("--skip-git-repo-check")
.arg("-s")
.arg("danger-full-access")
.arg("-c")
.arg("model_provider=\"test\"")
.arg("-c")
.arg(format!(
"model_providers.test={{name=\"test\",base_url={:?},wire_api=\"responses\",requires_openai_auth=false,supports_websockets=false}}",
format!("{}/v1", server.uri())
))
.arg("-c")
.arg("analytics.enabled=true")
.arg("-c")
.arg(format!("chatgpt_base_url={}", server.uri()))
.arg("write the file")
.assert()
.success();
let persisted = std::fs::read_to_string(run_dir.join("flushed.md"))
.context("read file written by apply_patch")?;
assert_eq!(persisted, "persist this line\n");
let requests = server
.received_requests()
.await
.context("read analytics requests")?;
let request_paths = requests
.iter()
.map(|request| request.url.path().to_string())
.collect::<Vec<_>>();
let event_types = requests
.iter()
.filter(|request| request.url.path().ends_with("events"))
.flat_map(|request| {
serde_json::from_slice::<serde_json::Value>(&request.body)
.ok()
.and_then(|body| {
body.get("events")
.and_then(serde_json::Value::as_array)
.cloned()
})
.unwrap_or_default()
.into_iter()
.filter_map(|event| event["event_type"].as_str().map(str::to_owned))
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
assert!(
deliveries.load(Ordering::Acquire) >= 3,
"the runtime exited before the delayed analytics deliveries completed (completed={}, events={event_types:?}, paths={request_paths:?})",
deliveries.load(Ordering::Acquire)
);
assert!(
event_types.iter().any(|event| event == "codex_turn_event"),
"no completed event was delivered; request paths: {request_paths:?}"
);
assert!(
event_types
.iter()
.any(|event| event == "codex_accepted_line_fingerprints"),
"no accepted-line event was delivered; request paths: {request_paths:?}"
);
Ok(())
}

View File

@@ -0,0 +1,78 @@
#![cfg(not(target_os = "windows"))]
#![allow(clippy::unwrap_used)]
use core_test_support::responses;
use core_test_support::test_codex_exec::test_codex_exec;
async fn run_exec_with_config(config_toml: &str, extra_args: &[&str]) -> anyhow::Result<String> {
let test = test_codex_exec();
std::fs::write(test.home_path().join("config.toml"), config_toml)?;
let server = responses::start_mock_server().await;
let body = responses::sse(vec![
responses::ev_response_created("response_1"),
responses::ev_assistant_message("response_1", "done"),
responses::ev_completed("response_1"),
]);
responses::mount_sse_once(&server, body).await;
let mut cmd = test.cmd_with_server(&server);
let output = cmd
.arg("--skip-git-repo-check")
.args(extra_args)
.arg("check approval mode")
.output()?;
assert!(output.status.success(), "exec run failed: {output:?}");
Ok(String::from_utf8(output.stderr)?)
}
async fn run_exec_with_auto_review_config(extra_args: &[&str]) -> anyhow::Result<String> {
run_exec_with_config(
r#"
approval_policy = "on-request"
approvals_reviewer = "auto_review"
"#,
extra_args,
)
.await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_preserves_on_request_for_auto_review_config() -> anyhow::Result<()> {
let stderr = run_exec_with_auto_review_config(&[]).await?;
assert!(
stderr.contains("approval: on-request"),
"stderr missing preserved auto-review approval mode: {stderr}"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_approve_for_me_flag_sets_approval_mode_and_sandbox() -> anyhow::Result<()> {
let stderr = run_exec_with_config("", &["--approve-for-me"]).await?;
assert!(
stderr.contains("approval: on-request"),
"stderr missing --approve-for-me approval mode: {stderr}"
);
assert!(
stderr.contains("sandbox: workspace-write"),
"stderr missing --approve-for-me sandbox mode: {stderr}"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_bypass_preserves_never_for_auto_review_config() -> anyhow::Result<()> {
let stderr =
run_exec_with_auto_review_config(&["--dangerously-bypass-approvals-and-sandbox"]).await?;
assert!(
stderr.contains("approval: never"),
"stderr missing bypass approval mode: {stderr}"
);
Ok(())
}

View File

@@ -0,0 +1,195 @@
#![allow(clippy::unwrap_used)]
use core_test_support::responses::ev_completed;
use core_test_support::responses::mount_sse_once_match;
use core_test_support::responses::sse;
use core_test_support::responses::start_mock_server;
use core_test_support::test_codex_exec::test_codex_exec;
use serde_json::json;
use wiremock::Mock;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_uses_codex_api_key_env_var() -> anyhow::Result<()> {
let test = test_codex_exec();
let server = start_mock_server().await;
let repo_root = codex_utils_cargo_bin::repo_root()?;
mount_sse_once_match(
&server,
header("Authorization", "Bearer dummy"),
sse(vec![ev_completed("request_0")]),
)
.await;
test.cmd_with_server(&server)
.arg("--skip-git-repo-check")
.arg("-C")
.arg(&repo_root)
.arg("echo testing codex api key")
.assert()
.success();
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_api_key_cannot_discard_stored_workspace_network_policy() -> anyhow::Result<()> {
let test = test_codex_exec();
let policy_server = start_mock_server().await;
let inference_server = start_mock_server().await;
let token = concat!(
"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.",
"eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF9wbGFuX3R5cGUiOiJlbnRlcnByaXNlIiwiY2hhdGdwdF9hY2NvdW50X2lkIjoid29ya3NwYWNlIn19.",
"c2lnbmF0dXJl",
);
std::fs::write(
test.home_path().join("auth.json"),
serde_json::to_vec(&json!({
"auth_mode": "chatgpt",
"tokens": {"id_token": token, "access_token": "workspace-token",
"refresh_token": "refresh-token", "account_id": "workspace"},
"last_refresh": "2099-01-01T00:00:00Z",
}))?,
)?;
std::fs::write(
test.home_path().join("config.toml"),
format!(
"chatgpt_base_url = '{}/backend-api/'\ncli_auth_credentials_store = 'file'\n",
policy_server.uri()
),
)?;
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.and(header("authorization", "Bearer workspace-token"))
.and(header("chatgpt-account-id", "workspace"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"requirements_toml": {"enterprise_managed": [{
"id": "workspace-network", "name": "Workspace network",
"contents": "[application.network]\nenabled = true",
}]},
})))
.expect(1..)
.mount(&policy_server)
.await;
let inference = mount_sse_once_match(
&inference_server,
header("Authorization", "Bearer dummy"),
sse(vec![ev_completed("unexpected-request")]),
)
.await;
test.cmd_with_server(&inference_server)
.arg("--skip-git-repo-check")
.arg("echo testing workspace network policy")
.assert()
.failure();
assert!(
inference.requests().is_empty(),
"an environment API key sent model traffic despite workspace policy"
);
policy_server.verify().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_bootstrap_rejects_redirected_oauth_and_cloud_policy() -> anyhow::Result<()> {
for redirect_oauth in [true, false] {
let test = test_codex_exec();
let origin = start_mock_server().await;
let destination = start_mock_server().await;
let inference = start_mock_server().await;
let token = concat!(
"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.",
"eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF9wbGFuX3R5cGUiOiJlbnRlcnByaXNlIiwiY2hhdGdwdF9hY2NvdW50X2lkIjoid29ya3NwYWNlIn19.",
"c2lnbmF0dXJl",
);
let last_refresh = if redirect_oauth {
"2000-01-01T00:00:00Z"
} else {
"2099-01-01T00:00:00Z"
};
std::fs::write(
test.home_path().join("auth.json"),
serde_json::to_vec(&json!({
"auth_mode": "chatgpt",
"tokens": {"id_token": token, "access_token": "workspace-token",
"refresh_token": "refresh-token", "account_id": "workspace"},
"last_refresh": last_refresh,
}))?,
)?;
std::fs::write(
test.home_path().join("config.toml"),
format!(
"chatgpt_base_url = '{}/backend-api/'\ncli_auth_credentials_store = 'file'\n",
origin.uri()
),
)?;
let cloud_response = if redirect_oauth {
Mock::given(method("POST"))
.and(path("/oauth/token"))
.and(wiremock::matchers::body_string_contains("refresh-token"))
.respond_with(
ResponseTemplate::new(307)
.insert_header("location", format!("{}/stolen", destination.uri())),
)
.expect(1..)
.mount(&origin)
.await;
Mock::given(method("POST"))
.and(path("/stolen"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"id_token": token, "access_token": "replacement", "refresh_token": "replacement",
})))
.mount(&destination)
.await;
ResponseTemplate::new(200).set_body_json(json!({}))
} else {
Mock::given(method("GET"))
.and(path("/policy"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"requirements_toml": {"enterprise_managed": [{
"id": "redirected", "name": "Redirected policy",
"contents": "[application.network.domains]\n'foreign.example' = 'allow'",
}]},
})))
.mount(&destination)
.await;
ResponseTemplate::new(308)
.insert_header("location", format!("{}/policy", destination.uri()))
};
let cloud = Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.respond_with(cloud_response);
if redirect_oauth {
cloud.mount(&origin).await;
} else {
cloud.expect(1..).mount(&origin).await;
}
mount_sse_once_match(
&inference,
header("Authorization", "Bearer dummy"),
sse(vec![ev_completed("request")]),
)
.await;
let output = test
.cmd_with_server(&inference)
.env(
codex_login::REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR,
format!("{}/oauth/token", origin.uri()),
)
.arg("--skip-git-repo-check")
.arg("exercise embedded discovery")
.output()?;
if !redirect_oauth {
assert!(!output.status.success());
}
origin.verify().await;
assert!(destination.received_requests().await.unwrap().is_empty());
}
Ok(())
}

View File

@@ -0,0 +1,225 @@
use core_test_support::responses;
use core_test_support::skip_if_no_network;
use core_test_support::test_codex_exec::test_codex_exec;
use pretty_assertions::assert_eq;
use serde_json::json;
const TRACE_REQUESTS: &str =
"codex_app_server::message_processor=trace,codex_app_server::outgoing_message=trace";
const PARENT_PROMPT: &str = "spawn a child and wait for it";
const CHILD_PROMPT: &str = "child: finish first";
const SPAWN_CALL_ID: &str = "spawn-call";
const WAIT_CALL_ID: &str = "wait-call";
fn body_contains(request: &wiremock::Request, text: &str) -> bool {
std::str::from_utf8(&request.body).is_ok_and(|body| body.contains(text))
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn ignores_unrelated_turn_completion_before_backfilling_primary_turn() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let spawn_args = json!({
"message": CHILD_PROMPT,
"task_name": "worker",
"fork_turns": "none",
})
.to_string();
let _parent_turn = responses::mount_sse_once_match(
&server,
|request: &wiremock::Request| body_contains(request, PARENT_PROMPT),
responses::sse(vec![
responses::ev_response_created("resp-parent-1"),
responses::ev_function_call_with_namespace(
SPAWN_CALL_ID,
"collaboration",
"spawn_agent",
&spawn_args,
),
responses::ev_completed("resp-parent-1"),
]),
)
.await;
let _child_turn = responses::mount_sse_once_match(
&server,
|request: &wiremock::Request| {
body_contains(request, CHILD_PROMPT) && !body_contains(request, SPAWN_CALL_ID)
},
responses::sse(vec![
responses::ev_response_created("resp-child"),
responses::ev_assistant_message("msg-child", "child done"),
responses::ev_completed("resp-child"),
]),
)
.await;
let _parent_wait = responses::mount_sse_once_match(
&server,
|request: &wiremock::Request| {
body_contains(request, SPAWN_CALL_ID) && !body_contains(request, WAIT_CALL_ID)
},
responses::sse(vec![
responses::ev_response_created("resp-parent-2"),
responses::ev_function_call_with_namespace(
WAIT_CALL_ID,
"collaboration",
"wait_agent",
"{}",
),
responses::ev_completed("resp-parent-2"),
]),
)
.await;
let _parent_completion = responses::mount_sse_once_match(
&server,
|request: &wiremock::Request| body_contains(request, WAIT_CALL_ID),
responses::sse(vec![
responses::ev_response_created("resp-parent-3"),
responses::ev_assistant_message("msg-parent", "parent done"),
responses::ev_completed("resp-parent-3"),
]),
)
.await;
let test = test_codex_exec();
let mock_provider = format!(
"model_providers.mock_provider={{name=\"Mock provider for test\",base_url=\"{}/v1\",wire_api=\"responses\",supports_websockets=false}}",
server.uri()
);
let output = test
.cmd()
.env("RUST_LOG", TRACE_REQUESTS)
.arg("--skip-git-repo-check")
.arg("--json")
.arg("-c")
.arg(mock_provider)
.args([
"-c",
"model_provider=\"mock_provider\"",
"-c",
"features.multi_agent=true",
"-c",
"features.multi_agent_v2=true",
"-c",
"features.enable_request_compression=false",
])
.arg(PARENT_PROMPT)
.output()?;
assert!(output.status.success(), "exec run failed: {output:?}");
let stdout = String::from_utf8(output.stdout)?;
assert!(
stdout.contains("parent done"),
"primary completion was not processed: {stdout}"
);
let stderr = String::from_utf8(output.stderr)?;
let lines = stderr.lines().collect::<Vec<_>>();
let turn_completions = lines
.iter()
.enumerate()
.filter_map(|(index, line)| {
line.contains("app-server event: turn/completed")
.then_some(index)
})
.collect::<Vec<_>>();
assert_eq!(
turn_completions.len(),
2,
"expected the child completion before the primary completion: {stderr}"
);
let [child_completion, primary_completion] = turn_completions.as_slice() else {
unreachable!("checked turn/completed count")
};
assert_eq!(
lines[*child_completion + 1..*primary_completion]
.iter()
.filter(|line| line.contains("app-server typed request"))
.count(),
0,
"the unrelated completion must not read history: {stderr}"
);
assert_eq!(
lines[*primary_completion + 1..]
.iter()
.filter(|line| line.contains("app-server typed request"))
.count(),
2,
"the primary completion should read its items and unsubscribe: {stderr}"
);
assert_eq!(
lines
.iter()
.filter(|line| line.contains("app-server typed request"))
.count(),
5,
"only the primary completion should issue an extra request: {stderr}"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn failed_fork_recovers_only_its_own_turn() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let test = test_codex_exec();
let last_message = test.cwd_path().join("last-message");
let mut events = vec![responses::ev_response_created("parent")];
// The parent's final answer must survive recovery across multiple item pages.
for index in 0..120 {
events.push(responses::ev_assistant_message(
&format!("msg-{index}"),
"working",
));
}
events.push(responses::ev_assistant_message("answer", "parent done"));
events.push(responses::ev_completed("parent"));
let _parent_response = responses::mount_sse_once(&server, responses::sse(events)).await;
let parent = test
.cmd_with_server(&server)
.args(["--skip-git-repo-check", "--json", "--output-last-message"])
.arg(&last_message)
.arg("Produce a long turn")
.assert()
.success();
assert_eq!(std::fs::read_to_string(last_message)?, "parent done");
let stdout = std::str::from_utf8(&parent.get_output().stdout)?;
let started: serde_json::Value = serde_json::from_str(stdout.lines().next().unwrap())?;
let parent_id = started["thread_id"].as_str().expect("parent thread ID");
let error = wiremock::ResponseTemplate::new(400).set_body_json(json!({
"error": {"code": "model_not_found", "message": "Unknown model", "type": "invalid_request_error"}
}));
let _fork_response = responses::mount_response_once(&server, error).await;
let fork = test
.cmd_with_server(&server)
.env("RUST_LOG", TRACE_REQUESTS)
.args(["--skip-git-repo-check", "--json", "fork", parent_id, "Fail"])
.assert()
.code(1);
let stdout = std::str::from_utf8(&fork.get_output().stdout)?;
let terminal: serde_json::Value = serde_json::from_str(stdout.lines().last().unwrap())?;
assert_eq!(
terminal,
json!({"type": "turn.failed", "error": {"message": "Unknown model"}})
);
let stderr = std::str::from_utf8(&fork.get_output().stderr)?;
let (_, completion) = stderr
.split_once("app-server event: turn/completed")
.expect("fork completed");
assert!(
!completion.contains("app-server event: deprecationNotice"),
"{completion}"
);
assert_eq!(
completion.matches("app-server typed request").count(),
2,
"the failed turn needs one item page and an unsubscribe: {completion}"
);
Ok(())
}

View File

@@ -0,0 +1,102 @@
//! Verify exec forwards Cyber selection per turn and rejects unsupported commands.
use core_test_support::responses;
use core_test_support::skip_if_no_network;
use core_test_support::test_codex_exec::test_codex_exec;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn cyber_access_program_is_selected_per_turn() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
let test = test_codex_exec();
std::fs::write(
test.home_path().join("config.toml"),
"[features]\napi_key_cyber_access_programs = true\napi_key_model_discovery = true\n",
)?;
let server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_sequence(
&server,
(0..4)
.map(|index| {
responses::sse(vec![responses::ev_completed(&format!(
"resp-cyber-{index}"
))])
})
.collect(),
)
.await;
let seed = test
.cmd_with_server(&server)
.args([
"--skip-git-repo-check",
"--json",
"--cyber-access-program",
"daybreak_blue",
"Respond only OK.",
])
.assert()
.success();
let events = std::str::from_utf8(&seed.get_output().stdout)?
.lines()
.map(serde_json::from_str::<Value>)
.collect::<Result<Vec<_>, _>>()?;
let thread_id = events
.iter()
.find(|event| event["type"] == "thread.started")
.and_then(|event| event["thread_id"].as_str())
.expect("new turn should emit a thread id");
for (command, prompt, program) in [
("resume", "Respond only OK.", Some("daybreak_red")),
("fork", "-", Some("standard")),
("fork", "Respond only OK.", None),
] {
let mut cmd = test.cmd_with_server(&server);
cmd.args(["--skip-git-repo-check", command, thread_id]);
if let Some(program) = program {
cmd.args(["--cyber-access-program", program]);
}
if prompt == "-" {
cmd.write_stdin("Respond only OK.");
}
cmd.arg(prompt).assert().success();
}
assert_eq!(
response_mock
.requests()
.iter()
.map(|request| request.body_json().get("access_programs").cloned())
.collect::<Vec<_>>(),
vec![
Some(json!({"cyber": "daybreak_blue"})),
Some(json!({"cyber": "daybreak_red"})),
Some(json!({"cyber": "standard"})),
None,
]
);
Ok(())
}
#[test]
fn cyber_access_program_requires_a_supported_turn() {
let test = test_codex_exec();
for (args, message) in [
(
vec!["review", "--uncommitted"],
"is not supported with `codex exec review`",
),
(vec!["fork", "synthetic-session"], "requires a prompt"),
] {
test.cmd()
.args(["--cyber-access-program", "daybreak_blue"])
.args(args)
.assert()
.failure()
.stderr(predicates::str::contains(message));
}
}

View File

@@ -0,0 +1,401 @@
use anyhow::Context;
use core_test_support::responses;
use core_test_support::test_codex_exec::TestCodexExecBuilder;
use core_test_support::test_codex_exec::test_codex_exec;
use predicates::prelude::*;
use pretty_assertions::assert_eq;
use serde_json::json;
fn started_thread(output: std::process::Output) -> anyhow::Result<String> {
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
String::from_utf8(output.stdout)?
.lines()
.filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
.find(|event| event["type"] == "thread.started")
.and_then(|event| event["thread_id"].as_str().map(str::to_owned))
.context("exec should report its thread ID")
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_resolves_daybreak_for_api_keys_and_allows_an_off_override() -> anyhow::Result<()> {
let (test, server) = configured_daybreak_exec().await?;
std::fs::remove_file(test.home_path().join("auth.json"))?;
for (args, expected) in [
(vec![], Some("daybreak_blue")),
(vec!["-c", "daybreak=false"], Some("standard")),
(vec!["-m", "unlisted-model"], None),
(
vec![
"-c",
"daybreak=false",
"-c",
"features.api_key_cyber_access_programs=false",
],
None,
),
] {
let response =
responses::mount_sse_once(&server, responses::sse_completed("response")).await;
test.cmd_with_server(&server)
.env_remove("CODEX_ACCESS_TOKEN")
.arg("--skip-git-repo-check")
.args(args)
.arg("hello")
.assert()
.success();
assert_eq!(
response.single_request().body_json().get("access_programs"),
expected.map(|program| json!({"cyber": program})).as_ref()
);
}
let response = responses::mount_sse_once(&server, responses::sse_completed("unexpected")).await;
test.cmd_with_server(&server)
.env_remove("CODEX_ACCESS_TOKEN")
.args([
"--skip-git-repo-check",
"-c",
"features.api_key_cyber_access_programs=false",
"hello",
])
.assert()
.failure()
.stderr(predicate::str::contains(
"Cyber access programs are disabled for this API-key session.",
));
assert!(response.requests().is_empty());
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_rejects_daybreak_for_non_openai_provider() -> anyhow::Result<()> {
let test = test_codex_exec();
let server = responses::start_mock_server().await;
std::fs::write(
test.home_path().join("config.toml"),
"daybreak = true\nfeatures.cli_daybreak = true\n",
)?;
let response = responses::mount_sse_once(&server, responses::sse_completed("response")).await;
test.cmd_with_server(&server)
.env_remove("CODEX_ACCESS_TOKEN")
.args([
"--oss",
"--local-provider",
"ollama",
"--skip-git-repo-check",
"hello",
])
.assert()
.failure()
.stderr(predicate::str::contains(
"Daybreak requires the OpenAI model provider",
));
assert!(response.requests().is_empty());
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_custom_provider_daybreak_uses_capability() -> anyhow::Result<()> {
let (test, server) = configured_daybreak_exec().await?;
std::fs::remove_file(test.home_path().join("auth.json"))?;
let config_path = test.home_path().join("config.toml");
let config = std::fs::read_to_string(&config_path)?;
for capability in [None, Some(false), Some(true)] {
let capability_config = capability
.map(|value| format!("capabilities.cyber_access_programs = {value}\n"))
.unwrap_or_default();
std::fs::write(
&config_path,
format!(
"{config}model_provider = 'proxy'\n[model_providers.proxy]\nname = 'Proxy'\nbase_url = '{}'\nwire_api = 'responses'\nrequires_openai_auth = true\n{capability_config}",
server.uri()
),
)?;
for (enabled, expected) in [(true, "daybreak_blue"), (false, "standard")] {
let rejected = enabled && capability != Some(true);
let previous_requests = responses::received_responses_requests(&server).await.len();
let response = if rejected {
None
} else {
Some(responses::mount_sse_once(&server, responses::sse_completed("response")).await)
};
let assertion = test
.cmd_with_server(&server)
.env_remove("CODEX_ACCESS_TOKEN")
.args([
"--skip-git-repo-check",
"-c",
&format!("daybreak={enabled}"),
"hello",
])
.assert();
if rejected {
assertion.failure().stderr(predicate::str::contains(
"Daybreak requires a model provider with Cyber access program support",
));
assert_eq!(
responses::received_responses_requests(&server).await.len(),
previous_requests
);
} else {
assertion.success();
assert_eq!(
response
.expect("successful turn response")
.single_request()
.body_json()
.get("access_programs"),
(capability == Some(true))
.then(|| json!({"cyber": expected}))
.as_ref()
);
}
}
}
Ok(())
}
async fn configured_daybreak_exec() -> anyhow::Result<(TestCodexExecBuilder, wiremock::MockServer)>
{
let test = test_codex_exec();
let server = responses::start_mock_server().await;
let token = concat!(
"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.",
"eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF9wbGFuX3R5cGUiOiJlbnRlcnByaXNlIiwiY2hhdGdwdF9hY2NvdW50X2lkIjoid29ya3NwYWNlIn19.",
"c2lnbmF0dXJl",
);
std::fs::write(
test.home_path().join("auth.json"),
serde_json::to_vec(&json!({
"auth_mode": "chatgpt",
"tokens": {"id_token": token, "access_token": "test-token",
"refresh_token": "refresh-token", "account_id": "workspace"},
"last_refresh": "2099-01-01T00:00:00Z"
}))?,
)?;
let catalog = test.home_path().join("catalog.json");
std::fs::write(
&catalog,
serde_json::to_vec(&json!({"models": [{
"slug": "gpt-test", "display_name": "Test", "base_instructions": "Test instructions", "supported_reasoning_levels": [],
"shell_type": "disabled", "visibility": "list", "supported_in_api": true,
"priority": 0, "support_verbosity": false,
"truncation_policy": {"mode": "tokens", "limit": 10000},
"experimental_supported_tools": [],
"available_access_programs": {"cyber": ["standard", "daybreak_red", "daybreak_blue"]}
}]}))?,
)?;
std::fs::write(
test.home_path().join("config.toml"),
format!(
"cli_auth_credentials_store = 'file'\nchatgpt_base_url = '{}/backend-api'\nmodel_catalog_json = '{}'\nmodel = 'gpt-test'\ndaybreak = true\nfeatures.cli_daybreak = true\n",
server.uri(),
catalog.display()
),
)?;
wiremock::Mock::given(wiremock::matchers::method("GET"))
.and(wiremock::matchers::path("/backend-api/wham/config/bundle"))
.respond_with(wiremock::ResponseTemplate::new(200).set_body_json(json!({
"config_toml": {"enterprise_managed": []}
})))
.mount(&server)
.await;
wiremock::Mock::given(wiremock::matchers::method("GET"))
.and(wiremock::matchers::path("/backend-api/wham/accounts/check"))
.respond_with(wiremock::ResponseTemplate::new(200).set_body_json(json!({
"accounts": [{"id": "workspace", "workspace_backend_origin": "https://chatgpt.com",
"account_routing_override": "NO_CONSTRAINT"}]
})))
.mount(&server)
.await;
Ok((test, server))
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_resumes_and_forks_the_saved_daybreak_choice() -> anyhow::Result<()> {
let (test, server) = configured_daybreak_exec().await?;
let response = responses::mount_sse_once(&server, responses::sse_completed("started")).await;
let output = test
.cmd_with_server(&server)
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.args(["--skip-git-repo-check", "--json", "hello"])
.output()?;
let thread_id = started_thread(output)?;
assert_eq!(
response.single_request().body_json()["access_programs"],
json!({"cyber": "daybreak_blue"})
);
// The saved choice wins over a changed default; a CLI override affects only its invocation.
std::fs::write(
test.home_path().join("config.toml"),
format!(
"cli_auth_credentials_store = 'file'\nchatgpt_base_url = '{}/backend-api'\nmodel_catalog_json = '{}'\nmodel = 'gpt-test'\nfeatures.cli_daybreak = true\n",
server.uri(),
test.home_path().join("catalog.json").display()
),
)?;
for (args, expected) in [
(
vec![
"-c",
"daybreak=false",
"resume",
thread_id.as_str(),
"continue",
],
Some("standard"),
),
(
vec!["resume", thread_id.as_str(), "continue"],
Some("daybreak_blue"),
),
(
vec!["fork", thread_id.as_str(), "continue"],
Some("daybreak_blue"),
),
(
vec![
"-c",
"features.cli_daybreak=false",
"--ephemeral",
"fork",
thread_id.as_str(),
"continue",
],
None,
),
(
vec![
"--ephemeral",
"-c",
"daybreak=false",
"fork",
thread_id.as_str(),
"continue",
],
Some("standard"),
),
] {
let response =
responses::mount_sse_once(&server, responses::sse_completed("continued")).await;
test.cmd_with_server(&server)
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.arg("--skip-git-repo-check")
.args(args)
.assert()
.success();
assert_eq!(
response.single_request().body_json().get("access_programs"),
expected.map(|program| json!({"cyber": program})).as_ref()
);
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_explicit_cyber_program_overrides_daybreak_for_one_turn() -> anyhow::Result<()> {
let (test, server) = configured_daybreak_exec().await?;
let response =
responses::mount_sse_once(&server, responses::sse_completed("explicit-program")).await;
let output = test
.cmd_with_server(&server)
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.args([
"--skip-git-repo-check",
"--json",
"-c",
"features.cli_daybreak=false",
"--cyber-access-program",
"daybreak_red",
"hello",
])
.output()?;
let thread_id = started_thread(output)?;
assert_eq!(
response.single_request().body_json()["access_programs"],
json!({"cyber": "daybreak_red"})
);
let response =
responses::mount_sse_once(&server, responses::sse_completed("saved-daybreak")).await;
test.cmd_with_server(&server)
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.args(["--skip-git-repo-check", "resume", &thread_id, "continue"])
.assert()
.success();
assert_eq!(
response.single_request().body_json()["access_programs"],
json!({"cyber": "daybreak_blue"})
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_resume_override_does_not_change_a_standard_thread() -> anyhow::Result<()> {
let (test, server) = configured_daybreak_exec().await?;
let response =
responses::mount_sse_once(&server, responses::sse_completed("started-standard")).await;
let output = test
.cmd_with_server(&server)
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.args([
"--skip-git-repo-check",
"--json",
"-c",
"features.cli_daybreak=false",
"-c",
"daybreak=false",
"hello",
])
.output()?;
let thread_id = started_thread(output)?;
assert_eq!(
response.single_request().body_json().get("access_programs"),
None
);
for (args, expected) in [
(
vec![
"-c",
"daybreak=true",
"resume",
thread_id.as_str(),
"continue",
],
"daybreak_blue",
),
(vec!["resume", thread_id.as_str(), "continue"], "standard"),
] {
let response =
responses::mount_sse_once(&server, responses::sse_completed("continued-standard"))
.await;
test.cmd_with_server(&server)
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.arg("--skip-git-repo-check")
.args(args)
.assert()
.success();
assert_eq!(
response.single_request().body_json()["access_programs"],
json!({"cyber": expected})
);
}
Ok(())
}

View File

@@ -0,0 +1,67 @@
#![cfg(not(target_os = "windows"))]
#![allow(clippy::unwrap_used)]
use core_test_support::responses;
use core_test_support::skip_if_no_network;
use core_test_support::test_codex_exec::test_codex_exec;
use walkdir::WalkDir;
use wiremock::MockServer;
fn exec_sse_response() -> String {
responses::sse(vec![
responses::ev_response_created("resp-ephemeral"),
responses::ev_assistant_message("msg-ephemeral", "ephemeral response"),
responses::ev_completed("resp-ephemeral"),
])
}
fn session_rollout_count(home_path: &std::path::Path) -> usize {
let sessions_dir = home_path.join("sessions");
if !sessions_dir.exists() {
return 0;
}
WalkDir::new(sessions_dir)
.into_iter()
.filter_map(Result::ok)
.filter(|entry| entry.file_type().is_file())
.filter(|entry| entry.file_name().to_string_lossy().ends_with(".jsonl"))
.count()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn persists_rollout_file_by_default() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
let test = test_codex_exec();
let server = MockServer::start().await;
let _response_mock = responses::mount_sse_once(&server, exec_sse_response()).await;
test.cmd_with_server(&server)
.arg("--skip-git-repo-check")
.arg("default persistence behavior")
.assert()
.code(0);
assert_eq!(session_rollout_count(test.home_path()), 1);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn does_not_persist_rollout_file_in_ephemeral_mode() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
let test = test_codex_exec();
let server = MockServer::start().await;
let _response_mock = responses::mount_sse_once(&server, exec_sse_response()).await;
test.cmd_with_server(&server)
.arg("--skip-git-repo-check")
.arg("--ephemeral")
.arg("ephemeral behavior")
.assert()
.code(0);
assert_eq!(session_rollout_count(test.home_path()), 0);
Ok(())
}

View File

@@ -0,0 +1,43 @@
#![cfg(not(target_os = "windows"))]
use core_test_support::responses;
use core_test_support::test_codex_exec::test_codex_exec;
use serde_json::json;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_hook_trust_bypass_runs_session_start_hook() -> anyhow::Result<()> {
let test = test_codex_exec();
let marker_path = test.home_path().join("session-start-ran");
let command = format!("touch {}", marker_path.display());
std::fs::write(
test.home_path().join("hooks.json"),
serde_json::to_vec_pretty(&json!({
"hooks": {
"SessionStart": [{
"hooks": [{
"type": "command",
"command": command,
}],
}],
},
}))?,
)?;
let server = responses::start_mock_server().await;
let body = responses::sse(vec![
responses::ev_response_created("response_1"),
responses::ev_assistant_message("response_1", "done"),
responses::ev_completed("response_1"),
]);
responses::mount_sse_once(&server, body).await;
test.cmd_with_server(&server)
.arg("--skip-git-repo-check")
.arg("--dangerously-bypass-hook-trust")
.arg("run the session start hook")
.assert()
.success();
assert!(marker_path.exists(), "session start hook did not run");
Ok(())
}

View File

@@ -0,0 +1,69 @@
use codex_core::config::set_project_trust_level;
use codex_protocol::config_types::TrustLevel;
use core_test_support::responses;
use core_test_support::test_codex_exec::test_codex_exec;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use std::fs;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exits_non_zero_when_required_mcp_server_fails_to_initialize() -> anyhow::Result<()> {
let test = test_codex_exec();
let config_toml = r#"
[mcp_servers.required_broken]
command = "codex-definitely-not-a-real-binary"
required = true
"#;
let user_config = test.home_path().join("config.toml");
fs::write(&user_config, config_toml)?;
let project = test.cwd_path().join("repo");
let cwd = project.join("subdir");
fs::create_dir_all(&cwd)?;
fs::create_dir(project.join(".codex"))?;
fs::create_dir(project.join(".git"))?;
fs::write(project.join(".git/HEAD"), "ref: refs/heads/main\n")?;
let server = responses::start_mock_server().await;
responses::mount_sse_once(&server, responses::sse_completed("resp_1")).await;
let run = |args: &[&str]| {
test.cmd_with_server(&server)
.arg("--cd")
.arg(&cwd)
.args(["--ephemeral", "--experimental-json"])
.args(args)
.arg("hello")
.assert()
};
let expect_mcp_failure = |args: &[&str]| {
run(args).code(1).stderr(contains(
"required MCP servers failed to initialize: required_broken",
));
};
expect_mcp_failure(&[]);
// The same server in project config requires explicit consent, even with write access.
fs::rename(&user_config, project.join(".codex/config.toml"))?;
let first = run(&["--sandbox", "workspace-write"]).success();
let stderr = std::str::from_utf8(&first.get_output().stderr)?;
let warning = stderr
.lines()
.find(|line| line.contains("codex exec --trust"))
.expect("project trust warning");
insta::assert_snapshot!(warning, @"warning: Untrusted project-local configuration is disabled. Run `codex exec --trust` to allow project configuration and MCP servers for this and future chats in the project, including MCP commands outside the sandbox. Explicitly untrusted projects must have their trust setting updated first.");
expect_mcp_failure(&["--sandbox", "read-only", "--trust"]);
expect_mcp_failure(&[]);
set_project_trust_level(test.home_path(), &project, TrustLevel::Untrusted)?;
let refusal = fs::read_to_string(&user_config)?;
run(&["--trust"])
.failure()
.stderr(contains("is marked as untrusted"));
run(&["--ignore-user-config", "resume", "--last", "--trust"])
.failure()
.stderr(contains(
"--trust cannot be combined with --ignore-user-config",
));
assert_eq!(fs::read_to_string(user_config)?, refusal);
Ok(())
}

View File

@@ -0,0 +1,24 @@
// Aggregates all former standalone integration tests as modules.
mod add_dir;
mod agents_md;
mod apply_patch;
mod approval_policy;
mod auth_env;
#[path = "completion_backfill_tests.rs"]
mod completion_backfill;
#[path = "cyber_access_program_tests.rs"]
mod cyber_access_program;
mod daybreak;
mod ephemeral;
mod hooks;
mod mcp_required_exit;
mod originator;
mod output_last_message;
mod output_schema;
mod prompt_stdin;
mod resume;
mod sandbox;
#[cfg(target_os = "macos")]
mod seatbelt;
mod server_error_exit;
mod worktree;

View File

@@ -0,0 +1,54 @@
#![cfg(not(target_os = "windows"))]
#![allow(clippy::unwrap_used)]
use codex_login::default_client::CODEX_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR;
use core_test_support::responses;
use core_test_support::test_codex_exec::test_codex_exec;
use wiremock::matchers::header;
/// Verify that when the server reports an error, `codex-exec` exits with a
/// non-zero status code so automation can detect failures.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_codex_exec_originator() -> anyhow::Result<()> {
let test = test_codex_exec();
let server = responses::start_mock_server().await;
let body = responses::sse(vec![
responses::ev_response_created("response_1"),
responses::ev_assistant_message("response_1", "Hello, world!"),
responses::ev_completed("response_1"),
]);
responses::mount_sse_once_match(&server, header("Originator", "codex_exec"), body).await;
test.cmd_with_server(&server)
.env_remove(CODEX_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR)
.arg("--skip-git-repo-check")
.arg("tell me something")
.assert()
.code(0);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn supports_originator_override() -> anyhow::Result<()> {
let test = test_codex_exec();
let server = responses::start_mock_server().await;
let body = responses::sse(vec![
responses::ev_response_created("response_1"),
responses::ev_assistant_message("response_1", "Hello, world!"),
responses::ev_completed("response_1"),
]);
responses::mount_sse_once_match(&server, header("Originator", "codex_exec_override"), body)
.await;
test.cmd_with_server(&server)
.env("CODEX_INTERNAL_ORIGINATOR_OVERRIDE", "codex_exec_override")
.arg("--skip-git-repo-check")
.arg("tell me something")
.assert()
.code(0);
Ok(())
}

View File

@@ -0,0 +1,110 @@
#![cfg(unix)]
//! Exercise the CLI output path used by automation with a synthetic model response.
use core_test_support::responses;
use core_test_support::test_codex_exec::test_codex_exec;
use pretty_assertions::assert_eq;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn human_output_to_redirected_stdout_prints_one_answer() -> anyhow::Result<()> {
core_test_support::skip_if_no_network!(Ok(()));
let test = test_codex_exec();
let server = responses::start_mock_server().await;
let command = test.cmd_with_server(&server);
let saved = test.cwd_path().join("stdout");
for alias in ["/dev/stdout", "/dev/fd/1", "/proc/self/fd/1"] {
responses::mount_sse_once(
&server,
responses::sse(vec![
responses::ev_response_created("r"),
responses::ev_assistant_message("m", "done"),
responses::ev_completed("r"),
]),
)
.await;
let output = std::process::Command::new(command.get_program())
.args(command.get_args())
.envs(command.get_envs().filter_map(|(k, v)| v.map(|v| (k, v))))
.current_dir(test.cwd_path())
.args(["--skip-git-repo-check", "-o", alias, "reply"])
.stdout(std::fs::File::create(&saved)?)
.output()?;
assert!(output.status.success(), "{output:?}");
assert_eq!(std::fs::read(&saved)?, b"done\n", "{alias}");
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn sandbox_link_cannot_redirect_this_or_the_next_invocation() -> anyhow::Result<()> {
core_test_support::skip_if_no_network!(Ok(()));
core_test_support::skip_if_sandbox!(Ok(()));
#[cfg(target_os = "linux")]
if super::sandbox::linux_sandbox_test_env().await.is_none() {
return Ok(());
}
for mode in [None, Some("--json")] {
let test = test_codex_exec();
let outside = tempfile::tempdir()?;
let target = outside.path().join("victim.txt");
let output = test.cwd_path().join("codex-output.md");
std::fs::write(&target, "original victim")?;
std::fs::write(&output, "original output")?;
let mut original = std::fs::File::open(&output)?;
let quoted_target = format!("'{}'", target.display().to_string().replace('\'', "'\\''"));
let attack = format!(
"if (printf forbidden > {quoted_target}) 2>/dev/null; then exit 1; fi; ln -sfn -- {quoted_target} codex-output.md"
);
let server = responses::start_mock_server().await;
let args = serde_json::json!({"cmd": attack, "shell": "/bin/sh", "login": false, "yield_time_ms": 10_000});
responses::mount_function_call_agent_response(
&server,
"plant-output",
&args.to_string(),
"exec_command",
)
.await;
let command = || {
let mut cmd = test.cmd_with_server(&server);
cmd.args(["--skip-git-repo-check", "--output-last-message"])
.arg(&output);
cmd.args(mode);
cmd
};
let mut cmd = command();
cmd.args([
"--sandbox",
"workspace-write",
"-c",
"approval_policy='never'",
"-c",
"sandbox_workspace_write.exclude_slash_tmp=true",
"-c",
"sandbox_workspace_write.exclude_tmpdir_env_var=true",
]);
cmd.arg("write a response")
.assert()
.failure()
.stderr(predicates::str::contains(
"Failed to write last message file",
));
let mut saved = String::new();
std::io::Read::read_to_string(&mut original, &mut saved)?;
assert_eq!(saved, "original output");
assert_eq!(std::fs::read_to_string(&target)?, "original victim");
assert_eq!(std::fs::read_link(&output)?, target);
// The link left by the first invocation must not gain authority on the next one.
command()
.arg("write another response")
.assert()
.failure()
.stderr(predicates::str::contains(
"Failed to open last message file",
));
assert_eq!(std::fs::read_to_string(&target)?, "original victim");
}
Ok(())
}

View File

@@ -0,0 +1,62 @@
#![cfg(not(target_os = "windows"))]
#![allow(clippy::unwrap_used)]
use core_test_support::responses;
use core_test_support::test_codex_exec::test_codex_exec;
use serde_json::Value;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_includes_output_schema_in_request() -> anyhow::Result<()> {
let test = test_codex_exec();
let schema_contents = serde_json::json!({
"type": "object",
"properties": {
"answer": { "type": "string" }
},
"required": ["answer"],
"additionalProperties": false
});
let schema_path = test.cwd_path().join("schema.json");
std::fs::write(&schema_path, serde_json::to_vec_pretty(&schema_contents)?)?;
let expected_schema: Value = schema_contents;
let server = responses::start_mock_server().await;
let body = responses::sse(vec![
responses::ev_response_created("resp1"),
responses::ev_assistant_message("m1", "fixture hello"),
responses::ev_completed("resp1"),
]);
let response_mock = responses::mount_sse_once(&server, body).await;
test.cmd_with_server(&server)
.arg("--skip-git-repo-check")
// keep using -C in the test to exercise the flag as well
.arg("-C")
.arg(test.cwd_path())
.arg("--output-schema")
.arg(&schema_path)
.arg("-m")
.arg("gpt-5.1")
.arg("tell me a joke")
.assert()
.success();
let request = response_mock.single_request();
let payload: Value = request.body_json();
let text = payload.get("text").expect("request missing text field");
let format = text
.get("format")
.expect("request missing text.format field");
assert_eq!(
format,
&serde_json::json!({
"name": "codex_output_schema",
"type": "json_schema",
"strict": true,
"schema": expected_schema,
})
);
Ok(())
}

View File

@@ -0,0 +1,171 @@
#![cfg(not(target_os = "windows"))]
#![allow(clippy::unwrap_used)]
use core_test_support::responses;
use core_test_support::test_codex_exec::test_codex_exec;
use predicates::str::contains;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_appends_piped_stdin_to_prompt_argument() -> anyhow::Result<()> {
let test = test_codex_exec();
let server = responses::start_mock_server().await;
let body = responses::sse(vec![
responses::ev_response_created("resp1"),
responses::ev_assistant_message("m1", "fixture hello"),
responses::ev_completed("resp1"),
]);
let response_mock = responses::mount_sse_once(&server, body).await;
// echo "my output" | codex exec --skip-git-repo-check -C <cwd> -m gpt-5.1 "Summarize this concisely"
test.cmd_with_server(&server)
.arg("--skip-git-repo-check")
.arg("-C")
.arg(test.cwd_path())
.arg("-m")
.arg("gpt-5.1")
.arg("Summarize this concisely")
.write_stdin("my output\n")
.assert()
.success();
let request = response_mock.single_request();
assert!(
request.has_message_with_input_texts("user", |texts| {
texts == ["Summarize this concisely\n\n<stdin>\nmy output\n</stdin>".to_string()]
}),
"request should include a user message with the prompt plus piped stdin context"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_ignores_empty_piped_stdin_when_prompt_argument_is_present() -> anyhow::Result<()> {
let test = test_codex_exec();
let server = responses::start_mock_server().await;
let body = responses::sse(vec![
responses::ev_response_created("resp1"),
responses::ev_assistant_message("m1", "fixture hello"),
responses::ev_completed("resp1"),
]);
let response_mock = responses::mount_sse_once(&server, body).await;
// printf "" | codex exec --skip-git-repo-check -C <cwd> -m gpt-5.1 "Summarize this concisely"
test.cmd_with_server(&server)
.arg("--skip-git-repo-check")
.arg("-C")
.arg(test.cwd_path())
.arg("-m")
.arg("gpt-5.1")
.arg("Summarize this concisely")
.write_stdin("")
.assert()
.success();
let request = response_mock.single_request();
assert!(
request.has_message_with_input_texts("user", |texts| texts
== ["Summarize this concisely".to_string()]),
"request should preserve the prompt when stdin is empty"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_dash_prompt_reads_stdin_as_the_prompt() -> anyhow::Result<()> {
let test = test_codex_exec();
let server = responses::start_mock_server().await;
let body = responses::sse(vec![
responses::ev_response_created("resp1"),
responses::ev_assistant_message("m1", "fixture hello"),
responses::ev_completed("resp1"),
]);
let response_mock = responses::mount_sse_once(&server, body).await;
// echo "prompt from stdin" | codex exec --skip-git-repo-check -C <cwd> -m gpt-5.1 -
test.cmd_with_server(&server)
.arg("--skip-git-repo-check")
.arg("-C")
.arg(test.cwd_path())
.arg("-m")
.arg("gpt-5.1")
.arg("-")
.write_stdin("prompt from stdin\n")
.assert()
.success();
let request = response_mock.single_request();
assert!(
request.has_message_with_input_texts("user", |texts| {
texts == ["prompt from stdin\n".to_string()]
}),
"dash prompt should preserve the existing forced-stdin behavior"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_without_prompt_argument_reads_piped_stdin_as_the_prompt() -> anyhow::Result<()> {
let test = test_codex_exec();
let server = responses::start_mock_server().await;
let body = responses::sse(vec![
responses::ev_response_created("resp1"),
responses::ev_assistant_message("m1", "fixture hello"),
responses::ev_completed("resp1"),
]);
let response_mock = responses::mount_sse_once(&server, body).await;
// echo "prompt from stdin" | codex exec --skip-git-repo-check -C <cwd> -m gpt-5.1
test.cmd_with_server(&server)
.arg("--skip-git-repo-check")
.arg("-C")
.arg(test.cwd_path())
.arg("-m")
.arg("gpt-5.1")
.write_stdin("prompt from stdin\n")
.assert()
.success();
let request = response_mock.single_request();
assert!(
request.has_message_with_input_texts("user", |texts| {
texts == ["prompt from stdin\n".to_string()]
}),
"missing prompt argument should preserve the existing piped-stdin prompt behavior"
);
Ok(())
}
#[test]
fn exec_without_prompt_argument_rejects_empty_piped_stdin() {
let test = test_codex_exec();
// printf "" | codex exec --skip-git-repo-check -C <cwd>
test.cmd()
.arg("--skip-git-repo-check")
.arg("-C")
.arg(test.cwd_path())
.write_stdin("")
.assert()
.code(1)
.stderr(contains("No prompt provided via stdin."));
}
#[test]
fn exec_dash_prompt_rejects_empty_piped_stdin() {
let test = test_codex_exec();
// printf "" | codex exec --skip-git-repo-check -C <cwd> -
test.cmd()
.arg("--skip-git-repo-check")
.arg("-C")
.arg(test.cwd_path())
.arg("-")
.write_stdin("")
.assert()
.code(1)
.stderr(contains("No prompt provided via stdin."));
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,553 @@
#![cfg(unix)]
use codex_core::spawn::StdioPolicy;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_absolute_path::test_support::PathBufExt;
use codex_utils_path_uri::PathUri;
use std::collections::HashMap;
use std::future::Future;
use std::io;
use std::process::ExitStatus;
use tokio::fs::create_dir_all;
use tokio::process::Child;
pub(super) async fn spawn_command_under_sandbox(
command: Vec<String>,
command_cwd: AbsolutePathBuf,
permission_profile: &PermissionProfile,
sandbox_cwd: &AbsolutePathBuf,
stdio_policy: StdioPolicy,
env: HashMap<String, String>,
) -> std::io::Result<Child> {
use codex_core::exec::ExecCapturePolicy;
use codex_core::exec::ExecParams;
use codex_core::exec::build_exec_request;
use codex_core::sandboxing::SandboxPermissions;
use codex_protocol::config_types::WindowsSandboxLevel;
use std::process::Stdio;
#[cfg(target_os = "linux")]
let codex_linux_sandbox_exe = Some(
core_test_support::find_codex_linux_sandbox_exe()
.map_err(|err| io::Error::new(io::ErrorKind::NotFound, err))?,
);
#[cfg(target_os = "macos")]
let codex_linux_sandbox_exe = None;
let exec_request = build_exec_request(
ExecParams {
command,
cwd: command_cwd,
expiration: 1000.into(),
capture_policy: ExecCapturePolicy::ShellTool,
env,
network: None,
network_environment_id: None,
sandbox_permissions: SandboxPermissions::UseDefault,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
justification: None,
arg0: None,
},
permission_profile,
sandbox_cwd,
&[PathUri::from_abs_path(sandbox_cwd)],
&codex_linux_sandbox_exe,
/*codex_self_exe*/ &None,
codex_protocol::sandbox::SandboxType::None,
/*use_legacy_landlock*/ false,
)
.await
.map_err(|err| io::Error::other(err.to_string()))?;
let (program, args) = exec_request
.command
.split_first()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "command args are empty"))?;
let mut child = tokio::process::Command::new(program);
if let Some(arg0) = exec_request.arg0.as_deref() {
child.arg0(arg0);
}
child.args(args);
// TODO(anp): Keep PathUri through the macOS sandbox process launch boundary.
let native_cwd = exec_request
.cwd
.to_abs_path()
.map_err(|err| io::Error::other(err.to_string()))?;
child.current_dir(native_cwd);
child.env_clear();
child.envs(exec_request.env);
match stdio_policy {
StdioPolicy::RedirectForShellTool => {
child.stdin(Stdio::null());
child.stdout(Stdio::piped()).stderr(Stdio::piped());
}
StdioPolicy::Inherit => {
child
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
}
}
child.kill_on_drop(true).spawn()
}
#[cfg(target_os = "linux")]
/// Determines whether Linux sandbox tests can run on this host.
///
/// These tests require an enforceable filesystem sandbox. We run a tiny command
/// under the production Landlock path and skip when enforcement is unavailable
/// (for example on kernels or container profiles where Landlock is not
/// enforced).
pub(super) async fn linux_sandbox_test_env() -> Option<HashMap<String, String>> {
let command_cwd = AbsolutePathBuf::current_dir().ok()?;
let sandbox_cwd = command_cwd.clone();
let permission_profile = PermissionProfile::read_only();
if can_apply_linux_sandbox_policy(
&permission_profile,
&command_cwd,
&sandbox_cwd,
HashMap::new(),
)
.await
{
return Some(HashMap::new());
}
eprintln!("Skipping test: Landlock is not enforceable on this host.");
None
}
#[cfg(target_os = "linux")]
/// Returns whether a minimal command can run successfully with the requested
/// Linux sandbox policy applied.
///
/// This is used as a capability probe so sandbox behavior tests only run when
/// Landlock enforcement is actually active.
async fn can_apply_linux_sandbox_policy(
permission_profile: &PermissionProfile,
command_cwd: &AbsolutePathBuf,
sandbox_cwd: &AbsolutePathBuf,
env: HashMap<String, String>,
) -> bool {
let spawn_result = spawn_command_under_sandbox(
vec!["/usr/bin/true".to_string()],
command_cwd.clone(),
permission_profile,
sandbox_cwd,
StdioPolicy::RedirectForShellTool,
env,
)
.await;
let Ok(mut child) = spawn_result else {
return false;
};
child
.wait()
.await
.map(|status| status.success())
.unwrap_or(false)
}
#[tokio::test]
async fn python_multiprocessing_lock_works_under_sandbox() {
core_test_support::skip_if_sandbox!();
#[cfg(target_os = "linux")]
let sandbox_env = match linux_sandbox_test_env().await {
Some(env) => env,
// Skip on Linux hosts where Landlock cannot actually be enforced.
None => return,
};
#[cfg(not(target_os = "linux"))]
let sandbox_env = HashMap::new();
#[cfg(target_os = "macos")]
let writable_roots = Vec::<AbsolutePathBuf>::new();
// From https://man7.org/linux/man-pages/man7/sem_overview.7.html
//
// > On Linux, named semaphores are created in a virtual filesystem,
// > normally mounted under /dev/shm.
#[cfg(target_os = "linux")]
let writable_roots: Vec<AbsolutePathBuf> = vec!["/dev/shm".try_into().unwrap()];
let permission_profile = PermissionProfile::workspace_write_with(
&writable_roots,
NetworkSandboxPolicy::Restricted,
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ true,
);
let python_code = r#"import multiprocessing
from multiprocessing import Lock, Process
def f(lock):
with lock:
print("Lock acquired in child process")
if __name__ == '__main__':
lock = Lock()
p = Process(target=f, args=(lock,))
p.start()
p.join()
"#;
let command_cwd = AbsolutePathBuf::current_dir().expect("should be able to get current dir");
let sandbox_cwd = command_cwd.clone();
let mut child = spawn_command_under_sandbox(
vec![
"python3".to_string(),
"-c".to_string(),
python_code.to_string(),
],
command_cwd,
&permission_profile,
&sandbox_cwd,
StdioPolicy::Inherit,
sandbox_env,
)
.await
.expect("should be able to spawn python under sandbox");
let status = child.wait().await.expect("should wait for child process");
assert!(status.success(), "python exited with {status:?}");
}
#[tokio::test]
async fn python_getpwuid_works_under_sandbox() {
core_test_support::skip_if_sandbox!();
#[cfg(target_os = "linux")]
let sandbox_env = match linux_sandbox_test_env().await {
Some(env) => env,
None => return,
};
#[cfg(not(target_os = "linux"))]
let sandbox_env = HashMap::new();
if std::process::Command::new("python3")
.arg("--version")
.status()
.is_err()
{
eprintln!("python3 not found in PATH, skipping test.");
return;
}
let permission_profile = PermissionProfile::read_only();
let command_cwd = AbsolutePathBuf::current_dir().expect("should be able to get current dir");
let sandbox_cwd = command_cwd.clone();
let mut child = spawn_command_under_sandbox(
vec![
"python3".to_string(),
"-c".to_string(),
"import pwd, os; print(pwd.getpwuid(os.getuid()))".to_string(),
],
command_cwd,
&permission_profile,
&sandbox_cwd,
StdioPolicy::RedirectForShellTool,
sandbox_env,
)
.await
.expect("should be able to spawn python under sandbox");
let status = child
.wait()
.await
.expect("should be able to wait for child process");
assert!(status.success(), "python exited with {status:?}");
}
#[tokio::test]
async fn sandbox_distinguishes_command_and_policy_cwds() {
core_test_support::skip_if_sandbox!();
#[cfg(target_os = "linux")]
let sandbox_env = match linux_sandbox_test_env().await {
Some(env) => env,
None => return,
};
#[cfg(not(target_os = "linux"))]
let sandbox_env = HashMap::new();
let temp = tempfile::tempdir().expect("should be able to create temp dir");
let sandbox_root = temp.path().join("sandbox");
let command_root = temp.path().join("command").abs();
create_dir_all(&sandbox_root).await.expect("mkdir");
create_dir_all(&command_root).await.expect("mkdir");
let canonical_sandbox_root = tokio::fs::canonicalize(&sandbox_root)
.await
.expect("canonicalize sandbox root")
.abs();
let canonical_allowed_path = canonical_sandbox_root.join("allowed.txt");
let disallowed_path = command_root.join("forbidden.txt");
// Note writable_roots is empty: verify that `canonical_allowed_path` is
// writable only because it is under the sandbox policy cwd, not because it
// is under a writable root.
let permission_profile = PermissionProfile::workspace_write_with(
&[],
NetworkSandboxPolicy::Restricted,
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ true,
);
// Attempt to write inside the command cwd, which is outside of the sandbox policy cwd.
let mut child = spawn_command_under_sandbox(
vec![
"bash".to_string(),
"-lc".to_string(),
"echo forbidden > forbidden.txt".to_string(),
],
command_root.clone(),
&permission_profile,
&canonical_sandbox_root,
StdioPolicy::Inherit,
sandbox_env.clone(),
)
.await
.expect("should spawn command writing to forbidden path");
let status = child
.wait()
.await
.expect("should wait for forbidden command");
assert!(
!status.success(),
"sandbox unexpectedly allowed writing to command cwd: {status:?}"
);
let forbidden_exists = tokio::fs::try_exists(&disallowed_path)
.await
.expect("try_exists failed");
assert!(
!forbidden_exists,
"forbidden path should not have been created"
);
// Writing to the sandbox policy cwd after changing directories into it should succeed.
let mut child = spawn_command_under_sandbox(
vec![
"/usr/bin/touch".to_string(),
canonical_allowed_path.to_string_lossy().into_owned(),
],
command_root,
&permission_profile,
&canonical_sandbox_root,
StdioPolicy::Inherit,
sandbox_env,
)
.await
.expect("should spawn command writing to sandbox root");
let status = child.wait().await.expect("should wait for allowed command");
assert!(
status.success(),
"sandbox blocked allowed write: {status:?}"
);
let allowed_exists = tokio::fs::try_exists(&canonical_allowed_path)
.await
.expect("try_exists allowed failed");
assert!(allowed_exists, "allowed path should exist");
}
#[tokio::test]
async fn sandbox_blocks_first_time_dot_codex_creation() {
core_test_support::skip_if_sandbox!();
#[cfg(target_os = "linux")]
let sandbox_env = match linux_sandbox_test_env().await {
Some(env) => env,
None => return,
};
#[cfg(not(target_os = "linux"))]
let sandbox_env = HashMap::new();
let temp = tempfile::tempdir().expect("should be able to create temp dir");
let repo_root = temp.path().join("repo").abs();
create_dir_all(&repo_root).await.expect("mkdir repo");
let dot_codex = repo_root.join(".codex");
let config_toml = dot_codex.join("config.toml");
let permission_profile = PermissionProfile::workspace_write_with(
&[],
NetworkSandboxPolicy::Restricted,
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ true,
);
let mut child = spawn_command_under_sandbox(
vec![
"bash".to_string(),
"-lc".to_string(),
"mkdir -p .codex && echo 'sandbox_mode = \"danger-full-access\"' > .codex/config.toml"
.to_string(),
],
repo_root.clone(),
&permission_profile,
&repo_root,
StdioPolicy::RedirectForShellTool,
sandbox_env,
)
.await
.expect("should spawn command creating .codex");
let status = child.wait().await.expect("should wait for .codex command");
assert!(
!status.success(),
"sandbox unexpectedly allowed first-time .codex creation: {status:?}"
);
let dot_codex_metadata = tokio::fs::symlink_metadata(&dot_codex).await;
if let Ok(metadata) = dot_codex_metadata {
assert!(
!metadata.is_dir(),
"{} should not be creatable as a directory",
dot_codex.display()
);
} else if let Err(err) = &dot_codex_metadata {
assert_eq!(
err.kind(),
io::ErrorKind::NotFound,
"unexpected metadata error for {}: {err}",
dot_codex.display()
);
}
let config_toml_exists = match tokio::fs::try_exists(&config_toml).await {
Ok(exists) => exists,
Err(err) if err.kind() == io::ErrorKind::NotADirectory => false,
Err(err) => panic!("try_exists {} failed: {err}", config_toml.display()),
};
assert!(
!config_toml_exists,
"{} should not have been created",
config_toml.display()
);
}
fn unix_sock_body() {
unsafe {
let mut fds = [0i32; 2];
let r = libc::socketpair(libc::AF_UNIX, libc::SOCK_DGRAM, 0, fds.as_mut_ptr());
assert_eq!(
r,
0,
"socketpair(AF_UNIX, SOCK_DGRAM) failed: {}",
io::Error::last_os_error()
);
let msg = b"hello_unix";
// write() from one end (generic write is allowed)
let sent = libc::write(fds[0], msg.as_ptr() as *const libc::c_void, msg.len());
assert!(sent >= 0, "write() failed: {}", io::Error::last_os_error());
// recvfrom() on the other end. We don’t need the address for socketpair,
// so we pass null pointers for src address.
let mut buf = [0u8; 64];
let recvd = libc::recvfrom(
fds[1],
buf.as_mut_ptr() as *mut libc::c_void,
buf.len(),
0,
std::ptr::null_mut(),
std::ptr::null_mut(),
);
assert!(
recvd >= 0,
"recvfrom() failed: {}",
io::Error::last_os_error()
);
let recvd_slice = &buf[..(recvd as usize)];
assert_eq!(
recvd_slice,
&msg[..],
"payload mismatch: sent {} bytes, got {} bytes",
msg.len(),
recvd
);
// Also exercise AF_UNIX stream socketpair quickly to ensure AF_UNIX in general works.
let mut sfds = [0i32; 2];
let sr = libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM, 0, sfds.as_mut_ptr());
assert_eq!(
sr,
0,
"socketpair(AF_UNIX, SOCK_STREAM) failed: {}",
io::Error::last_os_error()
);
let snt2 = libc::write(sfds[0], msg.as_ptr() as *const libc::c_void, msg.len());
assert!(
snt2 >= 0,
"write(stream) failed: {}",
io::Error::last_os_error()
);
let mut b2 = [0u8; 64];
let rcv2 = libc::recv(sfds[1], b2.as_mut_ptr() as *mut libc::c_void, b2.len(), 0);
assert!(
rcv2 >= 0,
"recv(stream) failed: {}",
io::Error::last_os_error()
);
// Clean up
let _ = libc::close(sfds[0]);
let _ = libc::close(sfds[1]);
let _ = libc::close(fds[0]);
let _ = libc::close(fds[1]);
}
}
#[tokio::test]
async fn allow_unix_socketpair_recvfrom() {
run_code_under_sandbox(
"allow_unix_socketpair_recvfrom",
&PermissionProfile::read_only(),
|| async { unix_sock_body() },
)
.await
.expect("should be able to reexec");
}
const IN_SANDBOX_ENV_VAR: &str = "IN_SANDBOX";
pub async fn run_code_under_sandbox<F, Fut>(
test_selector: &str,
permission_profile: &PermissionProfile,
child_body: F,
) -> io::Result<Option<ExitStatus>>
where
F: FnOnce() -> Fut + Send + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
if std::env::var(IN_SANDBOX_ENV_VAR).is_err() {
let exe = std::env::current_exe()?;
let mut cmds = vec![exe.to_string_lossy().into_owned(), "--exact".into()];
let mut stdio_policy = StdioPolicy::RedirectForShellTool;
// Allow for us to pass forward --nocapture / use the right stdio policy.
if std::env::args().any(|a| a == "--nocapture") {
cmds.push("--nocapture".into());
stdio_policy = StdioPolicy::Inherit;
}
cmds.push(test_selector.into());
// Your existing launcher:
let command_cwd =
AbsolutePathBuf::current_dir().expect("should be able to get current dir");
let sandbox_cwd = command_cwd.clone();
let mut child = spawn_command_under_sandbox(
cmds,
command_cwd,
permission_profile,
&sandbox_cwd,
stdio_policy,
HashMap::from([("IN_SANDBOX".into(), "1".into())]),
)
.await?;
let status = child.wait().await?;
Ok(Some(status))
} else {
// Child branch: run the provided body.
child_body().await;
Ok(None)
}
}

View File

@@ -0,0 +1,880 @@
use super::sandbox::spawn_command_under_sandbox;
use codex_core::spawn::StdioPolicy;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use std::fs;
use std::os::unix::fs::symlink;
use std::process::Output;
use std::time::Duration;
use tempfile::TempDir;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn codex_home_symlink_opt_out_uses_loaded_user_config() -> anyhow::Result<()> {
use core_test_support::responses;
use core_test_support::test_codex_exec::test_codex_exec;
use serde_json::json;
core_test_support::skip_if_sandbox!(Ok(()));
for (home_env, root_alias, enabled, ignore_user_config) in [
("user-home", Some("user-home"), true, false),
("home-link/../.codex", Some(".codex"), false, false),
("home-link/../.codex", None, true, false),
("user-home", Some("user-home"), true, true),
] {
let test = test_codex_exec();
let home = test.home_path().join(".codex");
let project_home = test.cwd_path().join(".codex");
let child = test.home_path().join("child");
for directory in [&home, &project_home, &child] {
fs::create_dir(directory)?;
}
symlink(&home, test.cwd_path().join("user-home"))?;
symlink(&child, test.cwd_path().join("home-link"))?;
fs::write(
home.join("config.toml"),
format!("allow_symlinked_codex_home = {enabled}\n"),
)?;
// The checkout must not enable the opt-out, even when `..` follows a symlink.
fs::write(
project_home.join("config.toml"),
"allow_symlinked_codex_home = true\n",
)?;
let target = TempDir::new()?;
for root in [&home, &project_home] {
symlink(target.path(), root.join("visualizations"))?;
}
let writable_home =
root_alias.map_or_else(|| home.clone(), |alias| test.cwd_path().join(alias));
let visualizations = writable_home.join("visualizations");
let shell_args = json!({
"cmd": "printf shell > shell.txt",
"workdir": visualizations,
"shell": "/bin/sh",
"login": false,
})
.to_string();
let patch = format!(
"*** Begin Patch\n*** Add File: {}/patch.txt\n+patched\n*** End Patch",
visualizations.display()
);
let server = responses::start_mock_server().await;
let should_run = enabled && !ignore_user_config;
let mock = responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_function_call("shell", "exec_command", &shell_args),
responses::ev_apply_patch_custom_tool_call("patch", &patch),
responses::ev_completed("response-1"),
]),
responses::sse(vec![responses::ev_completed("response-2")]),
],
)
.await;
let mut command = test.cmd_with_server(&server);
command
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove("CODEX_ACCESS_TOKEN")
.env("CODEX_HOME", home_env)
.args(["--skip-git-repo-check", "--sandbox", "workspace-write", "--add-dir"])
.arg(&visualizations)
.args(["-c", "approvals_reviewer=\"user\"", "-c", "features.shell_snapshot_v2=false"])
// Session overrides cannot authorize the host's exception either.
.args(["-c", "allow_symlinked_codex_home=true"])
.args(["-c", "model_provider=\"test\"", "-c"])
.arg(format!(
"model_providers.test={{name=\"test\",base_url={:?},wire_api=\"responses\",requires_openai_auth=false,supports_websockets=false}}",
format!("{}/v1", server.uri())
))
.arg("write the files");
if ignore_user_config {
command.arg("--ignore-user-config");
}
let output = command.output()?;
assert!(output.status.success(), "{output:?}");
assert_eq!(mock.requests().len(), 2);
if should_run {
assert_eq!(fs::read(target.path().join("shell.txt"))?, b"shell");
assert_eq!(fs::read(target.path().join("patch.txt"))?, b"patched\n");
} else {
let shell_output = mock
.function_call_output_text("shell")
.expect("shell tool output");
assert!(
shell_output.contains("symlinked writable roots are not supported"),
"{shell_output}"
);
assert!(!target.path().join("shell.txt").exists());
assert!(!target.path().join("patch.txt").exists());
}
}
Ok(())
}
fn workspace_fixture() -> (TempDir, AbsolutePathBuf) {
let temp_dir = TempDir::new().expect("create temporary directory");
let workspace = temp_dir.path().join("workspace");
fs::create_dir(&workspace).expect("create workspace");
let workspace = AbsolutePathBuf::from_absolute_path(
workspace.canonicalize().expect("canonicalize workspace"),
)
.expect("workspace is absolute");
(temp_dir, workspace)
}
fn permission_profile(
workspace: &AbsolutePathBuf,
restricted_paths: Vec<(FileSystemPath, FileSystemAccessMode)>,
) -> PermissionProfile {
let mut file_system_policy = FileSystemSandboxPolicy::read_only();
file_system_policy.entries.push(FileSystemSandboxEntry::new(
workspace.clone().into(),
FileSystemAccessMode::Write,
));
file_system_policy.entries.extend(
restricted_paths
.into_iter()
.map(|(path, access)| FileSystemSandboxEntry::new(path, access)),
);
PermissionProfile::from_runtime_permissions(
&file_system_policy,
NetworkSandboxPolicy::Restricted,
)
}
fn denied_glob_profile(workspace: &AbsolutePathBuf, pattern: String) -> PermissionProfile {
permission_profile(
workspace,
vec![(
FileSystemPath::GlobPattern { pattern },
FileSystemAccessMode::Deny,
)],
)
}
async fn run_sandboxed_command(
command: Vec<String>,
workspace: &AbsolutePathBuf,
permission_profile: &PermissionProfile,
) -> Output {
spawn_command_under_sandbox(
command,
workspace.clone(),
permission_profile,
workspace,
StdioPolicy::RedirectForShellTool,
HashMap::new(),
)
.await
.expect("spawn command under production Seatbelt policy")
.wait_with_output()
.await
.expect("wait for sandboxed command")
}
async fn run_path_command(
executable: &str,
path: &AbsolutePathBuf,
workspace: &AbsolutePathBuf,
profile: &PermissionProfile,
) -> Output {
run_sandboxed_command(
vec![executable.to_string(), path.display().to_string()],
workspace,
profile,
)
.await
}
async fn assert_denied_read(
path: &AbsolutePathBuf,
workspace: &AbsolutePathBuf,
profile: &PermissionProfile,
) {
let output = run_path_command("/bin/cat", path, workspace, profile).await;
assert!(
!output.status.success(),
"Seatbelt allowed reading {}: {output:?}",
path.display()
);
assert!(output.stdout.is_empty(), "protected contents leaked");
}
fn assert_file_contents(path: &AbsolutePathBuf, contents: &str) {
assert_eq!(fs::read_to_string(path).expect("read fixture"), contents);
}
async fn run_shell_command(
script: &str,
path: &AbsolutePathBuf,
workspace: &AbsolutePathBuf,
profile: &PermissionProfile,
) -> Output {
run_sandboxed_command(
vec![
"/bin/sh".to_string(),
"-c".to_string(),
script.to_string(),
"sh".to_string(),
path.display().to_string(),
],
workspace,
profile,
)
.await
}
async fn run_after_policy_applied(
operation: &str,
target: &AbsolutePathBuf,
extra_args: Vec<String>,
workspace: &AbsolutePathBuf,
profile: &PermissionProfile,
setup: impl FnOnce(),
) -> Output {
let label = target
.as_path()
.file_name()
.expect("filename")
.to_string_lossy();
let ready = workspace.join(format!("{label}.ready.txt"));
let proceed = workspace.join(format!("{label}.proceed.txt"));
let script = format!(
"printf ready > \"$2\"; while [ ! -e \"$3\" ]; do /bin/sleep 0.01; done; {operation}"
);
let mut command = vec![
"/bin/sh".to_string(),
"-c".to_string(),
script,
"sh".to_string(),
target.display().to_string(),
ready.display().to_string(),
proceed.display().to_string(),
];
command.extend(extra_args);
let child = spawn_command_under_sandbox(
command,
workspace.clone(),
profile,
workspace,
StdioPolicy::RedirectForShellTool,
HashMap::new(),
)
.await
.expect("spawn command before creating protected fixture");
tokio::time::timeout(Duration::from_secs(5), async {
while !ready.as_path().exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("sandboxed command did not signal policy application");
setup();
fs::write(&proceed, "proceed").expect("release sandboxed command");
child
.wait_with_output()
.await
.expect("wait for sandboxed command")
}
#[tokio::test]
async fn seatbelt_enforces_brace_alternation_and_escaped_deny_globs() {
core_test_support::skip_if_sandbox!();
let (temp_dir, workspace) = workspace_fixture();
let dotenv = workspace.join(".env");
let secrets = workspace.join("secrets.yml");
let escaped = workspace.join("config?.env");
let allowed = workspace.join("notes.txt");
for path in [&dotenv, &secrets, &escaped] {
fs::write(path, "protected contents").expect("write protected fixture");
}
fs::write(&allowed, "allowed contents").expect("write allowed fixture");
let config = format!(
r#"default_permissions = "test"
[permissions.test]
extends = ":read-only"
[permissions.test.filesystem]
"{workspace}" = "write"
"{workspace}/{{.env,secrets.yml}}*" = "deny"
'{workspace}/config\?.env' = "deny"
"#,
workspace = workspace.display()
);
fs::write(temp_dir.path().join("config.toml"), config).expect("write permissions config");
let profile = core_test_support::load_default_config_for_test(&temp_dir)
.await
.permissions
.effective_permission_profile();
for denied_path in [&dotenv, &secrets, &escaped] {
assert_denied_read(denied_path, &workspace, &profile).await;
}
let output = run_path_command("/bin/cat", &allowed, &workspace, &profile).await;
assert!(output.status.success(), "allowed read failed: {output:?}");
assert_eq!(output.stdout, b"allowed contents");
}
#[tokio::test]
async fn seatbelt_blocks_renaming_ancestors_of_explicit_protected_files() {
core_test_support::skip_if_sandbox!();
for access in [FileSystemAccessMode::Read, FileSystemAccessMode::Deny] {
let (_temp_dir, workspace) = workspace_fixture();
let private = workspace.join("private");
let protected = private.join("secret.env");
let renamed = workspace.join("exposed");
fs::create_dir(&private).expect("create protected directory");
fs::write(&protected, "protected contents").expect("write protected fixture");
let profile = permission_profile(&workspace, vec![(protected.clone().into(), access)]);
let command = vec![
"/bin/mv".to_string(),
private.display().to_string(),
renamed.display().to_string(),
];
let output = run_sandboxed_command(command.clone(), &workspace, &profile).await;
assert!(
!output.status.success(),
"Seatbelt allowed renaming an ancestor of a {access:?} path: {output:?}"
);
assert_file_contents(&protected, "protected contents");
assert!(!renamed.as_path().exists(), "rename unexpectedly succeeded");
let unprotected = permission_profile(&workspace, Vec::new());
let control = run_sandboxed_command(command, &workspace, &unprotected).await;
assert!(
control.status.success(),
"rename without a protected descendant should succeed: {control:?}"
);
}
}
#[tokio::test]
async fn seatbelt_blocks_renaming_dynamic_glob_ancestors() {
core_test_support::skip_if_sandbox!();
for component in [".githu?", "{.github,.gitlab}", r".githu\b", "*"] {
let (_temp_dir, workspace) = workspace_fixture();
let github = workspace.join(".github");
let workflows = github.join("workflows");
let protected = workflows.join("release.yml");
let renamed = workspace.join("exposed");
fs::create_dir_all(&workflows).expect("create protected directory");
fs::write(&protected, "protected workflow").expect("write protected fixture");
let profile = denied_glob_profile(
&workspace,
format!("{}/{component}/workflows/*.yml", workspace.display()),
);
let command = vec![
"/bin/mv".to_string(),
github.display().to_string(),
renamed.display().to_string(),
];
let output = run_sandboxed_command(command.clone(), &workspace, &profile).await;
assert!(
!output.status.success(),
"Seatbelt allowed renaming ancestor matched by {component:?}: {output:?}"
);
assert_file_contents(&protected, "protected workflow");
let unprotected = permission_profile(&workspace, Vec::new());
let control = run_sandboxed_command(command, &workspace, &unprotected).await;
assert!(
control.status.success(),
"rename without the deny glob should succeed: {control:?}"
);
}
}
#[tokio::test]
async fn seatbelt_blocks_renaming_protected_workspace_into_another_writable_root() {
core_test_support::skip_if_sandbox!();
let (_temp_dir, workspace) = workspace_fixture();
let destination = workspace
.parent()
.expect("workspace has a parent")
.join("destination");
let moved_workspace = destination.join("moved");
let protected = workspace.join("secret.env");
fs::create_dir(&destination).expect("create writable destination");
fs::write(&protected, "protected contents").expect("write protected fixture");
let profile = permission_profile(
&workspace,
vec![
(destination.clone().into(), FileSystemAccessMode::Write),
(protected.clone().into(), FileSystemAccessMode::Read),
],
);
let output = run_sandboxed_command(
vec![
"/bin/mv".to_string(),
workspace.display().to_string(),
moved_workspace.display().to_string(),
],
&workspace,
&profile,
)
.await;
assert!(
!output.status.success(),
"Seatbelt allowed moving the workspace into another writable root: {output:?}"
);
assert_file_contents(&protected, "protected contents");
assert!(
!moved_workspace.as_path().exists(),
"workspace unexpectedly moved"
);
}
#[tokio::test]
async fn seatbelt_ancestor_protection_does_not_block_unlinking_regular_files() {
core_test_support::skip_if_sandbox!();
let (_temp_dir, workspace) = workspace_fixture();
let regular_file = workspace.join("regular-file");
let hypothetical_descendant = regular_file.join("secret.env");
fs::write(&regular_file, "replaceable").expect("write regular file");
let profile = permission_profile(
&workspace,
vec![(hypothetical_descendant.into(), FileSystemAccessMode::Read)],
);
let output = run_path_command("/bin/rm", &regular_file, &workspace, &profile).await;
assert!(
output.status.success(),
"directory-only ancestor protection blocked a regular file: {output:?}"
);
assert!(
!regular_file.as_path().exists(),
"regular file was not removed"
);
}
#[tokio::test]
async fn seatbelt_deny_globs_block_writes_to_existing_and_new_files() {
core_test_support::skip_if_sandbox!();
let (_temp_dir, workspace) = workspace_fixture();
let protected = workspace.join("secret.env");
let allowed = workspace.join("notes.txt");
fs::write(&protected, "original").expect("write protected fixture");
let profile = denied_glob_profile(&workspace, format!("{}/*.env", workspace.display()));
for (operation, script) in [
("overwrite", "printf changed >> \"$1\""),
("truncate", ": > \"$1\""),
] {
let output = run_shell_command(script, &protected, &workspace, &profile).await;
assert!(
!output.status.success(),
"Seatbelt allowed {operation} on a denied file: {output:?}"
);
assert_file_contents(&protected, "original");
}
let unlink = run_path_command("/bin/rm", &protected, &workspace, &profile).await;
assert!(
!unlink.status.success(),
"Seatbelt unexpectedly allowed unlinking a denied glob: {unlink:?}"
);
assert_file_contents(&protected, "original");
for (operation, write_script) in [
("overwrite", "printf changed >> \"$1\""),
("truncate", ": > \"$1\""),
] {
let late_protected = workspace.join(format!("late-{operation}.env"));
let output = run_after_policy_applied(
write_script,
&late_protected,
Vec::new(),
&workspace,
&profile,
|| {
fs::write(&late_protected, "created after policy generation")
.expect("create protected fixture after sandbox launch");
},
)
.await;
assert!(
!output.status.success(),
"Seatbelt allowed {operation} on a file created after policy generation: {output:?}"
);
assert_file_contents(&late_protected, "created after policy generation");
}
let allowed_write =
run_shell_command("printf allowed > \"$1\"", &allowed, &workspace, &profile).await;
assert!(
allowed_write.status.success(),
"unrelated write should remain allowed: {allowed_write:?}"
);
assert_file_contents(&allowed, "allowed");
}
#[tokio::test]
async fn seatbelt_standard_profiles_preserve_expected_filesystem_access() {
core_test_support::skip_if_sandbox!();
let (_temp_dir, workspace) = workspace_fixture();
let inside = workspace.join("notes.txt");
let outside = workspace.parent().expect("parent").join("outside.txt");
fs::write(&inside, "original").expect("write workspace fixture");
let profile = permission_profile(&workspace, Vec::new());
let script = "set -e; /bin/cat \"$1\" >/dev/null; printf changed >> \"$1\"; /bin/mkdir \"$1.dir\"; /bin/mv \"$1\" \"$1.dir/moved\"; /bin/rm \"$1.dir/moved\"; /bin/rmdir \"$1.dir\"";
let inside_output = run_shell_command(script, &inside, &workspace, &profile).await;
assert!(
inside_output.status.success(),
"ordinary workspace operations failed: {inside_output:?}"
);
let outside_output =
run_shell_command("printf denied > \"$1\"", &outside, &workspace, &profile).await;
assert!(
!outside_output.status.success(),
"write outside the workspace unexpectedly succeeded: {outside_output:?}"
);
assert!(!outside.as_path().exists(), "outside file was created");
let readable = workspace.join("readable.txt");
fs::write(&readable, "readable contents").expect("write read-only fixture");
let profile = PermissionProfile::read_only();
let read = run_path_command("/bin/cat", &readable, &workspace, &profile).await;
assert!(read.status.success(), "ordinary read failed: {read:?}");
assert_eq!(read.stdout, b"readable contents");
let write = run_shell_command("printf changed > \"$1\"", &readable, &workspace, &profile).await;
assert!(
!write.status.success(),
"read-only write succeeded: {write:?}"
);
assert_file_contents(&readable, "readable contents");
}
#[tokio::test]
async fn seatbelt_blocks_protected_reads_and_writes_through_symlink_aliases() {
core_test_support::skip_if_sandbox!();
let (_temp_dir, workspace) = workspace_fixture();
let private = workspace.join("private");
let alias = workspace.join("alias");
let protected = private.join("secret.env");
let alias_path = alias.join("secret.env");
fs::create_dir(&private).expect("create protected directory");
fs::write(&protected, "protected contents").expect("write protected fixture");
symlink(private.as_path(), alias.as_path()).expect("create directory symlink");
for (restricted_path, accessed_path) in [
(FileSystemPath::from(protected.clone()), alias_path.clone()),
(
FileSystemPath::GlobPattern {
pattern: format!("{}/*.env", private.display()),
},
alias_path.clone(),
),
(
FileSystemPath::GlobPattern {
pattern: format!("{}/*.env", alias.display()),
},
protected.clone(),
),
] {
let profile = permission_profile(
&workspace,
vec![(restricted_path, FileSystemAccessMode::Deny)],
);
assert_denied_read(&accessed_path, &workspace, &profile).await;
let write = run_shell_command(
"printf changed > \"$1\"",
&accessed_path,
&workspace,
&profile,
)
.await;
assert!(
!write.status.success(),
"Seatbelt allowed writing through protected symlink alias: {write:?}"
);
assert_file_contents(&protected, "protected contents");
}
}
#[tokio::test]
async fn seatbelt_globstar_protects_files_and_ancestors_at_every_depth() {
core_test_support::skip_if_sandbox!();
let (_temp_dir, workspace) = workspace_fixture();
let first = workspace.join("first");
let second = first.join("second");
fs::create_dir_all(&second).expect("create nested fixture directories");
let protected_paths = [
workspace.join("root.env"),
first.join("first.env"),
second.join("second.env"),
];
for path in &protected_paths {
fs::write(path, "protected contents").expect("write protected fixture");
}
let profile = denied_glob_profile(&workspace, format!("{}/**/*.env", workspace.display()));
for path in &protected_paths {
assert_denied_read(path, &workspace, &profile).await;
}
for ancestor in [&first, &second] {
let destination = ancestor.with_extension("renamed");
let output = run_sandboxed_command(
vec![
"/bin/mv".to_string(),
ancestor.display().to_string(),
destination.display().to_string(),
],
&workspace,
&profile,
)
.await;
assert!(
!output.status.success(),
"globstar allowed renaming protected ancestor {}: {output:?}",
ancestor.display()
);
}
}
#[tokio::test]
async fn seatbelt_brace_alternatives_with_slashes_protect_each_branch() {
core_test_support::skip_if_sandbox!();
let (_temp_dir, workspace) = workspace_fixture();
let nested = workspace.join("private/nested");
let other = workspace.join("other");
let allowed = workspace.join("notes.txt");
fs::create_dir_all(&nested).expect("create nested protected directory");
fs::create_dir(&other).expect("create alternate protected directory");
let protected_paths = [nested.join("secret.env"), other.join("secret.env")];
for path in &protected_paths {
fs::write(path, "protected contents").expect("write protected fixture");
}
fs::write(&allowed, "allowed contents").expect("write allowed fixture");
let profile = denied_glob_profile(
&workspace,
format!("{}/{{private/nested,other}}/*.env", workspace.display()),
);
for path in &protected_paths {
assert_denied_read(path, &workspace, &profile).await;
}
for ancestor in [&workspace.join("private"), &nested, &other] {
let destination = ancestor.with_extension("renamed");
let output = run_sandboxed_command(
vec![
"/bin/mv".to_string(),
ancestor.display().to_string(),
destination.display().to_string(),
],
&workspace,
&profile,
)
.await;
assert!(
!output.status.success(),
"brace alternative allowed renaming {}: {output:?}",
ancestor.display()
);
}
let output = run_path_command("/bin/cat", &allowed, &workspace, &profile).await;
assert!(
output.status.success(),
"brace alternatives produced an invalid or overly broad policy: {output:?}"
);
assert_eq!(output.stdout, b"allowed contents");
}
#[tokio::test]
async fn seatbelt_protects_directory_trees_created_after_policy_application() {
core_test_support::skip_if_sandbox!();
for operation in ["read", "rename"] {
let (_temp_dir, workspace) = workspace_fixture();
let late_directory = workspace.join("late/deep");
let protected = late_directory.join("secret.env");
let destination = workspace.join("exposed");
let profile = denied_glob_profile(&workspace, format!("{}/**/*.env", workspace.display()));
let operation_script = match operation {
"read" => "/bin/cat \"$1\"",
"rename" => "/bin/mv \"$4\" \"$5\"",
_ => unreachable!("unknown operation"),
};
let output = run_after_policy_applied(
operation_script,
&protected,
vec![
workspace.join("late").display().to_string(),
destination.display().to_string(),
],
&workspace,
&profile,
|| {
fs::create_dir_all(&late_directory)
.expect("create protected directory after policy");
fs::write(&protected, "protected contents").expect("write protected fixture");
},
)
.await;
assert!(
!output.status.success(),
"Seatbelt allowed {operation} after protected directory appeared: {output:?}"
);
assert_file_contents(&protected, "protected contents");
}
}
#[tokio::test]
async fn seatbelt_blocks_atomic_rename_exchange_and_destination_replacement() {
core_test_support::skip_if_sandbox!();
for (operation, flags) in [("exchange", libc::RENAME_SWAP), ("replace", 0)] {
let (_temp_dir, workspace) = workspace_fixture();
let private = workspace.join("private");
let destination = workspace.join("destination");
let protected = private.join("secret.env");
fs::create_dir(&private).expect("create protected directory");
fs::create_dir(&destination).expect("create replacement directory");
fs::write(&protected, "protected contents").expect("write protected fixture");
let profile = permission_profile(
&workspace,
vec![(protected.clone().into(), FileSystemAccessMode::Read)],
);
let script = "import ctypes, os, sys; libc = ctypes.CDLL(None, use_errno=True); result = libc.renameatx_np(-2, os.fsencode(sys.argv[1]), -2, os.fsencode(sys.argv[2]), int(sys.argv[3])); sys.exit(0 if result == 0 else ctypes.get_errno())";
let command = vec![
"/usr/bin/python3".to_string(),
"-c".to_string(),
script.to_string(),
private.display().to_string(),
destination.display().to_string(),
flags.to_string(),
];
let output = run_sandboxed_command(command.clone(), &workspace, &profile).await;
assert!(
!output.status.success(),
"Seatbelt allowed atomic {operation} of a protected ancestor: {output:?}"
);
assert_file_contents(&protected, "protected contents");
let unprotected = permission_profile(&workspace, Vec::new());
let control = run_sandboxed_command(command, &workspace, &unprotected).await;
assert!(
control.status.success(),
"unprotected atomic {operation} should succeed: {control:?}"
);
}
}
#[tokio::test]
async fn seatbelt_blocks_protected_ancestor_moves_across_writable_roots() {
core_test_support::skip_if_sandbox!();
for destination_is_nested in [false, true] {
for use_glob in [false, true] {
let (_temp_dir, workspace) = workspace_fixture();
let private = workspace.join("private");
let protected = private.join("secret.env");
let destination = if destination_is_nested {
workspace.join("destination")
} else {
workspace
.parent()
.expect("workspace has a parent")
.join("destination")
};
let moved = destination.join("moved");
fs::create_dir(&private).expect("create protected directory");
fs::create_dir(&destination).expect("create writable destination");
fs::write(&protected, "protected contents").expect("write protected fixture");
let protected_path = if use_glob {
FileSystemPath::GlobPattern {
pattern: format!("{}/*.env", private.display()),
}
} else {
protected.clone().into()
};
let profile = permission_profile(
&workspace,
vec![
(destination.clone().into(), FileSystemAccessMode::Write),
(protected_path, FileSystemAccessMode::Deny),
],
);
let output = run_sandboxed_command(
vec![
"/bin/mv".to_string(),
private.display().to_string(),
moved.display().to_string(),
],
&workspace,
&profile,
)
.await;
assert!(
!output.status.success(),
"protected ancestor crossed writable roots: nested={destination_is_nested}, glob={use_glob}, output={output:?}"
);
assert_file_contents(&protected, "protected contents");
assert!(!moved.as_path().exists(), "protected ancestor was moved");
}
}
}
#[tokio::test]
async fn seatbelt_blocks_creating_files_matched_by_denied_globs() {
core_test_support::skip_if_sandbox!();
let (_temp_dir, workspace) = workspace_fixture();
let nested = workspace.join("nested");
fs::create_dir(&nested).expect("create nested directory");
let profile = denied_glob_profile(&workspace, format!("{}/**/*.env", workspace.display()));
for path in [workspace.join("created.env"), nested.join("created.env")] {
let output =
run_shell_command("printf created > \"$1\"", &path, &workspace, &profile).await;
assert!(
!output.status.success(),
"Seatbelt allowed creation at a denied path: {output:?}"
);
assert!(!path.as_path().exists(), "denied file was created");
}
let allowed = nested.join("created.txt");
let output = run_path_command("/usr/bin/touch", &allowed, &workspace, &profile).await;
assert!(
output.status.success(),
"unrelated file creation should succeed: {output:?}"
);
assert!(allowed.as_path().exists(), "unrelated file was not created");
}

View File

@@ -0,0 +1,33 @@
#![cfg(not(target_os = "windows"))]
#![allow(clippy::unwrap_used)]
use core_test_support::responses;
use core_test_support::test_codex_exec::test_codex_exec;
/// Verify that when the server reports an error, `codex-exec` exits with a
/// non-zero status code so automation can detect failures.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exits_non_zero_when_server_reports_error() -> anyhow::Result<()> {
let test = test_codex_exec();
// Mock a simple Responses API SSE stream that immediately reports a
// `response.failed` event with an error message.
let server = responses::start_mock_server().await;
let body = responses::sse(vec![serde_json::json!({
"type": "response.failed",
"response": {
"id": "resp_err_1",
"error": {"code": "rate_limit_exceeded", "message": "synthetic server error"}
}
})]);
responses::mount_sse_once(&server, body).await;
test.cmd_with_server(&server)
.arg("--skip-git-repo-check")
.arg("tell me something")
.arg("--experimental-json")
.assert()
.code(1);
Ok(())
}

View File

@@ -0,0 +1,423 @@
//! Exercises gated shared-pool execution and preserves existing checkout ownership.
//! Observe ownership at the first model request, before the process can finish.
use anyhow::Context;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_worktree::CreateWorktree;
use codex_worktree::WorktreeManager;
use codex_worktree::WorktreeSettings;
use core_test_support::responses;
use core_test_support::test_codex_exec::test_codex_exec;
use pretty_assertions::assert_eq;
use serde_json::Value;
use std::fs;
use std::path::Path;
use std::process::Command;
use std::process::Output;
use std::sync::Arc;
use std::sync::Mutex;
fn git(cwd: &Path, args: &[&str]) -> anyhow::Result<()> {
let output = Command::new("git")
.current_dir(cwd)
.args([
"-c",
"user.name=Worktree Test",
"-c",
"user.email=test@example.invalid",
])
.args(args)
.output()?;
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
Ok(())
}
fn started_thread(output: Output) -> anyhow::Result<String> {
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let events = String::from_utf8(output.stdout)?
.lines()
.map(serde_json::from_str::<Value>)
.collect::<Result<Vec<_>, _>>()?;
events
.iter()
.find(|event| event["type"] == "thread.started")
.and_then(|event| event["thread_id"].as_str())
.map(str::to_owned)
.context("exec should report its thread id")
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn worktree_start_and_fork_use_host_pool_and_preserve_legacy_resume() -> anyhow::Result<()> {
let test = test_codex_exec();
let home = AbsolutePathBuf::from_absolute_path(test.home_path())?
.canonicalize()?
.into_path_buf();
let source = AbsolutePathBuf::from_absolute_path(test.cwd_path())?
.canonicalize()?
.into_path_buf();
let extra = source.join("extra");
fs::create_dir(&extra)?;
fs::write(extra.join("tracked.txt"), "tracked")?;
fs::write(source.join("AGENTS.md"), "managed checkout instructions")?;
git(&source, &["init", "--quiet"])?;
git(&source, &["add", "."])?;
git(
&source,
&["commit", "--quiet", "--no-gpg-sign", "-m", "initial"],
)?;
let pool = home.join("shared-worktrees");
let other_pool = serde_json::to_string(&home.join("session-only-pool"))?;
fs::write(
home.join("config.toml"),
format!(
"sandbox_mode = \"workspace-write\"\nfeatures.worktrees = true\n[desktop]\ngit-worktree-root = {}\n[projects.{}]\ntrust_level = \"trusted\"\n",
serde_json::to_string(&pool)?,
serde_json::to_string(&source)?,
),
)?;
fs::write(
home.join("demo.config.toml"),
format!("features.worktrees = false\n[desktop]\ngit-worktree-root = {other_pool}\n"),
)?;
let mut settings = WorktreeSettings::for_cli(&home, /*desktop*/ None)?;
settings.root = pool;
let legacy_manager = WorktreeManager::new(WorktreeSettings {
root: home.join("worktrees-cli"),
..settings.clone()
});
let legacy = legacy_manager.create(&CreateWorktree {
source_cwd: source.clone(),
base: None,
})?;
let manager = WorktreeManager::new(settings);
let body = responses::sse(vec![
responses::ev_response_created("response_1"),
responses::ev_assistant_message("message_1", "done"),
responses::ev_completed("response_1"),
]);
let server = responses::start_mock_server().await;
let seed_mock = responses::mount_sse_once(&server, body.clone()).await;
let legacy_id = started_thread(
test.cmd_with_server(&server)
.current_dir(legacy.cwd.join("extra"))
.args(["--json", "legacy seed"])
.output()?,
)?;
seed_mock.single_request();
legacy_manager.bind_thread(&legacy.root, &legacy_id)?;
fs::write(source.join("AGENTS.md"), "uncommitted source instructions")?;
fs::create_dir(source.join(".codex"))?;
fs::write(source.join(".codex/config.toml"), "[invalid source config")?;
let launcher = tempfile::tempdir()?;
fs::create_dir(launcher.path().join("extra"))?;
let mut known_roots = Vec::new();
for (fork, overrides) in [
(false, Vec::new()),
(
true,
vec![
"--profile".to_owned(),
"demo".to_owned(),
"-c".to_owned(),
"features.worktrees=true".to_owned(),
"-c".to_owned(),
format!("desktop.git-worktree-root={other_pool}"),
"-c".to_owned(),
format!("desktop={{git-worktree-root={other_pool}}}"),
],
),
(true, vec!["--cd".to_owned(), extra.display().to_string()]),
] {
let explicit_cd = overrides.first().is_some_and(|arg| arg == "--cd");
let server = responses::start_mock_server().await;
let observed_owner = Arc::new(Mutex::<Option<String>>::default());
let captured_owner = Arc::clone(&observed_owner);
let observed_manager = manager.clone();
let observed_source = source.clone();
let previous_roots = known_roots.clone();
// A matcher is needed here to inspect metadata at request time, not after exit.
let response_mock = responses::mount_sse_once_match(
&server,
move |_: &wiremock::Request| {
let owner = observed_manager
.list(&observed_source)
.expect("list shared checkouts")
.into_iter()
.find(|checkout| !previous_roots.contains(&checkout.root))
.and_then(|checkout| {
observed_manager.owner(&checkout.root).expect("read owner")
});
*captured_owner.lock().expect("capture request owner") = owner;
true
},
body.clone(),
)
.await;
let mut command = test.cmd_with_server(&server);
command
.args(["--json", "--worktree", "--add-dir", "extra"])
.args(overrides);
if fork {
command
.current_dir(launcher.path())
.arg("fork")
.arg(&legacy_id);
}
let thread_id = started_thread(command.arg("describe checkout").output()?)?;
assert_eq!(
*observed_owner.lock().expect("read captured owner"),
Some(thread_id)
);
let checkout = manager
.list(&source)?
.into_iter()
.find(|checkout| !known_roots.contains(&checkout.root))
.context("one new shared checkout")?;
let request = response_mock.single_request();
let context = request
.message_input_texts("user")
.into_iter()
.chain(request.message_input_texts("developer"))
.collect::<Vec<_>>()
.join("\n");
let checkout_cwd = AbsolutePathBuf::from_absolute_path(if explicit_cd {
checkout.root.join("extra")
} else {
checkout.cwd.clone()
})?
.canonicalize()?;
assert!(
context.contains(checkout_cwd.to_string_lossy().as_ref()),
"{context}"
);
assert!(
context.contains(
if fork {
launcher.path().join("extra")
} else {
extra.clone()
}
.to_string_lossy()
.as_ref()
),
"{context}"
);
assert!(
context.contains("managed checkout instructions"),
"{context}"
);
assert!(
!context.contains("uncommitted source instructions"),
"{context}"
);
known_roots.push(checkout.root);
}
let server = responses::start_mock_server().await;
let resume_mock = responses::mount_sse_once(&server, body).await;
let resumed_id = started_thread(
test.cmd_with_server(&server)
.current_dir(legacy.cwd.join("extra"))
.args(["--json", "resume", &legacy_id, "continue legacy"])
.output()?,
)?;
assert_eq!(resumed_id, legacy_id);
assert_eq!(legacy_manager.owner(&legacy.root)?, Some(legacy_id.clone()));
let legacy_cwd =
AbsolutePathBuf::from_absolute_path(legacy.cwd.join("extra"))?.canonicalize()?;
assert!(
resume_mock
.single_request()
.message_input_texts("user")
.iter()
.any(|text| text.contains(legacy_cwd.to_string_lossy().as_ref()))
);
fs::write(
home.join("config.toml"),
format!(
"features.worktrees=true\n[projects.{}]\ntrust_level=\"untrusted\"\n",
serde_json::to_string(&source)?,
),
)?;
for args in [vec!["prompt"], vec!["fork", legacy_id.as_str(), "prompt"]] {
let output = test.cmd().arg("--worktree").args(args).output()?;
assert!(!output.status.success());
assert!(String::from_utf8_lossy(&output.stderr).contains("explicitly untrusted"));
}
assert!(!home.join("worktrees").exists());
// Synthetic enterprise claims let the cloud bundle, not a local project entry,
// supply the source's distrust decision.
fs::write(
home.join("auth.json"),
serde_json::to_vec(&serde_json::json!({
"auth_mode": "chatgpt",
"tokens": {
"id_token": "e30.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF9wbGFuX3R5cGUiOiJlbnRlcnByaXNlIiwiY2hhdGdwdF9hY2NvdW50X2lkIjoid29ya3NwYWNlLTEyMyIsImNoYXRncHRfdXNlcl9pZCI6InVzZXItMTIzIn19.signature",
"access_token": "test-access-token",
"refresh_token": "test-refresh-token",
"account_id": "workspace-123"
}
}))?,
)?;
fs::write(
home.join("config.toml"),
format!(
"features.worktrees=true\ncli_auth_credentials_store=\"file\"\nchatgpt_base_url=\"{}/backend-api\"\n",
server.uri(),
),
)?;
wiremock::Mock::given(wiremock::matchers::method("GET"))
.and(wiremock::matchers::path("/backend-api/wham/config/bundle"))
.respond_with(
wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
"config_toml": { "enterprise_managed": [{
"id": "source-trust", "name": "Source trust",
"contents": format!(
"[projects.{}]\ntrust_level=\"untrusted\"\n[projects.{}]\ntrust_level=\"untrusted\"\n",
serde_json::to_string(&source)?,
serde_json::to_string(&legacy.cwd.join("extra"))?,
)
}] }
})),
)
.mount(&server)
.await;
for args in [vec!["prompt"], vec!["fork", legacy_id.as_str(), "prompt"]] {
let request_count = if args.first() == Some(&"fork") {
// The saved checkout can choose file auth even when the launcher does not.
fs::remove_file(source.join(".codex/config.toml"))?;
fs::create_dir_all(legacy.cwd.join(".codex"))?;
fs::write(
legacy.cwd.join(".codex/config.toml"),
"cli_auth_credentials_store=\"file\"\n",
)?;
git(&legacy.cwd, &["add", ".codex/config.toml"])?;
git(
&legacy.cwd,
&["commit", "--quiet", "--no-gpg-sign", "-m", "file auth"],
)?;
fs::write(
home.join("config.toml"),
format!(
"features.worktrees=true\ncli_auth_credentials_store=\"ephemeral\"\nchatgpt_base_url=\"{}/backend-api\"\n[projects.{}]\ntrust_level=\"trusted\"\n",
server.uri(),
serde_json::to_string(&source)?,
),
)?;
let cache = home.join("cloud-config-bundle-cache.json");
if cache.exists() {
fs::remove_file(&cache)?;
}
Some(server.received_requests().await.context("requests")?.len())
} else {
None
};
let output = test
.cmd()
.current_dir(if request_count.is_some() {
launcher.path()
} else {
&source
})
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove("CODEX_ACCESS_TOKEN")
.args(["--json", "--worktree", "--strict-config"])
.args(args)
.output()?;
assert!(
!output.status.success()
&& String::from_utf8_lossy(&output.stderr).contains("explicitly untrusted"),
"{}",
String::from_utf8_lossy(&output.stderr)
);
if let Some(request_count) = request_count {
assert!(!String::from_utf8_lossy(&output.stdout).contains("thread.started"));
let denied_manager =
WorktreeManager::new(WorktreeSettings::for_cli(&home, /*desktop*/ None)?);
let checkout = denied_manager
.list(&legacy.cwd)?
.into_iter()
.next()
.context("denied checkout remains for manual removal")?;
assert_eq!(denied_manager.owner(&checkout.root)?, None);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains(
checkout
.root
.file_name()
.context("checkout name")?
.to_string_lossy()
.as_ref()
)
);
assert!(stderr.contains("Remove it manually with `git worktree remove`"));
assert!(
server
.received_requests()
.await
.context("requests")?
.iter()
.skip(request_count)
.any(|request| request.url.path() == "/backend-api/wham/config/bundle")
);
} else {
assert!(!home.join("worktrees").exists());
}
}
Ok(())
}
#[test]
fn worktree_rejects_remote_defaults_before_allocation() -> anyhow::Result<()> {
for route in ["environment", "file"] {
let test = test_codex_exec();
let mut command = test.cmd();
if route == "environment" {
command.env("CODEX_EXEC_SERVER_URL", "ws://127.0.0.1:9");
} else {
fs::write(
test.home_path().join("environments.toml"),
"default = 'remote'\n[[environments]]\nid = 'remote'\nurl = 'ws://127.0.0.1:9'\n",
)?;
}
let output = command
.args(["--worktree", "-c", "features.worktrees=true", "prompt"])
.output()?;
assert!(!output.status.success(), "{route}");
assert!(
String::from_utf8_lossy(&output.stderr).contains("--worktree requires local execution"),
"{route}: {}",
String::from_utf8_lossy(&output.stderr)
);
assert!(!test.home_path().join("worktrees").exists(), "{route}");
}
Ok(())
}
#[test]
fn worktree_rejects_ignored_config_before_allocation() -> anyhow::Result<()> {
let test = test_codex_exec();
let output = test
.cmd()
.args(["--worktree", "--ignore-user-config", "prompt"])
.output()?;
assert!(!output.status.success());
assert!(
String::from_utf8_lossy(&output.stderr)
.contains("--worktree cannot be combined with --ignore-user-config")
);
assert!(!test.home_path().join("worktrees").exists());
Ok(())
}