From b6d6011edba8a4b700017b4e71f8cb3216d25918 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Sun, 22 Feb 2026 14:15:52 +0000 Subject: [PATCH 01/13] feat: fork thread multi agent --- codex-rs/core/src/agent/control.rs | 61 ++++++++++++++++++- codex-rs/core/src/thread_manager.rs | 20 ++++++ .../core/src/tools/handlers/multi_agents.rs | 8 ++- codex-rs/core/src/tools/spec.rs | 9 +++ 4 files changed, 94 insertions(+), 4 deletions(-) diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 7287d2528353..25de04211743 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -4,6 +4,7 @@ use crate::agent::status::is_final; use crate::error::CodexErr; use crate::error::Result as CodexResult; use crate::find_thread_path_by_id_str; +use crate::rollout::RolloutRecorder; use crate::session_prefix::format_subagent_notification_message; use crate::state_db; use crate::thread_manager::ThreadManagerState; @@ -19,6 +20,11 @@ use tokio::sync::watch; const AGENT_NAMES: &str = include_str!("agent_names.txt"); +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct SpawnAgentOptions { + pub(crate) fork_parent_thread: bool, +} + fn agent_nickname_list() -> Vec<&'static str> { AGENT_NAMES .lines() @@ -57,6 +63,17 @@ impl AgentControl { config: crate::config::Config, items: Vec, session_source: Option, + ) -> CodexResult { + self.spawn_agent_with_options(config, items, session_source, SpawnAgentOptions::default()) + .await + } + + pub(crate) async fn spawn_agent_with_options( + &self, + config: crate::config::Config, + items: Vec, + session_source: Option, + options: SpawnAgentOptions, ) -> CodexResult { let state = self.upgrade()?; let mut reservation = self.state.reserve_spawn_slot(config.agent_max_threads)?; @@ -82,9 +99,47 @@ impl AgentControl { // The same `AgentControl` is sent to spawn the thread. let new_thread = match session_source { Some(session_source) => { - state - .spawn_new_thread_with_source(config, self.clone(), session_source, false) - .await? + if options.fork_parent_thread { + let SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + .. + }) = session_source.clone() + else { + return Err(CodexErr::Fatal( + "spawn_agent fork requires a thread-spawn session source".to_string(), + )); + }; + let rollout_path = match state.get_thread(parent_thread_id).await { + Ok(parent_thread) => parent_thread.rollout_path(), + Err(_) => None, + } + .or( + find_thread_path_by_id_str( + config.codex_home.as_path(), + &parent_thread_id.to_string(), + ) + .await?, + ) + .ok_or_else(|| { + CodexErr::Fatal(format!( + "parent thread rollout unavailable for fork: {parent_thread_id}" + )) + })?; + let initial_history = RolloutRecorder::get_rollout_history(&rollout_path).await?; + state + .fork_thread_with_source( + config, + initial_history, + self.clone(), + session_source, + false, + ) + .await? + } else { + state + .spawn_new_thread_with_source(config, self.clone(), session_source, false) + .await? + } } None => state.spawn_new_thread(config, self.clone()).await?, }; diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index cb7c464362a5..42eabe3873c3 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -464,6 +464,26 @@ impl ThreadManagerState { .await } + pub(crate) async fn fork_thread_with_source( + &self, + config: Config, + initial_history: InitialHistory, + agent_control: AgentControl, + session_source: SessionSource, + persist_extended_history: bool, + ) -> CodexResult { + self.spawn_thread_with_source( + config, + initial_history, + Arc::clone(&self.auth_manager), + agent_control, + session_source, + Vec::new(), + persist_extended_history, + ) + .await + } + /// Spawn a new thread with optional history and register it with the manager. pub(crate) async fn spawn_thread( &self, diff --git a/codex-rs/core/src/tools/handlers/multi_agents.rs b/codex-rs/core/src/tools/handlers/multi_agents.rs index 455a209526d1..7c02e210ddad 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents.rs @@ -94,6 +94,7 @@ impl ToolHandler for MultiAgentHandler { mod spawn { use super::*; use crate::agent::role::apply_role_to_config; + use crate::agent::control::SpawnAgentOptions; use crate::agent::exceeds_thread_spawn_depth_limit; use crate::agent::next_thread_spawn_depth; @@ -104,6 +105,8 @@ mod spawn { message: Option, items: Option>, agent_type: Option, + #[serde(default)] + fork_current_thread: bool, } #[derive(Debug, Serialize)] @@ -156,7 +159,7 @@ mod spawn { let result = session .services .agent_control - .spawn_agent( + .spawn_agent_with_options( config, input_items, Some(thread_spawn_source( @@ -164,6 +167,9 @@ mod spawn { child_depth, role_name, )), + SpawnAgentOptions { + fork_parent_thread: args.fork_current_thread, + }, ) .await .map_err(collab_spawn_error); diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index 7bd1fc9788da..86513f7baf85 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -552,6 +552,15 @@ fn create_spawn_agent_tool(config: &ToolsConfig) -> ToolSpec { )), }, ), + ( + "fork_current_thread".to_string(), + JsonSchema::Boolean { + description: Some( + "When true, fork the current thread history into the new agent before sending the initial prompt." + .to_string(), + ), + }, + ), ]); ToolSpec::Function(ResponsesApiTool { From e8de9b8d3f57e05136b59e5d7d6e3d6cb62b71c8 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Sun, 22 Feb 2026 14:21:09 +0000 Subject: [PATCH 02/13] nits --- codex-rs/core/src/agent/control.rs | 85 +++++++++++++++++-- .../core/src/tools/handlers/multi_agents.rs | 2 +- 2 files changed, 79 insertions(+), 8 deletions(-) diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 25de04211743..00ba20449094 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -113,19 +113,18 @@ impl AgentControl { Ok(parent_thread) => parent_thread.rollout_path(), Err(_) => None, } - .or( - find_thread_path_by_id_str( - config.codex_home.as_path(), - &parent_thread_id.to_string(), - ) - .await?, + .or(find_thread_path_by_id_str( + config.codex_home.as_path(), + &parent_thread_id.to_string(), ) + .await?) .ok_or_else(|| { CodexErr::Fatal(format!( "parent thread rollout unavailable for fork: {parent_thread_id}" )) })?; - let initial_history = RolloutRecorder::get_rollout_history(&rollout_path).await?; + let initial_history = + RolloutRecorder::get_rollout_history(&rollout_path).await?; state .fork_thread_with_source( config, @@ -476,6 +475,20 @@ mod tests { }) } + fn history_contains_text(history_items: &[ResponseItem], needle: &str) -> bool { + history_items.iter().any(|item| { + let ResponseItem::Message { content, .. } = item else { + return false; + }; + content.iter().any(|content_item| match content_item { + ContentItem::InputText { text } | ContentItem::OutputText { text } => { + text.contains(needle) + } + ContentItem::InputImage { .. } => false, + }) + }) + } + async fn wait_for_subagent_notification(parent_thread: &Arc) -> bool { let wait = async { loop { @@ -728,6 +741,64 @@ mod tests { assert_eq!(captured, Some(expected)); } + #[tokio::test] + async fn spawn_agent_can_fork_parent_thread_history() { + let harness = AgentControlHarness::new().await; + let (parent_thread_id, parent_thread) = harness.start_thread().await; + parent_thread + .inject_user_message_without_turn("parent seed context".to_string()) + .await; + parent_thread + .codex + .session + .ensure_rollout_materialized() + .await; + parent_thread.codex.session.flush_rollout().await; + + let child_thread_id = harness + .control + .spawn_agent_with_options( + harness.config.clone(), + text_input("child task"), + Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + depth: 1, + agent_nickname: None, + agent_role: None, + })), + SpawnAgentOptions { + fork_parent_thread: true, + }, + ) + .await + .expect("forked spawn should succeed"); + + let child_thread = harness + .manager + .get_thread(child_thread_id) + .await + .expect("child thread should be registered"); + let history_items = child_thread.codex.session.clone_history().await; + assert!(history_contains_text(&history_items, "parent seed context")); + + let expected = ( + child_thread_id, + Op::UserInput { + items: vec![UserInput::Text { + text: "child task".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + }, + ); + let captured = harness + .manager + .captured_ops() + .into_iter() + .find(|entry| *entry == expected); + assert_eq!(captured, Some(expected)); + } + #[tokio::test] async fn spawn_agent_respects_max_threads_limit() { let max_threads = 1usize; diff --git a/codex-rs/core/src/tools/handlers/multi_agents.rs b/codex-rs/core/src/tools/handlers/multi_agents.rs index 7c02e210ddad..9179ce22f7ee 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents.rs @@ -93,8 +93,8 @@ impl ToolHandler for MultiAgentHandler { mod spawn { use super::*; - use crate::agent::role::apply_role_to_config; use crate::agent::control::SpawnAgentOptions; + use crate::agent::role::apply_role_to_config; use crate::agent::exceeds_thread_spawn_depth_limit; use crate::agent::next_thread_spawn_depth; From 1befa182554b17d4fafa9cf0f25abe1e97254b68 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Sun, 22 Feb 2026 14:26:39 +0000 Subject: [PATCH 03/13] nits 2 --- codex-rs/core/src/agent/control.rs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 00ba20449094..89297588490e 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -739,6 +739,16 @@ mod tests { .into_iter() .find(|entry| *entry == expected); assert_eq!(captured, Some(expected)); + + let _ = harness + .control + .shutdown_agent(child_thread_id) + .await + .expect("child shutdown should submit"); + let _ = parent_thread + .submit(Op::Shutdown {}) + .await + .expect("parent shutdown should submit"); } #[tokio::test] @@ -778,8 +788,11 @@ mod tests { .get_thread(child_thread_id) .await .expect("child thread should be registered"); - let history_items = child_thread.codex.session.clone_history().await; - assert!(history_contains_text(&history_items, "parent seed context")); + let history = child_thread.codex.session.clone_history().await; + assert!(history_contains_text( + history.raw_items(), + "parent seed context" + )); let expected = ( child_thread_id, From c449d6b8cf347ad846987d4ca0b72474d4a262c6 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Sun, 22 Feb 2026 14:28:31 +0000 Subject: [PATCH 04/13] nits 3 --- codex-rs/core/src/agent/control.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 89297588490e..a799e9ef96c7 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -739,16 +739,6 @@ mod tests { .into_iter() .find(|entry| *entry == expected); assert_eq!(captured, Some(expected)); - - let _ = harness - .control - .shutdown_agent(child_thread_id) - .await - .expect("child shutdown should submit"); - let _ = parent_thread - .submit(Op::Shutdown {}) - .await - .expect("parent shutdown should submit"); } #[tokio::test] @@ -810,6 +800,16 @@ mod tests { .into_iter() .find(|entry| *entry == expected); assert_eq!(captured, Some(expected)); + + let _ = harness + .control + .shutdown_agent(child_thread_id) + .await + .expect("child shutdown should submit"); + let _ = parent_thread + .submit(Op::Shutdown {}) + .await + .expect("parent shutdown should submit"); } #[tokio::test] From b1f25d096b5aa827474e41421a6280d0ae755dbe Mon Sep 17 00:00:00 2001 From: jif-oai Date: Mon, 23 Feb 2026 10:16:34 +0000 Subject: [PATCH 05/13] fix --- codex-rs/core/src/agent/control.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index a799e9ef96c7..fde2b723d7dc 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -10,6 +10,7 @@ use crate::state_db; use crate::thread_manager::ThreadManagerState; use codex_protocol::ThreadId; use codex_protocol::protocol::Op; +use codex_protocol::protocol::InitialHistory; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::TokenUsage; @@ -123,8 +124,11 @@ impl AgentControl { "parent thread rollout unavailable for fork: {parent_thread_id}" )) })?; - let initial_history = - RolloutRecorder::get_rollout_history(&rollout_path).await?; + let initial_history = InitialHistory::Forked( + RolloutRecorder::get_rollout_history(&rollout_path) + .await? + .get_rollout_items(), + ); state .fork_thread_with_source( config, @@ -778,6 +782,7 @@ mod tests { .get_thread(child_thread_id) .await .expect("child thread should be registered"); + assert_ne!(child_thread_id, parent_thread_id); let history = child_thread.codex.session.clone_history().await; assert!(history_contains_text( history.raw_items(), From aa078d02c7daf8ba7c8e9b36c4fc7894081993b3 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Mon, 23 Feb 2026 10:30:13 +0000 Subject: [PATCH 06/13] fmt --- codex-rs/core/src/agent/control.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index fde2b723d7dc..0dd64b1a5e36 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -9,8 +9,8 @@ use crate::session_prefix::format_subagent_notification_message; use crate::state_db; use crate::thread_manager::ThreadManagerState; use codex_protocol::ThreadId; -use codex_protocol::protocol::Op; use codex_protocol::protocol::InitialHistory; +use codex_protocol::protocol::Op; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::TokenUsage; From f5ff85e89efc4b0a6f91fb605b997630468737e3 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Mon, 23 Feb 2026 18:04:24 +0000 Subject: [PATCH 07/13] better forking mechanism --- codex-rs/core/src/agent/control.rs | 102 +++++++++++++++++- .../core/src/tools/handlers/multi_agents.rs | 5 +- codex-rs/core/src/tools/spec.rs | 4 +- 3 files changed, 103 insertions(+), 8 deletions(-) diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 0dd64b1a5e36..9ee61de47000 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -9,8 +9,11 @@ use crate::session_prefix::format_subagent_notification_message; use crate::state_db; use crate::thread_manager::ThreadManagerState; use codex_protocol::ThreadId; +use codex_protocol::models::FunctionCallOutputPayload; +use codex_protocol::models::ResponseItem; use codex_protocol::protocol::InitialHistory; use codex_protocol::protocol::Op; +use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::TokenUsage; @@ -20,10 +23,12 @@ use std::sync::Weak; use tokio::sync::watch; const AGENT_NAMES: &str = include_str!("agent_names.txt"); +const FORKED_SPAWN_AGENT_OUTPUT_MESSAGE: &str = "You are the newly spawned agent. The prior conversation history was forked from your parent agent. Treat the next user message as your new task, and use the forked history only as background context."; -#[derive(Clone, Copy, Debug, Default)] +#[derive(Clone, Debug, Default)] pub(crate) struct SpawnAgentOptions { pub(crate) fork_parent_thread: bool, + pub(crate) fork_parent_spawn_call_id: Option, } fn agent_nickname_list() -> Vec<&'static str> { @@ -124,11 +129,23 @@ impl AgentControl { "parent thread rollout unavailable for fork: {parent_thread_id}" )) })?; - let initial_history = InitialHistory::Forked( + let mut forked_rollout_items = RolloutRecorder::get_rollout_history(&rollout_path) .await? - .get_rollout_items(), - ); + .get_rollout_items(); + if let Some(call_id) = options.fork_parent_spawn_call_id.as_ref() { + let mut output = FunctionCallOutputPayload::from_text( + FORKED_SPAWN_AGENT_OUTPUT_MESSAGE.to_string(), + ); + output.success = Some(true); + forked_rollout_items.push(RolloutItem::ResponseItem( + ResponseItem::FunctionCallOutput { + call_id: call_id.clone(), + output, + }, + )); + } + let initial_history = InitialHistory::Forked(forked_rollout_items); state .fork_thread_with_source( config, @@ -772,6 +789,7 @@ mod tests { })), SpawnAgentOptions { fork_parent_thread: true, + fork_parent_spawn_call_id: None, }, ) .await @@ -817,6 +835,82 @@ mod tests { .expect("parent shutdown should submit"); } + #[tokio::test] + async fn spawn_agent_fork_injects_output_for_parent_spawn_call() { + let harness = AgentControlHarness::new().await; + let (parent_thread_id, parent_thread) = harness.start_thread().await; + let turn_context = parent_thread.codex.session.new_default_turn().await; + let parent_spawn_call_id = "spawn-call-1".to_string(); + let parent_spawn_call = ResponseItem::FunctionCall { + id: None, + name: "spawn_agent".to_string(), + arguments: "{}".to_string(), + call_id: parent_spawn_call_id.clone(), + }; + parent_thread + .codex + .session + .record_conversation_items(turn_context.as_ref(), &[parent_spawn_call]) + .await; + parent_thread + .codex + .session + .ensure_rollout_materialized() + .await; + parent_thread.codex.session.flush_rollout().await; + + let child_thread_id = harness + .control + .spawn_agent_with_options( + harness.config.clone(), + text_input("child task"), + Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + depth: 1, + agent_nickname: None, + agent_role: None, + })), + SpawnAgentOptions { + fork_parent_thread: true, + fork_parent_spawn_call_id: Some(parent_spawn_call_id.clone()), + }, + ) + .await + .expect("forked spawn should succeed"); + + let child_thread = harness + .manager + .get_thread(child_thread_id) + .await + .expect("child thread should be registered"); + let history = child_thread.codex.session.clone_history().await; + let injected_output = history.raw_items().iter().find_map(|item| match item { + ResponseItem::FunctionCallOutput { call_id, output } + if call_id == &parent_spawn_call_id => + { + Some(output) + } + _ => None, + }); + let injected_output = + injected_output.expect("forked child should contain synthetic tool output"); + assert_eq!( + injected_output.text_content(), + Some(FORKED_SPAWN_AGENT_OUTPUT_MESSAGE) + ); + assert_eq!(injected_output.success, Some(true)); + + let _ = harness + .control + .shutdown_agent(child_thread_id) + .await + .expect("child shutdown should submit"); + let _ = parent_thread + .submit(Op::Shutdown {}) + .await + .expect("parent shutdown should submit"); + } + #[tokio::test] async fn spawn_agent_respects_max_threads_limit() { let max_threads = 1usize; diff --git a/codex-rs/core/src/tools/handlers/multi_agents.rs b/codex-rs/core/src/tools/handlers/multi_agents.rs index 9179ce22f7ee..e93606e2e59c 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents.rs @@ -106,7 +106,7 @@ mod spawn { items: Option>, agent_type: Option, #[serde(default)] - fork_current_thread: bool, + fork_mode: bool, } #[derive(Debug, Serialize)] @@ -168,7 +168,8 @@ mod spawn { role_name, )), SpawnAgentOptions { - fork_parent_thread: args.fork_current_thread, + fork_parent_thread: args.fork_mode, + fork_parent_spawn_call_id: args.fork_mode.then(|| call_id.clone()), }, ) .await diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index 86513f7baf85..8e333a96cae6 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -553,10 +553,10 @@ fn create_spawn_agent_tool(config: &ToolsConfig) -> ToolSpec { }, ), ( - "fork_current_thread".to_string(), + "fork_mode".to_string(), JsonSchema::Boolean { description: Some( - "When true, fork the current thread history into the new agent before sending the initial prompt." + "When true, fork the current thread history into the new agent before sending the initial prompt. This must be used when you want the new agent to have exactly the same context as you." .to_string(), ), }, From eb860909343cf834a5fae3507ca3c08c0b6c260e Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 24 Feb 2026 16:46:27 +0000 Subject: [PATCH 08/13] Flush before fork --- codex-rs/core/src/agent/control.rs | 113 +++++++++++++++++++++++++---- 1 file changed, 100 insertions(+), 13 deletions(-) diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 9ee61de47000..065d5ca7a09d 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -115,20 +115,30 @@ impl AgentControl { "spawn_agent fork requires a thread-spawn session source".to_string(), )); }; - let rollout_path = match state.get_thread(parent_thread_id).await { - Ok(parent_thread) => parent_thread.rollout_path(), - Err(_) => None, + let parent_thread = state.get_thread(parent_thread_id).await.ok(); + if let Some(parent_thread) = parent_thread.as_ref() { + // `record_conversation_items` only queues rollout writes asynchronously. + // Flush/materialize the live parent before snapshotting JSONL for a fork. + parent_thread + .codex + .session + .ensure_rollout_materialized() + .await; + parent_thread.codex.session.flush_rollout().await; } - .or(find_thread_path_by_id_str( - config.codex_home.as_path(), - &parent_thread_id.to_string(), - ) - .await?) - .ok_or_else(|| { - CodexErr::Fatal(format!( - "parent thread rollout unavailable for fork: {parent_thread_id}" - )) - })?; + let rollout_path = parent_thread + .as_ref() + .and_then(|parent_thread| parent_thread.rollout_path()) + .or(find_thread_path_by_id_str( + config.codex_home.as_path(), + &parent_thread_id.to_string(), + ) + .await?) + .ok_or_else(|| { + CodexErr::Fatal(format!( + "parent thread rollout unavailable for fork: {parent_thread_id}" + )) + })?; let mut forked_rollout_items = RolloutRecorder::get_rollout_history(&rollout_path) .await? @@ -911,6 +921,83 @@ mod tests { .expect("parent shutdown should submit"); } + #[tokio::test] + async fn spawn_agent_fork_flushes_parent_rollout_before_loading_history() { + let harness = AgentControlHarness::new().await; + let (parent_thread_id, parent_thread) = harness.start_thread().await; + let turn_context = parent_thread.codex.session.new_default_turn().await; + let parent_spawn_call_id = "spawn-call-unflushed".to_string(); + let parent_spawn_call = ResponseItem::FunctionCall { + id: None, + name: "spawn_agent".to_string(), + arguments: "{}".to_string(), + call_id: parent_spawn_call_id.clone(), + }; + parent_thread + .codex + .session + .record_conversation_items(turn_context.as_ref(), &[parent_spawn_call]) + .await; + + let child_thread_id = harness + .control + .spawn_agent_with_options( + harness.config.clone(), + text_input("child task"), + Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id, + depth: 1, + agent_nickname: None, + agent_role: None, + })), + SpawnAgentOptions { + fork_parent_thread: true, + fork_parent_spawn_call_id: Some(parent_spawn_call_id.clone()), + }, + ) + .await + .expect("forked spawn should flush parent rollout before loading history"); + + let child_thread = harness + .manager + .get_thread(child_thread_id) + .await + .expect("child thread should be registered"); + let history = child_thread.codex.session.clone_history().await; + + let mut parent_call_index = None; + let mut injected_output_index = None; + for (idx, item) in history.raw_items().iter().enumerate() { + match item { + ResponseItem::FunctionCall { call_id, .. } if call_id == &parent_spawn_call_id => { + parent_call_index = Some(idx); + } + ResponseItem::FunctionCallOutput { call_id, .. } + if call_id == &parent_spawn_call_id => + { + injected_output_index = Some(idx); + } + _ => {} + } + } + + let parent_call_index = + parent_call_index.expect("forked child should include the parent spawn_agent call"); + let injected_output_index = injected_output_index + .expect("forked child should include synthetic output for the parent spawn_agent call"); + assert!(parent_call_index < injected_output_index); + + let _ = harness + .control + .shutdown_agent(child_thread_id) + .await + .expect("child shutdown should submit"); + let _ = parent_thread + .submit(Op::Shutdown {}) + .await + .expect("parent shutdown should submit"); + } + #[tokio::test] async fn spawn_agent_respects_max_threads_limit() { let max_threads = 1usize; From 4d9b1aba1f7ada00137a092a5e437533624c0044 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 26 Feb 2026 15:46:24 +0000 Subject: [PATCH 09/13] process comments --- codex-rs/core/src/agent/control.rs | 44 ++++++---- .../core/src/tools/handlers/multi_agents.rs | 5 +- codex-rs/core/src/tools/spec.rs | 2 +- .../tests/suite/subagent_notifications.rs | 83 +++++++++++++++++++ 4 files changed, 112 insertions(+), 22 deletions(-) diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 065d5ca7a09d..7e1a61f29ee1 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -27,7 +27,6 @@ const FORKED_SPAWN_AGENT_OUTPUT_MESSAGE: &str = "You are the newly spawned agent #[derive(Clone, Debug, Default)] pub(crate) struct SpawnAgentOptions { - pub(crate) fork_parent_thread: bool, pub(crate) fork_parent_spawn_call_id: Option, } @@ -105,7 +104,7 @@ impl AgentControl { // The same `AgentControl` is sent to spawn the thread. let new_thread = match session_source { Some(session_source) => { - if options.fork_parent_thread { + if let Some(call_id) = options.fork_parent_spawn_call_id.as_ref() { let SessionSource::SubAgent(SubAgentSource::ThreadSpawn { parent_thread_id, .. @@ -143,18 +142,16 @@ impl AgentControl { RolloutRecorder::get_rollout_history(&rollout_path) .await? .get_rollout_items(); - if let Some(call_id) = options.fork_parent_spawn_call_id.as_ref() { - let mut output = FunctionCallOutputPayload::from_text( - FORKED_SPAWN_AGENT_OUTPUT_MESSAGE.to_string(), - ); - output.success = Some(true); - forked_rollout_items.push(RolloutItem::ResponseItem( - ResponseItem::FunctionCallOutput { - call_id: call_id.clone(), - output, - }, - )); - } + let mut output = FunctionCallOutputPayload::from_text( + FORKED_SPAWN_AGENT_OUTPUT_MESSAGE.to_string(), + ); + output.success = Some(true); + forked_rollout_items.push(RolloutItem::ResponseItem( + ResponseItem::FunctionCallOutput { + call_id: call_id.clone(), + output, + }, + )); let initial_history = InitialHistory::Forked(forked_rollout_items); state .fork_thread_with_source( @@ -506,6 +503,7 @@ mod tests { }) } + /// Returns true when any message item contains `needle` in a text span. fn history_contains_text(history_items: &[ResponseItem], needle: &str) -> bool { history_items.iter().any(|item| { let ResponseItem::Message { content, .. } = item else { @@ -779,6 +777,19 @@ mod tests { parent_thread .inject_user_message_without_turn("parent seed context".to_string()) .await; + let turn_context = parent_thread.codex.session.new_default_turn().await; + let parent_spawn_call_id = "spawn-call-history".to_string(); + let parent_spawn_call = ResponseItem::FunctionCall { + id: None, + name: "spawn_agent".to_string(), + arguments: "{}".to_string(), + call_id: parent_spawn_call_id.clone(), + }; + parent_thread + .codex + .session + .record_conversation_items(turn_context.as_ref(), &[parent_spawn_call]) + .await; parent_thread .codex .session @@ -798,8 +809,7 @@ mod tests { agent_role: None, })), SpawnAgentOptions { - fork_parent_thread: true, - fork_parent_spawn_call_id: None, + fork_parent_spawn_call_id: Some(parent_spawn_call_id), }, ) .await @@ -881,7 +891,6 @@ mod tests { agent_role: None, })), SpawnAgentOptions { - fork_parent_thread: true, fork_parent_spawn_call_id: Some(parent_spawn_call_id.clone()), }, ) @@ -951,7 +960,6 @@ mod tests { agent_role: None, })), SpawnAgentOptions { - fork_parent_thread: true, fork_parent_spawn_call_id: Some(parent_spawn_call_id.clone()), }, ) diff --git a/codex-rs/core/src/tools/handlers/multi_agents.rs b/codex-rs/core/src/tools/handlers/multi_agents.rs index 6d984a7d8bc4..2fd3765c7965 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents.rs @@ -107,7 +107,7 @@ mod spawn { items: Option>, agent_type: Option, #[serde(default)] - fork_mode: bool, + fork_context: bool, } #[derive(Debug, Serialize)] @@ -171,8 +171,7 @@ mod spawn { role_name, )), SpawnAgentOptions { - fork_parent_thread: args.fork_mode, - fork_parent_spawn_call_id: args.fork_mode.then(|| call_id.clone()), + fork_parent_spawn_call_id: args.fork_context.then(|| call_id.clone()), }, ) .await diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index 55498674ab16..5b1878ef5e93 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -553,7 +553,7 @@ fn create_spawn_agent_tool(config: &ToolsConfig) -> ToolSpec { }, ), ( - "fork_mode".to_string(), + "fork_context".to_string(), JsonSchema::Boolean { description: Some( "When true, fork the current thread history into the new agent before sending the initial prompt. This must be used when you want the new agent to have exactly the same context as you." diff --git a/codex-rs/core/tests/suite/subagent_notifications.rs b/codex-rs/core/tests/suite/subagent_notifications.rs index 422510f32864..3b4f4ebe4d1a 100644 --- a/codex-rs/core/tests/suite/subagent_notifications.rs +++ b/codex-rs/core/tests/suite/subagent_notifications.rs @@ -20,6 +20,8 @@ use tokio::time::sleep; use wiremock::MockServer; const SPAWN_CALL_ID: &str = "spawn-call-1"; +const FORKED_SPAWN_AGENT_OUTPUT_MESSAGE: &str = "You are the newly spawned agent. The prior conversation history was forked from your parent agent. Treat the next user message as your new task, and use the forked history only as background context."; +const TURN_0_FORK_PROMPT: &str = "seed fork context"; const TURN_1_PROMPT: &str = "spawn a child and continue"; const TURN_2_NO_WAIT_PROMPT: &str = "follow up without wait"; const CHILD_PROMPT: &str = "child: do work"; @@ -194,3 +196,84 @@ async fn subagent_notification_is_included_without_wait() -> Result<()> { Ok(()) } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn spawned_child_receives_forked_parent_context() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + + let seed_turn = mount_sse_once_match( + &server, + |req: &wiremock::Request| body_contains(req, TURN_0_FORK_PROMPT), + sse(vec![ + ev_response_created("resp-seed-1"), + ev_assistant_message("msg-seed-1", "seeded"), + ev_completed("resp-seed-1"), + ]), + ) + .await; + + let spawn_args = serde_json::to_string(&json!({ + "message": CHILD_PROMPT, + "fork_context": true, + }))?; + let spawn_turn = mount_sse_once_match( + &server, + |req: &wiremock::Request| body_contains(req, TURN_1_PROMPT), + sse(vec![ + ev_response_created("resp-turn1-1"), + ev_function_call(SPAWN_CALL_ID, "spawn_agent", &spawn_args), + ev_completed("resp-turn1-1"), + ]), + ) + .await; + + let child_request_log = mount_sse_once_match( + &server, + |req: &wiremock::Request| { + body_contains(req, CHILD_PROMPT) && !body_contains(req, SPAWN_CALL_ID) + }, + sse(vec![ + ev_response_created("resp-child-1"), + ev_assistant_message("msg-child-1", "child done"), + ev_completed("resp-child-1"), + ]), + ) + .await; + + let _turn1_followup = mount_sse_once_match( + &server, + |req: &wiremock::Request| body_contains(req, SPAWN_CALL_ID), + sse(vec![ + ev_response_created("resp-turn1-2"), + ev_assistant_message("msg-turn1-2", "parent done"), + ev_completed("resp-turn1-2"), + ]), + ) + .await; + + let mut builder = test_codex().with_config(|config| { + config.features.enable(Feature::Collab); + }); + let test = builder.build(&server).await?; + + test.submit_turn(TURN_0_FORK_PROMPT).await?; + let _ = seed_turn.single_request(); + + test.submit_turn(TURN_1_PROMPT).await?; + let _ = spawn_turn.single_request(); + + let child_request = child_request_log.single_request(); + assert!(child_request.body_contains_text(TURN_0_FORK_PROMPT)); + assert!(child_request.body_contains_text("seeded")); + let Some((content, success)) = + child_request.function_call_output_content_and_success(SPAWN_CALL_ID) + else { + panic!("expected forked child request to include synthetic spawn_agent output"); + }; + assert_eq!(content.as_deref(), Some(FORKED_SPAWN_AGENT_OUTPUT_MESSAGE)); + assert_eq!(success, Some(true)); + + Ok(()) +} From d077c5be1f3003f7d84e1796d4999d2c06076de1 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 26 Feb 2026 15:54:02 +0000 Subject: [PATCH 10/13] fix merge --- codex-rs/core/src/agent/control.rs | 2 +- codex-rs/core/src/thread_manager.rs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index ec9694ccc45d..e9a628edf1c7 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -164,7 +164,7 @@ impl AgentControl { .await? } else { state - .spawn_new_thread_with_source(config, self.clone(), session_source, false) + .spawn_new_thread_with_source(config, self.clone(), session_source, false, None) .await? } } diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index 6938ac8567b7..04ae92ce1e07 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -511,6 +511,7 @@ impl ThreadManagerState { session_source, Vec::new(), persist_extended_history, + None ) .await } From 4f6c59e7e8517181f6045b753bc8cb082ccbe81e Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 26 Feb 2026 16:49:34 +0000 Subject: [PATCH 11/13] fix test --- codex-rs/core/src/agent/control.rs | 8 +++++++- codex-rs/core/src/thread_manager.rs | 2 +- .../core/tests/suite/subagent_notifications.rs | 15 ++++++++++++++- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index e9a628edf1c7..bb1488b76118 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -164,7 +164,13 @@ impl AgentControl { .await? } else { state - .spawn_new_thread_with_source(config, self.clone(), session_source, false, None) + .spawn_new_thread_with_source( + config, + self.clone(), + session_source, + false, + None, + ) .await? } } diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index 04ae92ce1e07..ab2e4c2d202b 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -511,7 +511,7 @@ impl ThreadManagerState { session_source, Vec::new(), persist_extended_history, - None + None, ) .await } diff --git a/codex-rs/core/tests/suite/subagent_notifications.rs b/codex-rs/core/tests/suite/subagent_notifications.rs index 3b4f4ebe4d1a..1cc26b825af3 100644 --- a/codex-rs/core/tests/suite/subagent_notifications.rs +++ b/codex-rs/core/tests/suite/subagent_notifications.rs @@ -264,7 +264,20 @@ async fn spawned_child_receives_forked_parent_context() -> Result<()> { test.submit_turn(TURN_1_PROMPT).await?; let _ = spawn_turn.single_request(); - let child_request = child_request_log.single_request(); + let deadline = Instant::now() + Duration::from_secs(2); + let child_request = loop { + if let Some(request) = child_request_log + .requests() + .into_iter() + .find(|request| request.body_contains_text(CHILD_PROMPT)) + { + break request; + } + if Instant::now() >= deadline { + anyhow::bail!("timed out waiting for forked child request"); + } + sleep(Duration::from_millis(10)).await; + }; assert!(child_request.body_contains_text(TURN_0_FORK_PROMPT)); assert!(child_request.body_contains_text("seeded")); let Some((content, success)) = From 2236e584c3dd868021e6ea0406a44a95cd9ef5e2 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 26 Feb 2026 17:02:40 +0000 Subject: [PATCH 12/13] fix test 2 --- .../core/tests/suite/subagent_notifications.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/codex-rs/core/tests/suite/subagent_notifications.rs b/codex-rs/core/tests/suite/subagent_notifications.rs index 1cc26b825af3..b7a94dba0aca 100644 --- a/codex-rs/core/tests/suite/subagent_notifications.rs +++ b/codex-rs/core/tests/suite/subagent_notifications.rs @@ -266,11 +266,16 @@ async fn spawned_child_receives_forked_parent_context() -> Result<()> { let deadline = Instant::now() + Duration::from_secs(2); let child_request = loop { - if let Some(request) = child_request_log - .requests() - .into_iter() - .find(|request| request.body_contains_text(CHILD_PROMPT)) - { + if let Some(request) = child_request_log.requests().into_iter().find(|request| { + request.body_contains_text(CHILD_PROMPT) + && request.body_contains_text(TURN_0_FORK_PROMPT) + && request.body_contains_text("seeded") + && request.function_call_output_content_and_success(SPAWN_CALL_ID) + == Some(( + Some(FORKED_SPAWN_AGENT_OUTPUT_MESSAGE.to_string()), + Some(true), + )) + }) { break request; } if Instant::now() >= deadline { From 1e864b473667ff8fc8225a0bef7a5bbd5e7307c5 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 26 Feb 2026 17:42:00 +0000 Subject: [PATCH 13/13] fix further --- .../tests/suite/subagent_notifications.rs | 58 ++++++++++++------- 1 file changed, 36 insertions(+), 22 deletions(-) diff --git a/codex-rs/core/tests/suite/subagent_notifications.rs b/codex-rs/core/tests/suite/subagent_notifications.rs index b7a94dba0aca..3dc463c4abf0 100644 --- a/codex-rs/core/tests/suite/subagent_notifications.rs +++ b/codex-rs/core/tests/suite/subagent_notifications.rs @@ -229,11 +229,9 @@ async fn spawned_child_receives_forked_parent_context() -> Result<()> { ) .await; - let child_request_log = mount_sse_once_match( + let _child_request_log = mount_sse_once_match( &server, - |req: &wiremock::Request| { - body_contains(req, CHILD_PROMPT) && !body_contains(req, SPAWN_CALL_ID) - }, + |req: &wiremock::Request| body_contains(req, CHILD_PROMPT), sse(vec![ ev_response_created("resp-child-1"), ev_assistant_message("msg-child-1", "child done"), @@ -266,16 +264,16 @@ async fn spawned_child_receives_forked_parent_context() -> Result<()> { let deadline = Instant::now() + Duration::from_secs(2); let child_request = loop { - if let Some(request) = child_request_log.requests().into_iter().find(|request| { - request.body_contains_text(CHILD_PROMPT) - && request.body_contains_text(TURN_0_FORK_PROMPT) - && request.body_contains_text("seeded") - && request.function_call_output_content_and_success(SPAWN_CALL_ID) - == Some(( - Some(FORKED_SPAWN_AGENT_OUTPUT_MESSAGE.to_string()), - Some(true), - )) - }) { + if let Some(request) = server + .received_requests() + .await + .unwrap_or_default() + .into_iter() + .find(|request| { + body_contains(request, CHILD_PROMPT) + && body_contains(request, FORKED_SPAWN_AGENT_OUTPUT_MESSAGE) + }) + { break request; } if Instant::now() >= deadline { @@ -283,15 +281,31 @@ async fn spawned_child_receives_forked_parent_context() -> Result<()> { } sleep(Duration::from_millis(10)).await; }; - assert!(child_request.body_contains_text(TURN_0_FORK_PROMPT)); - assert!(child_request.body_contains_text("seeded")); - let Some((content, success)) = - child_request.function_call_output_content_and_success(SPAWN_CALL_ID) - else { - panic!("expected forked child request to include synthetic spawn_agent output"); + assert!(body_contains(&child_request, TURN_0_FORK_PROMPT)); + assert!(body_contains(&child_request, "seeded")); + + let child_body = child_request + .body_json::() + .expect("forked child request body should be json"); + let function_call_output = child_body["input"] + .as_array() + .and_then(|items| { + items.iter().find(|item| { + item["type"].as_str() == Some("function_call_output") + && item["call_id"].as_str() == Some(SPAWN_CALL_ID) + }) + }) + .unwrap_or_else(|| panic!("expected forked child request to include spawn_agent output")); + let (content, success) = match &function_call_output["output"] { + serde_json::Value::String(text) => (Some(text.as_str()), None), + serde_json::Value::Object(output) => ( + output.get("content").and_then(serde_json::Value::as_str), + output.get("success").and_then(serde_json::Value::as_bool), + ), + _ => (None, None), }; - assert_eq!(content.as_deref(), Some(FORKED_SPAWN_AGENT_OUTPUT_MESSAGE)); - assert_eq!(success, Some(true)); + assert_eq!(content, Some(FORKED_SPAWN_AGENT_OUTPUT_MESSAGE)); + assert_ne!(success, Some(false)); Ok(()) }