mirror of
https://github.com/openai/codex.git
synced 2026-11-25 23:30:49 +00:00
Add opt-in item-boundary interrupts for subagents (#61909)
## What changed Add the multi-agent v2 setting `interrupt_at_item_boundary`, disabled by default. When enabled, `interrupt_agent` lets a subagent finish and retain its current output item while cancelling tools immediately. Later output items are discarded, and retained tool calls that have not run receive an aborted result. Wait for the interrupted turn's terminal event before starting follow-up input, and prevent idle contributors from restarting the interrupted child. ## Testing Add streaming tests for retaining an assistant message or tool call, discarding later output, and preserving history and follow-up input when the child resumes. Update configuration and interrupt-routing tests. GitOrigin-RevId: 8b2b9b1383bfb4eefea7369a40012bebc5fff07b
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
//! Pending mail survives eviction without loading idle recipients.
|
||||
//! Child history survives interruption and pending mail survives eviction.
|
||||
|
||||
use super::*;
|
||||
use crate::suite::settings_commits::COMMITTED_MODEL;
|
||||
@@ -10,12 +10,16 @@ use codex_extension_api::MessageLifecycleInput;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::AgentStatus;
|
||||
use codex_protocol::protocol::Op;
|
||||
use codex_protocol::protocol::TurnAbortReason;
|
||||
use core_test_support::ThreadIdle;
|
||||
use core_test_support::streaming_sse::StreamingSseChunk;
|
||||
use core_test_support::streaming_sse::start_streaming_sse_server;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::mpsc;
|
||||
use test_case::test_case;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -34,6 +38,161 @@ impl MessageLifecycleContributor for Messages {
|
||||
}
|
||||
}
|
||||
|
||||
#[test_case(ev_assistant_message("sampled", "Keep this answer."); "message")]
|
||||
#[test_case(ev_function_call_with_namespace("sampled", MULTI_AGENT_V2_NAMESPACE, "send_message",
|
||||
r#"{"target":"/root","message":"Should never be sent."}"#); "tool")]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn interrupt_retains_one_sampled_item(mut done: serde_json::Value) -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
done["item"]["id"] = json!("sampled");
|
||||
if done["item"]["type"] == "message" {
|
||||
done["item"]["phase"] = json!("final_answer");
|
||||
}
|
||||
let chunk = |gate, events| StreamingSseChunk {
|
||||
gate,
|
||||
body: sse(events),
|
||||
};
|
||||
let complete = |id| vec![chunk(None, vec![ev_completed(id)])];
|
||||
let call =
|
||||
|name, args| ev_function_call_with_namespace(name, MULTI_AGENT_V2_NAMESPACE, name, args);
|
||||
let (spawned, spawn_gate) = oneshot::channel();
|
||||
let (release_item, item_gate) = oneshot::channel();
|
||||
let (_finish_response, response_gate) = oneshot::channel();
|
||||
let (server, _) = start_streaming_sse_server(vec![
|
||||
vec![
|
||||
chunk(
|
||||
None,
|
||||
vec![call(
|
||||
"spawn_agent",
|
||||
r#"{"task_name":"worker","message":"Work","fork_turns":"none"}"#,
|
||||
)],
|
||||
),
|
||||
chunk(Some(spawn_gate), vec![ev_completed("spawn")]),
|
||||
],
|
||||
vec![
|
||||
chunk(None, vec![ev_response_created("child")]),
|
||||
chunk(
|
||||
Some(item_gate),
|
||||
vec![done.clone(), ev_assistant_message("later", "Discard this.")],
|
||||
),
|
||||
chunk(Some(response_gate), vec![ev_completed("child")]),
|
||||
],
|
||||
vec![chunk(
|
||||
None,
|
||||
vec![
|
||||
call("interrupt_agent", r#"{"target":"worker"}"#),
|
||||
ev_completed("interrupt"),
|
||||
],
|
||||
)],
|
||||
complete("interrupt-result"),
|
||||
complete("resume"),
|
||||
])
|
||||
.await;
|
||||
let test = test_codex()
|
||||
.with_model("gpt-5.6-sol")
|
||||
.with_config(|config| {
|
||||
config
|
||||
.features
|
||||
.enable(Feature::MultiAgentV2)
|
||||
.expect("enable the parent collaboration tools");
|
||||
config
|
||||
.features
|
||||
.disable(Feature::EnableRequestCompression)
|
||||
.expect("capture uncompressed request bodies");
|
||||
config
|
||||
.features
|
||||
.disable(Feature::WakeOnAgentMessages)
|
||||
.expect("keep the parent idle after interrupting the child");
|
||||
config.multi_agent_v2.interrupt_at_item_boundary = true;
|
||||
})
|
||||
.build_with_streaming_server(&server)
|
||||
.await?;
|
||||
let mut created = test.thread_manager.subscribe_thread_created();
|
||||
let (spawn, ()) = tokio::join!(test.submit_turn(FIRST_PROMPT), async {
|
||||
server.wait_for_request_count(/*count*/ 2).await;
|
||||
spawned
|
||||
.send(())
|
||||
.expect("release the parent after the child starts sampling");
|
||||
});
|
||||
spawn?;
|
||||
let child = test
|
||||
.thread_manager
|
||||
.get_thread(created.recv().await?)
|
||||
.await?;
|
||||
// The settings reply confirms the child accepted the interrupt while its item is held.
|
||||
child
|
||||
.update_thread_settings(ThreadSettingsOverrides::default())
|
||||
.await?;
|
||||
wait_for_event(&child, |event| matches!(event, EventMsg::TurnStarted(_))).await;
|
||||
let (reply, resumed) = oneshot::channel();
|
||||
child
|
||||
.submit(Op::TurnInput {
|
||||
request: Box::new(codex_core::TurnInputRequest::user_input(vec![
|
||||
codex_protocol::user_input::UserInput::Text {
|
||||
text: "Resume.".into(),
|
||||
text_elements: vec![],
|
||||
},
|
||||
])),
|
||||
mode: codex_protocol::turn_input::TurnInputMode::StartOrSteer,
|
||||
reply,
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(child.agent_status().await, AgentStatus::Running);
|
||||
release_item.send(()).expect("release the sampled item");
|
||||
let next = |event: &EventMsg| match event {
|
||||
EventMsg::RawResponseItem(raw) => raw.item.id().is_some_and(|id| id.as_str() == "sampled"),
|
||||
EventMsg::TurnStarted(_) | EventMsg::TurnAborted(_) | EventMsg::TurnComplete(_) => true,
|
||||
_ => false,
|
||||
};
|
||||
assert!(matches!(
|
||||
wait_for_event(&child, next).await,
|
||||
EventMsg::RawResponseItem(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
wait_for_event(&child, next).await,
|
||||
EventMsg::TurnAborted(event) if event.reason == TurnAbortReason::Interrupted
|
||||
));
|
||||
assert!(matches!(
|
||||
resumed.await??,
|
||||
codex_core::TurnInputSubmission::Started { .. }
|
||||
));
|
||||
wait_for_event(&child, |event| matches!(event, EventMsg::TurnStarted(_))).await;
|
||||
wait_for_event(&child, |event| matches!(event, EventMsg::TurnComplete(_))).await;
|
||||
let requests = server.requests().await;
|
||||
assert_eq!(requests.len(), 5);
|
||||
let first: serde_json::Value = serde_json::from_slice(&requests[1])?;
|
||||
let resumed: serde_json::Value = serde_json::from_slice(&requests[4])?;
|
||||
let prefix = first["input"].as_array().context("child input")?;
|
||||
let items = resumed["input"].as_array().context("resumed input")?;
|
||||
assert_eq!(items.get(..prefix.len()), Some(prefix.as_slice()));
|
||||
assert_eq!(
|
||||
items
|
||||
.iter()
|
||||
.filter(|item| item["role"] == "user"
|
||||
&& item["content"] == json!([{"type": "input_text", "text": "Resume."}]))
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
let retained = &items[prefix.len()];
|
||||
if done["item"]["type"] == "message" {
|
||||
assert_eq!(retained["content"], done["item"]["content"]);
|
||||
assert_eq!(retained["phase"], done["item"]["phase"]);
|
||||
} else {
|
||||
assert_eq!(retained["arguments"], done["item"]["arguments"]);
|
||||
assert_eq!(retained["call_id"], "sampled");
|
||||
let output = &items[prefix.len() + 1];
|
||||
assert_eq!(output["call_id"], "sampled");
|
||||
assert_eq!(output["output"], "aborted before dispatch");
|
||||
}
|
||||
assert!(
|
||||
!items
|
||||
.iter()
|
||||
.any(|item| item.to_string().contains("Discard this."))
|
||||
);
|
||||
server.shutdown().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn idle_mail_survives_eviction_and_preserves_followup_order() -> Result<()> {
|
||||
const MAIL: &str = "Keep this note for later";
|
||||
|
||||
Reference in New Issue
Block a user