Report direct input capability for listed subagents (#35944)

## What changed

- Enrich `thread/list` and `thread/search` results for loaded spawned threads with live status and `canAcceptDirectInput`.
- Report `true` for V1 agents that accept direct input and `false` for parent-owned V2 agents, while leaving the capability `null` when it is unavailable or inapplicable.
- Distinguish untracked threads from threads known to have shut down when resolving loaded status.

## Testing

- Cover list, search, ancestor-filtered list, and rejected V2 direct-input behavior.

GitOrigin-RevId: d5faf2fc379a236661ff9167391541473ce5c1eb
This commit is contained in:
Tamir Duberstein authored and copyberry committed 2026-07-29 12:13:14 +00:00
1 parent a4d2f31022
commit 9a6668f674
7 files changed
+374 -42

No files matched your search

+10 -1
View File
@@ -383,7 +383,16 @@ Like `thread/resume`, experimental clients can pass `excludeTurns: true` to `thr
### Example: List threads (with pagination & filters) ### Example: List threads (with pagination & filters)
`thread/list` lets you render a history UI. Results default to `createdAt` (newest first) descending. Pass any combination of: `thread/list` lets you render a history UI. Results default to `createdAt` (newest first) descending.
For a loaded spawned thread, experimental `canAcceptDirectInput` is `true` when
a V1 agent accepts direct input and `false` when a V2 agent is owned by its
parent. It is `null` when the capability is unavailable or inapplicable,
including unloaded threads and ordinary CLI threads. Both `thread/list` and
`thread/search` derive the capability from loaded thread state, not persisted
metadata.
Pass any combination of:
- `cursor` — opaque string from a prior response; omit for the first page. - `cursor` — opaque string from a prior response; omit for the first page.
- `limit` — server defaults to a reasonable page size if unset. - `limit` — server defaults to a reasonable page size if unset.
@@ -536,6 +536,7 @@ mod plugins;
mod process_exec_processor; mod process_exec_processor;
mod remote_control_processor; mod remote_control_processor;
mod search; mod search;
mod thread_enrichment;
mod thread_fork_goal; mod thread_fork_goal;
mod thread_processor; mod thread_processor;
mod token_usage_replay; mod token_usage_replay;
@@ -0,0 +1,79 @@
use super::turn_processor::can_accept_direct_input;
use crate::thread_status::ThreadWatchManager;
use crate::thread_status::resolve_thread_status;
use codex_app_server_protocol::SessionSource;
use codex_app_server_protocol::Thread;
use codex_app_server_protocol::ThreadStatus;
use codex_core::ThreadManager;
use codex_protocol::ThreadId;
use codex_protocol::protocol::AgentStatus;
use codex_protocol::protocol::SubAgentSource;
pub(super) async fn enrich_loaded_threads<T>(
thread_manager: &ThreadManager,
thread_watch_manager: &ThreadWatchManager,
threads: &mut [T],
mut as_thread: impl FnMut(&mut T) -> &mut Thread,
) {
let statuses = thread_watch_manager
.loaded_statuses_for_threads(
threads
.iter_mut()
.map(&mut as_thread)
.map(|thread| thread.id.clone()),
)
.await;
futures::future::join_all(threads.iter_mut().map(as_thread).map(|thread| {
let statuses = &statuses;
async move {
let watched_status = statuses.get(&thread.id);
if let Some(status) = watched_status {
thread.status = status.clone();
}
if !matches!(
&thread.source,
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
) || matches!(watched_status, Some(ThreadStatus::NotLoaded))
{
return;
}
let Ok(thread_id) = ThreadId::from_string(&thread.id) else {
return;
};
let Ok(loaded_thread) = thread_manager.get_thread(thread_id).await else {
return;
};
match loaded_thread.agent_status().await {
AgentStatus::Running => {
if watched_status.is_none() {
thread.status = resolve_thread_status(
ThreadStatus::Idle,
/*has_in_progress_turn*/ true,
);
}
}
AgentStatus::PendingInit | AgentStatus::Interrupted | AgentStatus::Completed(_) => {
if watched_status.is_none() {
thread.status = ThreadStatus::Idle;
}
}
AgentStatus::Errored(_) => {
thread.status = ThreadStatus::SystemError;
}
AgentStatus::Shutdown | AgentStatus::NotFound => {
thread.status = ThreadStatus::NotLoaded;
return;
}
}
let config_snapshot = loaded_thread.config_snapshot().await;
thread.can_accept_direct_input = Some(can_accept_direct_input(
loaded_thread.multi_agent_version(),
&config_snapshot.session_source,
));
}
}))
.await;
}
@@ -1,3 +1,4 @@
use super::thread_enrichment::enrich_loaded_threads;
use super::thread_fork_goal::inherit_thread_goal_snapshot; use super::thread_fork_goal::inherit_thread_goal_snapshot;
use super::turn_processor::can_accept_direct_input; use super::turn_processor::can_accept_direct_input;
use super::*; use super::*;
@@ -2062,8 +2063,7 @@ impl ThreadRequestProcessor {
let backwards_cursor = stored_threads.first().and_then(|thread| { let backwards_cursor = stored_threads.first().and_then(|thread| {
thread_backwards_cursor_for_sort_key(thread, store_sort_key, sort_direction) thread_backwards_cursor_for_sort_key(thread, store_sort_key, sort_direction)
}); });
let mut threads = Vec::with_capacity(stored_threads.len()); let mut data = Vec::with_capacity(stored_threads.len());
let mut status_ids = Vec::with_capacity(stored_threads.len());
let fallback_provider = self.config.model_provider_id.clone(); let fallback_provider = self.config.model_provider_id.clone();
for stored_thread in stored_threads { for stored_thread in stored_threads {
@@ -2072,24 +2072,16 @@ impl ThreadRequestProcessor {
fallback_provider.as_str(), fallback_provider.as_str(),
&self.config.cwd, &self.config.cwd,
); );
status_ids.push(thread.id.clone()); data.push(thread);
threads.push(thread);
} }
let statuses = self enrich_loaded_threads(
.thread_watch_manager &self.thread_manager,
.loaded_statuses_for_threads(status_ids) &self.thread_watch_manager,
.await; data.as_mut_slice(),
|thread| thread,
let data: Vec<_> = threads )
.into_iter() .await;
.map(|mut thread| {
if let Some(status) = statuses.get(&thread.id) {
thread.status = status.clone();
}
thread
})
.collect();
Ok(ThreadListResponse { Ok(ThreadListResponse {
data, data,
next_cursor, next_cursor,
@@ -2191,30 +2183,26 @@ impl ThreadRequestProcessor {
) )
}); });
let fallback_provider = self.config.model_provider_id.clone(); let fallback_provider = self.config.model_provider_id.clone();
let mut results = Vec::with_capacity(search_results.len()); let mut data = Vec::with_capacity(search_results.len());
let mut status_ids = Vec::with_capacity(search_results.len());
for result in search_results { for result in search_results {
let (thread, _) = thread_from_stored_thread( let (thread, _) = thread_from_stored_thread(
result.thread, result.thread,
fallback_provider.as_str(), fallback_provider.as_str(),
&self.config.cwd, &self.config.cwd,
); );
status_ids.push(thread.id.clone()); data.push(ThreadSearchResult {
results.push((thread, result.snippet)); thread,
snippet: result.snippet,
});
} }
let statuses = self
.thread_watch_manager enrich_loaded_threads(
.loaded_statuses_for_threads(status_ids) &self.thread_manager,
.await; &self.thread_watch_manager,
let data = results data.as_mut_slice(),
.into_iter() |result| &mut result.thread,
.map(|(mut thread, snippet)| { )
if let Some(status) = statuses.get(&thread.id) { .await;
thread.status = status.clone();
}
ThreadSearchResult { thread, snippet }
})
.collect();
Ok(ThreadSearchResponse { Ok(ThreadSearchResponse {
data, data,
+14 -5
View File
@@ -116,14 +116,15 @@ impl ThreadWatchManager {
pub(crate) async fn loaded_statuses_for_threads( pub(crate) async fn loaded_statuses_for_threads(
&self, &self,
thread_ids: Vec<String>, thread_ids: impl IntoIterator<Item = String>,
) -> HashMap<String, ThreadStatus> { ) -> HashMap<String, ThreadStatus> {
let state = self.state.lock().await; let state = self.state.lock().await;
thread_ids thread_ids
.into_iter() .into_iter()
.map(|thread_id| { .filter_map(|thread_id| {
let status = state.loaded_status_for_thread(&thread_id); state
(thread_id, status) .status_for(&thread_id)
.map(|status| (thread_id, status))
}) })
.collect() .collect()
} }
@@ -641,15 +642,22 @@ mod tests {
} }
#[tokio::test] #[tokio::test]
async fn loaded_statuses_default_to_not_loaded_for_untracked_threads() { async fn loaded_statuses_distinguish_shutdown_from_untracked_threads() {
const UNTRACKED_THREAD_ID: &str = "00000000-0000-0000-0000-000000000003";
let manager = ThreadWatchManager::new(); let manager = ThreadWatchManager::new();
manager.upsert_thread(INTERACTIVE_THREAD_ID).await; manager.upsert_thread(INTERACTIVE_THREAD_ID).await;
manager.note_turn_started(INTERACTIVE_THREAD_ID).await; manager.note_turn_started(INTERACTIVE_THREAD_ID).await;
manager.upsert_thread(NON_INTERACTIVE_THREAD_ID).await;
manager
.note_thread_shutdown(NON_INTERACTIVE_THREAD_ID)
.await;
let statuses = manager let statuses = manager
.loaded_statuses_for_threads(vec![ .loaded_statuses_for_threads(vec![
INTERACTIVE_THREAD_ID.to_string(), INTERACTIVE_THREAD_ID.to_string(),
NON_INTERACTIVE_THREAD_ID.to_string(), NON_INTERACTIVE_THREAD_ID.to_string(),
UNTRACKED_THREAD_ID.to_string(),
]) ])
.await; .await;
@@ -663,6 +671,7 @@ mod tests {
statuses.get(NON_INTERACTIVE_THREAD_ID), statuses.get(NON_INTERACTIVE_THREAD_ID),
Some(&ThreadStatus::NotLoaded), Some(&ThreadStatus::NotLoaded),
); );
assert_eq!(statuses.get(UNTRACKED_THREAD_ID), None);
} }
#[tokio::test] #[tokio::test]
@@ -5,6 +5,7 @@ use app_test_support::create_fake_parented_rollout_with_source;
use app_test_support::create_fake_rollout; use app_test_support::create_fake_rollout;
use app_test_support::create_fake_rollout_with_source; use app_test_support::create_fake_rollout_with_source;
use app_test_support::create_final_assistant_message_sse_response; use app_test_support::create_final_assistant_message_sse_response;
use app_test_support::create_mock_responses_server_repeating_assistant;
use app_test_support::create_mock_responses_server_sequence; use app_test_support::create_mock_responses_server_sequence;
use app_test_support::rollout_path; use app_test_support::rollout_path;
use app_test_support::test_absolute_path; use app_test_support::test_absolute_path;
@@ -18,6 +19,8 @@ use codex_app_server_protocol::SessionSource;
use codex_app_server_protocol::SortDirection; use codex_app_server_protocol::SortDirection;
use codex_app_server_protocol::ThreadListCwdFilter; use codex_app_server_protocol::ThreadListCwdFilter;
use codex_app_server_protocol::ThreadListResponse; use codex_app_server_protocol::ThreadListResponse;
use codex_app_server_protocol::ThreadResumeParams;
use codex_app_server_protocol::ThreadResumeResponse;
use codex_app_server_protocol::ThreadSearchResponse; use codex_app_server_protocol::ThreadSearchResponse;
use codex_app_server_protocol::ThreadSortKey; use codex_app_server_protocol::ThreadSortKey;
use codex_app_server_protocol::ThreadSourceKind; use codex_app_server_protocol::ThreadSourceKind;
@@ -31,10 +34,13 @@ use codex_core::ARCHIVED_SESSIONS_SUBDIR;
use codex_git_utils::GitSha; use codex_git_utils::GitSha;
use codex_protocol::ThreadId; use codex_protocol::ThreadId;
use codex_protocol::protocol::GitInfo as CoreGitInfo; use codex_protocol::protocol::GitInfo as CoreGitInfo;
use codex_protocol::protocol::MultiAgentVersion;
use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::RolloutItem;
use codex_protocol::protocol::RolloutLine; use codex_protocol::protocol::RolloutLine;
use codex_protocol::protocol::SessionSource as CoreSessionSource; use codex_protocol::protocol::SessionSource as CoreSessionSource;
use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::SubAgentSource;
use codex_rollout::append_rollout_item_to_path;
use codex_rollout::read_session_meta_line;
use codex_state::DirectionalThreadSpawnEdgeStatus; use codex_state::DirectionalThreadSpawnEdgeStatus;
use codex_utils_absolute_path::test_support::PathExt; use codex_utils_absolute_path::test_support::PathExt;
use core_test_support::responses; use core_test_support::responses;
@@ -136,7 +142,7 @@ async fn list_threads_for_relation(
archived: None, archived: None,
section_id: None, section_id: None,
cwd: None, cwd: None,
use_state_db_only: false, use_state_db_only: true,
search_term: None, search_term: None,
parent_thread_id, parent_thread_id,
ancestor_thread_id, ancestor_thread_id,
@@ -1193,6 +1199,208 @@ async fn thread_list_empty_source_kinds_defaults_to_interactive_only() -> Result
Ok(()) Ok(())
} }
#[tokio::test]
async fn thread_list_reports_loaded_subagent_direct_input_capability() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
MockResponsesConfig::new(&server.uri()).write(codex_home.path())?;
let cli_id = create_fake_rollout(
codex_home.path(),
"2025-02-01T09-00-00",
"2025-02-01T09:00:00Z",
"CLI",
Some("mock_provider"),
/*git_info*/ None,
)?;
let parent_thread_id = ThreadId::from_string(&cli_id)?;
let mut expected = vec![(cli_id.clone(), None, false)];
let mut threads_to_resume = vec![cli_id.clone()];
for (filename_ts, timestamp, version, capability, should_resume) in [
(
"2025-02-01T10-00-00",
"2025-02-01T10:00:00Z",
MultiAgentVersion::V1,
Some(true),
true,
),
(
"2025-02-01T11-00-00",
"2025-02-01T11:00:00Z",
MultiAgentVersion::V2,
Some(false),
true,
),
(
"2025-02-01T12-00-00",
"2025-02-01T12:00:00Z",
MultiAgentVersion::V2,
None,
false,
),
] {
let thread_id = create_fake_rollout_with_source(
codex_home.path(),
filename_ts,
timestamp,
"Subagent",
Some("mock_provider"),
/*git_info*/ None,
CoreSessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id,
depth: 1,
agent_path: None,
agent_nickname: None,
agent_role: None,
}),
)?;
let path = rollout_path(codex_home.path(), filename_ts, &thread_id);
let mut session_meta = read_session_meta_line(&path).await?;
session_meta.meta.multi_agent_version = Some(version);
append_rollout_item_to_path(&path, &RolloutItem::SessionMeta(session_meta)).await?;
if should_resume {
threads_to_resume.push(thread_id.clone());
}
expected.push((thread_id, capability, !should_resume));
}
let mut mcp = init_mcp(codex_home.path()).await?;
for thread_id in threads_to_resume {
let request_id = mcp
.send_thread_resume_request(ThreadResumeParams {
thread_id,
..Default::default()
})
.await?;
let _: ThreadResumeResponse =
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await??;
}
let response = list_threads(
&mut mcp,
/*cursor*/ None,
Some(10),
Some(vec!["mock_provider".to_string()]),
Some(vec![
ThreadSourceKind::Cli,
ThreadSourceKind::SubAgentThreadSpawn,
]),
/*archived*/ None,
)
.await?;
expected.reverse();
assert_eq!(
response
.data
.into_iter()
.map(|thread| {
(
thread.id,
thread.can_accept_direct_input,
matches!(thread.status, ThreadStatus::NotLoaded),
)
})
.collect::<Vec<_>>(),
expected
);
assert_eq!(response.next_cursor, None);
let request_id = mcp
.send_thread_search_request(codex_app_server_protocol::ThreadSearchParams {
cursor: None,
limit: Some(10),
sort_key: None,
sort_direction: None,
source_kinds: Some(vec![ThreadSourceKind::SubAgentThreadSpawn]),
archived: None,
search_term: "Subagent".to_string(),
})
.await?;
let response: ThreadSearchResponse =
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await??;
let expected_subagents: Vec<_> = expected
.into_iter()
.filter(|(thread_id, _, _)| thread_id != &cli_id)
.collect();
assert_eq!(
response
.data
.into_iter()
.map(|result| {
let thread = result.thread;
(
thread.id,
thread.can_accept_direct_input,
matches!(thread.status, ThreadStatus::NotLoaded),
)
})
.collect::<Vec<_>>(),
expected_subagents
);
let state_db = codex_state::StateRuntime::init(
codex_state::SqliteConfig::new_for_testing(codex_home.path().abs()),
"mock_provider".to_string(),
)
.await?;
for (thread_id, _, _) in &expected_subagents {
state_db
.upsert_thread_spawn_edge(
parent_thread_id,
ThreadId::from_string(thread_id)?,
DirectionalThreadSpawnEdgeStatus::Open,
)
.await?;
}
state_db
.mark_backfill_complete(/*last_watermark*/ None)
.await?;
let response: ThreadListResponse = mcp
.request(|request_id| ClientRequest::ThreadList {
request_id,
params: codex_app_server_protocol::ThreadListParams {
cursor: None,
limit: Some(10),
sort_key: None,
sort_direction: None,
model_providers: Some(vec!["mock_provider".to_string()]),
source_kinds: Some(vec![ThreadSourceKind::SubAgentThreadSpawn]),
archived: None,
section_id: None,
cwd: None,
use_state_db_only: true,
search_term: None,
parent_thread_id: None,
ancestor_thread_id: Some(parent_thread_id.to_string()),
},
})
.await?;
assert!(
response
.data
.iter()
.all(|thread| thread.parent_thread_id.as_deref() == Some(cli_id.as_str()))
);
assert_eq!(
response
.data
.into_iter()
.map(|thread| {
(
thread.id,
thread.can_accept_direct_input,
matches!(thread.status, ThreadStatus::NotLoaded),
)
})
.collect::<Vec<_>>(),
expected_subagents
);
assert_eq!(response.next_cursor, None);
Ok(())
}
#[tokio::test] #[tokio::test]
async fn thread_list_filters_by_source_kind_subagent_thread_spawn() -> Result<()> { async fn thread_list_filters_by_source_kind_subagent_thread_spawn() -> Result<()> {
let codex_home = TempDir::new()?; let codex_home = TempDir::new()?;
@@ -3415,6 +3415,44 @@ async fn direct_input_to_multi_agent_v2_subagent_is_rejected() -> Result<()> {
}) })
.await??; .await??;
let listed: codex_app_server_protocol::ThreadListResponse = mcp
.request(|request_id| ClientRequest::ThreadList {
request_id,
params: codex_app_server_protocol::ThreadListParams {
cursor: None,
limit: Some(10),
sort_key: None,
sort_direction: None,
model_providers: None,
source_kinds: Some(vec![
codex_app_server_protocol::ThreadSourceKind::SubAgentThreadSpawn,
]),
archived: None,
section_id: None,
cwd: None,
use_state_db_only: true,
search_term: None,
parent_thread_id: None,
ancestor_thread_id: None,
},
})
.await?;
let listed_child = listed
.data
.iter()
.find(|listed| listed.id == child_thread_id)
.context("spawned child is missing from thread/list")?;
assert!(matches!(
&listed_child.source,
codex_app_server_protocol::SessionSource::SubAgent(
codex_protocol::protocol::SubAgentSource::ThreadSpawn {
agent_path: Some(_),
..
}
)
));
assert_eq!(listed_child.can_accept_direct_input, Some(false));
let direct_turn_req = mcp let direct_turn_req = mcp
.send_turn_start_request(TurnStartParams { .send_turn_start_request(TurnStartParams {
thread_id: child_thread_id.clone(), thread_id: child_thread_id.clone(),