Preserve client attribution when spawning subagents (#62072)

## Why

Delegated work should retain client attribution such as `cost_center` from the turn that requested it, even when a yielded code-mode cell spawns its child after a newer parent turn starts.

## What changed

Capture client metadata from the originating turn and apply it to the child's initial turn in both legacy and v2 agent spawning. Children and grandchildren retain the captured values when the parent is later steered with updated metadata.

Exclude `misalignment_override`, `parent_response_id`, and `mcp_request_meta` from inheritance, while preserving each child's own thread and turn identifiers.

## Testing

Add coverage for metadata filtering and snapshot isolation, legacy and v2 spawning with fresh or forked history, grandchild inheritance, and spawning from a yielded code-mode cell after the parent advances to another turn.

GitOrigin-RevId: 8c378c49239ccfac03deb2b793fc69aba1d41644
This commit is contained in:
jif
2026-11-17 16:15:55 +00:00
committed by copyberry
parent cac9284d24
commit 02d60fb5cc
11 changed files with 353 additions and 4 deletions
@@ -20,6 +20,7 @@ use codex_app_server_protocol::TurnStartResponse;
use codex_app_server_protocol::TurnSteerParams;
use codex_app_server_protocol::TurnSteerResponse;
use codex_app_server_protocol::UserInput as V2UserInput;
use codex_features::Feature;
use codex_protocol::ThreadId as CoreThreadId;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
@@ -623,6 +624,197 @@ async fn turn_steer_updates_client_metadata_on_follow_up_responses_request_v2(
Ok(())
}
#[test_case::test_case(false, "none"; "legacy")]
#[test_case::test_case(true, "none"; "v2 fresh")]
#[test_case::test_case(true, "all"; "v2 fork")]
#[tokio::test]
async fn subagents_inherit_spawn_metadata_without_live_parent_updates(
multi_agent_v2: bool,
fork_turns: &str,
) -> Result<()> {
skip_if_no_network!(Ok(()));
let spawn_args = if multi_agent_v2 {
json!({"task_name": "worker", "message": "Inspect the example", "fork_turns": fork_turns})
} else {
json!({"message": "Inspect the example"})
};
let namespace = if multi_agent_v2 {
"collaboration"
} else {
"multi_agent_v1"
};
let parent_wait = responses::ev_completed("parent-wait");
let child_wait = responses::ev_response_created("child-spawn");
let server = responses::start_websocket_server(vec![
vec![
vec![responses::ev_completed("parent-warm")],
vec![
responses::ev_function_call_with_namespace(
"spawn-worker",
namespace,
"spawn_agent",
&spawn_args.to_string(),
),
responses::ev_completed("parent-spawn"),
],
vec![parent_wait.clone()],
],
vec![
vec![responses::ev_completed("child-warm")],
vec![
child_wait.clone(),
responses::ev_function_call_with_namespace(
"spawn-grandchild",
namespace,
"spawn_agent",
&spawn_args.to_string(),
),
responses::ev_completed("child-spawn"),
],
vec![responses::ev_completed("child-done")],
],
vec![
vec![responses::ev_completed("grandchild-warm")],
vec![responses::ev_completed("grandchild-done")],
],
])
.await;
let _hold_parent = server.gate_response_event(&parent_wait);
let release_child = server.gate_response_event(&child_wait);
let codex_home = TempDir::new()?;
MockResponsesConfig::new(&server.uri().replacen("ws://", "http://", 1))
.with_model(if multi_agent_v2 {
"gpt-5.6-sol"
} else {
"gpt-5.6-luna"
})
.with_provider_config("supports_websockets = true")
.with_provider_config("supports_standalone_web_search = true")
.enable_feature(Feature::StandaloneWebSearch)
.with_root_config("web_search = \"live\"\ntools.client_search_provider = \"standalone\"")
.with_extra_config(&format!(
"[agents]\nmax_depth = 3\n[features.multi_agent_v2]\nenabled = {multi_agent_v2}"
))
.write(codex_home.path())?;
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
.await?;
let thread_req = app_server
.send_thread_start_request_with_auto_env(ThreadStartParams::default())
.await?;
let ThreadStartResponse { thread, .. } =
timeout(DEFAULT_READ_TIMEOUT, app_server.read_response(thread_req)).await??;
let turn_req = app_server
.send_turn_start_request(TurnStartParams {
thread_id: thread.id.clone(),
input: vec![V2UserInput::Text {
text: "Delegate the example".to_string(),
text_elements: Vec::new(),
}],
responsesapi_client_metadata: Some(HashMap::from([
("cost_center".to_string(), "before".to_string()),
("thread_id".to_string(), "spoofed-thread".to_string()),
("turn_id".to_string(), "spoofed-turn".to_string()),
("parent_response_id".to_string(), "root-only".to_string()),
(
"mcp_request_meta".to_string(),
r#"{"selected_connector_ids":["parent-connector"]}"#.to_string(),
),
(
"misalignment_override".to_string(),
r#"{"review_target":"root-only"}"#.to_string(),
),
])),
..Default::default()
})
.await?;
let TurnStartResponse { turn } =
timeout(DEFAULT_READ_TIMEOUT, app_server.read_response(turn_req)).await??;
let child_first = timeout(
DEFAULT_READ_TIMEOUT,
server.wait_for_request(/*connection_index*/ 1, /*request_index*/ 1),
)
.await?;
let steer_req = app_server
.send_turn_steer_request(TurnSteerParams {
thread_id: thread.id.clone(),
client_user_message_id: None,
expected_turn_id: turn.id.clone(),
input: vec![V2UserInput::Text {
text: "Update cost attribution".to_string(),
text_elements: Vec::new(),
}],
responsesapi_client_metadata: Some(HashMap::from([(
"cost_center".to_string(),
"after".to_string(),
)])),
responsesapi_client_metadata_patch: None,
additional_context: None,
})
.await?;
let _: TurnSteerResponse =
timeout(DEFAULT_READ_TIMEOUT, app_server.read_response(steer_req)).await??;
release_child.send(()).expect("child response is waiting");
let child_next = timeout(
DEFAULT_READ_TIMEOUT,
server.wait_for_request(/*connection_index*/ 1, /*request_index*/ 2),
)
.await?;
let grandchild = timeout(
DEFAULT_READ_TIMEOUT,
server.wait_for_request(/*connection_index*/ 2, /*request_index*/ 1),
)
.await?;
for request in [&child_first, &grandchild] {
let body = request.body_json();
let tools = body["input"]
.as_array()
.and_then(|items| {
items
.iter()
.rev()
.find(|item| item["type"] == "additional_tools")
})
.unwrap_or(&body);
assert!(tools.to_string().contains("### `web__run`"));
}
let metadata = [child_first, child_next, grandchild].map(|request| {
let body = request.body_json();
let metadata = parse_json_header(
body["client_metadata"]["x-codex-turn-metadata"]
.as_str()
.expect("canonical turn metadata"),
);
assert_eq!(metadata["thread_id"], body["client_metadata"]["thread_id"]);
assert_eq!(metadata["turn_id"], body["client_metadata"]["turn_id"]);
assert_ne!(metadata["thread_id"], json!(thread.id));
assert_ne!(metadata["turn_id"], json!(turn.id));
assert_ne!(metadata["thread_id"], json!("spoofed-thread"));
assert_ne!(metadata["turn_id"], json!("spoofed-turn"));
metadata
});
assert_eq!(
metadata.each_ref().map(|metadata| (
metadata["cost_center"].as_str(),
metadata["misalignment_override"].as_str(),
metadata["parent_response_id"].as_str(),
metadata["mcp_request_meta"].as_str(),
)),
[(Some("before"), None, None, None); 3],
);
assert_eq!(metadata[0]["turn_id"], metadata[1]["turn_id"]);
assert_eq!(metadata[0]["parent_turn_id"], json!(turn.id));
assert_eq!(metadata[2]["parent_turn_id"], metadata[0]["turn_id"]);
assert_ne!(metadata[2]["thread_id"], metadata[0]["thread_id"]);
assert_ne!(metadata[2]["turn_id"], metadata[0]["turn_id"]);
Ok(())
}
#[tokio::test]
async fn turn_start_forwards_client_metadata_to_responses_websocket_request_body_v2() -> Result<()>
{
+1
View File
@@ -994,6 +994,7 @@ impl LocalAgentControl {
turn_trigger: options.turn_trigger,
root_turn_id: options.root_turn_id,
cyber_access_program,
inherited_client_metadata: options.inherited_client_metadata,
..Default::default()
};
let input_admission_started_at = Instant::now();
+3
View File
@@ -7,6 +7,7 @@ use codex_protocol::AgentPath;
use codex_protocol::ThreadId;
use codex_protocol::protocol::AgentStatus;
use codex_protocol::turn_input::CyberAccessProgram;
use std::collections::HashMap;
/// Registry identity shared by loaded and unloaded agents.
/// Registered agents have an `agent_id`; a reserved spawn can still be awaiting its ID.
@@ -41,6 +42,8 @@ pub struct SpawnAgentOptions {
/// Attribute delegated usage to the turn that initiated it.
pub turn_trigger: Option<String>,
pub root_turn_id: Option<String>,
/// Client attribution captured from the turn that requested the child.
pub inherited_client_metadata: HashMap<String, String>,
/// Inheritable bindings captured by the step that requested the child.
pub environments: Option<TurnEnvironmentSnapshot>,
/// Plugin choices from the turn requesting the child. Omission inherits the parent's
+7
View File
@@ -160,6 +160,7 @@ impl PreparedTurnInputSettings {
initiating_agent_path,
root_turn_id,
cyber_access_program,
inherited_client_metadata,
} = self.start_options;
let helper_admission =
if kind == TurnStartKind::User && turn_trigger.as_deref() != Some("queue") {
@@ -203,6 +204,12 @@ impl PreparedTurnInputSettings {
let Some((turn_context, settings_snapshot)) = turn_context else {
return Ok(None);
};
turn_context
.turn_metadata_state
.update_responsesapi_client_metadata(ResponsesApiClientMetadataUpdate {
replacement: Some(inherited_client_metadata),
..Default::default()
});
if let Some(turn_trigger) = turn_trigger {
turn_context
.turn_metadata_state
+8
View File
@@ -641,6 +641,14 @@ impl Session {
if let Some(id) = start_options.root_turn_id {
turn_context.turn_metadata_state.set_root_turn_id(id);
}
turn_context
.turn_metadata_state
.update_responsesapi_client_metadata(
codex_protocol::turn_input::ResponsesApiClientMetadataUpdate {
replacement: Some(start_options.inherited_client_metadata),
..Default::default()
},
);
self.maybe_emit_model_warnings_for_turn(turn_context.as_ref())
.await;
// Context construction can outlive an interrupt or replacement. Do not let
+1
View File
@@ -204,6 +204,7 @@ pub(crate) async fn prepare(
parent_thread_id: Some(session.thread_id),
parent_turn_id: Some(turn.sub_id.clone()),
root_turn_id: turn.turn_metadata_state.root_turn_id(),
inherited_client_metadata: turn.turn_metadata_state.client_metadata_for_child(),
turn_trigger: turn.turn_metadata_state.current_turn_trigger(),
environments: Some(step_context.inherited_environments.clone()),
disabled_plugin_ids: Some(turn.disabled_plugin_ids.clone()),
@@ -138,6 +138,7 @@ async fn handle_spawn_agent(
parent_thread_id: Some(session.thread_id),
parent_turn_id: Some(turn.sub_id.clone()),
root_turn_id: turn.turn_metadata_state.root_turn_id(),
inherited_client_metadata: turn.turn_metadata_state.client_metadata_for_child(),
turn_trigger: turn.turn_metadata_state.current_turn_trigger(),
environments: Some(step_context.inherited_environments.clone()),
disabled_plugin_ids: Some(turn.disabled_plugin_ids.clone()),
+17
View File
@@ -1,4 +1,5 @@
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::future::Future;
use std::path::PathBuf;
use std::sync::Arc;
@@ -387,6 +388,22 @@ impl TurnMetadataState {
self.update_responsesapi_client_metadata(update);
}
/// Capture client attribution without carrying the parent's review or routing intent.
pub(crate) fn client_metadata_for_child(&self) -> HashMap<String, String> {
self.responsesapi_client_metadata
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.iter()
.filter(|(key, _)| {
!matches!(
key.as_str(),
"misalignment_override" | "parent_response_id" | "mcp_request_meta"
)
})
.map(|(key, value)| (key.clone(), value.clone()))
.collect()
}
pub(crate) fn update_responsesapi_client_metadata(
&self,
update: ResponsesApiClientMetadataUpdate,
+40
View File
@@ -830,6 +830,46 @@ fn turn_metadata_state_marks_user_input_requested_during_turn_only_for_mcp_reque
);
}
#[tokio::test]
async fn child_metadata_snapshot_excludes_parent_review_and_routing_fields() {
let (_, turn) = make_session_and_context().await;
let state = &turn.turn_metadata_state;
let client_metadata = HashMap::from([
("cost_center".to_string(), "before".to_string()),
("thread_id".to_string(), "parent-thread".to_string()),
("turn_id".to_string(), "parent-turn".to_string()),
(
"mcp_request_meta".to_string(),
r#"{"selected_connector_ids":["parent-connector"]}"#.to_string(),
),
(
"parent_response_id".to_string(),
"parent-response".to_string(),
),
(
"misalignment_override".to_string(),
r#"{"review_target":"parent-only"}"#.to_string(),
),
]);
state.update_responsesapi_client_metadata(ResponsesApiClientMetadataUpdate {
replacement: Some(client_metadata),
..Default::default()
});
let snapshot = state.client_metadata_for_child();
state.update_responsesapi_client_metadata(ResponsesApiClientMetadataUpdate {
patch: Some(HashMap::from([(
"cost_center".to_string(),
"after".to_string(),
)])),
..Default::default()
});
assert_eq!(
[snapshot, state.client_metadata_for_child()],
["before", "after"]
.map(|value| HashMap::from([("cost_center".to_string(), value.to_string(),)])),
);
}
#[test]
fn turn_metadata_state_ignores_client_reserved_metadata_before_start() {
let temp_dir = TempDir::new().expect("temp dir");
@@ -1,9 +1,11 @@
//! Exec-spawned tasks reach the child model as attributed plaintext.
//! Exec-spawned tasks retain their originating turn's attribution and plaintext input.
use anyhow::Result;
use codex_features::Feature;
use codex_protocol::openai_models::ToolMode;
use codex_protocol::protocol::EventMsg;
use codex_protocol::turn_input::TurnInputRequest;
use codex_protocol::user_input::UserInput;
use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_custom_tool_call;
@@ -19,10 +21,11 @@ use core_test_support::wait_for_event;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::collections::HashMap;
use wiremock::matchers::header;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn code_mode_spawn_delivers_plaintext() -> Result<()> {
async fn yielded_code_mode_spawn_preserves_metadata_and_plaintext() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
@@ -31,6 +34,9 @@ async fn code_mode_spawn_delivers_plaintext() -> Result<()> {
.with_model_info_override("gpt-5.6-sol", |model| {
model.tool_mode = Some(ToolMode::CodeMode);
model.use_responses_lite = true;
model
.experimental_supported_tools
.push("test_sync_tool".to_string());
})
.with_config(|config| {
for feature in [
@@ -50,6 +56,14 @@ async fn code_mode_spawn_delivers_plaintext() -> Result<()> {
.await?;
let root_header = test.session_configured.thread_id.to_string();
let mut created = test.thread_manager.subscribe_thread_created();
// Keep the old cell blocked until the next turn is executing, then keep that
// turn active until the old cell has spawned its child.
let start_barrier = r#"await tools.test_sync_tool({barrier: {
id: "spawn-origin", participants: 2, timeout_ms: 60000
}});"#;
let done_barrier = r#"await tools.test_sync_tool({barrier: {
id: "spawn-finished", participants: 2, timeout_ms: 60000
}});"#;
mount_sse_once_match(
&server,
@@ -59,12 +73,53 @@ async fn code_mode_spawn_delivers_plaintext() -> Result<()> {
ev_custom_tool_call(
"spawn-worker",
"exec",
r#"text(await tools.collaboration__spawn_agent({task_name: "worker", message: "Summarize the three stories.", fork_turns: "all"}));"#,
&format!(r#"yield_control();
{start_barrier}
text(await tools.collaboration__spawn_agent({{task_name: "worker", message: "Summarize the three stories.", fork_turns: "all"}}));
{done_barrier}"#),
),
ev_completed("spawn"),
]),
)
.await;
mount_sse_once_match(
&server,
header("thread-id", root_header.as_str()),
sse(vec![
ev_assistant_message("yielded", "Waiting for the next turn."),
ev_completed("yielded"),
]),
)
.await;
test.codex
.start_or_steer_turn(
TurnInputRequest::user_input(vec![UserInput::Text {
text: "Delegate the summary task.".to_string(),
text_elements: Vec::new(),
}])
.with_responses_metadata(Some(HashMap::from([(
"cost_center".to_string(),
"origin".to_string(),
)]))),
)
.await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
mount_sse_once_match(
&server,
header("thread-id", root_header.as_str()),
sse(vec![
ev_custom_tool_call(
"release-worker",
"exec",
&format!("{start_barrier}\n{done_barrier}"),
),
ev_completed("release-worker"),
]),
)
.await;
mount_sse_once_match(
&server,
header("thread-id", root_header.as_str()),
@@ -85,7 +140,22 @@ async fn code_mode_spawn_delivers_plaintext() -> Result<()> {
sse(vec![ev_response_created("child"), ev_completed("child")]),
)
.await;
test.submit_turn("Delegate the summary task.").await?;
test.codex
.start_or_steer_turn(
TurnInputRequest::user_input(vec![UserInput::Text {
text: "Release the previous turn's cell.".to_string(),
text_elements: Vec::new(),
}])
.with_responses_metadata(Some(HashMap::from([(
"cost_center".to_string(),
"current".to_string(),
)]))),
)
.await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
let child_id = created.try_recv()?;
let child = test.thread_manager.get_thread(child_id).await?;
wait_for_event(&child, |event| matches!(event, EventMsg::TurnComplete(_))).await;
@@ -95,6 +165,12 @@ async fn code_mode_spawn_delivers_plaintext() -> Result<()> {
.into_iter()
.find(|request| request.header("thread-id") == Some(child_id.to_string()))
.expect("child receives its task");
let child_metadata: Value = serde_json::from_str(
child_request.body_json()["client_metadata"]["x-codex-turn-metadata"]
.as_str()
.expect("canonical child metadata"),
)?;
assert_eq!(child_metadata["cost_center"], "origin");
assert_eq!(
strip_response_item_ids_from_json(strip_metadata_from_json(Value::Array(
child_request.inputs_of_type("agent_message"),
+3
View File
@@ -307,6 +307,9 @@ pub struct TurnStartOptions {
/// Explicit cyber treatment for this turn. Omission preserves the backend's
/// automatic behavior.
pub cyber_access_program: Option<CyberAccessProgram>,
/// Client attribution copied when spawning a child. Applied only to its initial
/// turn; later parent updates do not change this snapshot.
pub inherited_client_metadata: HashMap<String, String>,
}
/// What Core did with input submitted through `start_or_steer_turn`.