mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Preserve subagent capabilities independently of forked history (#52241)
## Why Subagents should retain the spawning turn's selected skills and plugin choices whether `fork_turns` is `none` or `all`. Capability selection should not depend on copied conversation metadata. ## What changed - Use a shared child startup path for fresh and history-forked agents, inheriting selected capability roots from the spawning environment snapshot. - Pass the spawning turn's `disabled_plugin_ids` through both spawn handlers. When omitted, inherit the parent's current choices; explicit lists, including an empty list, override them. - Resolve the parent before startup so inherited client MCP settings apply even when only the session source identifies the parent. - Carry plugin choices into delegates with inherited isolation and preserve saved capability roots when resuming a child. ## Testing Add regression coverage for executor skill listing and reading, plugin MCP registration with both history modes, plugin overrides, capability-root precedence and isolation, and restoring saved child settings after parent settings change. GitOrigin-RevId: 2a6891a9bc6372fd2d1f30add2b5611f96b60594
This commit is contained in:
committed by
copyberry
parent
137f25f643
commit
845345b1dd
@@ -0,0 +1,256 @@
|
||||
//! Executor skill selection survives subagent spawning independently of forked history.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use app_test_support::MockResponsesConfig;
|
||||
use app_test_support::TestAppServer;
|
||||
use app_test_support::to_response;
|
||||
use codex_app_server_protocol::CapabilityRootLocation;
|
||||
use codex_app_server_protocol::ListMcpServerStatusParams;
|
||||
use codex_app_server_protocol::ListMcpServerStatusResponse;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::SelectedCapabilityRoot;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_app_server_protocol::ThreadStartResponse;
|
||||
use codex_app_server_protocol::TurnStartParams;
|
||||
use codex_app_server_protocol::UserInput;
|
||||
use codex_exec_server::CreateDirectoryOptions;
|
||||
use core_test_support::responses;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
use test_case::test_case;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::time::timeout;
|
||||
use wiremock::Mock;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
/// Both capability roots and the parent's plugin choices apply regardless of copied history.
|
||||
#[test_case("none", false; "no history enabled")]
|
||||
#[test_case("all", false; "full history enabled")]
|
||||
#[test_case("none", true; "no history disabled")]
|
||||
#[test_case("all", true; "full history disabled")]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn spawned_agent_inherits_selected_executor_skill(
|
||||
fork_turns: &str,
|
||||
disabled: bool,
|
||||
) -> Result<()> {
|
||||
let server = responses::start_mock_server().await;
|
||||
let codex_home = TempDir::new()?;
|
||||
MockResponsesConfig::new(&server.uri())
|
||||
.with_extra_config(
|
||||
"[features.multi_agent_v2]\nenabled = true\n\n[skills]\ninclude_instructions = true\n",
|
||||
)
|
||||
.write(codex_home.path())?;
|
||||
let mut app_server = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
.build_initialized()
|
||||
.await?;
|
||||
|
||||
// Install only on the executor, and select the root through the same API as the bridge.
|
||||
let auto_env = app_server.auto_env()?;
|
||||
let environment_id = auto_env.selection().environment_id.clone();
|
||||
let plugin_dir = auto_env.selection().cwd.join("spawn-plugin")?;
|
||||
let manifest_dir = plugin_dir.join(".codex-plugin")?;
|
||||
let skill_dir = plugin_dir.join("skills/deploy")?;
|
||||
let file_system = auto_env.environment().get_filesystem();
|
||||
for directory in [&manifest_dir, &skill_dir] {
|
||||
file_system
|
||||
.create_directory(
|
||||
directory,
|
||||
CreateDirectoryOptions {
|
||||
recursive: true,
|
||||
follow_symlinks: true,
|
||||
},
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
file_system
|
||||
.write_file(
|
||||
&manifest_dir.join("plugin.json")?,
|
||||
br#"{"name":"spawn-plugin"}"#.to_vec(),
|
||||
Default::default(),
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await?;
|
||||
// A registered but unreachable server is still visible in mcpServerStatus/list.
|
||||
// Disabled plugins must not register it at all.
|
||||
file_system
|
||||
.write_file(
|
||||
&plugin_dir.join(".mcp.json")?,
|
||||
br#"{"mcpServers":{"spawn-probe":{"type":"http","url":"http://127.0.0.1:9/mcp"}}}"#
|
||||
.to_vec(),
|
||||
Default::default(),
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await?;
|
||||
let skill_contents = "---\nname: deploy\ndescription: Deploy through the inherited executor.\n---\n\nINHERITED_EXECUTOR_SKILL_BODY\n";
|
||||
file_system
|
||||
.write_file(
|
||||
&skill_dir.join("SKILL.md")?,
|
||||
skill_contents.as_bytes().to_vec(),
|
||||
Default::default(),
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await?;
|
||||
let request_id = app_server
|
||||
.send_thread_start_request_with_auto_env(ThreadStartParams {
|
||||
selected_capability_roots: Some(vec![SelectedCapabilityRoot {
|
||||
id: "spawn-plugin@1".to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id,
|
||||
path: plugin_dir,
|
||||
},
|
||||
}]),
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
let ThreadStartResponse { thread, .. } = to_response(
|
||||
app_server
|
||||
.read_stream_until_response_message(RequestId::Integer(request_id))
|
||||
.await?,
|
||||
)?;
|
||||
let parent_id = thread.id.clone();
|
||||
let fork_turns = fork_turns.to_string();
|
||||
let child_read_completed = Arc::new(Notify::new());
|
||||
let notify_child_read = Arc::clone(&child_read_completed);
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/v1/responses"))
|
||||
.respond_with(move |request: &wiremock::Request| {
|
||||
let body: Value = serde_json::from_slice(&request.body).expect("responses request");
|
||||
let parent = request.headers["thread-id"] == parent_id;
|
||||
let agent = if parent { "parent" } else { "child" };
|
||||
let completed = |call_id: &str| {
|
||||
body["input"]
|
||||
.as_array()
|
||||
.expect("input array")
|
||||
.iter()
|
||||
.any(|item| {
|
||||
item["type"] == "function_call_output" && item["call_id"] == call_id
|
||||
})
|
||||
};
|
||||
let list_call = format!("{agent}-list");
|
||||
let read_call = format!("{agent}-read");
|
||||
let item = if !completed(&list_call) {
|
||||
responses::ev_function_call_with_namespace(
|
||||
&list_call,
|
||||
"skills",
|
||||
"list",
|
||||
r#"{"authority":{"kind":"executor"}}"#,
|
||||
)
|
||||
} else if !completed(&read_call) {
|
||||
responses::ev_function_call_with_namespace(
|
||||
&read_call,
|
||||
"skills",
|
||||
"read",
|
||||
r#"{"package":"e0/skills/deploy"}"#,
|
||||
)
|
||||
} else if parent && !completed("spawn-worker") {
|
||||
responses::ev_function_call_with_namespace(
|
||||
"spawn-worker",
|
||||
"collaboration",
|
||||
"spawn_agent",
|
||||
&json!({
|
||||
"task_name": "worker",
|
||||
"message": "List the executor skills and read the deploy skill.",
|
||||
"fork_turns": fork_turns,
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
} else {
|
||||
if !parent {
|
||||
notify_child_read.notify_one();
|
||||
}
|
||||
responses::ev_assistant_message(&format!("{agent}-done"), "Done")
|
||||
};
|
||||
responses::sse_response(responses::sse(vec![
|
||||
responses::ev_response_created("response"),
|
||||
item,
|
||||
responses::ev_completed("response"),
|
||||
]))
|
||||
})
|
||||
.mount(&server)
|
||||
.await;
|
||||
timeout(
|
||||
Duration::from_secs(/*secs*/ 30),
|
||||
app_server.start_turn_and_wait_for_completion(TurnStartParams {
|
||||
thread_id: thread.id.clone(),
|
||||
disabled_plugin_ids: Some(if disabled {
|
||||
vec!["spawn-plugin@1".to_string()]
|
||||
} else {
|
||||
Vec::new()
|
||||
}),
|
||||
input: vec![UserInput::Text {
|
||||
text: "List and read the deploy skill, then delegate the same task.".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.await??;
|
||||
timeout(
|
||||
Duration::from_secs(/*secs*/ 30),
|
||||
child_read_completed.notified(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let requests = responses::received_responses_requests(&server).await;
|
||||
let mut catalogs = Vec::new();
|
||||
for agent in ["parent", "child"] {
|
||||
let read_call = format!("{agent}-read");
|
||||
let request = requests
|
||||
.iter()
|
||||
.find(|request| request.function_call_output_text(&read_call).is_some())
|
||||
.expect("agent should return its skill read result to the model");
|
||||
let output = request
|
||||
.function_call_output_text(&read_call)
|
||||
.expect("skill read result");
|
||||
let list: Value = serde_json::from_str(
|
||||
&request
|
||||
.function_call_output_text(&format!("{agent}-list"))
|
||||
.expect("skill list result"),
|
||||
)?;
|
||||
if disabled {
|
||||
assert_eq!(list["skills"], json!([]), "{agent} disabled plugin catalog");
|
||||
assert!(
|
||||
!output.contains("INHERITED_EXECUTOR_SKILL_BODY"),
|
||||
"{agent} read a disabled skill: {output}"
|
||||
);
|
||||
} else {
|
||||
let read: Value = serde_json::from_str(&output)
|
||||
.unwrap_or_else(|_| panic!("{agent} could not read the executor skill: {output}"));
|
||||
assert_eq!(read["contents"], skill_contents, "{agent} skill contents");
|
||||
assert_eq!(read["skill_root"], skill_dir.inferred_native_path_string());
|
||||
assert_eq!(list["skills"][0]["name"], "spawn-plugin:deploy");
|
||||
}
|
||||
let status_id = app_server
|
||||
.send_list_mcp_server_status_request(ListMcpServerStatusParams {
|
||||
thread_id: Some(request.header("thread-id").expect("agent thread ID")),
|
||||
server_name: None,
|
||||
cursor: None,
|
||||
limit: None,
|
||||
detail: None,
|
||||
})
|
||||
.await?;
|
||||
let status: ListMcpServerStatusResponse = app_server.read_response(status_id).await?;
|
||||
let has_plugin_server = status
|
||||
.data
|
||||
.iter()
|
||||
.any(|server| server.name.contains("spawn-probe"));
|
||||
assert_eq!(
|
||||
has_plugin_server, !disabled,
|
||||
"{agent} plugin MCP registration"
|
||||
);
|
||||
catalogs.push(list);
|
||||
}
|
||||
assert_eq!(
|
||||
catalogs[0], catalogs[1],
|
||||
"parent and child executor catalogs"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -53,6 +53,8 @@ mod exec_server_test_support;
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
mod executor_mcp;
|
||||
mod executor_skills;
|
||||
#[path = "executor_skills_spawn_tests.rs"]
|
||||
mod executor_skills_spawn;
|
||||
mod experimental_api;
|
||||
mod experimental_feature_list;
|
||||
mod external_agent_config;
|
||||
|
||||
@@ -169,19 +169,17 @@ async fn spawn_v2_subagent(
|
||||
label: &str,
|
||||
) -> crate::thread_manager::NewThread {
|
||||
state
|
||||
.spawn_new_thread_with_source(
|
||||
config,
|
||||
.spawn_child_thread(
|
||||
crate::thread_manager::StartThreadOptions {
|
||||
session_source: Some(SessionSource::SubAgent(SubAgentSource::Other(
|
||||
label.to_string(),
|
||||
))),
|
||||
thread_source: Some(ThreadSource::Subagent),
|
||||
..crate::thread_manager::StartThreadOptions::new(config)
|
||||
},
|
||||
control.clone(),
|
||||
SessionSource::SubAgent(SubAgentSource::Other(label.to_string())),
|
||||
/*history_mode*/ None,
|
||||
/*dynamic_tools*/ Vec::new(),
|
||||
Some(parent_thread_id),
|
||||
/*forked_from_thread_id*/ None,
|
||||
Some(ThreadSource::Subagent),
|
||||
/*metrics_service_name*/ None,
|
||||
/*inherited_environments*/ None,
|
||||
/*inherited_exec_policy*/ None,
|
||||
/*environments*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("spawn v2 subagent")
|
||||
|
||||
@@ -22,9 +22,9 @@ use crate::context::MultiAgentModeInstructions;
|
||||
use crate::context::MultiAgentRoleInstructions;
|
||||
use crate::context::world_state::PersistentModeState;
|
||||
use crate::session::multi_agents::resolve_usage_hints;
|
||||
use crate::thread_manager::StartThreadOptions;
|
||||
use codex_context_fragments::set_annotated_content;
|
||||
use codex_context_fragments::to_annotated_content;
|
||||
use codex_extension_api::ExtensionDataInit;
|
||||
use codex_features::Feature;
|
||||
use codex_history::ResponseItemEnvelope;
|
||||
use codex_prompts::ResolvedModelMessages;
|
||||
@@ -35,22 +35,10 @@ use codex_thread_store::PersistContext;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use futures::StreamExt;
|
||||
use futures::stream;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
const AGENT_NAMES: &str = include_str!("../../../assets/agent/agent_names.txt");
|
||||
|
||||
struct SpawnAgentThreadInheritance {
|
||||
environments: Option<TurnEnvironmentSnapshot>,
|
||||
exec_policy: Option<Arc<crate::exec_policy::ExecPolicyManager>>,
|
||||
}
|
||||
|
||||
struct SpawnedThreadResult {
|
||||
new_thread: crate::thread_manager::NewThread,
|
||||
fork_context: Option<Duration>,
|
||||
child_create: Duration,
|
||||
}
|
||||
|
||||
/// Initial input delivered after a spawned agent acquires execution capacity.
|
||||
///
|
||||
/// V2 communication spawns keep the communication and its context paired so centralized
|
||||
@@ -690,11 +678,17 @@ impl LocalAgentControl {
|
||||
let membership = self.runtime.admit_start()?;
|
||||
let spawn_started_at = Instant::now();
|
||||
let state = self.runtime.upgrade()?;
|
||||
// Resolve the parent before inheriting settings or copying attachments.
|
||||
// Recovering it later from history only repairs the child's metadata.
|
||||
let parent_thread_id = session_source
|
||||
.as_ref()
|
||||
.and_then(SessionSource::parent_thread_id)
|
||||
.or(options.parent_thread_id);
|
||||
let multi_agent_version = state
|
||||
.effective_multi_agent_version_for_spawn(
|
||||
&InitialHistory::New,
|
||||
session_source.as_ref(),
|
||||
options.parent_thread_id,
|
||||
parent_thread_id,
|
||||
/*forked_from_thread_id*/ None,
|
||||
&config,
|
||||
)
|
||||
@@ -734,18 +728,30 @@ impl LocalAgentControl {
|
||||
.runtime
|
||||
.registry
|
||||
.reserve_spawn_slot(reservation_max_threads)?;
|
||||
let inheritance = SpawnAgentThreadInheritance {
|
||||
environments: match &options.environments {
|
||||
Some(environments) => Some(environments.clone()),
|
||||
None => {
|
||||
self.inherited_environments_for_source(&state, session_source.as_ref())
|
||||
.await
|
||||
}
|
||||
},
|
||||
exec_policy: self
|
||||
.inherited_exec_policy_for_source(&state, session_source.as_ref(), &config)
|
||||
.await,
|
||||
let inherited_environments = match &options.environments {
|
||||
Some(environments) => Some(environments.clone()),
|
||||
None => {
|
||||
self.inherited_environments_for_source(&state, session_source.as_ref())
|
||||
.await
|
||||
}
|
||||
};
|
||||
// Omitted plugin choices follow the parent even when no history is copied.
|
||||
// Explicit choices, including an empty list, belong to the spawning turn.
|
||||
let mut disabled_plugin_ids = options.disabled_plugin_ids.clone();
|
||||
if disabled_plugin_ids.is_none()
|
||||
&& let Some(parent_thread_id) = parent_thread_id
|
||||
&& let Ok(parent_thread) = state.get_thread(parent_thread_id).await
|
||||
{
|
||||
disabled_plugin_ids = Some(
|
||||
parent_thread
|
||||
.thread_settings_snapshot()
|
||||
.await
|
||||
.disabled_plugin_ids,
|
||||
);
|
||||
}
|
||||
let inherited_exec_policy = self
|
||||
.inherited_exec_policy_for_source(&state, session_source.as_ref(), &config)
|
||||
.await;
|
||||
let (session_source, mut agent_metadata) = match session_source {
|
||||
Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id,
|
||||
@@ -769,82 +775,69 @@ impl LocalAgentControl {
|
||||
};
|
||||
let notification_source = session_source.clone();
|
||||
|
||||
// The same `LocalAgentControl` is sent to spawn the thread.
|
||||
let SpawnedThreadResult {
|
||||
new_thread,
|
||||
fork_context,
|
||||
child_create,
|
||||
} = match (session_source, options.fork_mode.as_ref(), inheritance) {
|
||||
(Some(session_source), Some(_), inheritance) => Box::pin(self.spawn_forked_thread(
|
||||
&state,
|
||||
config,
|
||||
session_source,
|
||||
&options,
|
||||
inheritance,
|
||||
multi_agent_version,
|
||||
))
|
||||
.await
|
||||
.map_err(|err| err.with_agent_context(AgentErrorContext::ForkHistory))?,
|
||||
(Some(session_source), None, inheritance) => {
|
||||
let (history_mode, dynamic_tools) = if let Some(parent_thread_id) =
|
||||
options.parent_thread_id
|
||||
// Capture child defaults once. Copying conversation history must not change
|
||||
// the capabilities of the turn which requested the spawn.
|
||||
let mut start_options = StartThreadOptions {
|
||||
session_source: session_source.clone(),
|
||||
thread_source: session_source.as_ref().map(|_| ThreadSource::Subagent),
|
||||
environments: options.environments.as_ref().map(|snapshot| {
|
||||
snapshot
|
||||
.inheritable_selections()
|
||||
.into_iter()
|
||||
.map(codex_protocol::protocol::TurnEnvironmentSelection::into_request)
|
||||
.collect()
|
||||
}),
|
||||
inherited_environments,
|
||||
disabled_plugin_ids,
|
||||
..StartThreadOptions::new(config.clone())
|
||||
};
|
||||
let fork_context = match (session_source, options.fork_mode.as_ref()) {
|
||||
(Some(session_source), Some(_)) => {
|
||||
let fork_context_started_at = Instant::now();
|
||||
let (initial_history, history_mode) = self
|
||||
.prepare_forked_history(
|
||||
&state,
|
||||
&session_source,
|
||||
&options,
|
||||
&config,
|
||||
multi_agent_version,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| err.with_agent_context(AgentErrorContext::ForkHistory))?;
|
||||
start_options.initial_history = initial_history;
|
||||
start_options.history_mode = history_mode;
|
||||
Some(fork_context_started_at.elapsed())
|
||||
}
|
||||
(Some(_), None) => {
|
||||
if let Some(parent_thread_id) = parent_thread_id
|
||||
&& let Ok(parent_thread) = state.get_thread(parent_thread_id).await
|
||||
{
|
||||
let history_mode = matches!(
|
||||
start_options.history_mode = matches!(
|
||||
parent_thread.config_snapshot().await.history_mode,
|
||||
ThreadHistoryMode::Paginated
|
||||
)
|
||||
.then_some(ThreadHistoryMode::Paginated);
|
||||
let dynamic_tools = if multi_agent_version == MultiAgentVersion::V2
|
||||
if multi_agent_version == MultiAgentVersion::V2
|
||||
&& config.features.enabled(Feature::MultiAgentV2DynamicTools)
|
||||
{
|
||||
parent_thread.session.dynamic_tools().await
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
(history_mode, dynamic_tools)
|
||||
} else {
|
||||
(None, Vec::new())
|
||||
};
|
||||
let environments = options
|
||||
.environments
|
||||
.as_ref()
|
||||
.map(TurnEnvironmentSnapshot::inheritable_selections);
|
||||
let child_create_started_at = Instant::now();
|
||||
let new_thread = Box::pin(state.spawn_new_thread_with_source(
|
||||
config.clone(),
|
||||
self.clone(),
|
||||
session_source,
|
||||
history_mode,
|
||||
dynamic_tools,
|
||||
options.parent_thread_id,
|
||||
/*forked_from_thread_id*/ None,
|
||||
/*thread_source*/ Some(ThreadSource::Subagent),
|
||||
/*metrics_service_name*/ None,
|
||||
inheritance.environments,
|
||||
inheritance.exec_policy,
|
||||
environments,
|
||||
))
|
||||
.await
|
||||
.map_err(|err| err.with_agent_context(AgentErrorContext::ChildStartup))?;
|
||||
SpawnedThreadResult {
|
||||
new_thread,
|
||||
fork_context: None,
|
||||
child_create: child_create_started_at.elapsed(),
|
||||
}
|
||||
}
|
||||
(None, _, _) => {
|
||||
let child_create_started_at = Instant::now();
|
||||
let new_thread = Box::pin(state.spawn_new_thread(config.clone(), self.clone()))
|
||||
.await
|
||||
.map_err(|err| err.with_agent_context(AgentErrorContext::ChildStartup))?;
|
||||
SpawnedThreadResult {
|
||||
new_thread,
|
||||
fork_context: None,
|
||||
child_create: child_create_started_at.elapsed(),
|
||||
start_options.dynamic_tools = parent_thread.session.dynamic_tools().await;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
(None, _) => None,
|
||||
};
|
||||
let child_create_started_at = Instant::now();
|
||||
let new_thread = state
|
||||
.spawn_child_thread(
|
||||
start_options,
|
||||
self.clone(),
|
||||
parent_thread_id,
|
||||
inherited_exec_policy,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| err.with_agent_context(AgentErrorContext::ChildStartup))?;
|
||||
let child_create = child_create_started_at.elapsed();
|
||||
agent_metadata.agent_id = Some(new_thread.thread_id);
|
||||
let mut pending_spawn =
|
||||
PendingSpawn::new(Arc::clone(&state), new_thread.thread_id, membership);
|
||||
@@ -1010,19 +1003,15 @@ impl LocalAgentControl {
|
||||
Ok((agent, config))
|
||||
}
|
||||
|
||||
async fn spawn_forked_thread(
|
||||
/// Prepare copied history while leaving startup settings and timing with the caller.
|
||||
async fn prepare_forked_history(
|
||||
&self,
|
||||
state: &Arc<ThreadManagerState>,
|
||||
config: Config,
|
||||
session_source: SessionSource,
|
||||
session_source: &SessionSource,
|
||||
options: &SpawnAgentOptions,
|
||||
inheritance: SpawnAgentThreadInheritance,
|
||||
config: &Config,
|
||||
multi_agent_version: MultiAgentVersion,
|
||||
) -> CodexResult<SpawnedThreadResult> {
|
||||
let SpawnAgentThreadInheritance {
|
||||
environments: inherited_environments,
|
||||
exec_policy: inherited_exec_policy,
|
||||
} = inheritance;
|
||||
) -> CodexResult<(InitialHistory, Option<ThreadHistoryMode>)> {
|
||||
if options.fork_parent_spawn_call_id.is_none() {
|
||||
return Err(CodexErr::Fatal(
|
||||
"spawn_agent fork requires a parent spawn call id".to_string(),
|
||||
@@ -1035,14 +1024,13 @@ impl LocalAgentControl {
|
||||
}
|
||||
let SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id, ..
|
||||
}) = &session_source
|
||||
}) = session_source
|
||||
else {
|
||||
return Err(CodexErr::Fatal(
|
||||
"spawn_agent fork requires a thread-spawn session source".to_string(),
|
||||
));
|
||||
};
|
||||
|
||||
let fork_context_started_at = Instant::now();
|
||||
let parent_thread_id = *parent_thread_id;
|
||||
let parent_thread = state.get_thread(parent_thread_id).await?;
|
||||
let (subagent_developer_instructions, parent_developer_instructions) = match (
|
||||
@@ -1091,15 +1079,6 @@ impl LocalAgentControl {
|
||||
})?
|
||||
.items;
|
||||
|
||||
let selected_capability_roots = forked_rollout_items
|
||||
.iter()
|
||||
.find_map(|item| {
|
||||
let RolloutItem::SessionMeta(meta_line) = item else {
|
||||
return None;
|
||||
};
|
||||
Some(meta_line.meta.selected_capability_roots.clone())
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let multi_agent_v2_usage_hint_texts_to_filter: Vec<String> =
|
||||
if multi_agent_version == MultiAgentVersion::V2 {
|
||||
let parent_config = parent_thread.session.get_config().await;
|
||||
@@ -1320,34 +1299,10 @@ impl LocalAgentControl {
|
||||
subagent_usage_hint_message.into(),
|
||||
));
|
||||
}
|
||||
let mut thread_extension_init = ExtensionDataInit::new();
|
||||
thread_extension_init.insert(selected_capability_roots);
|
||||
|
||||
let fork_context = fork_context_started_at.elapsed();
|
||||
let child_create_started_at = Instant::now();
|
||||
let new_thread = state
|
||||
.fork_thread_with_source(
|
||||
config.clone(),
|
||||
InitialHistory::Forked(forked_rollout_items),
|
||||
destination_history_mode,
|
||||
self.clone(),
|
||||
session_source,
|
||||
/*thread_source*/ Some(ThreadSource::Subagent),
|
||||
/*parent_thread_id*/ Some(parent_thread_id),
|
||||
/*forked_from_thread_id*/ Some(parent_thread_id),
|
||||
inherited_environments,
|
||||
inherited_exec_policy,
|
||||
/*environments*/ None,
|
||||
thread_extension_init,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| err.with_agent_context(AgentErrorContext::ChildStartup))?;
|
||||
let child_create = child_create_started_at.elapsed();
|
||||
Ok(SpawnedThreadResult {
|
||||
new_thread,
|
||||
fork_context: Some(fork_context),
|
||||
child_create,
|
||||
})
|
||||
Ok((
|
||||
InitialHistory::Forked(forked_rollout_items),
|
||||
destination_history_mode,
|
||||
))
|
||||
}
|
||||
|
||||
/// Resume an existing agent thread from a recorded rollout file.
|
||||
|
||||
@@ -84,12 +84,14 @@ use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::SubAgentSource;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_protocol::protocol::ThreadSettingsAppliedEvent;
|
||||
use codex_protocol::protocol::ThreadSettingsOverrides;
|
||||
use codex_protocol::protocol::ThreadSettingsSnapshot;
|
||||
use codex_protocol::protocol::TokenUsage;
|
||||
use codex_protocol::protocol::TokenUsageRecord;
|
||||
use codex_protocol::protocol::TurnAbortReason;
|
||||
use codex_protocol::protocol::TurnAbortedEvent;
|
||||
use codex_protocol::protocol::TurnCompleteEvent;
|
||||
use codex_protocol::protocol::TurnEnvironmentRequests;
|
||||
use codex_protocol::protocol::TurnEnvironmentSelection;
|
||||
use codex_protocol::protocol::TurnEnvironmentSelections;
|
||||
use codex_protocol::protocol::TurnStartedEvent;
|
||||
@@ -2194,10 +2196,98 @@ async fn ephemeral_spawn_does_not_persist_agent_graph_edge() {
|
||||
);
|
||||
}
|
||||
|
||||
/// New children inherit omitted plugin choices independently of copied history;
|
||||
/// explicit choices, including an empty list, override the parent's selection.
|
||||
#[test_case::test_case(None, None, vec!["parent-plugin".to_string()]; "fresh inherits")]
|
||||
#[test_case::test_case(None, Some(vec!["child-plugin".to_string()]), vec!["child-plugin".to_string()]; "fresh overrides")]
|
||||
#[test_case::test_case(None, Some(Vec::new()), Vec::new(); "fresh clears")]
|
||||
#[test_case::test_case(Some(SpawnAgentForkMode::FullHistory), None, vec!["parent-plugin".to_string()]; "fork inherits")]
|
||||
#[test_case::test_case(Some(SpawnAgentForkMode::FullHistory), Some(vec!["child-plugin".to_string()]), vec!["child-plugin".to_string()]; "fork overrides")]
|
||||
#[test_case::test_case(Some(SpawnAgentForkMode::FullHistory), Some(Vec::new()), Vec::new(); "fork clears")]
|
||||
#[tokio::test]
|
||||
async fn spawn_agent_fork_from_paginated_parent_uses_model_context_prefix() {
|
||||
async fn spawn_agent_disabled_plugins_follow_parent_unless_overridden(
|
||||
fork_mode: Option<SpawnAgentForkMode>,
|
||||
disabled_plugin_ids: Option<Vec<String>>,
|
||||
expected: Vec<String>,
|
||||
) {
|
||||
let harness = AgentControlHarness::new().await;
|
||||
let (parent_thread_id, parent_thread) = harness.start_paginated_thread().await;
|
||||
let parent = harness
|
||||
.manager
|
||||
.start_thread(StartThreadOptions {
|
||||
history_mode: Some(ThreadHistoryMode::Paginated),
|
||||
environments: Some(Vec::new()),
|
||||
disabled_plugin_ids: Some(vec!["parent-plugin".to_string()]),
|
||||
..StartThreadOptions::new(harness.config.clone())
|
||||
})
|
||||
.await
|
||||
.expect("start parent with a disabled plugin");
|
||||
let parent_spawn_call_id = "spawn-plugin-child";
|
||||
let parent_turn = parent.thread.session.new_default_turn().await;
|
||||
parent
|
||||
.thread
|
||||
.session
|
||||
.record_conversation_items(
|
||||
parent_turn.as_ref(),
|
||||
parent_turn.model_info(),
|
||||
&[spawn_agent_call(parent_spawn_call_id)],
|
||||
)
|
||||
.await;
|
||||
let child_thread_id = harness
|
||||
.spawn_anonymous_child(
|
||||
parent.thread_id,
|
||||
SpawnAgentOptions {
|
||||
fork_parent_spawn_call_id: fork_mode
|
||||
.as_ref()
|
||||
.map(|_| parent_spawn_call_id.to_string()),
|
||||
fork_mode,
|
||||
disabled_plugin_ids,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let child = harness
|
||||
.manager
|
||||
.get_thread(child_thread_id)
|
||||
.await
|
||||
.expect("child should be registered");
|
||||
assert_eq!(
|
||||
child.thread_settings_snapshot().await.disabled_plugin_ids,
|
||||
expected
|
||||
);
|
||||
|
||||
harness
|
||||
.control
|
||||
.shutdown_live_agent(child_thread_id)
|
||||
.await
|
||||
.expect("shut down child");
|
||||
parent
|
||||
.thread
|
||||
.shutdown_and_wait()
|
||||
.await
|
||||
.expect("shut down parent");
|
||||
}
|
||||
|
||||
#[test_case::test_case(false; "parent in session source")]
|
||||
#[test_case::test_case(true; "parent in session source and options")]
|
||||
#[tokio::test]
|
||||
async fn spawn_agent_fork_from_paginated_parent_uses_model_context_prefix(
|
||||
include_parent_in_options: bool,
|
||||
) {
|
||||
let harness = AgentControlHarness::new().await;
|
||||
let client_mcp_extensions =
|
||||
ClientMcpExtensions::new([(OPENAI_FORM_EXTENSION_ID.to_string(), serde_json::json!({}))]);
|
||||
let parent = harness
|
||||
.manager
|
||||
.start_thread(StartThreadOptions {
|
||||
history_mode: Some(ThreadHistoryMode::Paginated),
|
||||
environments: Some(Vec::new()),
|
||||
client_mcp_extensions: client_mcp_extensions.clone(),
|
||||
..StartThreadOptions::new(harness.config.clone())
|
||||
})
|
||||
.await
|
||||
.expect("start paginated parent");
|
||||
let parent_thread_id = parent.thread_id;
|
||||
let parent_thread = parent.thread;
|
||||
parent_thread
|
||||
.inject_response_items(vec![user_message("paginated parent context")])
|
||||
.await
|
||||
@@ -2270,6 +2360,9 @@ async fn spawn_agent_fork_from_paginated_parent_uses_model_context_prefix() {
|
||||
.spawn_anonymous_child(
|
||||
parent_thread_id,
|
||||
SpawnAgentOptions {
|
||||
// The source identifies the parent in both cases. Fork startup must
|
||||
// resolve it before inheriting client MCP settings, not just for metadata.
|
||||
parent_thread_id: include_parent_in_options.then_some(parent_thread_id),
|
||||
fork_parent_spawn_call_id: Some(parent_spawn_call_id),
|
||||
fork_mode: Some(SpawnAgentForkMode::FullHistory),
|
||||
..Default::default()
|
||||
@@ -2307,6 +2400,7 @@ async fn spawn_agent_fork_from_paginated_parent_uses_model_context_prefix() {
|
||||
assert_eq!(meta_line.meta.history_mode, ThreadHistoryMode::Paginated);
|
||||
assert_eq!(meta_line.meta.parent_thread_id, Some(parent_thread_id));
|
||||
assert_eq!(meta_line.meta.forked_from_id, Some(parent_thread_id));
|
||||
assert_eq!(child_thread.client_mcp_extensions(), client_mcp_extensions);
|
||||
let prefix_end = usize::try_from(
|
||||
meta_line
|
||||
.meta
|
||||
@@ -4582,6 +4676,7 @@ async fn spawn_thread_subagent_uses_role_specific_nickname_candidates() {
|
||||
assert_eq!(agent_nickname, Some("Atlas".to_string()));
|
||||
}
|
||||
|
||||
/// Resume restores the child's saved metadata and roots even after its parent deselects an environment.
|
||||
#[tokio::test]
|
||||
async fn resume_thread_subagent_restores_stored_metadata() {
|
||||
let (home, config) = test_config().await;
|
||||
@@ -4612,7 +4707,25 @@ async fn resume_thread_subagent_restores_stored_metadata() {
|
||||
manager,
|
||||
control,
|
||||
};
|
||||
let (parent_thread_id, _parent_thread) = harness.start_thread().await;
|
||||
let roots = vec![SelectedCapabilityRoot {
|
||||
id: "saved-root".to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: codex_exec_server::LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
path: PathUri::from_abs_path(&harness.config.cwd),
|
||||
},
|
||||
}];
|
||||
let mut thread_extension_init = ExtensionDataInit::new();
|
||||
thread_extension_init.insert(roots.clone());
|
||||
let parent = harness
|
||||
.manager
|
||||
.start_thread(StartThreadOptions {
|
||||
thread_extension_init,
|
||||
..StartThreadOptions::new(harness.config.clone())
|
||||
})
|
||||
.await
|
||||
.expect("start parent with roots");
|
||||
let parent_thread_id = parent.thread_id;
|
||||
let parent_thread = parent.thread;
|
||||
let agent_path = AgentPath::from_string("/root/explorer".to_string())
|
||||
.expect("test agent path should be valid");
|
||||
|
||||
@@ -4662,6 +4775,11 @@ async fn resume_thread_subagent_restores_stored_metadata() {
|
||||
.await
|
||||
.expect("child should initialize before shutdown");
|
||||
}
|
||||
let original_environments = child_thread.environment_selections().await;
|
||||
assert_eq!(
|
||||
child_thread.session.services.selected_capability_roots,
|
||||
roots
|
||||
);
|
||||
let original_snapshot = child_thread.config_snapshot().await;
|
||||
let original_nickname = original_snapshot
|
||||
.session_source
|
||||
@@ -4694,6 +4812,26 @@ async fn resume_thread_subagent_restores_stored_metadata() {
|
||||
.await
|
||||
.expect("child shutdown should submit");
|
||||
|
||||
parent_thread
|
||||
.update_thread_settings(ThreadSettingsOverrides {
|
||||
environments: Some(TurnEnvironmentRequests::new(
|
||||
harness.config.cwd.clone(),
|
||||
Vec::new(),
|
||||
)),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.expect("deselect parent environment");
|
||||
// Resume inherits the parent's current attachments, so activate the accepted settings.
|
||||
let parent_turn = parent_thread
|
||||
.session
|
||||
.new_turn_with_default_settings("parent-deselected".to_string(), Default::default())
|
||||
.await;
|
||||
assert_eq!(
|
||||
parent_turn.initial_environments.selected_capability_roots(),
|
||||
Vec::new()
|
||||
);
|
||||
|
||||
let resumed_thread_id = harness
|
||||
.control
|
||||
.resume_agent_from_rollout(
|
||||
@@ -4711,13 +4849,42 @@ async fn resume_thread_subagent_restores_stored_metadata() {
|
||||
.expect("resume should succeed");
|
||||
assert_eq!(resumed_thread_id, child_thread_id);
|
||||
|
||||
let resumed_snapshot = harness
|
||||
let resumed_thread = harness
|
||||
.manager
|
||||
.get_thread(resumed_thread_id)
|
||||
.await
|
||||
.expect("resumed child thread should exist")
|
||||
.config_snapshot()
|
||||
.expect("resumed child thread should exist");
|
||||
assert_eq!(
|
||||
resumed_thread.session.services.selected_capability_roots,
|
||||
roots
|
||||
);
|
||||
resumed_thread
|
||||
.update_thread_settings(ThreadSettingsOverrides {
|
||||
environments: Some(TurnEnvironmentRequests::new(
|
||||
harness.config.cwd.clone(),
|
||||
original_environments
|
||||
.clone()
|
||||
.into_iter()
|
||||
.map(TurnEnvironmentSelection::into_request)
|
||||
.collect(),
|
||||
)),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.expect("reselect child environment");
|
||||
assert_eq!(
|
||||
resumed_thread.environment_selections().await,
|
||||
original_environments
|
||||
);
|
||||
let child_turn = resumed_thread
|
||||
.session
|
||||
.new_turn_with_default_settings("child-reselected".to_string(), Default::default())
|
||||
.await;
|
||||
assert_eq!(
|
||||
child_turn.initial_environments.selected_capability_roots(),
|
||||
roots
|
||||
);
|
||||
let resumed_snapshot = resumed_thread.config_snapshot().await;
|
||||
let SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id: resumed_parent_thread_id,
|
||||
depth: resumed_depth,
|
||||
@@ -4791,8 +4958,10 @@ async fn resume_agent_from_rollout_reads_archived_rollout_path() {
|
||||
.expect("resumed child shutdown should succeed");
|
||||
}
|
||||
|
||||
#[test_case::test_case(vec!["child-plugin".to_string()]; "saved disabled plugin")]
|
||||
#[test_case::test_case(Vec::new(); "saved empty selection")]
|
||||
#[tokio::test]
|
||||
async fn resume_agent_from_paginated_rollout_loads_model_context() {
|
||||
async fn resume_agent_from_paginated_rollout_loads_model_context(disabled_plugin_ids: Vec<String>) {
|
||||
let harness = AgentControlHarness::new().await;
|
||||
let (parent_thread_id, parent_thread) = harness.start_paginated_thread().await;
|
||||
let child_thread_id = harness
|
||||
@@ -4800,6 +4969,7 @@ async fn resume_agent_from_paginated_rollout_loads_model_context() {
|
||||
parent_thread_id,
|
||||
SpawnAgentOptions {
|
||||
parent_thread_id: Some(parent_thread_id),
|
||||
disabled_plugin_ids: Some(disabled_plugin_ids.clone()),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
@@ -4820,6 +4990,15 @@ async fn resume_agent_from_paginated_rollout_loads_model_context() {
|
||||
.await
|
||||
.expect("child shutdown should succeed");
|
||||
|
||||
// Resuming restores the child's saved selection even after its parent changes.
|
||||
parent_thread
|
||||
.update_thread_settings(ThreadSettingsOverrides {
|
||||
disabled_plugin_ids: Some(vec!["parent-plugin".to_string()]),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.expect("change parent plugin selection");
|
||||
|
||||
let resumed_thread_id = harness
|
||||
.control
|
||||
.resume_agent_from_rollout(harness.config.clone(), child_thread_id, SessionSource::Exec)
|
||||
@@ -4831,6 +5010,13 @@ async fn resume_agent_from_paginated_rollout_loads_model_context() {
|
||||
.get_thread(resumed_thread_id)
|
||||
.await
|
||||
.expect("resumed child thread should exist");
|
||||
assert_eq!(
|
||||
resumed_thread
|
||||
.thread_settings_snapshot()
|
||||
.await
|
||||
.disabled_plugin_ids,
|
||||
disabled_plugin_ids
|
||||
);
|
||||
assert!(
|
||||
history_contains_text(
|
||||
resumed_thread.session.clone_history().await.raw_items(),
|
||||
|
||||
@@ -34,6 +34,9 @@ pub struct SpawnAgentOptions {
|
||||
pub root_turn_id: Option<String>,
|
||||
/// Exact environment bindings from the step that requested the child.
|
||||
pub environments: Option<TurnEnvironmentSnapshot>,
|
||||
/// Plugin choices from the turn requesting the child. Omission inherits the parent's
|
||||
/// current choices; an explicit list, including an empty one, overrides them and history.
|
||||
pub disabled_plugin_ids: Option<Vec<String>>,
|
||||
pub multi_agent_v2_usage_hints: Option<ResolvedMultiAgentV2UsageHints>,
|
||||
pub cyber_access_program: Option<CyberAccessProgram>,
|
||||
}
|
||||
|
||||
@@ -113,7 +113,8 @@ pub(crate) async fn run_codex_thread_interactive(
|
||||
code_mode_session_provider: parent_session.services.code_mode_service.session_provider(),
|
||||
extensions,
|
||||
conversation_history,
|
||||
disabled_plugin_ids: None,
|
||||
disabled_plugin_ids: (isolation == codex_extension_api::SessionIsolation::Inherit)
|
||||
.then(|| parent_ctx.disabled_plugin_ids.clone()),
|
||||
requested_history_mode: None,
|
||||
fork_persistence: ForkPersistence::Copied,
|
||||
session_source,
|
||||
|
||||
@@ -4,6 +4,8 @@ use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::ExtensionRegistryBuilder;
|
||||
use codex_extension_api::ThreadLifecycleContributor;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use codex_protocol::error::CodexErrorDetails;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::AgentStatus;
|
||||
@@ -14,6 +16,7 @@ use codex_protocol::protocol::McpStartupUpdateEvent;
|
||||
use codex_protocol::protocol::RawResponseItemEvent;
|
||||
use codex_protocol::protocol::TurnAbortReason;
|
||||
use codex_protocol::protocol::TurnAbortedEvent;
|
||||
use codex_protocol::protocol::TurnEnvironmentSelection;
|
||||
use futures::FutureExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
@@ -313,8 +316,11 @@ async fn delegate_start_analytics_honors_child_opt_out_with_enabled_parent() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn delegate_isolation_does_not_depend_on_attribution() {
|
||||
let (mut parent_session, parent_ctx, _rx_events) =
|
||||
let (mut parent_session, mut parent_ctx, _rx_events) =
|
||||
crate::session::tests::make_session_and_context_with_rx().await;
|
||||
Arc::get_mut(&mut parent_ctx)
|
||||
.expect("parent turn should be uniquely owned")
|
||||
.disabled_plugin_ids = vec!["parent-root".to_string()];
|
||||
let thread_starts = Arc::new(AtomicUsize::new(0));
|
||||
let mut extensions = ExtensionRegistryBuilder::<Config>::new();
|
||||
extensions
|
||||
@@ -324,6 +330,28 @@ async fn delegate_isolation_does_not_depend_on_attribution() {
|
||||
.services
|
||||
.extensions = Arc::new(extensions.build());
|
||||
|
||||
let selection = parent_ctx
|
||||
.initial_environments
|
||||
.inheritable_selections()
|
||||
.into_iter()
|
||||
.next()
|
||||
.expect("parent environment");
|
||||
let root = SelectedCapabilityRoot {
|
||||
id: "parent-root".to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: selection.environment_id.clone(),
|
||||
path: selection.cwd.clone(),
|
||||
},
|
||||
};
|
||||
parent_session
|
||||
.services
|
||||
.turn_environments
|
||||
.update_selections(&[TurnEnvironmentSelection::new(
|
||||
selection.into_request(),
|
||||
std::slice::from_ref(&root),
|
||||
)]);
|
||||
let parent_environments = parent_session.services.turn_environments.snapshot().await;
|
||||
|
||||
for (subagent_source, isolation, expected_thread_starts, expected_thread_source) in [
|
||||
(
|
||||
SubAgentSource::Other(crate::guardian::GUARDIAN_REVIEWER_NAME.to_string()),
|
||||
@@ -352,7 +380,7 @@ async fn delegate_isolation_does_not_depend_on_attribution() {
|
||||
Arc::clone(&parent_session.services.models_manager),
|
||||
Arc::clone(&parent_session),
|
||||
Arc::clone(&parent_ctx),
|
||||
parent_ctx.initial_environments.clone(),
|
||||
parent_environments.clone(),
|
||||
CancellationToken::new(),
|
||||
subagent_source,
|
||||
isolation,
|
||||
@@ -376,6 +404,28 @@ async fn delegate_isolation_does_not_depend_on_attribution() {
|
||||
session.thread_config_snapshot().await.thread_source,
|
||||
Some(expected_thread_source)
|
||||
);
|
||||
let expected_roots = match isolation {
|
||||
codex_extension_api::SessionIsolation::Inherit => vec![root.clone()],
|
||||
codex_extension_api::SessionIsolation::Isolated => Vec::new(),
|
||||
};
|
||||
assert_eq!(session.services.selected_capability_roots, expected_roots);
|
||||
let expected_disabled_plugins = match isolation {
|
||||
codex_extension_api::SessionIsolation::Inherit => vec!["parent-root".to_string()],
|
||||
codex_extension_api::SessionIsolation::Isolated => Vec::new(),
|
||||
};
|
||||
assert_eq!(
|
||||
session.thread_settings_snapshot().await.disabled_plugin_ids,
|
||||
expected_disabled_plugins,
|
||||
);
|
||||
assert_eq!(
|
||||
session
|
||||
.services
|
||||
.turn_environments
|
||||
.snapshot()
|
||||
.await
|
||||
.selected_capability_roots(),
|
||||
expected_roots,
|
||||
);
|
||||
io.shutdown_and_wait()
|
||||
.await
|
||||
.expect("delegate session should shut down");
|
||||
|
||||
@@ -614,7 +614,16 @@ impl Session {
|
||||
match thread_extension_init.get::<Vec<SelectedCapabilityRoot>>() {
|
||||
Some(roots) => roots.as_ref().clone(),
|
||||
None => {
|
||||
let roots = conversation_history.get_selected_capability_roots();
|
||||
// Resume restores this thread's saved roots, including roots for environments
|
||||
// it will select again later. New children inherit roots regardless of copied history.
|
||||
let roots = if !matches!(&conversation_history, InitialHistory::Resumed(_))
|
||||
&& isolation == codex_extension_api::SessionIsolation::Inherit
|
||||
&& let Some(environments) = &inherited_environments
|
||||
{
|
||||
environments.selected_capability_roots()
|
||||
} else {
|
||||
conversation_history.get_selected_capability_roots()
|
||||
};
|
||||
if !roots.is_empty() {
|
||||
thread_extension_init.insert(roots.clone());
|
||||
}
|
||||
|
||||
@@ -1937,67 +1937,26 @@ impl ThreadManagerState {
|
||||
)
|
||||
}
|
||||
|
||||
/// Spawn a new thread with no history using a provided config.
|
||||
pub(crate) async fn spawn_new_thread(
|
||||
/// Start a newly spawned agent. Both history modes use the same options captured
|
||||
/// from the spawning turn; only history ownership and persistence differ.
|
||||
pub(crate) async fn spawn_child_thread(
|
||||
&self,
|
||||
config: Config,
|
||||
mut options: StartThreadOptions,
|
||||
agent_control: LocalAgentControl,
|
||||
) -> CodexResult<NewThread> {
|
||||
Box::pin(self.spawn_new_thread_with_source(
|
||||
config,
|
||||
agent_control,
|
||||
self.session_source.clone(),
|
||||
/*history_mode*/ None,
|
||||
/*dynamic_tools*/ Vec::new(),
|
||||
/*parent_thread_id*/ None,
|
||||
/*forked_from_thread_id*/ None,
|
||||
/*thread_source*/ None,
|
||||
/*metrics_service_name*/ None,
|
||||
/*inherited_environments*/ None,
|
||||
/*inherited_exec_policy*/ None,
|
||||
/*environments*/ None,
|
||||
))
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) async fn spawn_new_thread_with_source(
|
||||
&self,
|
||||
config: Config,
|
||||
agent_control: LocalAgentControl,
|
||||
session_source: SessionSource,
|
||||
history_mode: Option<ThreadHistoryMode>,
|
||||
dynamic_tools: Vec<codex_protocol::dynamic_tools::DynamicToolSpec>,
|
||||
parent_thread_id: Option<ThreadId>,
|
||||
forked_from_thread_id: Option<ThreadId>,
|
||||
thread_source: Option<ThreadSource>,
|
||||
metrics_service_name: Option<String>,
|
||||
inherited_environments: Option<TurnEnvironmentSnapshot>,
|
||||
inherited_exec_policy: Option<Arc<crate::exec_policy::ExecPolicyManager>>,
|
||||
environments: Option<Vec<TurnEnvironmentSelection>>,
|
||||
) -> CodexResult<NewThread> {
|
||||
let client_mcp_extensions = self.client_mcp_extensions_for_child(parent_thread_id).await;
|
||||
let options = StartThreadOptions {
|
||||
history_mode,
|
||||
session_source: Some(session_source),
|
||||
thread_source,
|
||||
metrics_service_name,
|
||||
environments: environments.map(|selections| {
|
||||
selections
|
||||
.into_iter()
|
||||
.map(TurnEnvironmentSelection::into_request)
|
||||
.collect()
|
||||
}),
|
||||
client_mcp_extensions,
|
||||
dynamic_tools,
|
||||
..StartThreadOptions::new(config)
|
||||
};
|
||||
options.client_mcp_extensions =
|
||||
self.client_mcp_extensions_for_child(parent_thread_id).await;
|
||||
let forked = matches!(options.initial_history, InitialHistory::Forked(_));
|
||||
let mut request =
|
||||
ThreadSpawnRequest::new(options, Arc::clone(&self.auth_manager), agent_control);
|
||||
request.parent_thread_id = parent_thread_id;
|
||||
request.forked_from_thread_id = forked_from_thread_id;
|
||||
request.inherited_environments = inherited_environments;
|
||||
request.inherited_exec_policy = inherited_exec_policy;
|
||||
if forked {
|
||||
request.forked_from_thread_id = parent_thread_id;
|
||||
request.fork_persistence = ForkPersistence::CopiedDeferred;
|
||||
}
|
||||
Box::pin(self.spawn_thread(request)).await
|
||||
}
|
||||
|
||||
@@ -2044,48 +2003,6 @@ impl ThreadManagerState {
|
||||
Box::pin(self.spawn_thread(request)).await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) async fn fork_thread_with_source(
|
||||
&self,
|
||||
config: Config,
|
||||
initial_history: InitialHistory,
|
||||
history_mode: Option<ThreadHistoryMode>,
|
||||
agent_control: LocalAgentControl,
|
||||
session_source: SessionSource,
|
||||
thread_source: Option<ThreadSource>,
|
||||
parent_thread_id: Option<ThreadId>,
|
||||
forked_from_thread_id: Option<ThreadId>,
|
||||
inherited_environments: Option<TurnEnvironmentSnapshot>,
|
||||
inherited_exec_policy: Option<Arc<crate::exec_policy::ExecPolicyManager>>,
|
||||
environments: Option<Vec<TurnEnvironmentSelection>>,
|
||||
thread_extension_init: ExtensionDataInit,
|
||||
) -> CodexResult<NewThread> {
|
||||
let client_mcp_extensions = self.client_mcp_extensions_for_child(parent_thread_id).await;
|
||||
let options = StartThreadOptions {
|
||||
initial_history,
|
||||
history_mode,
|
||||
session_source: Some(session_source),
|
||||
thread_source,
|
||||
environments: environments.map(|selections| {
|
||||
selections
|
||||
.into_iter()
|
||||
.map(TurnEnvironmentSelection::into_request)
|
||||
.collect()
|
||||
}),
|
||||
thread_extension_init,
|
||||
client_mcp_extensions,
|
||||
..StartThreadOptions::new(config)
|
||||
};
|
||||
let mut request =
|
||||
ThreadSpawnRequest::new(options, Arc::clone(&self.auth_manager), agent_control);
|
||||
request.fork_persistence = ForkPersistence::CopiedDeferred;
|
||||
request.parent_thread_id = parent_thread_id;
|
||||
request.forked_from_thread_id = forked_from_thread_id;
|
||||
request.inherited_environments = inherited_environments;
|
||||
request.inherited_exec_policy = inherited_exec_policy;
|
||||
Box::pin(self.spawn_thread(request)).await
|
||||
}
|
||||
|
||||
async fn client_mcp_extensions_for_child(
|
||||
&self,
|
||||
parent_thread_id: Option<ThreadId>,
|
||||
|
||||
@@ -14,6 +14,7 @@ use crate::session::tests::make_session_and_context;
|
||||
use crate::tasks::InterruptedTurnHistoryMarker;
|
||||
use crate::tasks::interrupted_turn_history_marker;
|
||||
use crate::windows_sandbox::WindowsSandboxLevelExt;
|
||||
use codex_extension_api::SessionIsolation;
|
||||
use codex_extension_api::empty_extension_registry;
|
||||
use codex_history::InitialHistory;
|
||||
use codex_history::ResumedHistory;
|
||||
@@ -1998,6 +1999,107 @@ async fn selected_capability_roots_round_trip_through_fork() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Shared startup honors explicit root selections and only inherits roots when isolation permits.
|
||||
#[tokio::test]
|
||||
async fn selected_capability_roots_respect_startup_precedence_and_isolation() {
|
||||
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 manager = ThreadManager::with_models_provider_and_home_for_tests(
|
||||
CodexAuth::from_api_key("dummy"),
|
||||
config.model_provider.clone(),
|
||||
config.codex_home.to_path_buf(),
|
||||
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
|
||||
);
|
||||
let root = |id: &str| SelectedCapabilityRoot {
|
||||
id: id.to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: "local".to_string(),
|
||||
path: PathUri::from_abs_path(&config.cwd),
|
||||
},
|
||||
};
|
||||
let mut parent_init = ExtensionDataInit::new();
|
||||
parent_init.insert(vec![root("parent")]);
|
||||
let parent = manager
|
||||
.start_thread(StartThreadOptions {
|
||||
thread_extension_init: parent_init,
|
||||
..StartThreadOptions::new(config.clone())
|
||||
})
|
||||
.await
|
||||
.expect("start parent");
|
||||
let parent_environments = parent
|
||||
.thread
|
||||
.session
|
||||
.services
|
||||
.turn_environments
|
||||
.snapshot()
|
||||
.await;
|
||||
|
||||
for (isolation, explicit_roots, expected_roots) in [
|
||||
(SessionIsolation::Inherit, None, vec![root("parent")]),
|
||||
(
|
||||
SessionIsolation::Inherit,
|
||||
Some(vec![root("explicit")]),
|
||||
vec![root("explicit")],
|
||||
),
|
||||
(SessionIsolation::Inherit, Some(Vec::new()), Vec::new()),
|
||||
(SessionIsolation::Isolated, None, vec![root("saved")]),
|
||||
(
|
||||
SessionIsolation::Isolated,
|
||||
Some(vec![root("explicit")]),
|
||||
vec![root("explicit")],
|
||||
),
|
||||
] {
|
||||
let mut thread_extension_init = ExtensionDataInit::new();
|
||||
thread_extension_init.insert(isolation);
|
||||
if let Some(roots) = explicit_roots {
|
||||
thread_extension_init.insert(roots);
|
||||
}
|
||||
let child = manager
|
||||
.start_thread(StartThreadOptions {
|
||||
initial_history: InitialHistory::Forked(vec![RolloutItem::SessionMeta(
|
||||
SessionMetaLine {
|
||||
meta: SessionMeta {
|
||||
selected_capability_roots: vec![root("saved")],
|
||||
..SessionMeta::default()
|
||||
},
|
||||
git: None,
|
||||
},
|
||||
)]),
|
||||
inherited_environments: Some(parent_environments.clone()),
|
||||
thread_extension_init,
|
||||
..StartThreadOptions::new(config.clone())
|
||||
})
|
||||
.await
|
||||
.expect("start child");
|
||||
assert_eq!(
|
||||
child.thread.session.services.selected_capability_roots,
|
||||
expected_roots
|
||||
);
|
||||
assert_eq!(
|
||||
child
|
||||
.thread
|
||||
.session
|
||||
.services
|
||||
.turn_environments
|
||||
.snapshot()
|
||||
.await
|
||||
.selected_capability_roots(),
|
||||
expected_roots
|
||||
);
|
||||
child.thread.ensure_rollout_materialized().await;
|
||||
child.thread.flush_rollout().await.expect("flush child");
|
||||
let history = RolloutRecorder::get_rollout_history(
|
||||
&child.thread.rollout_path().expect("child rollout path"),
|
||||
)
|
||||
.await
|
||||
.expect("read child rollout");
|
||||
assert_eq!(history.get_selected_capability_roots(), expected_roots);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resume_and_fork_do_not_restore_thread_environments_from_rollout() {
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
|
||||
@@ -132,6 +132,7 @@ async fn handle_spawn_agent(
|
||||
root_turn_id: turn.turn_metadata_state.root_turn_id(),
|
||||
turn_trigger: turn.turn_metadata_state.current_turn_trigger(),
|
||||
environments: Some(step_context.environments.clone()),
|
||||
disabled_plugin_ids: Some(turn.disabled_plugin_ids.clone()),
|
||||
multi_agent_v2_usage_hints: None,
|
||||
cyber_access_program: turn.cyber_access_program,
|
||||
},
|
||||
|
||||
@@ -201,6 +201,7 @@ async fn handle_spawn_agent(
|
||||
root_turn_id: turn.turn_metadata_state.root_turn_id(),
|
||||
turn_trigger: turn.turn_metadata_state.current_turn_trigger(),
|
||||
environments: Some(step_context.environments.clone()),
|
||||
disabled_plugin_ids: Some(turn.disabled_plugin_ids.clone()),
|
||||
multi_agent_v2_usage_hints,
|
||||
cyber_access_program: turn.cyber_access_program,
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user