Enforce session ownership in V1 multi-agent tools (#65287)

## Why

V1 tools could use a thread ID to reach agents in another session. A
thread ID can also resolve to a different runtime after a thread is
unloaded and reloaded.

## What changed

- Check session ownership before sending input, interrupting, waiting on,
  closing, or resuming a V1 agent. Keep live operations bound to the
  runtime that passed the check.
- Check ownership in saved rollouts before resuming agents and their
  descendants. Follow the recorded parent chain for legacy rollouts that
  lack a session ID. Release the agent slot when closing a known ephemeral
  agent that has already been unloaded.
- Preserve failed `wait` calls in thread history and show the failure in
  the TUI without listing rejected targets as completed agents.

## Testing

Add regression coverage for cross-session input, close, and resume
requests, slot reuse after closing an unloaded ephemeral agent, legacy
session recovery, and failed wait history and display.

GitOrigin-RevId: 4712a53315d24d5658d746ed277738e00a4e2dac
This commit is contained in:
ioanbudea-OAI
2026-12-02 16:21:14 +00:00
committed by copyberry
parent 1396b2e0e7
commit 01192c6e19
21 changed files with 849 additions and 224 deletions
@@ -1269,6 +1269,21 @@ impl ThreadHistoryBuilder {
&mut self,
payload: &codex_protocol::protocol::CollabWaitingEndEvent,
) {
// The compatibility event can omit rejected targets from the completed wait.
if let Some(turn) = &mut self.current_turn
&& let Some(index) = turn.item_index.position(&turn.items, &payload.call_id)
&& matches!(
&turn.items[index],
ThreadItemPayload::CollabAgentToolCall {
tool: CollabAgentTool::Wait,
status: CollabAgentToolCallStatus::Completed
| CollabAgentToolCallStatus::Failed,
..
}
)
{
return;
}
let status = if payload
.statuses
.values()
@@ -5609,6 +5624,48 @@ mod tests {
);
}
#[test]
fn legacy_wait_end_preserves_canonical_failure() {
use codex_protocol::items::CollabAgentTool as CoreCollabAgentTool;
use codex_protocol::items::CollabAgentToolCallItem;
use codex_protocol::items::CollabAgentToolCallStatus as CoreCollabAgentToolCallStatus;
use codex_protocol::protocol::HasLegacyEvent;
let mut builder = ThreadHistoryBuilder::new();
let thread_id = ThreadId::new();
let completed = ItemCompletedEvent {
content_token_count: None,
thread_id,
turn_id: builder.ensure_turn().id.clone(),
item: CoreTurnItem::CollabAgentToolCall(CollabAgentToolCallItem {
id: "wait-1".into(),
tool: CoreCollabAgentTool::Wait,
status: CoreCollabAgentToolCallStatus::Failed,
sender_thread_id: thread_id,
receiver_thread_ids: Vec::new(),
receiver_agents: Vec::new(),
prompt: None,
model: None,
reasoning_effort: None,
agents_states: HashMap::new(),
}),
started_at_ms: None,
completed_at_ms: 1,
};
let legacy = completed
.as_legacy_events(/*show_raw_agent_reasoning*/ false)
.pop()
.expect("legacy wait completion");
let expected = ThreadItem::from(&completed);
builder.handle_event(&EventMsg::ItemCompleted(completed));
assert!(builder.handle_event_with_changes(&legacy).is_empty());
assert_eq!(
builder.active_turn_snapshot().expect("active turn").items,
[expected]
);
}
#[test]
fn canonical_hook_prompt_completion_updates_turn_history() {
let hook_prompt = CoreTurnItem::HookPrompt(codex_protocol::items::HookPromptItem {
@@ -153,6 +153,13 @@ async fn thread_archive_shuts_down_resumed_archived_descendant() -> Result<()> {
)?;
let parent_thread_id = ThreadId::from_string(&parent_id)?;
let child_thread_id = ThreadId::from_string(&child_id)?;
let child_rollout =
app_test_support::rollout_path(codex_home.path(), "2025-01-01T00-01-00", &child_id);
let contents = std::fs::read_to_string(&child_rollout)?;
let (header, history) = contents.split_once('\n').expect("session header");
let mut meta: Value = serde_json::from_str(header)?;
meta["payload"]["session_id"] = json!(parent_id);
std::fs::write(child_rollout, format!("{meta}\n{history}"))?;
let state_db = StateRuntime::init(
codex_state::SqliteConfig::new_for_testing(codex_home.path().abs()),
"mock_provider".into(),
+47 -18
View File
@@ -1,3 +1,4 @@
use crate::CodexThread;
use crate::TurnInputRequest;
use crate::TurnInputSubmission;
use crate::TurnStartOptions;
@@ -147,6 +148,18 @@ impl LocalAgentControl {
) -> CodexResult<String> {
let state = self.runtime.upgrade()?;
let thread = state.get_thread(agent_id).await?;
self.send_input_to_thread(&thread, input, start_options)
.await
}
/// Send input to the selected runtime without resolving its thread ID again.
pub(crate) async fn send_input_to_thread(
&self,
thread: &Arc<CodexThread>,
input: Vec<ResolvedUserInput>,
start_options: TurnStartOptions,
) -> CodexResult<String> {
let state = self.runtime.upgrade()?;
let result = match thread
.start_or_steer_resolved_turn(
TurnInputRequest::<ResolvedUserInput>::user_input(input).on_start(start_options),
@@ -167,7 +180,7 @@ impl LocalAgentControl {
)),
Err(err) => Err(err),
};
self.handle_thread_request_result(agent_id, &state, result)
self.handle_thread_request_result(thread, &state, result)
.await
}
@@ -337,39 +350,55 @@ impl LocalAgentControl {
},
)
.await;
self.handle_thread_request_result(agent_id, state, result)
self.handle_thread_request_result(&thread, state, result)
.await
}
/// Interrupt the current task for an existing agent thread.
pub(crate) async fn interrupt_agent(&self, agent_id: ThreadId, op: Op) -> CodexResult<String> {
let state = self.runtime.upgrade()?;
self.handle_thread_request_result(
agent_id,
&state,
state
.send_op(
agent_id, op, /*parent_turn_id*/ None, /*root_turn_id*/ None,
/*message_delivery*/ None,
)
.await,
)
.await
let thread = state.get_thread(agent_id).await?;
self.interrupt_thread(&thread, op).await
}
pub(crate) async fn interrupt_thread(
&self,
thread: &Arc<CodexThread>,
op: Op,
) -> CodexResult<String> {
let state = self.runtime.upgrade()?;
let result = state
.send_pinned_op(
thread, op, /*parent_turn_id*/ None, /*root_turn_id*/ None,
/*residency_guard*/ None, /*message_delivery*/ None,
)
.await;
self.handle_thread_request_result(thread, &state, result)
.await
}
async fn handle_thread_request_result<T>(
&self,
agent_id: ThreadId,
state: &Arc<ThreadManagerState>,
thread: &Arc<CodexThread>,
state: &ThreadManagerState,
result: CodexResult<T>,
) -> CodexResult<T> {
let agent_id = thread.session.thread_id;
if result
.as_ref()
.is_err_and(|err| matches!(err.details(), CodexErrorDetails::InternalAgentDied))
{
let _ = state.remove_thread(&agent_id).await;
self.forget_v2_residency(agent_id);
self.runtime.registry.release_spawned_thread(agent_id);
let _ = state.remove_thread_if_matches(&agent_id, thread).await;
let threads = state.threads.read().await;
if threads.get(&agent_id).is_none_or(|thread| {
!Arc::ptr_eq(
&self.runtime.registry,
&thread.session.services.local_agent_runtime.registry,
)
}) {
self.forget_v2_residency(agent_id);
self.runtime.registry.release_spawned_thread(agent_id);
}
}
result
}
+1 -1
View File
@@ -65,7 +65,7 @@ impl LocalAgentControl {
// If eviction won, pinning returns ThreadNotFound and the worker is already idle.
let _resident = self.runtime.pin_v2_residency(&thread).await?;
let result = thread.stop_worker().await;
self.handle_thread_request_result(target, &state, result)
self.handle_thread_request_result(&thread, &state, result)
.await
}
}
+107 -32
View File
@@ -2,49 +2,73 @@ use super::*;
use crate::agent::api::AgentInfo;
use codex_protocol::error::CodexErrorDetails;
use codex_thread_store::PersistContext;
use codex_thread_store::ThreadStoreError;
impl LocalAgentControl {
/// Submit a shutdown request for a live agent without marking it explicitly closed in
/// persisted spawn-edge state.
#[cfg(test)]
pub(crate) async fn shutdown_live_agent(&self, agent_id: ThreadId) -> CodexResult<String> {
let state = self.runtime.upgrade()?;
let result = if let Ok(thread) = state.get_thread(agent_id).await {
thread
.session
.ensure_rollout_materialized(PersistContext::Standard)
.await;
thread.session.flush_rollout().await?;
let result = if matches!(thread.agent_status().await, AgentStatus::Shutdown) {
Ok(String::new())
} else {
state
.send_op(
agent_id,
Op::Shutdown {},
/*parent_turn_id*/ None,
/*root_turn_id*/ None,
/*message_delivery*/ None,
)
.await
};
thread.wait_until_terminated().await;
result
let thread = state.get_thread(agent_id).await?;
self.shutdown_live_thread(&state, &thread).await
}
async fn shutdown_live_thread(
&self,
state: &ThreadManagerState,
thread: &Arc<CodexThread>,
) -> CodexResult<String> {
let agent_id = thread.session.thread_id;
thread
.session
.ensure_rollout_materialized(PersistContext::Standard)
.await;
if let Some(live_thread) = thread.session.live_thread() {
match live_thread.flush().await {
Ok(()) => {}
// Flush can also report missing metadata while a writer is still live.
Err(ThreadStoreError::ThreadNotFound { thread_id })
if thread_id == agent_id
&& (matches!(
live_thread.local_rollout_path().await,
Err(ThreadStoreError::ThreadNotFound { .. })
) || !thread.is_running()) => {}
Err(err) => return Err(std::io::Error::other(err).into()),
}
}
let result = if matches!(thread.agent_status().await, AgentStatus::Shutdown) {
Ok(String::new())
} else {
state
.send_op(
agent_id,
.send_pinned_op(
thread,
Op::Shutdown {},
/*parent_turn_id*/ None,
/*root_turn_id*/ None,
/*residency_guard*/ None,
/*message_delivery*/ None,
)
.await
};
let _ = state.remove_thread(&agent_id).await;
thread.wait_until_terminated().await;
let _ = state.remove_thread_if_matches(&agent_id, thread).await;
let threads = state.threads.read().await;
if threads.get(&agent_id).is_none_or(|thread| {
!Arc::ptr_eq(
&self.runtime.registry,
&thread.session.services.local_agent_runtime.registry,
)
}) {
self.release_agent_registration(agent_id);
}
result
}
fn release_agent_registration(&self, agent_id: ThreadId) {
self.forget_v2_residency(agent_id);
self.runtime.registry.release_spawned_thread(agent_id);
self.runtime.mailboxes.remove(agent_id);
result
}
/// Mark `agent_id` as explicitly closed in persisted spawn-edge state, then shut down the
@@ -53,8 +77,11 @@ impl LocalAgentControl {
let state = self.runtime.upgrade()?;
let metadata = self.get_agent_metadata(agent_id);
let known_agent = metadata.is_some();
let snapshot = match state.get_thread(agent_id).await {
let (snapshot, thread) = match state.get_thread(agent_id).await {
Ok(thread) => {
if thread.session.session_id() != self.session_id() {
return Err(CodexErr::ThreadNotFound(agent_id));
}
let agent = LiveAgent {
thread_id: agent_id,
metadata: metadata.unwrap_or_default(),
@@ -72,7 +99,7 @@ impl LocalAgentControl {
{
warn!("failed to persist thread-spawn edge status for {agent_id}: {err}");
}
AgentInfo::Loaded { agent, config }
(AgentInfo::Loaded { agent, config }, Some(thread))
}
Err(err)
if known_agent && matches!(err.details(), CodexErrorDetails::ThreadNotFound(_)) =>
@@ -89,11 +116,22 @@ impl LocalAgentControl {
"failed to persist stale thread-spawn edge status for {agent_id}: {err}"
)));
}
AgentInfo::Unloaded(metadata.unwrap_or_default())
(AgentInfo::Unloaded(metadata.unwrap_or_default()), None)
}
Err(err) => return Err(err),
};
match Box::pin(self.shutdown_agent_tree(agent_id)).await {
let descendant_ids = self.runtime.live_thread_spawn_descendants(agent_id).await?;
let result = if let Some(thread) = thread {
self.shutdown_live_thread(&state, &thread).await.map(drop)
} else {
let threads = state.threads.read().await;
if !threads.contains_key(&agent_id) {
self.release_agent_registration(agent_id);
}
Ok(())
};
self.shutdown_descendants(descendant_ids).await?;
match result {
Err(err)
if known_agent
&& matches!(
@@ -107,12 +145,49 @@ impl LocalAgentControl {
}
}
/// Release an unloaded agent's slot and close any live descendants it owns.
pub(crate) async fn close_unloaded_agent(&self, agent_id: ThreadId) -> CodexResult<AgentInfo> {
let descendant_ids = self.runtime.live_thread_spawn_descendants(agent_id).await?;
let state = self.runtime.upgrade()?;
let metadata = self.runtime.ensure_agent_known(agent_id)?;
{
let threads = state.threads.read().await;
if threads.contains_key(&agent_id) {
return Err(CodexErr::ThreadNotFound(agent_id));
}
self.release_agent_registration(agent_id);
}
self.shutdown_descendants(descendant_ids).await?;
Ok(AgentInfo::Unloaded(metadata))
}
/// Shut down `agent_id` and any live descendants reachable from the in-memory spawn tree.
#[cfg(test)]
pub(crate) async fn shutdown_agent_tree(&self, agent_id: ThreadId) -> CodexResult<String> {
let descendant_ids = self.runtime.live_thread_spawn_descendants(agent_id).await?;
let result = self.shutdown_live_agent(agent_id).await;
for descendant_id in descendant_ids {
match self.shutdown_live_agent(descendant_id).await {
self.shutdown_descendants(descendant_ids).await?;
result
}
pub(super) async fn shutdown_descendants(&self, ids: Vec<ThreadId>) -> CodexResult<()> {
let state = self.runtime.upgrade()?;
for descendant_id in ids {
let thread = match state.threads.read().await.get(&descendant_id) {
Some(thread)
if !thread.session_source().is_internal()
&& thread.session.session_id() == self.session_id() =>
{
Arc::clone(thread)
}
Some(_) => continue,
None => {
// The app-server may have unloaded this runtime. Drop its slot in this tree.
self.release_agent_registration(descendant_id);
continue;
}
};
match self.shutdown_live_thread(&state, &thread).await {
Ok(_) => {}
Err(err)
if matches!(
@@ -122,6 +197,6 @@ impl LocalAgentControl {
Err(err) => return Err(err),
}
}
result
Ok(())
}
}
+9 -3
View File
@@ -110,10 +110,16 @@ impl LocalAgentControl {
) -> CodexResult<(LiveAgent, ThreadConfigSnapshot)> {
let manager = self.runtime.upgrade()?;
let thread = match manager.get_thread(thread_id).await {
Ok(thread) => thread,
Ok(thread) if thread.session.session_id() == self.session_id() => thread,
Ok(_) => return Err(CodexErr::ThreadNotFound(thread_id)),
Err(err) if matches!(err.details(), CodexErrorDetails::ThreadNotFound(_)) => {
Box::pin(self.resume_agent_from_rollout(config, thread_id, source)).await?;
manager.get_thread(thread_id).await?
Box::pin(self.resume_agent_tree_from_rollout(
config,
thread_id,
source,
self.session_id(),
))
.await?
}
Err(err) => return Err(err),
};
@@ -1,17 +1,102 @@
//! Local registry lookups for startup, legacy context and loaded descendant checks.
//! Local identity lookups for startup, legacy context and session ownership checks.
//! These use the same local registry and thread manager as lifecycle operations.
use super::LocalAgentControl;
use super::LocalAgentRuntime;
use crate::agent::types::AgentMetadata;
use crate::session_prefix::format_subagent_context_line;
use crate::thread_manager::ThreadManagerState;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use codex_protocol::error::AgentErrorContext;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result as CodexResult;
use codex_protocol::protocol::MultiAgentVersion;
use codex_protocol::protocol::SessionMeta;
use codex_thread_store::LoadThreadHistoryParams;
use codex_thread_store::ThreadStoreError;
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
impl LocalAgentControl {
/// Validate ownership before V1 tools can interrupt, reload or operate on a target.
pub(crate) async fn ensure_agent_in_session(&self, agent_id: ThreadId) -> CodexResult<()> {
let owner = self
.resolve_agent_session_id(agent_id, /*resumed_meta*/ None)
.await?;
if owner == Some(self.session_id()) {
return Ok(());
}
Err(CodexErr::ThreadNotFound(agent_id))
}
/// Look up an agent's owning session, following parents for legacy self-ID metadata.
/// Returns `None` when there is no live thread or saved metadata for the target itself.
pub(crate) async fn resolve_agent_session_id(
&self,
agent_id: ThreadId,
mut resumed_meta: Option<&SessionMeta>,
) -> CodexResult<Option<SessionId>> {
let state = self.runtime.upgrade()?;
let mut current = agent_id;
let mut visited = HashSet::new();
while visited.insert(current) {
// Startup may have selected a rollout outside the store's lookup paths.
let stored_meta;
let meta = if let Some(meta) = resumed_meta.take() {
meta
} else if let Ok(thread) = state.get_thread(current).await {
return Ok(Some(thread.session.session_id()));
} else {
stored_meta = match state
.thread_store
.read_session_meta(LoadThreadHistoryParams {
thread_id: current,
include_archived: true,
})
.await
{
Ok(meta) => meta,
Err(ThreadStoreError::ThreadNotFound { thread_id })
if thread_id == agent_id && current == agent_id =>
{
return Ok(None);
}
Err(_) => return Err(CodexErr::ThreadNotFound(agent_id)),
};
&stored_meta
};
if meta.id != current {
break;
}
let source_parent = meta.source.parent_thread_id();
if meta.session_id != current.into()
|| matches!(
meta.multi_agent_version,
Some(MultiAgentVersion::Disabled | MultiAgentVersion::V2)
)
|| (meta.source.is_non_root_agent() && source_parent.is_none())
{
return Ok(Some(meta.session_id));
}
// Before session_id was persisted, decoding defaults it to the thread's own ID.
if meta
.parent_thread_id
.zip(source_parent)
.is_some_and(|(stored, source)| stored != source)
{
break;
}
let Some(parent) = meta.parent_thread_id.or(source_parent) else {
return Ok(Some(meta.session_id));
};
current = parent;
}
Err(CodexErr::ThreadNotFound(agent_id))
}
}
impl LocalAgentRuntime {
pub(crate) fn register_session_root(
&self,
+55 -17
View File
@@ -19,6 +19,7 @@ use crate::codex_thread::ThreadConfigSnapshot;
use crate::config::PermissionProfileSnapshot;
use crate::thread_manager::StartThreadOptions;
use codex_features::Feature;
use codex_history::RolloutItem;
use codex_protocol::dynamic_tools::DynamicToolSpec;
use codex_protocol::error::AgentErrorContext;
use codex_protocol::intersect_effective_permission_profiles;
@@ -26,6 +27,7 @@ use codex_protocol::protocol::EnvironmentConfigState;
use codex_utils_path_uri::PathUri;
use futures::StreamExt;
use futures::stream;
use std::collections::HashSet;
use std::time::Instant;
use tracing::Instrument;
use tracing::instrument::WithSubscriber;
@@ -626,6 +628,7 @@ impl LocalAgentControl {
inherited_instructions,
inherited_exec_policy,
client_mcp_extensions,
required_session_id: None,
})
.await
{
@@ -1091,29 +1094,56 @@ impl LocalAgentControl {
Ok((agent, config))
}
/// Resume an existing agent thread from a recorded rollout file.
pub(crate) async fn resume_agent_from_rollout(
pub(crate) async fn ensure_resume_history_in_session(
&self,
thread_id: ThreadId,
history: &[RolloutItem],
session_id: SessionId,
) -> CodexResult<()> {
let meta = history
.iter()
.find_map(|item| match item {
RolloutItem::SessionMeta(line) => Some(&line.meta),
_ => None,
})
.ok_or(CodexErr::ThreadNotFound(thread_id))?;
let owner = self.resolve_agent_session_id(thread_id, Some(meta)).await?;
if owner != Some(session_id) {
return Err(CodexErr::ThreadNotFound(thread_id));
}
Ok(())
}
/// Resume a saved agent and its open V1 descendants.
pub(super) async fn resume_agent_tree_from_rollout(
&self,
config: Config,
thread_id: ThreadId,
session_source: SessionSource,
) -> CodexResult<ThreadId> {
required_session_id: SessionId,
) -> CodexResult<Arc<CodexThread>> {
let _membership = self.runtime.admit_start()?;
let root_depth = thread_spawn_depth(&session_source).unwrap_or(0);
let (resumed_thread_id, resumed_multi_agent_version) = Box::pin(
self.resume_single_agent_from_rollout(config.clone(), thread_id, session_source),
)
.await?;
let (resumed, resumed_multi_agent_version) =
Box::pin(self.resume_single_agent_from_rollout(
config.clone(),
thread_id,
session_source,
required_session_id,
))
.await?;
let state = self.runtime.upgrade()?;
if config.multi_agent_version_from_features().uses_v2_runtime()
|| resumed_multi_agent_version.uses_v2_runtime()
{
return Ok(resumed_thread_id);
return Ok(resumed);
}
let Some(agent_graph_store) = state.agent_graph_store() else {
return Ok(resumed_thread_id);
return Ok(resumed);
};
let owner = self.runtime.control(resumed.session.session_id());
let mut visited = HashSet::from([thread_id]);
let mut resume_queue = VecDeque::from([(thread_id, root_depth)]);
while let Some((parent_thread_id, parent_depth)) = resume_queue.pop_front() {
let child_ids = match agent_graph_store
@@ -1133,9 +1163,12 @@ impl LocalAgentControl {
};
for child_thread_id in child_ids {
if !visited.insert(child_thread_id) {
continue;
}
let child_depth = parent_depth + 1;
let child_resumed = if state.get_thread(child_thread_id).await.is_ok() {
true
let child_resumed = if let Ok(thread) = state.get_thread(child_thread_id).await {
thread.session.session_id() == owner.session_id()
} else {
let child_session_source =
SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
@@ -1145,10 +1178,11 @@ impl LocalAgentControl {
agent_nickname: None,
agent_role: None,
});
match Box::pin(self.resume_single_agent_from_rollout(
match Box::pin(owner.resume_single_agent_from_rollout(
config.clone(),
child_thread_id,
child_session_source,
owner.session_id(),
))
.await
{
@@ -1165,7 +1199,7 @@ impl LocalAgentControl {
}
}
Ok(resumed_thread_id)
Ok(resumed)
}
async fn resume_single_agent_from_rollout(
@@ -1173,7 +1207,8 @@ impl LocalAgentControl {
config: Config,
thread_id: ThreadId,
session_source: SessionSource,
) -> CodexResult<(ThreadId, MultiAgentVersion)> {
required_session_id: SessionId,
) -> CodexResult<(Arc<CodexThread>, MultiAgentVersion)> {
let state = self.runtime.upgrade()?;
let stored_thread = state
.read_stored_thread(ReadThreadParams {
@@ -1182,6 +1217,10 @@ impl LocalAgentControl {
include_history: false,
})
.await?;
let history =
load_agent_model_context(&state, thread_id, stored_thread.history_mode).await?;
self.ensure_resume_history_in_session(thread_id, &history.items, required_session_id)
.await?;
let resumed_agent_path = stored_thread
.agent_path
.as_deref()
@@ -1190,8 +1229,6 @@ impl LocalAgentControl {
.map_err(|err| CodexErr::InvalidRequest(format!("invalid stored agent path: {err}")))?;
let resumed_agent_nickname = stored_thread.agent_nickname.clone();
let resumed_agent_role = stored_thread.agent_role.clone();
let history =
load_agent_model_context(&state, thread_id, stored_thread.history_mode).await?;
let initial_history = InitialHistory::Resumed(ResumedHistory {
history_revision: history.revision,
conversation_id: thread_id,
@@ -1259,6 +1296,7 @@ impl LocalAgentControl {
inherited_instructions: None,
inherited_exec_policy,
client_mcp_extensions: None,
required_session_id: Some(required_session_id),
})
.await?;
let mut agent_metadata = agent_metadata;
@@ -1288,6 +1326,6 @@ impl LocalAgentControl {
)
.await;
Ok((resumed_thread.thread_id, multi_agent_version))
Ok((resumed_thread.thread, multi_agent_version))
}
}
+23 -2
View File
@@ -2,9 +2,11 @@
//! Subscriptions retain no runtime handle and preserve the watch channel's coalescing.
use super::LocalAgentControl;
use crate::CodexThread;
use crate::agent::api::AgentInfo;
use crate::agent::types::LiveAgent;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result as CodexResult;
use futures::StreamExt;
use futures::stream;
@@ -22,6 +24,25 @@ impl LocalAgentControl {
) -> CodexResult<StatusSubscription> {
let manager = self.runtime.upgrade()?;
let thread = manager.get_thread(agent_id).await?;
Ok(self.subscribe_thread_status(thread).await)
}
pub(crate) async fn owned_live_thread(
&self,
agent_id: ThreadId,
) -> CodexResult<Arc<CodexThread>> {
let thread = self.runtime.upgrade()?.get_thread(agent_id).await?;
if thread.session.session_id() != self.session_id() {
return Err(CodexErr::ThreadNotFound(agent_id));
}
Ok(thread)
}
pub(crate) async fn subscribe_thread_status(
&self,
thread: Arc<CodexThread>,
) -> StatusSubscription {
let agent_id = thread.session.thread_id;
// Subscribe before reading settings; mark the initial status seen only afterward.
let mut receiver = thread.subscribe_status();
let config = Box::new(thread.config_snapshot().await);
@@ -53,13 +74,13 @@ impl LocalAgentControl {
}
},
);
Ok(stream::once(async move {
stream::once(async move {
Ok(AgentInfo::Loaded {
agent: initial,
config,
})
})
.chain(changes)
.boxed())
.boxed()
}
}
+84 -17
View File
@@ -132,6 +132,21 @@ use toml::Value as TomlValue;
mod spawn_publication;
impl LocalAgentControl {
async fn resume_agent_from_rollout(
&self,
config: Config,
thread_id: ThreadId,
source: SessionSource,
) -> CodexResult<ThreadId> {
let session_id = self
.resolve_agent_session_id(thread_id, /*resumed_meta*/ None)
.await?
.unwrap_or(self.session_id());
self.resume_agent_tree_from_rollout(config, thread_id, source, session_id)
.await
.map(|thread| thread.session.thread_id())
}
/// Create a child fixture through the production spawn entry point.
pub(crate) async fn spawn_agent_with_metadata(
&self,
@@ -896,7 +911,7 @@ async fn resume_agent_errors_when_manager_dropped() {
let control = LocalAgentControl::default();
let (_home, config) = test_config().await;
let err = control
.resume_agent_from_rollout(config, ThreadId::new(), SessionSource::Exec)
.resume_agent(config, ThreadId::new(), SessionSource::Exec)
.await
.expect_err("resume_agent should fail without a manager");
assert_eq!(
@@ -4224,10 +4239,24 @@ async fn spawn_agent_releases_slot_after_shutdown() {
)
.await
.expect("spawn_agent should succeed after shutdown");
// Close the writer before the runtime reports shutdown.
manager
.get_thread(second_agent_id)
.await
.expect("agent thread should be loaded")
.session
.live_thread()
.expect("agent should have a rollout writer")
.shutdown()
.await
.expect("close agent rollout writer");
let _ = control
.shutdown_live_agent(second_agent_id)
.await
.expect("shutdown agent");
.expect("finish agent cleanup after shutdown");
let registry = &control.runtime.registry;
assert!(registry.reserve_spawn_slot(Some(max_threads)).is_ok());
}
#[tokio::test]
@@ -5415,7 +5444,7 @@ async fn list_agent_subtree_thread_ids_finds_live_descendants_of_unloaded_root()
}
#[tokio::test]
async fn shutdown_agent_tree_closes_live_descendants() {
async fn shutdown_owned_descendants_releases_unloaded_slots() -> anyhow::Result<()> {
let harness = AgentControlHarness::new().await;
let (parent_thread_id, _parent_thread) = harness.start_thread().await;
@@ -5467,11 +5496,16 @@ async fn shutdown_agent_tree_closes_live_descendants() {
wait_for_live_thread_spawn_children(&harness.control, child_thread_id, &[grandchild_thread_id])
.await;
let _ = harness
.control
.shutdown_agent_tree(parent_thread_id)
.await
.expect("tree shutdown should succeed");
let control = &harness.control;
let descendants = control
.runtime
.live_thread_spawn_descendants(parent_thread_id)
.await?;
grandchild_thread.shutdown_and_wait().await?;
harness.manager.remove_thread(&grandchild_thread_id).await;
control.shutdown_live_agent(parent_thread_id).await?;
control.shutdown_descendants(descendants).await?;
assert_eq!(
harness.control.get_status(parent_thread_id).await,
@@ -5481,10 +5515,8 @@ async fn shutdown_agent_tree_closes_live_descendants() {
harness.control.get_status(child_thread_id).await,
AgentStatus::NotFound
);
assert_eq!(
harness.control.get_status(grandchild_thread_id).await,
AgentStatus::NotFound
);
let registry = &control.runtime.registry;
assert!(registry.reserve_spawn_slot(/*max_threads*/ Some(1)).is_ok());
let shutdown_ids = harness
.manager
@@ -5492,11 +5524,12 @@ async fn shutdown_agent_tree_closes_live_descendants() {
.into_iter()
.filter_map(|(thread_id, op)| matches!(op, Op::Shutdown).then_some(thread_id))
.collect::<Vec<_>>();
let mut expected_shutdown_ids = vec![parent_thread_id, child_thread_id, grandchild_thread_id];
let mut expected_shutdown_ids = vec![parent_thread_id, child_thread_id];
expected_shutdown_ids.sort_by_key(std::string::ToString::to_string);
let mut shutdown_ids = shutdown_ids;
shutdown_ids.sort_by_key(std::string::ToString::to_string);
assert_eq!(shutdown_ids, expected_shutdown_ids);
Ok(())
}
#[tokio::test]
@@ -5592,9 +5625,10 @@ async fn shutdown_agent_tree_closes_descendants_when_started_at_child() {
#[tokio::test]
async fn resume_agent_from_rollout_does_not_reopen_closed_descendants() {
let harness = AgentControlHarness::new().await;
let mut harness = AgentControlHarness::new().await;
let (parent_thread_id, parent_thread) = harness.start_thread().await;
harness.control = harness.control.runtime.control(parent_thread_id.into());
let child_thread_id = harness
.control
.spawn_agent(
@@ -5784,9 +5818,10 @@ async fn resume_closed_child_reopens_open_descendants() {
#[tokio::test]
async fn resume_agent_from_rollout_reopens_open_descendants_after_manager_shutdown() {
let harness = AgentControlHarness::new().await;
let mut harness = AgentControlHarness::new().await;
let (parent_thread_id, parent_thread) = harness.start_thread().await;
harness.control = harness.control.runtime.control(parent_thread_id.into());
let child_thread_id = harness
.control
.spawn_agent(
@@ -5836,6 +5871,20 @@ async fn resume_agent_from_rollout_reopens_open_descendants_after_manager_shutdo
wait_for_live_thread_spawn_children(&harness.control, child_thread_id, &[grandchild_thread_id])
.await;
let (foreign_thread_id, foreign_thread) = harness.start_thread().await;
persist_thread_for_tree_resume(&foreign_thread, "foreign thread persisted").await;
harness
.state_db
.as_ref()
.expect("agent graph store")
.upsert_thread_spawn_edge(
child_thread_id,
foreign_thread_id,
codex_state::DirectionalThreadSpawnEdgeStatus::Open,
)
.await
.expect("persist cross-session edge");
let report = harness
.manager
.shutdown_all_threads_bounded(Duration::from_secs(5))
@@ -5866,6 +5915,22 @@ async fn resume_agent_from_rollout_reopens_open_descendants_after_manager_shutdo
AgentStatus::NotFound
);
assert_thread_not_loaded(&harness.manager, foreign_thread_id).await;
let error = harness
.control
.resume_agent(
harness.config.clone(),
foreign_thread_id,
child_thread.session_source().clone(),
)
.await
.expect_err("cold resume must check the rollout's owner");
assert!(matches!(
error.details(),
CodexErrorDetails::ThreadNotFound(id) if *id == foreign_thread_id
));
assert_thread_not_loaded(&harness.manager, foreign_thread_id).await;
let _ = harness
.control
.shutdown_agent_tree(parent_thread_id)
@@ -5875,9 +5940,10 @@ async fn resume_agent_from_rollout_reopens_open_descendants_after_manager_shutdo
#[tokio::test]
async fn resume_agent_from_rollout_uses_edge_data_when_descendant_metadata_source_is_stale() {
let harness = AgentControlHarness::new().await;
let mut harness = AgentControlHarness::new().await;
let (parent_thread_id, parent_thread) = harness.start_thread().await;
harness.control = harness.control.runtime.control(parent_thread_id.into());
let child_thread_id = harness
.control
.spawn_agent(
@@ -6006,9 +6072,10 @@ async fn resume_agent_from_rollout_uses_edge_data_when_descendant_metadata_sourc
#[tokio::test]
async fn resume_agent_from_rollout_skips_descendants_when_parent_resume_fails() {
let harness = AgentControlHarness::new().await;
let mut harness = AgentControlHarness::new().await;
let (parent_thread_id, parent_thread) = harness.start_thread().await;
harness.control = harness.control.runtime.control(parent_thread_id.into());
let child_thread_id = harness
.control
.spawn_agent(
+34 -3
View File
@@ -26,6 +26,7 @@ use crate::runtime_auth::RuntimeAuthSlot;
use crate::shell_snapshot::ShellSnapshot;
use crate::shell_snapshot::SnapshotCredentialBrokerState;
use crate::state::ActiveTurn;
use crate::thread_manager::RequiredResumeSessionId;
use crate::turn_metadata::ExecutionMetadata;
use codex_analytics::ThreadProductUpdate;
use codex_attachment_store::AttachmentStore;
@@ -996,22 +997,43 @@ impl Session {
| InitialHistory::Resumed(_)
| InitialHistory::Forked(_) => None,
};
let resumed_session_id = match &initial_history {
let resumed_meta = match &initial_history {
InitialHistory::Resumed(resumed) => {
resumed.history.iter().find_map(|item| match item {
RolloutItem::SessionMeta(meta_line) => Some(meta_line.meta.session_id),
RolloutItem::SessionMeta(meta_line) => Some(&meta_line.meta),
_ => None,
})
}
InitialHistory::New | InitialHistory::Cleared | InitialHistory::Forked(_) => None,
};
let required_resume_session_id = thread_extension_init
.remove::<RequiredResumeSessionId>()
.map(|required| required.0);
// Recover a legacy V1 child's owner even if the current config disables agents.
let resumed_session_id = if required_resume_session_id.is_none()
&& let Some(meta) = resumed_meta
&& meta.session_id == SessionId::from(thread_id)
&& matches!(
session_configuration.session_source,
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
)
&& let AgentControlInit::Local(control) = &agent_control
{
control
.resolve_agent_session_id(thread_id, Some(meta))
.await
.unwrap_or_default()
} else {
resumed_meta.map(|meta| meta.session_id)
};
// Legacy subagent rollouts synthesized session_id from their own thread ID.
let resumed_session_id = resumed_session_id.filter(|session_id| {
!session_configuration.session_source.is_non_root_agent()
|| *session_id != SessionId::from(thread_id)
});
// session_id is equal to the root thread's ID.
let session_id = resumed_session_id
let session_id = required_resume_session_id
.or(resumed_session_id)
.or(inherited_session_id)
.unwrap_or_else(|| {
if session_configuration.session_source.is_non_root_agent() {
@@ -1344,6 +1366,15 @@ impl Session {
let session_result: anyhow::Result<Arc<Self>> = Box::pin(async {
if let InitialHistory::Resumed(resumed) = &mut initial_history {
if let Some(history) = resume_context {
// The store can refresh the history while acquiring the rollout writer.
if let Some(session_id) = required_resume_session_id
&& !Arc::ptr_eq(&history, &resumed.history)
{
local_agent_runtime
.control(session_id)
.ensure_resume_history_in_session(thread_id, &history, session_id)
.await?;
}
resumed.history = history;
resumed.history_revision = None;
}
+44 -44
View File
@@ -84,6 +84,7 @@ use codex_model_provider_info::ModelProviderInfo;
use codex_model_provider_info::OPENAI_PROVIDER_ID;
use codex_models_manager::manager::RefreshStrategy;
use codex_models_manager::manager::SharedModelsManager;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use codex_protocol::config_types::CollaborationModeMask;
use codex_protocol::error::CodexErr;
@@ -638,6 +639,10 @@ fn effective_originator_value(
.unwrap_or(default_originator)
}
/// The V1 owner checked against the supplied history. Reused runtimes and refreshed history
/// must belong to this session too.
pub(crate) struct RequiredResumeSessionId(pub SessionId);
pub(crate) struct ResumeThreadWithHistoryOptions {
pub(crate) config: Config,
pub(crate) request_country: codex_protocol::RequestCountry,
@@ -651,6 +656,7 @@ pub(crate) struct ResumeThreadWithHistoryOptions {
pub(crate) inherited_instructions: Option<SessionInstructions>,
pub(crate) inherited_exec_policy: Option<Arc<crate::exec_policy::ExecPolicyManager>>,
pub(crate) client_mcp_extensions: Option<ClientMcpExtensions>,
pub(crate) required_session_id: Option<SessionId>,
}
/// Shared, `Arc`-owned state for [`ThreadManager`]. This `Arc` is required to have a single
@@ -677,7 +683,7 @@ pub(crate) struct ThreadManagerState {
pub(crate) extensions: Arc<ExtensionRegistry<Config>>,
user_instructions_provider: Arc<dyn UserInstructionsProvider>,
image_store: Arc<dyn AttachmentStore>,
thread_store: Arc<dyn ThreadStore>,
pub(crate) thread_store: Arc<dyn ThreadStore>,
agent_graph_store: Option<Arc<dyn AgentGraphStore>>,
attestation_provider: Option<Arc<dyn AttestationProvider>>,
external_time_provider: Option<Arc<dyn TimeProvider>>,
@@ -1821,17 +1827,9 @@ impl ThreadManager {
thread_id: &ThreadId,
expected: &Arc<CodexThread>,
) -> Option<Arc<CodexThread>> {
let mut threads = self.state.threads.write().await;
if threads
.get(thread_id)
.is_some_and(|thread| Arc::ptr_eq(thread, expected))
{
threads.remove(thread_id).inspect(|thread| {
thread.session.services.mcp_runtime.revoke_ema();
})
} else {
None
}
self.state
.remove_thread_if_matches(thread_id, expected)
.await
}
/// Tries to shut down all tracked threads concurrently within the provided timeout.
@@ -2283,37 +2281,6 @@ impl ThreadManagerState {
})
}
/// Send an operation to a thread by ID.
pub(crate) async fn send_op(
&self,
thread_id: ThreadId,
op: Op,
parent_turn_id: Option<String>,
root_turn_id: Option<String>,
message_delivery: Option<crate::agent_communication::MessageDelivery>,
) -> CodexResult<String> {
let thread = self.get_thread(thread_id).await?;
let residency_guard = if matches!(op, Op::InterAgentCommunication { .. }) {
thread
.session
.services
.local_agent_runtime
.pin_v2_residency(&thread)
.await?
} else {
None
};
self.send_pinned_op(
&thread,
op,
parent_turn_id,
root_turn_id,
residency_guard,
message_delivery,
)
.await
}
pub(crate) async fn send_pinned_op(
&self,
thread: &CodexThread,
@@ -2342,6 +2309,24 @@ impl ThreadManagerState {
.await
}
pub(crate) async fn remove_thread_if_matches(
&self,
thread_id: &ThreadId,
expected: &Arc<CodexThread>,
) -> Option<Arc<CodexThread>> {
let mut threads = self.threads.write().await;
if threads
.get(thread_id)
.is_some_and(|thread| Arc::ptr_eq(thread, expected))
{
threads.remove(thread_id).inspect(|thread| {
thread.session.services.mcp_runtime.revoke_ema();
})
} else {
None
}
}
/// Remove a thread from the manager by ID, returning it when present.
pub(crate) async fn remove_thread(&self, thread_id: &ThreadId) -> Option<Arc<CodexThread>> {
self.threads
@@ -2585,13 +2570,14 @@ impl ThreadManagerState {
inherited_instructions,
inherited_exec_policy,
client_mcp_extensions,
required_session_id,
} = options;
let (parent_client_mcp_extensions, inherited_prompt_cache_key) =
self.inherited_child_settings(parent_thread_id).await;
let client_mcp_extensions = client_mcp_extensions.unwrap_or(parent_client_mcp_extensions);
let prompt_cache_key = prompt_cache_key.unwrap_or(inherited_prompt_cache_key);
let thread_source = initial_history.get_resumed_thread_source();
let options = StartThreadOptions {
let mut options = StartThreadOptions {
request_country,
prompt_cache_key,
initial_history,
@@ -2606,6 +2592,11 @@ impl ThreadManagerState {
client_mcp_extensions,
..StartThreadOptions::new(config)
};
if let Some(session_id) = required_session_id {
options
.thread_extension_init
.insert(RequiredResumeSessionId(session_id));
}
let mut request =
ThreadSpawnRequest::new(options, Arc::clone(&self.auth_manager), agent_control);
request.parent_thread_id = parent_thread_id;
@@ -2845,6 +2836,15 @@ impl ThreadManagerState {
if let InitialHistory::Resumed(resumed) = &initial_history {
let mut threads = self.threads.write().await;
if let Some(thread) = threads.get(&resumed.conversation_id).cloned() {
if thread_extension_init
.get::<RequiredResumeSessionId>()
.is_some_and(|required| {
thread.session_source.is_internal()
|| required.0 != thread.session.session_id()
})
{
return Err(CodexErr::ThreadNotFound(resumed.conversation_id));
}
if thread.is_running() {
// The parent's pool still owns this runtime and its rollout writer.
// Returning it would report success without allowing client access.
@@ -1,6 +1,7 @@
use super::*;
use crate::tools::handlers::multi_agents_spec::create_close_agent_tool_v1;
use codex_otel::SubagentStopAction;
use codex_protocol::error::CodexErr;
use codex_tools::ToolSpec;
pub(crate) struct Handler;
@@ -44,6 +45,22 @@ async fn handle_close_agent(
.local_agent_runtime
.control(session.session_id());
let receiver_agent = local_agent_control.get_agent_metadata(agent_id);
let owner = if receiver_agent.is_some() {
local_agent_control
.resolve_agent_session_id(agent_id, /*resumed_meta*/ None)
.await
} else {
local_agent_control
.owned_live_thread(agent_id)
.await
.map(|thread| Some(thread.session.session_id()))
}
.map_err(|err| collab_agent_error(agent_id, err))?;
let close_unloaded = owner.is_none() && receiver_agent.is_some();
if owner != Some(session.session_id()) && !close_unloaded {
let error = CodexErr::ThreadNotFound(agent_id);
return Err(collab_agent_error(agent_id, error));
}
let receiver_agent = receiver_agent.unwrap_or_default();
session
.emit_turn_item_started(
@@ -62,12 +79,20 @@ async fn handle_close_agent(
}),
)
.await;
// Shutdown may remove the target before a descendant fails to close.
let previous_status = local_agent_control.get_status(agent_id).await;
let result = local_agent_control.close_agent(agent_id).await;
let (previous_status, result) = if close_unloaded {
let result = local_agent_control.close_unloaded_agent(agent_id).await;
(AgentStatus::NotFound, result)
} else {
// Shutdown may remove the target before a descendant fails to close.
let previous_status = match local_agent_control.owned_live_thread(agent_id).await {
Ok(thread) => thread.agent_status().await,
Err(_) => AgentStatus::NotFound,
};
let result = local_agent_control.close_agent(agent_id).await;
(previous_status, result)
};
let (status, receiver_agent) = match &result {
Ok(snapshot) => {
// Legacy close can also address unrelated loaded threads.
if snapshot.metadata().agent_id.is_some()
&& agent_id != ThreadId::from(session.session_id())
{
@@ -57,6 +57,11 @@ async fn handle_resume_agent(
));
}
local_agent_control
.ensure_agent_in_session(receiver_thread_id)
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err))?;
session
.emit_turn_item_started(
&turn,
@@ -96,11 +101,16 @@ async fn handle_resume_agent(
.await;
let (status, receiver_agent, error) = match result {
Ok((agent, _)) => (agent.status, agent.metadata, None),
Err(err) => (
local_agent_control.get_status(receiver_thread_id).await,
receiver_agent,
Some(err),
),
Err(err) => {
let status = match local_agent_control
.owned_live_thread(receiver_thread_id)
.await
{
Ok(thread) => thread.agent_status().await,
Err(_) => AgentStatus::NotFound,
};
(status, receiver_agent, Some(err))
}
};
session
.emit_turn_item_completed(
@@ -1,9 +1,9 @@
use super::*;
use crate::agent::api::AgentTarget;
use crate::agent::child_config::build_agent_resume_config;
use crate::agent::control::render_input_preview;
use crate::tools::handlers::multi_agents_spec::create_send_input_tool_v1;
use codex_protocol::protocol::MultiAgentVersion;
use codex_protocol::error::CodexErrorDetails;
use codex_protocol::protocol::Op;
use codex_tools::ToolSpec;
use codex_user_input::ResolvedUserInput;
@@ -57,6 +57,10 @@ impl Handler {
.control(session.session_id());
let receiver_agent = local_agent_control.get_agent_metadata(receiver_thread_id);
let residency_pin = if receiver_agent.is_some() {
local_agent_control
.ensure_agent_in_session(receiver_thread_id)
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err))?;
let resume_config = build_agent_resume_config(turn.as_ref())
.map_err(FunctionCallError::RespondToModel)?;
local_agent_control
@@ -67,15 +71,13 @@ impl Handler {
None
};
let receiver_agent = receiver_agent.unwrap_or_default();
let thread = local_agent_control
.owned_live_thread(receiver_thread_id)
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err))?;
if args.interrupt {
session
.services
.agent_control
.interrupt(
session.thread_id,
AgentTarget::Id(receiver_thread_id),
MultiAgentVersion::V1,
)
local_agent_control
.interrupt_thread(&thread, Op::Interrupt)
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err))?;
}
@@ -97,8 +99,8 @@ impl Handler {
)
.await;
let result = local_agent_control
.send_input(
receiver_thread_id,
.send_input_to_thread(
&thread,
input_items,
crate::TurnStartOptions {
parent_turn_id: Some(turn.sub_id.clone()),
@@ -108,10 +110,16 @@ impl Handler {
..Default::default()
},
)
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err));
.await;
drop(residency_pin);
let status = local_agent_control.get_status(receiver_thread_id).await;
let status = if result
.as_ref()
.is_err_and(|err| matches!(err.details(), CodexErrorDetails::InternalAgentDied))
{
AgentStatus::NotFound
} else {
thread.agent_status().await
};
session
.emit_turn_item_completed(
&turn,
@@ -133,7 +141,7 @@ impl Handler {
}),
)
.await;
let submission_id = result?;
let submission_id = result.map_err(|err| collab_agent_error(receiver_thread_id, err))?;
Ok(boxed_tool_output(SendInputResult { submission_id }))
}
@@ -1,7 +1,6 @@
use super::*;
use crate::agent::control::StatusSubscription;
use crate::agent::status::is_final;
use crate::session::session::Session;
use crate::tools::handlers::multi_agents_spec::WaitAgentTimeoutOptions;
use crate::tools::handlers::multi_agents_spec::create_wait_agent_tool_v1;
use codex_protocol::error::CodexErr;
@@ -11,7 +10,6 @@ use futures::FutureExt;
use futures::StreamExt;
use futures::stream::FuturesUnordered;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::time::Instant;
@@ -68,9 +66,18 @@ impl Handler {
.services
.local_agent_runtime
.control(session.session_id());
let mut threads = Vec::with_capacity(receiver_thread_ids.len());
let mut receiver_agents = Vec::with_capacity(receiver_thread_ids.len());
let mut target_by_thread_id = HashMap::with_capacity(receiver_thread_ids.len());
for receiver_thread_id in &receiver_thread_ids {
let thread = local_agent_control
.owned_live_thread(*receiver_thread_id)
.await;
let authorized = thread.is_ok();
threads.push(thread);
if !authorized {
continue;
}
let agent_metadata = local_agent_control
.get_agent_metadata(*receiver_thread_id)
.unwrap_or_default();
@@ -107,7 +114,10 @@ impl Handler {
tool: CollabAgentTool::Wait,
status: CollabAgentToolCallStatus::InProgress,
sender_thread_id: session.thread_id,
receiver_thread_ids: receiver_thread_ids.clone(),
receiver_thread_ids: receiver_agents
.iter()
.map(|agent| agent.thread_id)
.collect(),
receiver_agents: receiver_agents.clone(),
prompt: None,
model: None,
@@ -119,9 +129,9 @@ impl Handler {
let mut status_rxs = Vec::with_capacity(receiver_thread_ids.len());
let mut initial_final_statuses = Vec::new();
for id in &receiver_thread_ids {
for (id, thread) in receiver_thread_ids.iter().zip(threads) {
let subscription = async {
let mut updates = local_agent_control.subscribe_status(*id).await?;
let mut updates = local_agent_control.subscribe_thread_status(thread?).await;
let initial = updates
.next()
.await
@@ -142,22 +152,20 @@ impl Handler {
initial_final_statuses.push((*id, AgentStatus::NotFound));
}
Err(err) => {
let mut statuses = HashMap::with_capacity(1);
statuses.insert(*id, local_agent_control.get_status(*id).await);
session
.emit_turn_item_completed(
&turn,
TurnItem::CollabAgentToolCall(CollabAgentToolCallItem {
id: call_id.to_string(),
tool: CollabAgentTool::Wait,
status: wait_tool_call_status(&statuses),
status: CollabAgentToolCallStatus::Failed,
sender_thread_id: session.thread_id,
receiver_thread_ids: statuses.keys().copied().collect(),
receiver_agents: wait_receiver_agents(&statuses, &receiver_agents),
receiver_thread_ids: Vec::new(),
receiver_agents: Vec::new(),
prompt: None,
model: None,
reasoning_effort: None,
agents_states: statuses,
agents_states: Default::default(),
}),
)
.await;
@@ -171,8 +179,7 @@ impl Handler {
} else {
let mut futures = FuturesUnordered::new();
for (id, rx) in status_rxs.into_iter() {
let session = session.clone();
futures.push(wait_for_final_status(session, id, rx));
futures.push(wait_for_final_status(id, rx));
}
let mut results = Vec::new();
let deadline = Instant::now() + Duration::from_millis(timeout_ms as u64);
@@ -201,15 +208,17 @@ impl Handler {
};
let timed_out = statuses.is_empty();
let statuses_by_id = statuses.clone().into_iter().collect::<HashMap<_, _>>();
let mut statuses_by_id = statuses.clone().into_iter().collect::<HashMap<_, _>>();
let status = wait_tool_call_status(&statuses_by_id);
statuses_by_id.retain(|id, status| {
target_by_thread_id.contains_key(id) && !matches!(status, AgentStatus::NotFound)
});
let result = WaitAgentResult {
status: statuses
.into_iter()
.filter_map(|(thread_id, status)| {
target_by_thread_id
.get(&thread_id)
.cloned()
.map(|target| (target, status))
.map(|(id, status)| {
let target = target_by_thread_id.get(&id).cloned();
(target.unwrap_or_else(|| id.to_string()), status)
})
.collect(),
timed_out,
@@ -221,7 +230,7 @@ impl Handler {
TurnItem::CollabAgentToolCall(CollabAgentToolCallItem {
id: call_id.into(),
tool: CollabAgentTool::Wait,
status: wait_tool_call_status(&statuses_by_id),
status,
sender_thread_id: session.thread_id,
receiver_thread_ids: statuses_by_id.keys().copied().collect(),
receiver_agents: wait_receiver_agents(&statuses_by_id, &receiver_agents),
@@ -317,7 +326,6 @@ impl ToolOutput for WaitAgentResult {
}
async fn wait_for_final_status(
session: Arc<Session>,
thread_id: ThreadId,
mut updates: StatusSubscription,
) -> Result<Option<(ThreadId, AgentStatus)>, FunctionCallError> {
@@ -328,11 +336,6 @@ async fn wait_for_final_status(
return Ok(Some((thread_id, status)));
}
}
let latest = session
.services
.local_agent_runtime
.control(session.session_id())
.get_status(thread_id)
.await;
Ok(is_final(&latest).then_some((thread_id, latest)))
// The authorized runtime is gone; a new runtime with this ID has a different subscription.
Ok(Some((thread_id, AgentStatus::NotFound)))
}
@@ -14,9 +14,11 @@ use crate::environment_selection::TurnEnvironmentState;
use crate::function_tool::FunctionCallError;
use crate::init_state_db;
use crate::local_agent_graph_store_from_state_db;
use crate::session::session::Session;
use crate::session::step_context::StepContext;
use crate::session::tests::make_session_and_context;
use crate::session::tests::make_session_and_context_with_auth_config_home_and_rx;
use crate::session::tests::make_session_and_context_with_rx;
use crate::session::tests::update_selected_settings_for_test;
use crate::session::tests::update_turn_settings_for_test;
use crate::session::turn_context::TurnContext;
@@ -99,6 +101,12 @@ fn set_agent_control(
session.services.agent_control = Arc::new(control);
}
fn bind_session_to_thread(session: &mut Session, thread: &crate::CodexThread) {
session.services.local_agent_runtime = thread.session.services.local_agent_runtime.clone();
session.services.agent_control = Arc::clone(&thread.session.services.agent_control);
session.thread_id = thread.session.thread_id;
}
fn invocation(
session: Arc<crate::session::session::Session>,
turn: Arc<TurnContext>,
@@ -2632,13 +2640,13 @@ async fn send_input_reports_missing_agent() {
async fn send_input_interrupts_before_prompt() {
let (mut session, turn) = make_session_and_context().await;
let manager = thread_manager();
set_agent_control(&mut session, manager.agent_control());
let config = turn.config.as_ref().clone();
let thread = manager
.start_thread(StartThreadOptions::new(config.clone()))
.await
.expect("start thread");
let agent_id = thread.thread_id;
bind_session_to_thread(&mut session, &thread.thread);
let invocation = invocation(
Arc::new(session),
Arc::new(turn),
@@ -2681,13 +2689,13 @@ async fn send_input_interrupts_before_prompt() {
async fn send_input_accepts_structured_items() {
let (mut session, turn) = make_session_and_context().await;
let manager = thread_manager();
set_agent_control(&mut session, manager.agent_control());
let config = turn.config.as_ref().clone();
let thread = manager
.start_thread(StartThreadOptions::new(config.clone()))
.await
.expect("start thread");
let agent_id = thread.thread_id;
bind_session_to_thread(&mut session, &thread.thread);
let invocation = invocation(
Arc::new(session),
Arc::new(turn),
@@ -2770,13 +2778,13 @@ async fn resume_agent_reports_missing_agent() {
async fn resume_agent_noops_for_active_agent() {
let (mut session, turn) = make_session_and_context().await;
let manager = thread_manager();
set_agent_control(&mut session, manager.agent_control());
let config = turn.config.as_ref().clone();
let thread = manager
.start_thread(StartThreadOptions::new(config.clone()))
.await
.expect("start thread");
let agent_id = thread.thread_id;
bind_session_to_thread(&mut session, &thread.thread);
let status_before = manager.agent_control().get_status(agent_id).await;
let invocation = invocation(
Arc::new(session),
@@ -2809,7 +2817,6 @@ async fn resume_agent_noops_for_active_agent() {
async fn resume_agent_restores_closed_agent_and_accepts_send_input() {
let (mut session, turn) = make_session_and_context().await;
let manager = thread_manager();
set_agent_control(&mut session, manager.agent_control());
let config = turn.config.as_ref().clone();
let thread = manager
.resume_thread_with_history(
@@ -2835,6 +2842,7 @@ async fn resume_agent_restores_closed_agent_and_accepts_send_input() {
.await
.expect("start thread");
let agent_id = thread.thread_id;
bind_session_to_thread(&mut session, &thread.thread);
let _ = manager
.agent_control()
.shutdown_live_agent(agent_id)
@@ -3315,18 +3323,20 @@ async fn multi_agent_v2_wait_agent_accepts_explicit_timeout_at_configured_max()
}
#[tokio::test]
async fn wait_agent_returns_not_found_for_missing_agents() {
let (mut session, turn) = make_session_and_context().await;
async fn wait_agent_hides_foreign_targets_from_events() {
let (session, turn, events) = make_session_and_context_with_rx().await;
let mut session = Arc::into_inner(session).expect("test session");
let manager = thread_manager();
set_agent_control(&mut session, manager.agent_control());
let id_a = ThreadId::new();
let id_b = ThreadId::new();
let start = || manager.start_thread(StartThreadOptions::new(turn.config.as_ref().clone()));
let owned = start().await.expect("start owned thread");
let foreign = start().await.expect("start foreign thread");
bind_session_to_thread(&mut session, &owned.thread);
let invocation = invocation(
Arc::new(session),
Arc::new(turn),
turn,
"wait_agent",
function_payload(json!({
"targets": [id_a.to_string(), id_b.to_string()],
"targets": [owned.thread_id, foreign.thread_id],
"timeout_ms": 10_000
})),
);
@@ -3340,27 +3350,42 @@ async fn wait_agent_returns_not_found_for_missing_agents() {
assert_eq!(
result,
wait::WaitAgentResult {
status: HashMap::from([
(id_a.to_string(), AgentStatus::NotFound),
(id_b.to_string(), AgentStatus::NotFound),
]),
status: HashMap::from([(foreign.thread_id.to_string(), AgentStatus::NotFound)]),
timed_out: false
}
);
assert_eq!(success, None);
let mut items =
std::iter::from_fn(|| events.try_recv().ok()).filter_map(|event| match event.msg {
EventMsg::ItemStarted(event) => Some(event.item),
EventMsg::ItemCompleted(event) => Some(event.item),
_ => None,
});
let (Some(TurnItem::CollabAgentToolCall(start)), Some(TurnItem::CollabAgentToolCall(end))) =
(items.next(), items.next())
else {
panic!("expected wait start and completion");
};
assert_eq!(start.receiver_thread_ids, vec![owned.thread_id]);
let owned_id = owned.thread_id;
assert!(matches!(start.receiver_agents.as_slice(), [agent] if agent.thread_id == owned_id));
assert_eq!(end.status, CollabAgentToolCallStatus::Failed);
assert!(end.receiver_thread_ids.is_empty());
assert!(end.receiver_agents.is_empty());
assert!(end.agents_states.is_empty());
}
#[tokio::test]
async fn wait_agent_times_out_when_status_is_not_final() {
let (mut session, turn) = make_session_and_context().await;
let manager = thread_manager();
set_agent_control(&mut session, manager.agent_control());
let config = turn.config.as_ref().clone();
let thread = manager
.start_thread(StartThreadOptions::new(config.clone()))
.await
.expect("start thread");
let agent_id = thread.thread_id;
bind_session_to_thread(&mut session, &thread.thread);
let invocation = invocation(
Arc::new(session),
Arc::new(turn),
@@ -3397,13 +3422,13 @@ async fn wait_agent_times_out_when_status_is_not_final() {
async fn wait_agent_clamps_short_timeouts_to_minimum() {
let (mut session, turn) = make_session_and_context().await;
let manager = thread_manager();
set_agent_control(&mut session, manager.agent_control());
let config = turn.config.as_ref().clone();
let thread = manager
.start_thread(StartThreadOptions::new(config.clone()))
.await
.expect("start thread");
let agent_id = thread.thread_id;
bind_session_to_thread(&mut session, &thread.thread);
let invocation = invocation(
Arc::new(session),
Arc::new(turn),
@@ -3435,13 +3460,13 @@ async fn wait_agent_clamps_short_timeouts_to_minimum() {
async fn wait_agent_returns_final_status_without_timeout() {
let (mut session, turn) = make_session_and_context().await;
let manager = thread_manager();
set_agent_control(&mut session, manager.agent_control());
let config = turn.config.as_ref().clone();
let thread = manager
.start_thread(StartThreadOptions::new(config.clone()))
.await
.expect("start thread");
let agent_id = thread.thread_id;
bind_session_to_thread(&mut session, &thread.thread);
let mut status_rx = thread.thread.subscribe_status();
let _ = thread
@@ -4339,13 +4364,13 @@ async fn multi_agent_v2_interrupt_agent_rejects_self_target_by_task_name() {
async fn close_agent_submits_shutdown_and_returns_previous_status() {
let (mut session, turn) = make_session_and_context().await;
let manager = thread_manager();
set_agent_control(&mut session, manager.agent_control());
let config = turn.config.as_ref().clone();
let thread = manager
.start_thread(StartThreadOptions::new(config.clone()))
.await
.expect("start thread");
let agent_id = thread.thread_id;
bind_session_to_thread(&mut session, &thread.thread);
let status_before = manager.agent_control().get_status(agent_id).await;
let invocation = invocation(
@@ -4575,11 +4600,6 @@ async fn tool_handlers_cascade_close_and_resume_and_keep_explicitly_closed_subtr
AgentStatus::NotFound
);
let operator = manager
.start_thread(StartThreadOptions::new(config.clone()))
.await
.expect("operator thread should start");
let operator_session = operator.thread.session.clone();
let _ = manager
.agent_control()
.shutdown_live_agent(parent_thread_id)
@@ -4592,8 +4612,8 @@ async fn tool_handlers_cascade_close_and_resume_and_keep_explicitly_closed_subtr
let parent_resume_output = ResumeAgentHandler
.handle(invocation(
operator_session,
operator.thread.session.new_default_turn().await,
parent_session.clone(),
parent_session.new_default_turn().await,
"resume_agent",
function_payload(json!({"id": parent_thread_id.to_string()})),
))
+2
View File
@@ -169,6 +169,8 @@ mod models_etag_responses;
mod multi_agent_mode;
mod multi_agent_resume;
mod multi_agent_tool_descriptions;
#[path = "multi_agent_v1_ownership_tests.rs"]
mod multi_agent_v1_ownership;
#[cfg(unix)]
mod multi_exec_server_sandbox;
mod network_approval;
@@ -0,0 +1,100 @@
//! V1 tool ownership across live threads and saved rollouts.
use anyhow::Result;
use codex_protocol::ThreadId;
use codex_protocol::protocol::MultiAgentVersion;
use codex_protocol::protocol::ThreadHistoryMode;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_function_call_with_namespace;
use core_test_support::responses::mount_sse_once_match;
use core_test_support::responses::mount_sse_sequence;
use core_test_support::responses::sse;
use core_test_support::responses::sse_completed;
use core_test_support::responses::start_mock_server;
use core_test_support::test_codex::test_codex;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use wiremock::matchers::header;
#[tokio::test]
async fn v1_session_ownership() -> Result<()> {
let server = start_mock_server().await;
let test = test_codex()
.with_model_info_override("gpt-5.5", |model| {
model.multi_agent_version = Some(MultiAgentVersion::V1);
})
.with_config(|config| {
config.ephemeral = true;
config.agent_max_threads = Some(1);
})
.build_with_auto_env(&server)
.await?;
let manager = &test.thread_manager;
let call = async |tool: &str, args: Value| -> Result<String> {
let id = ThreadId::new().to_string();
let event = ev_function_call_with_namespace(&id, "multi_agent_v1", tool, &args.to_string());
let response = sse(vec![event, ev_completed("tool")]);
let mock = mount_sse_sequence(&server, vec![response, sse_completed("done")]).await;
test.submit_text_turn(tool).await?;
Ok(mock.function_call_output_text(&id).expect("tool output"))
};
for _ in 0..=1 {
let child_request = header("x-openai-subagent", "collab_spawn");
mount_sse_once_match(&server, child_request, sse_completed("child-done")).await;
let response = call("spawn_agent", json!({"message": "ephemeral helper"})).await?;
let spawned: Value = serde_json::from_str(&response)?;
let child = ThreadId::from_string(spawned["agent_id"].as_str().expect("spawned agent ID"))?;
let thread = manager.get_thread(child).await?;
thread.shutdown_and_wait().await?;
manager.remove_thread(&child).await;
let response = call("close_agent", json!({"target": child})).await?;
let closed: Value = serde_json::from_str(&response)?;
assert_eq!(closed, json!({"previous_status": "not_found"}));
}
let mut options = test.start_thread_options().await;
options.config.ephemeral = false;
options.history_mode = Some(ThreadHistoryMode::Legacy);
let mut resume_config = options.config.clone();
let foreign = manager.start_thread(options).await?;
let id = foreign.thread_id;
foreign.thread.ensure_rollout_materialized().await;
foreign.thread.flush_rollout().await?;
let denied = format!("agent with id {id} not found");
let interrupt = json!({"target": id, "message": "hello", "interrupt": true});
assert_eq!(call("send_input", interrupt).await?, denied);
assert_eq!(call("close_agent", json!({"target": id})).await?, denied);
let path = foreign.thread.rollout_path().expect("saved rollout");
let saved = std::fs::read_to_string(&path)?;
let (header, history) = saved.split_once('\n').expect("session header");
let mut header: Value = serde_json::from_str(header)?;
let meta = &mut header["payload"];
let parent = test.session_configured.thread_id;
meta.as_object_mut().unwrap().remove("session_id");
meta["source"] =
json!({"subagent": {"thread_spawn": {"parent_thread_id": parent, "depth": 1}}});
foreign.thread.shutdown_and_wait().await?;
manager.remove_thread(&id).await;
assert_eq!(call("resume_agent", json!({"id": id})).await?, denied);
let external = tempfile::tempdir()?;
let path = external.path().join(path.file_name().unwrap());
std::fs::write(&path, format!("{header}\n{history}"))?;
resume_config.agents_enabled = false;
let resumed = manager
.resume_legacy_thread_from_rollout(
resume_config,
path,
manager.auth_manager(),
/*parent_trace*/ None,
Default::default(),
)
.await?;
let session_id = resumed.session_configured.session_id;
assert_eq!(session_id, test.session_configured.session_id);
Ok(())
}
+45 -7
View File
@@ -294,6 +294,7 @@ fn render_tool_call(
Some(waiting_begin(receiver_thread_ids, &mut agent_metadata))
} else {
Some(waiting_end(
status,
receiver_thread_ids,
agents_states,
&mut agent_metadata,
@@ -449,12 +450,18 @@ fn waiting_begin(
}
fn waiting_end(
status: &CollabAgentToolCallStatus,
receiver_thread_ids: &[String],
agents_states: &std::collections::HashMap<String, CollabAgentState>,
agent_metadata: &mut impl FnMut(ThreadId) -> AgentMetadata,
) -> WebHyperlinkHistoryCell {
let title = if matches!(status, CollabAgentToolCallStatus::Failed) {
"Finished waiting with an error"
} else {
"Finished waiting"
};
let details = wait_complete_lines(receiver_thread_ids, agents_states, agent_metadata);
collab_event(title_text("Finished waiting"), details)
collab_event(title_text(title), details)
}
fn close_end(
@@ -600,7 +607,7 @@ fn wait_complete_lines(
let parsed_thread_id = parse_thread_id(thread_id)?;
let status = agents_states.get(thread_id)?;
seen.insert(parsed_thread_id);
Some((parsed_thread_id, agent_metadata(parsed_thread_id), status))
Some((parsed_thread_id, status))
})
.collect::<Vec<_>>();
@@ -608,20 +615,20 @@ fn wait_complete_lines(
.iter()
.filter_map(|(thread_id, status)| {
let parsed_thread_id = parse_thread_id(thread_id)?;
(!seen.contains(&parsed_thread_id))
.then(|| (parsed_thread_id, agent_metadata(parsed_thread_id), status))
(!seen.contains(&parsed_thread_id)).then_some((parsed_thread_id, status))
})
.collect::<Vec<_>>();
extras.sort_by_key(|entry| entry.0.to_string());
entries.extend(extras);
entries.retain(|(_, status)| status.status != CollabAgentStatus::NotFound);
if entries.is_empty() {
vec!["No agents completed yet".into()]
} else {
entries
.into_iter()
.map(|(thread_id, metadata, status)| {
let mut line = agent_label_line(agent_label(thread_id, &metadata));
.map(|(thread_id, status)| {
let mut line = agent_label_line(agent_label(thread_id, &agent_metadata(thread_id)));
line.line.push_span(": ".dim());
line.line.spans.extend(status_summary_spans(status));
line
@@ -843,6 +850,37 @@ mod tests {
.map(|link| (link.agent_id(), link.terminal_destination()))
.collect();
assert_eq!(targets, vec![(Some(robie_id), None), (Some(bob_id), None)]);
let finished_with_error = tool_call_history_cell(
&ThreadItemPayload::CollabAgentToolCall {
id: "call-wait-mixed".to_string(),
tool: CollabAgentTool::Wait,
status: CollabAgentToolCallStatus::Failed,
sender_thread_id: sender_thread_id.to_string(),
receiver_thread_ids: vec![robie_id.to_string(), bob_id.to_string()],
prompt: None,
model: None,
reasoning_effort: None,
agents_states: HashMap::from([
(
robie_id.to_string(),
agent_state(CollabAgentStatus::Completed, Some("39916800")),
),
(
bob_id.to_string(),
agent_state(CollabAgentStatus::NotFound, /*message*/ None),
),
(
"00000000-0000-0000-0000-000000000004".to_string(),
agent_state(CollabAgentStatus::NotFound, /*message*/ None),
),
]),
},
/*cached_spawn_request*/ None,
|thread_id| metadata_for(thread_id, robie_id, bob_id),
)
.expect("wait with a rejected target renders");
let close = tool_call_history_cell(
&ThreadItemPayload::CollabAgentToolCall {
id: "call-close".to_string(),
@@ -887,7 +925,7 @@ mod tests {
)
.expect("wait without targets renders")
});
let snapshot = [spawn, send, waiting, finished, close]
let snapshot = [spawn, send, waiting, finished, finished_with_error, close]
.iter()
.chain(&waits_without_targets)
.map(cell_to_text)
@@ -14,6 +14,9 @@ expression: snapshot
└ Robie [explorer]: Completed - 39916800
Bob [worker]: Error - tool timeout
• Finished waiting with an error
└ Robie [explorer]: Completed - 39916800
• Closed Robie [explorer]
• Waiting