Merge remote-tracking branch 'origin/main' into guinness/realtime-terminal-output

# Conflicts:
#	codex-rs/core/src/session/turn.rs
This commit is contained in:
Guinness Chen
2026-06-09 18:16:31 -07:00
235 changed files with 11906 additions and 1312 deletions
+1
View File
@@ -103,6 +103,7 @@ pub(crate) async fn run_codex_thread_interactive(
parent_rollout_thread_trace: codex_rollout_trace::ThreadTraceContext::disabled(),
parent_trace: None,
environment_selections: parent_ctx.environments.clone(),
thread_extension_init: codex_extension_api::ExtensionDataInit::default(),
analytics_events_client: Some(parent_session.services.analytics_events_client.clone()),
thread_store: Arc::clone(&parent_session.services.thread_store),
attestation_provider: parent_session.services.attestation_provider.clone(),
+1
View File
@@ -1428,6 +1428,7 @@ impl Config {
codex_linux_sandbox_exe: self.codex_linux_sandbox_exe.clone(),
use_legacy_landlock: self.features.use_legacy_landlock(),
apps_enabled: self.features.enabled(Feature::Apps),
legacy_apps_mcp_loader_enabled: true,
prefix_mcp_tool_names: self.prefix_mcp_tool_names(),
client_elicitation_capability: if self.features.enabled(Feature::AuthElicitation) {
ElicitationCapability {
+21 -6
View File
@@ -1,4 +1,3 @@
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::LazyLock;
@@ -41,8 +40,8 @@ use codex_mcp::ToolInfo;
use codex_mcp::ToolPluginProvenance;
use codex_mcp::codex_apps_tools_cache_key;
use codex_mcp::compute_auth_statuses;
use codex_mcp::effective_mcp_servers;
use codex_mcp::host_owned_codex_apps_enabled;
use codex_mcp::with_codex_apps_mcp;
const CONNECTORS_READY_TIMEOUT_ON_EMPTY_TOOLS: Duration = Duration::from_secs(30);
@@ -220,6 +219,23 @@ pub async fn list_accessible_connectors_from_mcp_tools_with_environment_manager(
config: &Config,
force_refetch: bool,
environment_manager: Arc<EnvironmentManager>,
) -> anyhow::Result<AccessibleConnectorsStatus> {
let plugins_manager = Arc::new(PluginsManager::new(config.codex_home.to_path_buf()));
let mcp_manager = Arc::new(McpManager::new(plugins_manager));
list_accessible_connectors_from_mcp_tools_with_mcp_manager(
config,
force_refetch,
environment_manager,
mcp_manager,
)
.await
}
pub async fn list_accessible_connectors_from_mcp_tools_with_mcp_manager(
config: &Config,
force_refetch: bool,
environment_manager: Arc<EnvironmentManager>,
mcp_manager: Arc<McpManager>,
) -> anyhow::Result<AccessibleConnectorsStatus> {
let auth_manager =
AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await;
@@ -234,8 +250,6 @@ pub async fn list_accessible_connectors_from_mcp_tools_with_environment_manager(
});
}
let cache_key = accessible_connectors_cache_key(config, auth.as_ref());
let plugins_manager = Arc::new(PluginsManager::new(config.codex_home.to_path_buf()));
let mcp_manager = McpManager::new(Arc::clone(&plugins_manager));
let tool_plugin_provenance = mcp_manager.tool_plugin_provenance(config).await;
if !force_refetch && let Some(cached_connectors) = read_cached_accessible_connectors(&cache_key)
{
@@ -250,8 +264,9 @@ pub async fn list_accessible_connectors_from_mcp_tools_with_environment_manager(
});
}
let mcp_config = config.to_mcp_config(plugins_manager.as_ref()).await;
let mcp_servers = with_codex_apps_mcp(HashMap::new(), auth.as_ref(), &mcp_config);
let mcp_config = mcp_manager.runtime_config(config).await;
let mut mcp_servers = effective_mcp_servers(&mcp_config, auth.as_ref());
mcp_servers.retain(|name, _| name == CODEX_APPS_MCP_SERVER_NAME);
let host_owned_codex_apps_enabled = host_owned_codex_apps_enabled(&mcp_config, auth.as_ref());
if mcp_servers.is_empty() {
return Ok(AccessibleConnectorsStatus {
-40
View File
@@ -340,46 +340,6 @@ async fn test_get_has_changes_with_untracked_change_returns_true() {
assert_eq!(get_has_changes(&repo_path).await, Some(true));
}
#[cfg(unix)]
#[tokio::test]
async fn test_get_has_changes_ignores_repo_fsmonitor_config() {
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let repo_path = create_test_git_repo(&temp_dir).await;
let helper_path = repo_path.join("fsmonitor-helper.sh");
let marker_path = repo_path.join("fsmonitor-ran");
fs::write(
&helper_path,
format!(
"#!/bin/sh\nprintf ran > \"{}\"\n",
marker_path.to_string_lossy()
),
)
.expect("write fsmonitor helper");
let mut permissions = fs::metadata(&helper_path)
.expect("read fsmonitor helper metadata")
.permissions();
permissions.set_mode(0o755);
fs::set_permissions(&helper_path, permissions).expect("mark fsmonitor helper executable");
Command::new("git")
.args([
"config",
"core.fsmonitor",
helper_path.to_string_lossy().as_ref(),
])
.current_dir(&repo_path)
.output()
.await
.expect("configure fsmonitor helper");
assert_eq!(get_has_changes(&repo_path).await, Some(true));
assert!(
!marker_path.exists(),
"metadata collection should not invoke repository fsmonitor helpers"
);
}
#[cfg(unix)]
#[tokio::test]
async fn test_get_has_changes_ignores_configured_hooks_path() {
+68 -2
View File
@@ -4,8 +4,12 @@ use std::sync::Arc;
use crate::config::Config;
use codex_config::McpServerConfig;
use codex_core_plugins::PluginsManager;
use codex_extension_api::ExtensionRegistry;
use codex_extension_api::McpServerContribution;
use codex_login::CodexAuth;
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
use codex_mcp::EffectiveMcpServer;
use codex_mcp::McpConfig;
use codex_mcp::ToolPluginProvenance;
use codex_mcp::configured_mcp_servers;
use codex_mcp::effective_mcp_servers;
@@ -14,29 +18,91 @@ use codex_mcp::tool_plugin_provenance as collect_tool_plugin_provenance;
#[derive(Clone)]
pub struct McpManager {
plugins_manager: Arc<PluginsManager>,
extensions: Arc<ExtensionRegistry<Config>>,
}
impl McpManager {
pub fn new(plugins_manager: Arc<PluginsManager>) -> Self {
Self { plugins_manager }
Self {
plugins_manager,
extensions: codex_extension_api::empty_extension_registry(),
}
}
/// Creates a manager that resolves host-installed MCP contributions.
pub fn new_with_extensions(
plugins_manager: Arc<PluginsManager>,
extensions: Arc<ExtensionRegistry<Config>>,
) -> Self {
Self {
plugins_manager,
extensions,
}
}
/// Returns the MCP config after applying runtime-only extension overlays.
pub async fn runtime_config(&self, config: &Config) -> McpConfig {
let mut mcp_config = config.to_mcp_config(self.plugins_manager.as_ref()).await;
let contributions = self.contributions(config).await;
if contributions
.iter()
.any(|contribution| contribution.name() == CODEX_APPS_MCP_SERVER_NAME)
{
mcp_config.legacy_apps_mcp_loader_enabled = false;
}
Self::apply_to_configured_servers(&contributions, &mut mcp_config.configured_mcp_servers);
mcp_config
}
/// Returns config- and plugin-backed servers without runtime contributions.
pub async fn configured_servers(&self, config: &Config) -> HashMap<String, McpServerConfig> {
let mcp_config = config.to_mcp_config(self.plugins_manager.as_ref()).await;
configured_mcp_servers(&mcp_config)
}
/// Returns configured and host-contributed servers before auth gating.
pub async fn runtime_servers(&self, config: &Config) -> HashMap<String, McpServerConfig> {
let mcp_config = self.runtime_config(config).await;
configured_mcp_servers(&mcp_config)
}
/// Returns runtime servers after auth gating and compatibility built-ins.
pub async fn effective_servers(
&self,
config: &Config,
auth: Option<&CodexAuth>,
) -> HashMap<String, EffectiveMcpServer> {
let mcp_config = config.to_mcp_config(self.plugins_manager.as_ref()).await;
let mcp_config = self.runtime_config(config).await;
effective_mcp_servers(&mcp_config, auth)
}
/// Returns provenance for plugin-owned servers in the configured view.
pub async fn tool_plugin_provenance(&self, config: &Config) -> ToolPluginProvenance {
let mcp_config = config.to_mcp_config(self.plugins_manager.as_ref()).await;
collect_tool_plugin_provenance(&mcp_config)
}
async fn contributions(&self, config: &Config) -> Vec<McpServerContribution> {
let mut contributions = Vec::new();
for contributor in self.extensions.mcp_server_contributors() {
contributions.extend(contributor.contribute(config).await);
}
contributions
}
fn apply_to_configured_servers(
contributions: &[McpServerContribution],
servers: &mut HashMap<String, McpServerConfig>,
) {
for contribution in contributions {
match contribution {
McpServerContribution::Set { name, config } => {
servers.insert(name.clone(), config.as_ref().clone());
}
McpServerContribution::Remove { name } => {
servers.remove(name);
}
}
}
}
}
+14 -8
View File
@@ -56,7 +56,7 @@ pub(crate) async fn maybe_prompt_and_install_mcp_dependencies(
let installed = sess
.services
.mcp_manager
.configured_servers(config.as_ref())
.runtime_servers(config.as_ref())
.await;
let missing = collect_missing_mcp_dependencies(mentioned_skills, &installed);
if missing.is_empty() {
@@ -98,7 +98,7 @@ pub(crate) async fn maybe_install_mcp_dependencies(
}
let codex_home = config.codex_home.clone();
let installed = sess.services.mcp_manager.configured_servers(config).await;
let installed = sess.services.mcp_manager.runtime_servers(config).await;
let missing = collect_missing_mcp_dependencies(mentioned_skills, &installed);
if missing.is_empty() {
return;
@@ -190,16 +190,22 @@ pub(crate) async fn maybe_install_mcp_dependencies(
}
}
// Refresh from the config-backed merged MCP map (global + repo + managed)
// and overlay the updated global servers so we don't drop repo-scoped
// servers. Runtime additions such as built-ins are rebuilt by the refresh
// path from the current config.
let mut refresh_servers = sess.services.mcp_manager.configured_servers(config).await;
let mut refresh_config = config.clone();
let mut configured_servers = config.mcp_servers.get().clone();
for (name, server_config) in &servers {
refresh_servers
configured_servers
.entry(name.clone())
.or_insert_with(|| server_config.clone());
}
if let Err(err) = refresh_config.mcp_servers.set(configured_servers) {
warn!("failed to refresh MCP dependencies for mentioned skills: {err}");
return;
}
let refresh_servers = sess
.services
.mcp_manager
.runtime_servers(&refresh_config)
.await;
sess.refresh_mcp_servers_now(
turn_context,
refresh_servers,
@@ -7,7 +7,7 @@ use crate::plugins::test_support::write_plugins_feature_config;
use codex_core_plugins::OPENAI_BUNDLED_MARKETPLACE_NAME;
use codex_core_plugins::PluginInstallRequest;
use codex_core_plugins::PluginsManager;
use codex_core_plugins::remote::RemotePluginScope;
use codex_core_plugins::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
use codex_core_plugins::remote::RemotePluginServiceConfig;
use codex_core_plugins::remote::fetch_and_cache_global_remote_plugin_catalog;
use codex_core_plugins::startup_sync::curated_plugins_repo_path;
@@ -362,7 +362,7 @@ remote_plugin = true
.build_and_cache_remote_installed_plugin_marketplaces(
&config.plugins_config_input(),
Some(&auth),
&[RemotePluginScope::Global],
&[REMOTE_GLOBAL_MARKETPLACE_NAME],
/*on_effective_plugins_changed*/ None,
)
.await
+6 -1
View File
@@ -1,5 +1,6 @@
use crate::client::ModelClient;
use crate::realtime_context::build_realtime_startup_context;
use crate::realtime_context::truncate_realtime_text_to_token_budget;
use crate::realtime_prompt::prepare_realtime_backend_prompt;
use crate::session::session::Session;
use anyhow::Context;
@@ -64,6 +65,7 @@ const USER_TEXT_IN_QUEUE_CAPACITY: usize = 64;
const ASSISTANT_OUTPUT_QUEUE_CAPACITY: usize = 64;
const OUTPUT_EVENTS_QUEUE_CAPACITY: usize = 256;
const REALTIME_STARTUP_CONTEXT_TOKEN_BUDGET: usize = 5_300;
const REALTIME_ASSISTANT_OUTPUT_TOKEN_BUDGET: usize = 1_000;
const DEFAULT_REALTIME_MODEL: &str = "gpt-realtime-1.5";
pub(crate) const REALTIME_USER_TEXT_PREFIX: &str = "[USER] ";
const DEFAULT_HANDOFF_ID: &str = "codex";
@@ -202,7 +204,10 @@ impl RealtimeHandoffState {
async fn assistant_output(&self, output_text: String) -> RealtimeAssistantOutput {
RealtimeAssistantOutput {
handoff_id: self.active_handoff.lock().await.clone(),
output_text,
output_text: truncate_realtime_text_to_token_budget(
&output_text,
REALTIME_ASSISTANT_OUTPUT_TOKEN_BUDGET,
),
}
}
@@ -8,6 +8,7 @@ use async_channel::bounded;
use codex_config::config_toml::RealtimeWsVersion;
use codex_protocol::protocol::RealtimeHandoffRequested;
use codex_protocol::protocol::RealtimeTranscriptEntry;
use codex_utils_output_truncation::approx_token_count;
use pretty_assertions::assert_eq;
#[test]
@@ -178,6 +179,22 @@ async fn assistant_output_without_handoff_has_no_active_id() {
);
}
#[tokio::test]
async fn assistant_output_is_capped_for_realtime_context() {
let (tx, _rx) = bounded(1);
let state = RealtimeHandoffState::new(tx);
*state.active_handoff.lock().await = Some("handoff_1".to_string());
let output = state
.assistant_output(format!("start {} end", "middle ".repeat(2_000)))
.await;
assert_eq!(output.handoff_id.as_deref(), Some("handoff_1"));
assert!(approx_token_count(&output.output_text) <= 1_000);
assert!(output.output_text.starts_with("start "));
assert!(output.output_text.ends_with(" end"));
assert!(output.output_text.contains("tokens truncated"));
}
#[tokio::test]
async fn finishing_turn_consumes_handoff() {
let (tx, _rx) = bounded(1);
+4 -2
View File
@@ -311,8 +311,10 @@ impl Session {
) {
let auth = self.services.auth_manager.auth().await;
let config = self.get_config().await;
let mcp_config = config
.to_mcp_config(self.services.plugins_manager.as_ref())
let mcp_config = self
.services
.mcp_manager
.runtime_config(config.as_ref())
.await;
let tool_plugin_provenance = self
.services
+4
View File
@@ -51,6 +51,7 @@ use codex_config::types::OAuthCredentialsStoreMode;
use codex_exec_server::Environment;
use codex_exec_server::EnvironmentManager;
use codex_exec_server::FileSystemSandboxContext;
use codex_extension_api::ExtensionDataInit;
use codex_extension_api::PromptSlot;
use codex_features::FEATURES;
use codex_features::Feature;
@@ -416,6 +417,7 @@ pub(crate) struct CodexSpawnArgs {
pub(crate) user_shell_override: Option<shell::Shell>,
pub(crate) parent_trace: Option<W3cTraceContext>,
pub(crate) environment_selections: ResolvedTurnEnvironments,
pub(crate) thread_extension_init: ExtensionDataInit,
pub(crate) analytics_events_client: Option<AnalyticsEventsClient>,
pub(crate) thread_store: Arc<dyn ThreadStore>,
pub(crate) attestation_provider: Option<Arc<dyn AttestationProvider>>,
@@ -496,6 +498,7 @@ impl Codex {
parent_rollout_thread_trace,
parent_trace: _,
environment_selections,
thread_extension_init,
analytics_events_client,
thread_store,
attestation_provider,
@@ -640,6 +643,7 @@ impl Codex {
plugins_manager,
mcp_manager.clone(),
extensions,
thread_extension_init,
agent_control,
environment_manager,
analytics_events_client,
+2 -2
View File
@@ -91,7 +91,7 @@ pub(super) async fn spawn_review_thread(
forked_from_thread_id,
parent_turn_context.parent_thread_id,
&session_source,
parent_turn_context.thread_source,
parent_turn_context.thread_source.clone(),
review_turn_id.clone(),
#[allow(deprecated)]
parent_turn_context.cwd.clone(),
@@ -121,7 +121,7 @@ pub(super) async fn spawn_review_thread(
reasoning_summary,
session_source,
parent_thread_id: parent_turn_context.parent_thread_id,
thread_source: parent_turn_context.thread_source,
thread_source: parent_turn_context.thread_source.clone(),
environments: parent_turn_context.environments.clone(),
available_models,
unified_exec_shell_mode,
+9 -5
View File
@@ -4,6 +4,7 @@ use crate::agents_md::LoadedAgentsMd;
use crate::config::ConstraintError;
use crate::skills::SkillError;
use crate::state::ActiveTurn;
use codex_extension_api::ExtensionDataInit;
use codex_protocol::SessionId;
use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE;
use codex_protocol::config_types::ServiceTier;
@@ -192,7 +193,7 @@ impl SessionConfiguration {
session_source: self.session_source.clone(),
forked_from_thread_id: self.forked_from_thread_id,
parent_thread_id: self.parent_thread_id,
thread_source: self.thread_source,
thread_source: self.thread_source.clone(),
}
}
@@ -487,6 +488,7 @@ impl Session {
plugins_manager: Arc<PluginsManager>,
mcp_manager: Arc<McpManager>,
extensions: Arc<codex_extension_api::ExtensionRegistry<crate::config::Config>>,
thread_extension_init: ExtensionDataInit,
agent_control: AgentControl,
environment_manager: Arc<EnvironmentManager>,
analytics_events_client: Option<AnalyticsEventsClient>,
@@ -547,7 +549,7 @@ impl Session {
forked_from_id,
parent_thread_id,
source: session_source,
thread_source: session_configuration.thread_source,
thread_source: session_configuration.thread_source.clone(),
base_instructions: BaseInstructions {
text: session_configuration.base_instructions.clone(),
},
@@ -961,8 +963,10 @@ impl Session {
);
let session_extension_data =
codex_extension_api::ExtensionData::new(session_id.to_string());
let thread_extension_data =
codex_extension_api::ExtensionData::new(thread_id.to_string());
let thread_extension_data = codex_extension_api::ExtensionData::new_with_init(
thread_id.to_string(),
thread_extension_init,
);
for contributor in extensions.thread_lifecycle_contributors() {
contributor.on_thread_start(codex_extension_api::ThreadStartInput {
config: config.as_ref(),
@@ -1085,7 +1089,7 @@ impl Session {
thread_id,
forked_from_id,
parent_thread_id,
thread_source: session_configuration.thread_source,
thread_source: session_configuration.thread_source.clone(),
thread_name: session_configuration.thread_name.clone(),
model: session_configuration.collaboration_mode.model().to_string(),
model_provider_id: config.model_provider_id.clone(),
+3
View File
@@ -4690,6 +4690,7 @@ async fn session_new_fails_when_zsh_fork_enabled_without_packaged_zsh() {
plugins_manager,
mcp_manager,
Arc::new(codex_extension_api::ExtensionRegistryBuilder::new().build()),
codex_extension_api::ExtensionDataInit::default(),
AgentControl::default(),
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
/*analytics_events_client*/ None,
@@ -5030,6 +5031,7 @@ async fn make_session_with_config_and_rx(
plugins_manager,
mcp_manager,
Arc::new(codex_extension_api::ExtensionRegistryBuilder::new().build()),
codex_extension_api::ExtensionDataInit::default(),
AgentControl::default(),
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
/*analytics_events_client*/ None,
@@ -5131,6 +5133,7 @@ async fn make_session_with_history_source_and_agent_control_and_rx(
plugins_manager,
mcp_manager,
Arc::new(codex_extension_api::ExtensionRegistryBuilder::new().build()),
codex_extension_api::ExtensionDataInit::default(),
agent_control,
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
/*analytics_events_client*/ None,
@@ -731,6 +731,7 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() {
environment_selections: ResolvedTurnEnvironments {
turn_environments: Vec::new(),
},
thread_extension_init: codex_extension_api::ExtensionDataInit::default(),
analytics_events_client: None,
thread_store,
attestation_provider: None,
+3 -3
View File
@@ -239,7 +239,7 @@ impl TurnContext {
reasoning_summary: self.reasoning_summary,
session_source: self.session_source.clone(),
parent_thread_id: self.parent_thread_id,
thread_source: self.thread_source,
thread_source: self.thread_source.clone(),
environments: self.environments.clone(),
#[allow(deprecated)]
cwd: self.cwd.clone(),
@@ -514,7 +514,7 @@ impl Session {
session_configuration.forked_from_thread_id,
session_configuration.parent_thread_id,
&session_configuration.session_source,
session_configuration.thread_source,
session_configuration.thread_source.clone(),
sub_id.clone(),
cwd.clone(),
&session_configuration.permission_profile(),
@@ -538,7 +538,7 @@ impl Session {
reasoning_summary,
session_source,
parent_thread_id: session_configuration.parent_thread_id,
thread_source: session_configuration.thread_source,
thread_source: session_configuration.thread_source.clone(),
environments,
#[allow(deprecated)]
cwd,
+19 -1
View File
@@ -21,6 +21,7 @@ use codex_app_server_protocol::ThreadHistoryBuilder;
use codex_app_server_protocol::TurnStatus;
use codex_core_plugins::PluginsManager;
use codex_exec_server::EnvironmentManager;
use codex_extension_api::ExtensionDataInit;
use codex_extension_api::ExtensionRegistry;
use codex_extension_api::empty_extension_registry;
use codex_features::Feature;
@@ -182,6 +183,7 @@ pub struct StartThreadOptions {
pub metrics_service_name: Option<String>,
pub parent_trace: Option<W3cTraceContext>,
pub environments: Vec<TurnEnvironmentSelection>,
pub thread_extension_init: ExtensionDataInit,
}
pub(crate) struct ResumeThreadWithHistoryOptions {
@@ -270,7 +272,10 @@ impl ThreadManager {
codex_home.to_path_buf(),
restriction_product,
));
let mcp_manager = Arc::new(McpManager::new(Arc::clone(&plugins_manager)));
let mcp_manager = Arc::new(McpManager::new_with_extensions(
Arc::clone(&plugins_manager),
Arc::clone(&extensions),
));
let skills_manager = Arc::new(SkillsManager::new_with_restriction_product(
codex_home,
config.bundled_skills_enabled(),
@@ -576,6 +581,7 @@ impl ThreadManager {
metrics_service_name: None,
parent_trace: None,
environments,
thread_extension_init: ExtensionDataInit::default(),
}))
.await
}
@@ -614,6 +620,7 @@ impl ThreadManager {
/*inherited_exec_policy*/ None,
options.parent_trace,
options.environments,
options.thread_extension_init,
/*user_shell_override*/ None,
))
.await
@@ -702,6 +709,7 @@ impl ThreadManager {
/*inherited_exec_policy*/ None,
parent_trace,
environments,
/*thread_extension_init*/ ExtensionDataInit::default(),
/*user_shell_override*/ None,
))
.await
@@ -728,6 +736,7 @@ impl ThreadManager {
/*metrics_service_name*/ None,
/*parent_trace*/ None,
environments,
/*thread_extension_init*/ ExtensionDataInit::default(),
/*user_shell_override*/ Some(user_shell_override),
))
.await
@@ -763,6 +772,7 @@ impl ThreadManager {
/*inherited_exec_policy*/ None,
/*parent_trace*/ None,
environments,
/*thread_extension_init*/ ExtensionDataInit::default(),
/*user_shell_override*/ Some(user_shell_override),
))
.await
@@ -931,6 +941,7 @@ impl ThreadManager {
/*metrics_service_name*/ None,
parent_trace,
environments,
/*thread_extension_init*/ ExtensionDataInit::default(),
/*user_shell_override*/ None,
))
.await
@@ -1136,6 +1147,7 @@ impl ThreadManagerState {
inherited_exec_policy,
/*parent_trace*/ None,
environments,
/*thread_extension_init*/ ExtensionDataInit::default(),
/*user_shell_override*/ None,
))
.await
@@ -1172,6 +1184,7 @@ impl ThreadManagerState {
inherited_exec_policy,
/*parent_trace*/ None,
environments,
/*thread_extension_init*/ ExtensionDataInit::default(),
/*user_shell_override*/ None,
))
.await
@@ -1209,6 +1222,7 @@ impl ThreadManagerState {
inherited_exec_policy,
/*parent_trace*/ None,
environments,
/*thread_extension_init*/ ExtensionDataInit::default(),
/*user_shell_override*/ None,
))
.await
@@ -1229,6 +1243,7 @@ impl ThreadManagerState {
metrics_service_name: Option<String>,
parent_trace: Option<W3cTraceContext>,
environments: Vec<TurnEnvironmentSelection>,
thread_extension_init: ExtensionDataInit,
user_shell_override: Option<crate::shell::Shell>,
) -> CodexResult<NewThread> {
Box::pin(self.spawn_thread_with_source(
@@ -1246,6 +1261,7 @@ impl ThreadManagerState {
/*inherited_exec_policy*/ None,
parent_trace,
environments,
thread_extension_init,
user_shell_override,
))
.await
@@ -1268,6 +1284,7 @@ impl ThreadManagerState {
inherited_exec_policy: Option<Arc<crate::exec_policy::ExecPolicyManager>>,
parent_trace: Option<W3cTraceContext>,
environments: Vec<TurnEnvironmentSelection>,
thread_extension_init: ExtensionDataInit,
user_shell_override: Option<crate::shell::Shell>,
) -> CodexResult<NewThread> {
let is_resumed_thread = matches!(&initial_history, InitialHistory::Resumed(_));
@@ -1332,6 +1349,7 @@ impl ThreadManagerState {
user_shell_override,
parent_trace,
environment_selections,
thread_extension_init,
analytics_events_client: self.analytics_events_client.clone(),
thread_store: Arc::clone(&self.thread_store),
attestation_provider: self.attestation_provider.clone(),
+79
View File
@@ -331,6 +331,7 @@ async fn start_thread_rejects_explicit_local_environment_when_default_provider_i
environment_id: "local".to_string(),
cwd: config.cwd.clone(),
}],
thread_extension_init: Default::default(),
})
.await;
let err = match result {
@@ -368,6 +369,7 @@ async fn start_thread_keeps_internal_threads_hidden_from_normal_lookups() {
metrics_service_name: None,
parent_trace: None,
environments: Vec::new(),
thread_extension_init: Default::default(),
})
.await
.expect("internal thread should start");
@@ -384,6 +386,81 @@ async fn start_thread_keeps_internal_threads_hidden_from_normal_lookups() {
assert!(manager.list_thread_ids().await.is_empty());
}
#[tokio::test]
async fn start_thread_seeds_extension_data_before_lifecycle_contributors_run() {
struct InitialMarker(&'static str);
struct InitialDataRecorder {
observed: Arc<std::sync::Mutex<Option<(String, String)>>>,
}
#[async_trait::async_trait]
impl codex_extension_api::ThreadLifecycleContributor<Config> for InitialDataRecorder {
async fn on_thread_start(&self, input: codex_extension_api::ThreadStartInput<'_, Config>) {
let marker = input
.thread_store
.get::<InitialMarker>()
.expect("initial extension data should be available");
*self
.observed
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some((
input.thread_store.level_id().to_string(),
marker.0.to_string(),
));
}
}
let temp_dir = tempdir().expect("tempdir");
let mut config = test_config().await;
config.codex_home = temp_dir.path().join("codex-home").abs();
config.cwd = config.codex_home.abs();
std::fs::create_dir_all(&config.codex_home).expect("create codex home");
let observed = Arc::new(std::sync::Mutex::new(None));
let mut extensions = codex_extension_api::ExtensionRegistryBuilder::new();
extensions.thread_lifecycle_contributor(Arc::new(InitialDataRecorder {
observed: Arc::clone(&observed),
}));
let manager = ThreadManager::new(
&config,
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()),
SessionSource::Exec,
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
Arc::new(extensions.build()),
/*analytics_events_client*/ None,
thread_store_from_config(&config, /*state_db*/ None),
/*state_db*/ None,
TEST_INSTALLATION_ID.to_string(),
/*attestation_provider*/ None,
);
let mut thread_extension_init = codex_extension_api::ExtensionDataInit::new();
thread_extension_init.insert(InitialMarker("seeded"));
let thread = manager
.start_thread_with_options(StartThreadOptions {
config,
initial_history: InitialHistory::New,
session_source: None,
thread_source: None,
dynamic_tools: Vec::new(),
metrics_service_name: None,
parent_trace: None,
environments: Vec::new(),
thread_extension_init,
})
.await
.expect("start thread");
assert_eq!(
observed
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone(),
Some((thread.thread_id.to_string(), "seeded".to_string()))
);
}
#[tokio::test]
async fn resume_and_fork_do_not_restore_thread_environments_from_rollout() {
let temp_dir = tempdir().expect("tempdir");
@@ -423,6 +500,7 @@ async fn resume_and_fork_do_not_restore_thread_environments_from_rollout() {
metrics_service_name: None,
parent_trace: None,
environments: environments.clone(),
thread_extension_init: Default::default(),
})
.await
.expect("start source thread");
@@ -693,6 +771,7 @@ async fn resume_stopped_thread_from_rollout_preserves_thread_source() {
metrics_service_name: None,
parent_trace: None,
environments: Vec::new(),
thread_extension_init: Default::default(),
})
.await
.expect("start source thread");
@@ -14,15 +14,11 @@ use crate::tools::registry::ToolExecutor;
use codex_protocol::AgentPath;
use codex_protocol::models::ResponseInputItem;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::CollabAgentInteractionBeginEvent;
use codex_protocol::protocol::CollabAgentInteractionEndEvent;
use codex_protocol::protocol::CollabAgentSpawnBeginEvent;
use codex_protocol::protocol::CollabAgentSpawnEndEvent;
use codex_protocol::protocol::CollabCloseBeginEvent;
use codex_protocol::protocol::CollabCloseEndEvent;
use codex_protocol::protocol::CollabWaitingBeginEvent;
use codex_protocol::protocol::CollabWaitingEndEvent;
use codex_protocol::protocol::InterAgentCommunication;
use codex_protocol::protocol::SubAgentActivityEvent;
use codex_protocol::protocol::SubAgentActivityKind;
use codex_protocol::user_input::UserInput;
use codex_tools::ToolName;
use serde::Deserialize;
@@ -59,18 +59,9 @@ async fn handle_interrupt_agent(
.to_string(),
));
}
session
.send_event(
&turn,
CollabCloseBeginEvent {
call_id: call_id.clone(),
started_at_ms: now_unix_timestamp_ms(),
sender_thread_id: session.thread_id,
receiver_thread_id: agent_id,
}
.into(),
)
.await;
let receiver_agent_path = receiver_agent.agent_path.clone().ok_or_else(|| {
FunctionCallError::RespondToModel("target agent is missing an agent_path".to_string())
})?;
let status = session.services.agent_control.get_status(agent_id).await;
let result = match session
.services
@@ -81,22 +72,20 @@ async fn handle_interrupt_agent(
Ok(_) | Err(CodexErr::ThreadNotFound(_)) | Err(CodexErr::InternalAgentDied) => Ok(()),
Err(err) => Err(collab_agent_error(agent_id, err)),
};
result?;
session
.send_event(
&turn,
CollabCloseEndEvent {
call_id,
completed_at_ms: now_unix_timestamp_ms(),
sender_thread_id: session.thread_id,
receiver_thread_id: agent_id,
receiver_agent_nickname: receiver_agent.agent_nickname,
receiver_agent_role: receiver_agent.agent_role,
status: status.clone(),
SubAgentActivityEvent {
event_id: call_id,
occurred_at_ms: now_unix_timestamp_ms(),
agent_thread_id: agent_id,
agent_path: receiver_agent_path,
kind: SubAgentActivityKind::Interrupted,
}
.into(),
)
.await;
result?;
Ok(InterruptAgentResult {
previous_status: status,
@@ -69,7 +69,6 @@ pub(crate) async fn handle_message_string_tool(
call_id,
..
} = invocation;
let prompt = String::new();
let receiver_thread_id = resolve_agent_target(&session, &turn, &target).await?;
let receiver_agent = session
.services
@@ -96,52 +95,32 @@ pub(crate) async fn handle_message_string_tool(
.ensure_v2_agent_loaded(resume_config, receiver_thread_id)
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err))?;
session
.send_event(
&turn,
CollabAgentInteractionBeginEvent {
call_id: call_id.clone(),
started_at_ms: now_unix_timestamp_ms(),
sender_thread_id: session.thread_id,
receiver_thread_id,
prompt: prompt.clone(),
}
.into(),
)
.await;
let author = turn
.session_source
.get_agent_path()
.unwrap_or_else(AgentPath::root);
let communication = communication_from_tool_message(author, receiver_agent_path, message);
let communication =
communication_from_tool_message(author, receiver_agent_path.clone(), message);
let result = session
.services
.agent_control
.send_inter_agent_communication(receiver_thread_id, mode.apply(communication))
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err));
let status = session
.services
.agent_control
.get_status(receiver_thread_id)
.await;
result?;
session
.send_event(
&turn,
CollabAgentInteractionEndEvent {
call_id,
completed_at_ms: now_unix_timestamp_ms(),
sender_thread_id: session.thread_id,
receiver_thread_id,
receiver_agent_nickname: receiver_agent.agent_nickname,
receiver_agent_role: receiver_agent.agent_role,
prompt,
status,
SubAgentActivityEvent {
event_id: call_id,
occurred_at_ms: now_unix_timestamp_ms(),
agent_thread_id: receiver_thread_id,
agent_path: receiver_agent_path,
kind: SubAgentActivityKind::Interacted,
}
.into(),
)
.await;
result?;
Ok(FunctionToolOutput::from_text(String::new(), Some(true)))
}
@@ -61,24 +61,8 @@ async fn handle_spawn_agent(
let message = args.message.clone();
let initial_operation = parse_collab_input(Some(args.message), /*items*/ None)?;
let prompt = String::new();
let session_source = turn.session_source.clone();
let child_depth = next_thread_spawn_depth(&session_source);
session
.send_event(
&turn,
CollabAgentSpawnBeginEvent {
call_id: call_id.clone(),
started_at_ms: now_unix_timestamp_ms(),
sender_thread_id: session.thread_id,
prompt: prompt.clone(),
model: args.model.clone().unwrap_or_default(),
reasoning_effort: args.reasoning_effort.clone().unwrap_or_default(),
}
.into(),
)
.await;
let mut config =
build_agent_spawn_config(&session.get_base_instructions().await, turn.as_ref())?;
if let Some(service_tier) = args.service_tier.as_ref() {
@@ -119,11 +103,16 @@ async fn handle_spawn_agent(
role_name,
Some(args.task_name.clone()),
)?;
let result = Box::pin(
let new_agent_path = spawn_source.get_agent_path().ok_or_else(|| {
FunctionCallError::RespondToModel(
"spawned agent is missing a canonical task name".to_string(),
)
})?;
let spawned_agent = Box::pin(
session.services.agent_control.spawn_agent_with_metadata(
config,
match (spawn_source.get_agent_path(), initial_operation) {
(Some(recipient), Op::UserInput { items, .. })
match initial_operation {
Op::UserInput { items, .. }
if items
.iter()
.all(|item| matches!(item, UserInput::Text { .. })) =>
@@ -132,10 +121,11 @@ async fn handle_spawn_agent(
.session_source
.get_agent_path()
.unwrap_or_else(AgentPath::root);
let communication = communication_from_tool_message(author, recipient, message);
let communication =
communication_from_tool_message(author, new_agent_path.clone(), message);
Op::InterAgentCommunication { communication }
}
(_, initial_operation) => initial_operation,
initial_operation => initial_operation,
},
Some(spawn_source),
SpawnAgentOptions {
@@ -147,78 +137,37 @@ async fn handle_spawn_agent(
),
)
.await
.map_err(collab_spawn_error);
let (new_thread_id, new_agent_metadata, status) = match &result {
Ok(spawned_agent) => (
Some(spawned_agent.thread_id),
Some(spawned_agent.metadata.clone()),
spawned_agent.status.clone(),
),
Err(_) => (None, None, AgentStatus::NotFound),
};
let agent_snapshot = match new_thread_id {
Some(thread_id) => {
session
.services
.agent_control
.get_agent_config_snapshot(thread_id)
.await
}
None => None,
};
let (new_agent_path, new_agent_nickname, new_agent_role) =
match (&agent_snapshot, new_agent_metadata) {
(Some(snapshot), _) => (
snapshot.session_source.get_agent_path().map(String::from),
snapshot.session_source.get_nickname(),
snapshot.session_source.get_agent_role(),
),
(None, Some(metadata)) => (
metadata.agent_path.map(String::from),
metadata.agent_nickname,
metadata.agent_role,
),
(None, None) => (None, None, None),
};
let effective_model = agent_snapshot
.map_err(collab_spawn_error)?;
let new_thread_id = spawned_agent.thread_id;
let agent_snapshot = session
.services
.agent_control
.get_agent_config_snapshot(new_thread_id)
.await;
let nickname = agent_snapshot
.as_ref()
.map(|snapshot| snapshot.model.clone())
.unwrap_or_else(|| args.model.clone().unwrap_or_default());
let effective_reasoning_effort = agent_snapshot
.as_ref()
.and_then(|snapshot| snapshot.reasoning_effort.clone())
.unwrap_or(args.reasoning_effort.unwrap_or_default());
let nickname = new_agent_nickname.clone();
.and_then(|snapshot| snapshot.session_source.get_nickname())
.or(spawned_agent.metadata.agent_nickname);
session
.send_event(
&turn,
CollabAgentSpawnEndEvent {
call_id,
completed_at_ms: now_unix_timestamp_ms(),
sender_thread_id: session.thread_id,
new_thread_id,
new_agent_nickname,
new_agent_role,
prompt,
model: effective_model,
reasoning_effort: effective_reasoning_effort,
status,
SubAgentActivityEvent {
event_id: call_id,
occurred_at_ms: now_unix_timestamp_ms(),
agent_thread_id: new_thread_id,
agent_path: new_agent_path.clone(),
kind: SubAgentActivityKind::Started,
}
.into(),
)
.await;
let _ = result?;
let role_tag = role_name.unwrap_or(DEFAULT_ROLE_NAME);
turn.session_telemetry.counter(
"codex.multi_agent.spawn",
/*inc*/ 1,
&[("role", role_tag)],
);
let task_name = new_agent_path.ok_or_else(|| {
FunctionCallError::RespondToModel(
"spawned agent is missing a canonical task name".to_string(),
)
})?;
let task_name = String::from(new_agent_path);
let hide_agent_metadata = turn.config.multi_agent_v2.hide_spawn_agent_metadata;
if hide_agent_metadata {
+6
View File
@@ -86,6 +86,7 @@ use codex_tools::shell_type_for_model_and_features;
use std::collections::BTreeMap;
use std::collections::HashSet;
use std::sync::Arc;
use tracing::instrument;
use tracing::warn;
const MULTI_AGENT_V2_NAMESPACE_DESCRIPTION: &str = "Tools for spawning and managing sub-agents.";
@@ -148,6 +149,7 @@ struct CoreToolPlanContext<'a> {
wait_agent_timeouts: WaitAgentTimeoutOptions,
}
#[instrument(level = "trace", skip_all)]
pub(crate) fn build_tool_router(
turn_context: &TurnContext,
params: ToolRouterParams<'_>,
@@ -156,6 +158,7 @@ pub(crate) fn build_tool_router(
ToolRouter::from_parts(registry, model_visible_specs)
}
#[instrument(level = "trace", skip_all)]
fn build_tool_specs_and_registry(
turn_context: &TurnContext,
params: ToolRouterParams<'_>,
@@ -186,6 +189,7 @@ fn build_tool_specs_and_registry(
build_model_visible_specs_and_registry(turn_context, planned_tools)
}
#[instrument(level = "trace", skip_all)]
fn build_model_visible_specs_and_registry(
turn_context: &TurnContext,
planned_tools: PlannedTools,
@@ -557,6 +561,7 @@ fn code_mode_namespace_descriptions(
namespace_descriptions
}
#[instrument(level = "trace", skip_all)]
fn add_tool_sources(context: &CoreToolPlanContext<'_>, planned_tools: &mut PlannedTools) {
add_shell_tools(context, planned_tools);
add_mcp_resource_tools(context, planned_tools);
@@ -837,6 +842,7 @@ fn add_extension_tools(context: &CoreToolPlanContext<'_>, planned_tools: &mut Pl
);
}
#[instrument(level = "trace", skip_all)]
fn append_tool_search_executor(
context: &CoreToolPlanContext<'_>,
planned_tools: &mut PlannedTools,
+14 -1
View File
@@ -14,6 +14,7 @@ use tokio_util::sync::CancellationToken;
use crate::exec::is_likely_sandbox_denied;
use codex_exec_server::ExecProcess;
use codex_exec_server::ProcessSignal as ExecServerProcessSignal;
use codex_exec_server::ReadResponse as ExecReadResponse;
use codex_exec_server::StartedExecProcess;
use codex_exec_server::WriteStatus;
@@ -23,6 +24,7 @@ use codex_protocol::protocol::TruncationPolicy;
use codex_sandboxing::SandboxType;
use codex_utils_output_truncation::formatted_truncate_text;
use codex_utils_pty::ExecCommandSession;
use codex_utils_pty::ProcessSignal as PtyProcessSignal;
use codex_utils_pty::SpawnedPty;
use super::UNIFIED_EXEC_OUTPUT_MAX_TOKENS;
@@ -31,7 +33,6 @@ use super::head_tail_buffer::HeadTailBuffer;
use super::process_state::ProcessState;
const EARLY_EXIT_GRACE_PERIOD: Duration = Duration::from_millis(150);
pub(crate) trait SpawnLifecycle: std::fmt::Debug + Send + Sync {
/// Returns file descriptors that must stay open across the child `exec()`.
///
@@ -212,6 +213,18 @@ impl UnifiedExecProcess {
}
}
pub(super) async fn interrupt(&self) -> Result<(), UnifiedExecError> {
match &self.process_handle {
ProcessHandle::Local(process_handle) => process_handle
.signal(PtyProcessSignal::Interrupt)
.map_err(|err| UnifiedExecError::process_failed(err.to_string())),
ProcessHandle::ExecServer(process_handle) => process_handle
.signal(ExecServerProcessSignal::Interrupt)
.await
.map_err(|err| UnifiedExecError::process_failed(err.to_string())),
}
}
pub(super) fn fail_and_terminate(&self, message: String) {
let state = self.state_rx.borrow().clone();
if state.failure_message.is_none() {
@@ -72,6 +72,7 @@ const UNIFIED_EXEC_ENV: [(&str, &str); 10] = [
const NETWORK_ACCESS_DENIED_MESSAGE: &str =
"Network access was denied by the Codex sandbox network proxy.";
const LATE_NETWORK_DENIAL_GRACE_PERIOD: Duration = Duration::from_millis(100);
const INTERRUPT: &str = "\u{3}";
/// Test-only override for deterministic unified exec process IDs.
///
@@ -617,24 +618,29 @@ impl UnifiedExecProcessManager {
if !request.input.is_empty() {
if !tty {
return Err(UnifiedExecError::StdinClosed);
}
match process.write(request.input.as_bytes()).await {
Ok(()) => {
// Give the remote process a brief window to react so that we are
// more likely to capture its output in the poll below.
tokio::time::sleep(Duration::from_millis(100)).await;
if request.input == INTERRUPT {
process.interrupt().await?;
} else {
return Err(UnifiedExecError::StdinClosed);
}
Err(err) => {
let status = self.refresh_process_state(process_id).await;
if matches!(status, ProcessStatus::Exited { .. }) {
status_after_write = Some(status);
} else if matches!(err, UnifiedExecError::ProcessFailed { .. }) {
process.terminate();
self.release_process_id(process_id).await;
return Err(err);
} else {
return Err(err);
} else {
match process.write(request.input.as_bytes()).await {
Ok(()) => {
// Give the remote process a brief window to react so that we are
// more likely to capture its output in the poll below.
tokio::time::sleep(Duration::from_millis(100)).await;
}
Err(err) => {
let status = self.refresh_process_state(process_id).await;
if matches!(status, ProcessStatus::Exited { .. }) {
status_after_write = Some(status);
} else if matches!(err, UnifiedExecError::ProcessFailed { .. }) {
process.terminate();
self.release_process_id(process_id).await;
return Err(err);
} else {
return Err(err);
}
}
}
}
@@ -5,6 +5,7 @@ use codex_exec_server::ExecProcess;
use codex_exec_server::ExecProcessEventReceiver;
use codex_exec_server::ExecServerError;
use codex_exec_server::ProcessId;
use codex_exec_server::ProcessSignal;
use codex_exec_server::ReadResponse;
use codex_exec_server::StartedExecProcess;
use codex_exec_server::WriteResponse;
@@ -63,6 +64,10 @@ impl ExecProcess for MockExecProcess {
Ok(self.write_response.clone())
}
async fn signal(&self, _signal: ProcessSignal) -> Result<(), ExecServerError> {
Ok(())
}
async fn terminate(&self) -> Result<(), ExecServerError> {
Ok(())
}
+601 -1
View File
@@ -1,18 +1,46 @@
use anyhow::Result;
use anyhow::anyhow;
use codex_core::ForkSnapshot;
use codex_exec_server::CreateDirectoryOptions;
use codex_features::Feature;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
use codex_protocol::user_input::UserInput;
use codex_utils_absolute_path::AbsolutePathBuf;
use core_test_support::PathBufExt;
use core_test_support::create_directory_symlink;
use core_test_support::load_default_config_for_test;
use core_test_support::responses;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_response_created;
use core_test_support::responses::mount_sse_once;
use core_test_support::responses::sse;
use core_test_support::responses::start_mock_server;
use core_test_support::skip_if_no_network;
use core_test_support::test_codex::TestCodexBuilder;
use core_test_support::test_codex::test_codex;
use core_test_support::wait_for_event;
use core_test_support::wait_for_event_match;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::sync::Arc;
use std::time::Duration;
use tempfile::TempDir;
const GLOBAL_AGENTS_FILENAME: &str = "AGENTS.md";
const GLOBAL_AGENTS_OVERRIDE_FILENAME: &str = "AGENTS.override.md";
const GLOBAL_INSTRUCTIONS: &str = "global instructions";
const NEW_GLOBAL_INSTRUCTIONS: &str = "new global instructions";
const NEW_PROJECT_INSTRUCTIONS: &str = "new project instructions";
const OLD_GLOBAL_INSTRUCTIONS: &str = "old global instructions";
const PROJECT_INSTRUCTIONS: &str = "project instructions";
const PROJECT_SEPARATOR: &str = "--- project-doc ---";
const SPAWN_CALL_ID: &str = "spawn-global-instructions-child";
const SPAWN_CHILD_PROMPT: &str = "inspect inherited global instructions";
const SPAWN_FRESH_PARENT_PROMPT: &str = "spawn a child with fresh context";
const SPAWN_PARENT_PROMPT: &str = "spawn a child with the parent context";
const SPAWN_SEED_PROMPT: &str = "seed parent history";
async fn agents_instructions(mut builder: TestCodexBuilder) -> Result<String> {
let server = start_mock_server().await;
let resp_mock = mount_sse_once(
@@ -32,6 +60,52 @@ async fn agents_instructions(mut builder: TestCodexBuilder) -> Result<String> {
.ok_or_else(|| anyhow::anyhow!("instructions message not found"))
}
fn write_global_file(
home: &TempDir,
filename: &str,
contents: impl AsRef<[u8]>,
) -> Result<AbsolutePathBuf> {
let path = home.path().join(filename);
std::fs::write(&path, contents)?;
Ok(path.abs())
}
fn instruction_fragments(request: &responses::ResponsesRequest) -> Vec<String> {
request
.message_input_texts("user")
.into_iter()
.filter(|text| text.starts_with("# AGENTS.md instructions for "))
.collect()
}
fn expected_instruction_fragment(cwd: &AbsolutePathBuf, contents: &str) -> String {
let cwd = cwd.as_path().display();
format!("# AGENTS.md instructions for {cwd}\n\n<INSTRUCTIONS>\n{contents}\n</INSTRUCTIONS>")
}
fn assert_single_instruction_fragment(request: &responses::ResponsesRequest, expected: &str) {
assert_eq!(instruction_fragments(request), vec![expected.to_string()]);
}
fn request_body_contains(request: &wiremock::Request, text: &str) -> bool {
let is_zstd = request
.headers
.get("content-encoding")
.and_then(|value| value.to_str().ok())
.is_some_and(|value| {
value
.split(',')
.any(|entry| entry.trim().eq_ignore_ascii_case("zstd"))
});
let body = if is_zstd {
zstd::stream::decode_all(std::io::Cursor::new(&request.body)).ok()
} else {
Some(request.body.clone())
};
body.and_then(|body| String::from_utf8(body).ok())
.is_some_and(|body| body.contains(text))
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn agents_override_is_preferred_over_agents_md() -> Result<()> {
let instructions =
@@ -250,7 +324,7 @@ async fn selected_environment_sources_match_model_visible_instructions() -> Resu
});
let test = builder.build_with_remote_env(&server).await?;
let project_agents = test.config.cwd.join("AGENTS.md");
let global_agents = AbsolutePathBuf::try_from(global_agents).expect("absolute path");
let global_agents = global_agents.abs();
assert_eq!(
test.codex.instruction_sources().await,
@@ -268,3 +342,529 @@ async fn selected_environment_sources_match_model_visible_instructions() -> Resu
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn fresh_thread_composes_global_before_project_and_reports_sources() -> Result<()> {
// Set up one global source, one project source, and two ordinary model turns.
let server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_response_created("response-1"),
responses::ev_completed("response-1"),
]),
responses::sse(vec![
responses::ev_response_created("response-2"),
responses::ev_completed("response-2"),
]),
],
)
.await;
let home = Arc::new(TempDir::new()?);
let global_source =
write_global_file(home.as_ref(), GLOBAL_AGENTS_FILENAME, GLOBAL_INSTRUCTIONS)?;
let mut builder = test_codex()
.with_home(Arc::clone(&home))
.with_workspace_setup(|cwd, fs| async move {
fs.write_file(
&cwd.join("AGENTS.md"),
PROJECT_INSTRUCTIONS.as_bytes().to_vec(),
/*sandbox*/ None,
)
.await?;
Ok(())
});
let test = builder.build_with_remote_env(&server).await?;
let project_source = test.config.cwd.join(GLOBAL_AGENTS_FILENAME);
let creation_sources = vec![global_source.clone(), project_source.clone()];
// Confirm the thread records both creation-time sources in composition order.
assert_eq!(test.codex.instruction_sources().await, creation_sources);
// Materialize the initial snapshot, then rewrite both selected files in place before another
// ordinary turn.
test.submit_turn("first turn").await?;
let rewritten_global_source = write_global_file(
home.as_ref(),
GLOBAL_AGENTS_FILENAME,
NEW_GLOBAL_INSTRUCTIONS,
)?;
test.fs()
.write_file(
&project_source,
NEW_PROJECT_INSTRUCTIONS.as_bytes().to_vec(),
/*sandbox*/ None,
)
.await?;
assert_eq!(
rewritten_global_source, global_source,
"same-path mutation should retain the selected global source path"
);
test.submit_turn("second turn").await?;
// Assert the running thread keeps its original rendering and structured prefix even though
// both files at the reported source paths now contain different text.
let requests = response_mock.requests();
assert_eq!(requests.len(), 2);
let expected_contents =
format!("{GLOBAL_INSTRUCTIONS}\n\n{PROJECT_SEPARATOR}\n\n{PROJECT_INSTRUCTIONS}");
let expected_fragment = expected_instruction_fragment(&test.config.cwd, &expected_contents);
let fragments = instruction_fragments(&requests[0]);
assert_eq!(fragments, vec![expected_fragment.clone()]);
assert_single_instruction_fragment(&requests[1], &expected_fragment);
let rendered = fragments
.into_iter()
.next()
.ok_or_else(|| anyhow!("expected one rendered instruction fragment"))?;
let global_position = rendered.find(GLOBAL_INSTRUCTIONS).ok_or_else(|| {
anyhow!(
"expected rendered instructions to contain {GLOBAL_INSTRUCTIONS:?}; observed: {rendered}"
)
})?;
let project_position = rendered.find(PROJECT_INSTRUCTIONS).ok_or_else(|| {
anyhow!(
"expected rendered instructions to contain {PROJECT_INSTRUCTIONS:?}; observed: {rendered}"
)
})?;
assert!(
global_position < project_position,
"global instructions should precede project instructions: {rendered}"
);
assert!(
rendered.contains(PROJECT_SEPARATOR),
"expected rendered instructions to contain {PROJECT_SEPARATOR:?}; observed: {rendered}"
);
assert_eq!(
test.codex.instruction_sources().await,
creation_sources,
"ordinary turns retain the creation-time source list"
);
let first_input = requests[0].input();
let second_input = requests[1].input();
assert_eq!(
second_input.get(..first_input.len()),
Some(first_input.as_slice()),
"the ordinary second turn should retain the cached prefix"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn global_loading_warning_surfaces_during_thread_creation() -> Result<()> {
// Set up a malformed global instruction file and one model response.
let server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_once(
&server,
responses::sse(vec![
responses::ev_response_created("warning-response"),
responses::ev_completed("warning-response"),
]),
)
.await;
let home = Arc::new(TempDir::new()?);
let source = write_global_file(
home.as_ref(),
GLOBAL_AGENTS_FILENAME,
b"global\xFFinstructions",
)?;
// Create the thread, capture its load warning, and submit one turn for rendered output.
let mut builder = test_codex().with_home(home);
let test = builder.build(&server).await?;
let warning = wait_for_event_match(&test.codex, |event| match event {
EventMsg::Warning(warning)
if warning
.message
.contains(source.as_path().display().to_string().as_str()) =>
{
Some(warning.message.clone())
}
_ => None,
})
.await;
test.submit_turn("inspect lossy global instructions")
.await?;
// Assert the source is reported, the warning is specific, and rendering is lossily decoded.
assert_eq!(test.codex.instruction_sources().await, vec![source.clone()]);
assert!(
warning.contains("invalid UTF-8"),
"expected warning to contain \"invalid UTF-8\"; observed: {warning}"
);
let expected_fragment =
expected_instruction_fragment(&test.config.cwd, "global\u{FFFD}instructions");
assert_single_instruction_fragment(&response_mock.single_request(), &expected_fragment);
Ok(())
}
// TODO(anp): Align cold-resume instruction sources with the historical instructions replayed to
// the model so the API source list and model-visible context describe the same files.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn cold_resume_replays_rendered_instructions_but_reports_current_config_sources() -> Result<()>
{
// Set up an initial turn and a later cold-resumed turn against the same rollout.
let server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_response_created("initial-response"),
responses::ev_completed("initial-response"),
]),
responses::sse(vec![
responses::ev_response_created("resumed-response"),
responses::ev_completed("resumed-response"),
]),
],
)
.await;
let home = Arc::new(TempDir::new()?);
let old_source = write_global_file(
home.as_ref(),
GLOBAL_AGENTS_FILENAME,
OLD_GLOBAL_INSTRUCTIONS,
)?;
// Create the initial thread and persist its creation-time instruction snapshot.
let mut initial_builder = test_codex().with_home(Arc::clone(&home));
let initial = initial_builder.build(&server).await?;
// Assert the pre-resume thread reports the source used to create its snapshot.
assert_eq!(
initial.codex.instruction_sources().await,
vec![old_source.clone()],
"initial thread reports the creation-time global source"
);
initial.submit_turn("persist instructions").await?;
let rollout_path = initial
.session_configured
.rollout_path
.clone()
.expect("rollout path");
initial.codex.submit(Op::Shutdown).await?;
wait_for_event(&initial.codex, |event| {
matches!(event, EventMsg::ShutdownComplete)
})
.await;
// Add a preferred override source, then cold-resume with freshly loaded configuration.
let new_source = write_global_file(
home.as_ref(),
GLOBAL_AGENTS_OVERRIDE_FILENAME,
NEW_GLOBAL_INSTRUCTIONS,
)?;
assert_ne!(old_source, new_source);
let mut resume_builder = test_codex().with_home(Arc::clone(&home));
let resumed = resume_builder
.resume(&server, Arc::clone(&home), rollout_path)
.await?;
// Assert the API reports the new source while model history replays the old structured prefix.
assert_eq!(
resumed.codex.instruction_sources().await,
vec![new_source],
"resume reports sources from the newly loaded config"
);
resumed.submit_turn("continue resumed thread").await?;
let requests = response_mock.requests();
assert_eq!(requests.len(), 2);
let initial_input = requests[0].input();
let resumed_input = requests[1].input();
assert_eq!(
resumed_input.get(..initial_input.len()),
Some(initial_input.as_slice()),
"cold resume should replay the original structured input prefix"
);
let expected_fragment =
expected_instruction_fragment(&initial.config.cwd, OLD_GLOBAL_INSTRUCTIONS);
assert_single_instruction_fragment(&requests[0], &expected_fragment);
assert_single_instruction_fragment(&requests[1], &expected_fragment);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn fork_replays_rendered_instructions_from_shared_history() -> Result<()> {
// Set up a parent turn and a later fork turn against the parent's rollout.
let server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_response_created("parent-response"),
responses::ev_completed("parent-response"),
]),
responses::sse(vec![
responses::ev_response_created("fork-response"),
responses::ev_completed("fork-response"),
]),
],
)
.await;
let home = Arc::new(TempDir::new()?);
let source = write_global_file(
home.as_ref(),
GLOBAL_AGENTS_FILENAME,
OLD_GLOBAL_INSTRUCTIONS,
)?;
// Create the parent and persist its creation-time instruction snapshot.
let mut builder = test_codex().with_home(Arc::clone(&home));
let parent = builder.build(&server).await?;
// Assert the parent reports the source used to create its snapshot.
assert_eq!(
parent.codex.instruction_sources().await,
vec![source.clone()],
"parent reports the creation-time global source"
);
parent.submit_turn("persist instructions").await?;
parent.codex.ensure_rollout_materialized().await;
parent.codex.flush_rollout().await?;
let rollout_path = parent.codex.rollout_path().expect("rollout path");
// Add a preferred override source, then fork with freshly loaded configuration.
let new_source = write_global_file(
home.as_ref(),
GLOBAL_AGENTS_OVERRIDE_FILENAME,
NEW_GLOBAL_INSTRUCTIONS,
)?;
assert_ne!(source, new_source);
let mut fork_config = load_default_config_for_test(home.as_ref()).await;
fork_config.cwd = parent.config.cwd.clone();
fork_config.model = parent.config.model.clone();
fork_config.model_provider = parent.config.model_provider.clone();
fork_config.model_catalog = parent.config.model_catalog.clone();
fork_config.codex_self_exe = parent.config.codex_self_exe.clone();
let forked = parent
.thread_manager
.fork_thread(
ForkSnapshot::Interrupted,
fork_config,
rollout_path,
/*thread_source*/ None,
/*parent_trace*/ None,
)
.await?;
// Assert the fork reports the new source before issuing its first turn.
assert_eq!(
forked.thread.instruction_sources().await,
vec![new_source],
"fork config should reflect the newly loaded global source"
);
forked
.thread
.submit(Op::UserInput {
items: vec![UserInput::Text {
text: "continue fork".to_string(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
additional_context: Default::default(),
thread_settings: Default::default(),
})
.await?;
wait_for_event(&forked.thread, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
// Assert the forked model request replays the parent's exact structured history.
let requests = response_mock.requests();
assert_eq!(requests.len(), 2);
let parent_input = requests[0].input();
let fork_input = requests[1].input();
assert_eq!(
fork_input.get(..parent_input.len()),
Some(parent_input.as_slice()),
"fork should replay the parent's original structured input prefix"
);
let expected_fragment =
expected_instruction_fragment(&parent.config.cwd, OLD_GLOBAL_INSTRUCTIONS);
assert_single_instruction_fragment(&requests[0], &expected_fragment);
assert_single_instruction_fragment(&requests[1], &expected_fragment);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn forked_subagent_replays_one_creation_time_global_instruction_fragment() -> Result<()> {
skip_if_no_network!(Ok(()));
run_subagent_global_instruction_case(/*fork_context*/ true).await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn fresh_subagent_uses_creation_time_instructions_without_parent_history() -> Result<()> {
skip_if_no_network!(Ok(()));
run_subagent_global_instruction_case(/*fork_context*/ false).await
}
async fn run_subagent_global_instruction_case(fork_context: bool) -> Result<()> {
// Set up matched responses for the parent seed, spawn call, child turn, and parent follow-up.
let server = responses::start_mock_server().await;
let parent_prompt = if fork_context {
SPAWN_PARENT_PROMPT
} else {
SPAWN_FRESH_PARENT_PROMPT
};
let seed_mock = responses::mount_sse_once_match(
&server,
|request: &wiremock::Request| request_body_contains(request, SPAWN_SEED_PROMPT),
responses::sse(vec![
responses::ev_response_created("seed-response"),
responses::ev_assistant_message("seed-message", "seeded"),
responses::ev_completed("seed-response"),
]),
)
.await;
let spawn_args = serde_json::to_string(&json!({
"message": SPAWN_CHILD_PROMPT,
"fork_context": fork_context,
}))?;
let spawn_mock = responses::mount_sse_once_match(
&server,
move |request: &wiremock::Request| request_body_contains(request, parent_prompt),
responses::sse(vec![
responses::ev_response_created("spawn-response"),
responses::ev_function_call_with_namespace(
SPAWN_CALL_ID,
"multi_agent_v1",
"spawn_agent",
&spawn_args,
),
responses::ev_completed("spawn-response"),
]),
)
.await;
let child_mock = responses::mount_sse_once_match(
&server,
|request: &wiremock::Request| {
request_body_contains(request, SPAWN_CHILD_PROMPT)
&& !request_body_contains(request, SPAWN_CALL_ID)
},
responses::sse(vec![
responses::ev_response_created("child-response"),
responses::ev_assistant_message("child-message", "done"),
responses::ev_completed("child-response"),
]),
)
.await;
responses::mount_sse_once_match(
&server,
|request: &wiremock::Request| request_body_contains(request, SPAWN_CALL_ID),
responses::sse(vec![
responses::ev_response_created("spawn-follow-up-response"),
responses::ev_assistant_message("spawn-follow-up-message", "child started"),
responses::ev_completed("spawn-follow-up-response"),
]),
)
.await;
// Create the parent thread, record its source, and seed the history inherited by the child.
let home = Arc::new(TempDir::new()?);
let source = write_global_file(
home.as_ref(),
GLOBAL_AGENTS_FILENAME,
OLD_GLOBAL_INSTRUCTIONS,
)?;
let mut builder = test_codex()
.with_home(Arc::clone(&home))
.with_config(|config| {
let _ = config.features.enable(Feature::Collab);
let _ = config.features.disable(Feature::EnableRequestCompression);
});
let test = builder.build(&server).await?;
// Assert the parent reports the creation-time source before spawning.
assert_eq!(
test.codex.instruction_sources().await,
vec![source.clone()],
"parent reports the creation-time global source before spawning"
);
test.submit_turn(SPAWN_SEED_PROMPT).await?;
let seed_request = seed_mock.single_request();
// Add a preferred override, then spawn a full-history child while observing its thread ID.
let new_source = write_global_file(
home.as_ref(),
GLOBAL_AGENTS_OVERRIDE_FILENAME,
NEW_GLOBAL_INSTRUCTIONS,
)?;
assert_ne!(source, new_source);
let mut created_threads = test.thread_manager.subscribe_thread_created();
test.submit_turn(parent_prompt).await?;
let child_thread_id = tokio::time::timeout(Duration::from_secs(10), created_threads.recv())
.await
.map_err(|_| anyhow!("timed out waiting for the subagent thread"))??;
let child_thread = test.thread_manager.get_thread(child_thread_id).await?;
let spawn_request = spawn_mock.single_request();
let child_request = tokio::time::timeout(Duration::from_secs(10), async {
loop {
if let Some(request) = child_mock.requests().into_iter().find(|request| {
request
.message_input_texts("user")
.iter()
.any(|text| text == SPAWN_CHILD_PROMPT)
}) {
break request;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.map_err(|_| anyhow!("timed out waiting for the subagent request"))?;
// Assert parent and child report and render the parent's creation-time snapshot exactly once.
let expected_fragment =
expected_instruction_fragment(&test.config.cwd, OLD_GLOBAL_INSTRUCTIONS);
assert_single_instruction_fragment(&seed_request, &expected_fragment);
assert_single_instruction_fragment(&spawn_request, &expected_fragment);
assert_single_instruction_fragment(&child_request, &expected_fragment);
assert_eq!(
test.codex.instruction_sources().await,
vec![source.clone()],
"running parent retains the creation-time global source after spawning"
);
assert_eq!(
child_thread.instruction_sources().await,
vec![source],
"subagent reports the parent's creation-time source"
);
if fork_context {
let seed_input = seed_request.input();
let child_input = child_request.input();
assert_eq!(
child_input.get(..seed_input.len()),
Some(seed_input.as_slice()),
"forked subagent should replay the parent's original structured input prefix"
);
} else {
let child_user_texts = child_request.message_input_texts("user");
assert_eq!(
child_user_texts
.iter()
.filter(|text| text.as_str() == SPAWN_SEED_PROMPT)
.count(),
0,
"fresh-context subagent should omit parent user history; observed: {child_user_texts:?}"
);
assert_eq!(
child_user_texts
.iter()
.filter(|text| text.as_str() == SPAWN_CHILD_PROMPT)
.count(),
1,
"fresh-context subagent should contain its own prompt exactly once; observed: {child_user_texts:?}"
);
}
Ok(())
}
+384
View File
@@ -1,4 +1,6 @@
#![allow(clippy::expect_used)]
use anyhow::Result;
use anyhow::anyhow;
use codex_core::compact::SUMMARIZATION_PROMPT;
use codex_core::compact::SUMMARY_PREFIX;
use codex_core::config::Config;
@@ -23,11 +25,13 @@ use codex_protocol::protocol::RolloutItem;
use codex_protocol::protocol::RolloutLine;
use codex_protocol::protocol::WarningEvent;
use codex_protocol::user_input::UserInput;
use codex_utils_absolute_path::AbsolutePathBuf;
use core_test_support::PathBufExt;
use core_test_support::context_snapshot;
use core_test_support::context_snapshot::ContextSnapshotOptions;
use core_test_support::context_snapshot::ContextSnapshotRenderMode;
use core_test_support::hooks::trust_discovered_hooks;
use core_test_support::responses;
use core_test_support::responses::ev_reasoning_item;
use core_test_support::responses::mount_models_once;
use core_test_support::skip_if_no_network;
@@ -57,6 +61,8 @@ use serde_json::Value;
use serde_json::json;
use std::fs;
use std::path::Path;
use std::sync::Arc;
use tempfile::TempDir;
use wiremock::MockServer;
// --- Test helpers -----------------------------------------------------------
@@ -78,6 +84,11 @@ const DUMMY_CALL_ID: &str = "call-multi-auto";
const FUNCTION_CALL_LIMIT_MSG: &str = "function call limit push";
const POST_AUTO_USER_MSG: &str = "post auto follow-up";
const PRETURN_CONTEXT_DIFF_CWD: &str = "/tmp/PRETURN_CONTEXT_DIFF_CWD";
const GLOBAL_AGENTS_FILENAME: &str = "AGENTS.md";
const GLOBAL_AGENTS_OVERRIDE_FILENAME: &str = "AGENTS.override.md";
const NEW_GLOBAL_INSTRUCTIONS: &str = "new global instructions";
const OLD_GLOBAL_INSTRUCTIONS: &str = "old global instructions";
const REMOTE_V2_SUMMARY: &str = "global-instructions-remote-v2-summary";
pub(super) const COMPACT_WARNING_MESSAGE: &str = "Heads up: Long threads and multiple compactions can cause the model to be less accurate. Start a new thread when possible to keep threads small and targeted.";
@@ -267,6 +278,92 @@ fn non_openai_model_provider(server: &MockServer) -> ModelProviderInfo {
provider
}
fn write_global_file(
home: &TempDir,
filename: &str,
contents: impl AsRef<[u8]>,
) -> Result<AbsolutePathBuf> {
let path = home.path().join(filename);
std::fs::write(&path, contents)?;
Ok(path.abs())
}
fn instruction_fragments(request: &responses::ResponsesRequest) -> Vec<String> {
request
.message_input_texts("user")
.into_iter()
.filter(|text| text.starts_with("# AGENTS.md instructions for "))
.collect()
}
fn instruction_fragments_in_items(items: &[Value]) -> Vec<String> {
items
.iter()
.filter(|item| {
item.get("type").and_then(Value::as_str) == Some("message")
&& item.get("role").and_then(Value::as_str) == Some("user")
})
.filter_map(|item| item.get("content").and_then(Value::as_array))
.flatten()
.filter_map(|span| span.get("text").and_then(Value::as_str))
.filter(|text| text.starts_with("# AGENTS.md instructions for "))
.map(str::to_string)
.collect()
}
fn expected_instruction_fragment(cwd: &AbsolutePathBuf, contents: &str) -> String {
let cwd = cwd.as_path().display();
format!("# AGENTS.md instructions for {cwd}\n\n<INSTRUCTIONS>\n{contents}\n</INSTRUCTIONS>")
}
fn assert_single_instruction_fragment(request: &responses::ResponsesRequest, expected: &str) {
assert_eq!(instruction_fragments(request), vec![expected.to_string()]);
}
fn replacement_history_from_rollout(path: &Path) -> Result<Vec<Value>> {
let rollout_text = fs::read_to_string(path)?;
let mut replacement_history = None;
for line in rollout_text
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
{
let entry: RolloutLine = serde_json::from_str(line)?;
if let RolloutItem::Compacted(compacted) = entry.item
&& let Some(items) = compacted.replacement_history
{
replacement_history = Some(
items
.into_iter()
.map(serde_json::to_value)
.collect::<std::result::Result<Vec<_>, _>>()?,
);
}
}
replacement_history.ok_or_else(|| anyhow!("expected rollout replacement history"))
}
fn remote_v2_compaction_response() -> String {
responses::sse(vec![
json!({
"type": "response.output_item.done",
"item": {
"type": "compaction",
"encrypted_content": REMOTE_V2_SUMMARY,
}
}),
responses::ev_completed("remote-v2-compact-response"),
])
}
fn local_compaction_provider(server: &wiremock::MockServer) -> ModelProviderInfo {
let mut provider = built_in_model_providers(/*openai_base_url*/ None)["openai"].clone();
provider.name = "OpenAI-compatible test provider".to_string();
provider.base_url = Some(format!("{}/v1", server.uri()));
provider.supports_websockets = false;
provider
}
fn model_info_with_context_window(slug: &str, context_window: i64) -> ModelInfo {
let models_response = bundled_models_response()
.unwrap_or_else(|err| panic!("bundled models.json should parse: {err}"));
@@ -3998,3 +4095,290 @@ async fn snapshot_request_shape_manual_compact_without_previous_user_messages()
)
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn manual_compaction_keeps_the_creation_time_global_instructions() -> Result<()> {
// Set up an initial turn, a manual compaction response, and a post-compaction turn.
let server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_response_created("first-response"),
responses::ev_completed("first-response"),
]),
responses::sse(vec![
responses::ev_response_created("compact-response"),
responses::ev_assistant_message("compact-message", "summary"),
responses::ev_completed("compact-response"),
]),
responses::sse(vec![
responses::ev_response_created("follow-up-response"),
responses::ev_completed("follow-up-response"),
]),
],
)
.await;
let home = Arc::new(TempDir::new()?);
let source = write_global_file(
home.as_ref(),
GLOBAL_AGENTS_FILENAME,
OLD_GLOBAL_INSTRUCTIONS,
)?;
let provider = local_compaction_provider(&server);
// Create the thread with the old global source loaded into its instruction snapshot.
let mut builder = test_codex()
.with_home(Arc::clone(&home))
.with_config(move |config| {
config.model_provider = provider;
});
let test = builder.build(&server).await?;
// Assert the pre-compaction source list points at the creation-time file.
assert_eq!(
test.codex.instruction_sources().await,
vec![source.clone()],
"thread reports the creation-time global source before compaction"
);
// Materialize the old snapshot, rewrite the selected file in place, and manually compact.
test.submit_turn("first turn").await?;
let rewritten_source = write_global_file(
home.as_ref(),
GLOBAL_AGENTS_FILENAME,
NEW_GLOBAL_INSTRUCTIONS,
)?;
assert_eq!(source, rewritten_source);
test.codex.submit(Op::Compact).await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
test.submit_turn("after compact").await?;
// Assert ordinary and compact turns keep the old rendering even though the reported source
// path now contains new text.
let requests = response_mock.requests();
assert_eq!(requests.len(), 3);
let expected_fragment =
expected_instruction_fragment(&test.config.cwd, OLD_GLOBAL_INSTRUCTIONS);
assert_single_instruction_fragment(&requests[0], &expected_fragment);
assert_single_instruction_fragment(&requests[1], &expected_fragment);
assert_single_instruction_fragment(&requests[2], &expected_fragment);
assert_eq!(
test.codex.instruction_sources().await,
vec![source],
"thread retains the creation-time global source after compaction"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn mid_turn_compaction_keeps_the_creation_time_global_instructions() -> Result<()> {
// Set up a turn that crosses the auto-compaction limit and a post-compaction response.
let server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_function_call("call-1", "unsupported_tool", "{}"),
responses::ev_completed_with_tokens("first-response", /*total_tokens*/ 96),
]),
responses::sse(vec![
responses::ev_assistant_message("compact-message", "summary"),
responses::ev_completed_with_tokens("compact-response", /*total_tokens*/ 10),
]),
responses::sse(vec![
responses::ev_assistant_message("final-message", "done"),
responses::ev_completed_with_tokens("follow-up-response", /*total_tokens*/ 10),
]),
],
)
.await;
let home = Arc::new(TempDir::new()?);
let source = write_global_file(
home.as_ref(),
GLOBAL_AGENTS_FILENAME,
OLD_GLOBAL_INSTRUCTIONS,
)?;
let provider = local_compaction_provider(&server);
// Create the thread with the old global source loaded into its instruction snapshot.
let mut builder = test_codex()
.with_home(Arc::clone(&home))
.with_config(move |config| {
config.model_provider = provider;
config.model_context_window = Some(100);
config.model_auto_compact_token_limit = Some(90);
});
let test = builder.build(&server).await?;
// Assert the pre-compaction source list points at the creation-time file.
assert_eq!(
test.codex.instruction_sources().await,
vec![source.clone()],
"thread reports the creation-time global source before mid-turn compaction"
);
// Add a preferred override before the turn triggers automatic mid-turn compaction.
let new_source = write_global_file(
home.as_ref(),
GLOBAL_AGENTS_OVERRIDE_FILENAME,
NEW_GLOBAL_INSTRUCTIONS,
)?;
assert_ne!(source, new_source);
test.submit_turn("trigger mid-turn compaction").await?;
// Assert the initial, compact, and resumed requests all keep the old snapshot and source.
let requests = response_mock.requests();
assert_eq!(requests.len(), 3);
let expected_fragment =
expected_instruction_fragment(&test.config.cwd, OLD_GLOBAL_INSTRUCTIONS);
assert_single_instruction_fragment(&requests[0], &expected_fragment);
assert_single_instruction_fragment(&requests[1], &expected_fragment);
assert_single_instruction_fragment(&requests[2], &expected_fragment);
assert_eq!(
test.codex.instruction_sources().await,
vec![source],
"thread retains the creation-time global source after mid-turn compaction"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_v2_compaction_keeps_creation_time_instructions_after_same_path_mutation()
-> Result<()> {
skip_if_no_network!(Ok(()));
// Set up an ordinary turn, a remote-v2 compact response, and a post-compaction turn.
let server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_response_created("remote-v2-initial-response"),
responses::ev_completed("remote-v2-initial-response"),
]),
remote_v2_compaction_response(),
responses::sse(vec![
responses::ev_response_created("remote-v2-follow-up-response"),
responses::ev_completed("remote-v2-follow-up-response"),
]),
responses::sse(vec![
responses::ev_response_created("remote-v2-resumed-response"),
responses::ev_completed("remote-v2-resumed-response"),
]),
],
)
.await;
let home = Arc::new(TempDir::new()?);
let source = write_global_file(
home.as_ref(),
GLOBAL_AGENTS_FILENAME,
OLD_GLOBAL_INSTRUCTIONS,
)?;
let mut builder = test_codex()
.with_home(Arc::clone(&home))
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
.with_config(|config| {
let _ = config.features.enable(Feature::RemoteCompactionV2);
});
let test = builder.build(&server).await?;
// Materialize the old snapshot, rewrite the selected file in place, and compact remotely.
test.submit_turn("before remote v2 compaction").await?;
let rewritten_source = write_global_file(
home.as_ref(),
GLOBAL_AGENTS_FILENAME,
NEW_GLOBAL_INSTRUCTIONS,
)?;
assert_eq!(source, rewritten_source);
test.codex.submit(Op::Compact).await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
test.submit_turn("after remote v2 compaction").await?;
test.codex.flush_rollout().await?;
// Assert the compact request, installed replacement history, and follow-up all keep the
// creation-time item despite the file-backed source now containing new text.
let requests = response_mock.requests();
assert_eq!(requests.len(), 3);
let old_fragment = expected_instruction_fragment(&test.config.cwd, OLD_GLOBAL_INSTRUCTIONS);
assert_single_instruction_fragment(&requests[0], &old_fragment);
assert_single_instruction_fragment(&requests[1], &old_fragment);
assert_single_instruction_fragment(&requests[2], &old_fragment);
assert_eq!(
requests[1].input().last(),
Some(&json!({"type": "compaction_trigger"})),
"remote-v2 compact request should append exactly one compaction trigger"
);
let rollout_path = test.codex.rollout_path().expect("rollout path");
let replacement_history = replacement_history_from_rollout(&rollout_path)?;
assert_eq!(
instruction_fragments_in_items(&replacement_history),
Vec::<String>::new(),
"remote-v2 replacement history currently omits the global-instruction fragment"
);
assert_eq!(
test.codex.instruction_sources().await,
vec![source.clone()],
"running thread retains the selected same-path source"
);
assert_eq!(
fs::read_to_string(source.as_path())?,
NEW_GLOBAL_INSTRUCTIONS,
"the selected source path should contain the rewritten text"
);
// Cold-resume the persisted replacement history with freshly loaded same-path configuration.
test.codex.submit(Op::Shutdown).await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::ShutdownComplete)
})
.await;
let resumed_cwd = test.config.cwd.clone();
let mut resume_builder = test_codex()
.with_home(Arc::clone(&home))
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
.with_config(move |config| {
config.cwd = resumed_cwd;
let _ = config.features.enable(Feature::RemoteCompactionV2);
});
let resumed = resume_builder
.resume(&server, Arc::clone(&home), rollout_path)
.await?;
resumed
.submit_turn("after remote v2 compaction cold resume")
.await?;
// Modern replacement-history resume replays the persisted checkpoint and its later old-context
// suffix even though the same source path now contains new text.
let requests = response_mock.requests();
assert_eq!(requests.len(), 4);
assert_single_instruction_fragment(&requests[3], &old_fragment);
let resumed_input = requests[3].input();
assert_eq!(
resumed_input.get(..replacement_history.len()),
Some(replacement_history.as_slice()),
"remote-v2 cold resume should replay persisted replacement history verbatim"
);
let post_compact_input = requests[2].input();
assert_eq!(
resumed_input.get(..post_compact_input.len()),
Some(post_compact_input.as_slice()),
"remote-v2 cold resume should replay the complete post-compaction structured prefix"
);
assert_eq!(
resumed.codex.instruction_sources().await,
vec![source],
"cold-resumed thread reports the same rewritten source path"
);
Ok(())
}
@@ -757,6 +757,7 @@ async fn subagent_stop_replaces_stop_and_skips_internal_subagents() -> Result<()
metrics_service_name: None,
parent_trace: None,
environments: Vec::new(),
thread_extension_init: Default::default(),
})
.await?;
+243
View File
@@ -1995,6 +1995,249 @@ async fn write_stdin_returns_exit_metadata_and_clears_session() -> Result<()> {
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn write_stdin_ctrl_c_interrupts_non_tty_session() -> Result<()> {
assert_write_stdin_ctrl_c_interrupts_non_tty_session(
"trap",
"trap 'echo INT-TRAP; exit 42' INT; echo READY; while true; do sleep 30; done",
/*expected_exit_code*/ 42,
Some("INT-TRAP"),
)
.await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn write_stdin_ctrl_c_default_interrupt_reports_130_for_non_tty_session() -> Result<()> {
assert_write_stdin_ctrl_c_interrupts_non_tty_session(
"default",
"echo READY; exec sleep 30",
/*expected_exit_code*/ 130,
/*expected_interrupt_output*/ None,
)
.await
}
async fn assert_write_stdin_ctrl_c_interrupts_non_tty_session(
test_name: &str,
command: &str,
expected_exit_code: i32,
expected_interrupt_output: Option<&str>,
) -> Result<()> {
skip_if_no_network!(Ok(()));
skip_if_sandbox!(Ok(()));
skip_if_windows!(Ok(()));
let server = start_mock_server().await;
let mut builder = test_codex().with_config(|config| {
if let Err(err) = config.features.enable(Feature::UnifiedExec) {
panic!("test config should allow feature update: {err}");
}
});
let test = builder.build_with_remote_env(&server).await?;
let start_call_id = format!("uexec-non-tty-interrupt-{test_name}-start");
let interrupt_call_id = format!("uexec-non-tty-interrupt-{test_name}");
let start_args = serde_json::json!({
"cmd": command,
"yield_time_ms": 250,
"tty": false,
});
let interrupt_args = serde_json::json!({
"chars": "\u{3}",
"session_id": 1000,
"yield_time_ms": 1000,
});
let responses = vec![
sse(vec![
ev_response_created("resp-1"),
ev_function_call(
&start_call_id,
"exec_command",
&serde_json::to_string(&start_args)?,
),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_function_call(
&interrupt_call_id,
"write_stdin",
&serde_json::to_string(&interrupt_args)?,
),
ev_completed("resp-2"),
]),
sse(vec![
ev_assistant_message("msg-1", "done"),
ev_completed("resp-3"),
]),
];
let request_log = mount_sse_sequence(&server, responses).await;
submit_unified_exec_turn(
&test,
"interrupt non-tty unified exec",
PermissionProfile::Disabled,
)
.await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
let requests = request_log.requests();
assert!(!requests.is_empty(), "expected at least one POST request");
let bodies = requests
.into_iter()
.map(|request| request.body_json())
.collect::<Vec<_>>();
let outputs = collect_tool_outputs(&bodies)?;
let start_output = outputs
.get(&start_call_id)
.with_context(|| format!("missing start output for exec_command {start_call_id}"))?;
assert_eq!(
start_output.process_id.as_deref(),
Some("1000"),
"exec_command should leave a running non-TTY session"
);
assert!(
start_output.exit_code.is_none(),
"initial exec_command should not include exit_code while session is running"
);
assert!(
start_output.output.contains("READY"),
"start output should include command readiness marker, got {:?}",
start_output.output
);
let interrupt_output = outputs
.get(&interrupt_call_id)
.with_context(|| format!("missing interrupt output for write_stdin {interrupt_call_id}"))?;
assert!(
interrupt_output.process_id.is_none(),
"interrupted process should be cleared from the session map"
);
assert_eq!(
interrupt_output.exit_code,
Some(expected_exit_code),
"interrupt should preserve the process-reported exit code"
);
if let Some(expected_interrupt_output) = expected_interrupt_output {
assert!(
interrupt_output.output.contains(expected_interrupt_output),
"interrupt should drain output from the signal handler, got {:?}",
interrupt_output.output
);
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[cfg_attr(not(windows), ignore = "Windows-only unified exec interrupt test")]
async fn write_stdin_ctrl_c_reports_unsupported_interrupt_to_model_on_windows() -> Result<()> {
skip_if_no_network!(Ok(()));
skip_if_sandbox!(Ok(()));
let server = start_mock_server().await;
let mut builder = test_codex().with_config(|config| {
config
.features
.enable(Feature::UnifiedExec)
.expect("test config should allow feature update");
});
let test = builder.build_with_remote_env(&server).await?;
let start_call_id = "uexec-windows-interrupt-start";
let interrupt_call_id = "uexec-windows-interrupt";
let start_args = serde_json::json!({
"shell": "cmd",
"cmd": "echo READY && ping -n 30 127.0.0.1 >NUL",
"yield_time_ms": 250,
"tty": false,
});
let interrupt_args = serde_json::json!({
"chars": "\u{3}",
"session_id": 1000,
"yield_time_ms": 1000,
});
let responses = vec![
sse(vec![
ev_response_created("resp-1"),
ev_function_call(
start_call_id,
"exec_command",
&serde_json::to_string(&start_args)?,
),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_function_call(
interrupt_call_id,
"write_stdin",
&serde_json::to_string(&interrupt_args)?,
),
ev_completed("resp-2"),
]),
sse(vec![
ev_response_created("resp-3"),
ev_assistant_message("msg-1", "done"),
ev_completed("resp-3"),
]),
];
let request_log = mount_sse_sequence(&server, responses).await;
submit_unified_exec_turn(
&test,
"interrupt non-tty unified exec on Windows",
PermissionProfile::Disabled,
)
.await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
let start_output = request_log
.function_call_output_text(start_call_id)
.expect("missing start output for exec_command");
let start_output = parse_unified_exec_output(&start_output)?;
assert_eq!(
start_output.process_id.as_deref(),
Some("1000"),
"exec_command should leave a running non-TTY session"
);
assert!(
start_output.output.contains("READY"),
"start output should include command readiness marker, got {:?}",
start_output.output
);
let interrupt_output = request_log
.function_call_output_text(interrupt_call_id)
.expect("missing interrupt output for write_stdin");
assert!(
interrupt_output.contains("write_stdin failed"),
"model-visible write_stdin output should report failure, got {interrupt_output:?}"
);
assert!(
interrupt_output.contains("process interrupt is not supported by this process backend"),
"model-visible write_stdin output should explain unsupported interrupt, got {interrupt_output:?}"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn unified_exec_emits_end_event_when_session_dies_via_stdin() -> Result<()> {
skip_if_no_network!(Ok(()));