diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index bc69103e2a..83e1a16c29 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -383,7 +383,16 @@ Like `thread/resume`, experimental clients can pass `excludeTurns: true` to `thr ### 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. - `limit` — server defaults to a reasonable page size if unset. diff --git a/codex-rs/app-server/src/request_processors.rs b/codex-rs/app-server/src/request_processors.rs index 9afaf18ede..1c4f2feda2 100644 --- a/codex-rs/app-server/src/request_processors.rs +++ b/codex-rs/app-server/src/request_processors.rs @@ -536,6 +536,7 @@ mod plugins; mod process_exec_processor; mod remote_control_processor; mod search; +mod thread_enrichment; mod thread_fork_goal; mod thread_processor; mod token_usage_replay; diff --git a/codex-rs/app-server/src/request_processors/thread_enrichment.rs b/codex-rs/app-server/src/request_processors/thread_enrichment.rs new file mode 100644 index 0000000000..e8e46a64c5 --- /dev/null +++ b/codex-rs/app-server/src/request_processors/thread_enrichment.rs @@ -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( + 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; +} diff --git a/codex-rs/app-server/src/request_processors/thread_processor.rs b/codex-rs/app-server/src/request_processors/thread_processor.rs index 15513bfd96..c4e1ce1cf6 100644 --- a/codex-rs/app-server/src/request_processors/thread_processor.rs +++ b/codex-rs/app-server/src/request_processors/thread_processor.rs @@ -1,3 +1,4 @@ +use super::thread_enrichment::enrich_loaded_threads; use super::thread_fork_goal::inherit_thread_goal_snapshot; use super::turn_processor::can_accept_direct_input; use super::*; @@ -2062,8 +2063,7 @@ impl ThreadRequestProcessor { let backwards_cursor = stored_threads.first().and_then(|thread| { thread_backwards_cursor_for_sort_key(thread, store_sort_key, sort_direction) }); - let mut threads = Vec::with_capacity(stored_threads.len()); - let mut status_ids = Vec::with_capacity(stored_threads.len()); + let mut data = Vec::with_capacity(stored_threads.len()); let fallback_provider = self.config.model_provider_id.clone(); for stored_thread in stored_threads { @@ -2072,24 +2072,16 @@ impl ThreadRequestProcessor { fallback_provider.as_str(), &self.config.cwd, ); - status_ids.push(thread.id.clone()); - threads.push(thread); + data.push(thread); } - let statuses = self - .thread_watch_manager - .loaded_statuses_for_threads(status_ids) - .await; - - let data: Vec<_> = threads - .into_iter() - .map(|mut thread| { - if let Some(status) = statuses.get(&thread.id) { - thread.status = status.clone(); - } - thread - }) - .collect(); + enrich_loaded_threads( + &self.thread_manager, + &self.thread_watch_manager, + data.as_mut_slice(), + |thread| thread, + ) + .await; Ok(ThreadListResponse { data, next_cursor, @@ -2191,30 +2183,26 @@ impl ThreadRequestProcessor { ) }); let fallback_provider = self.config.model_provider_id.clone(); - let mut results = Vec::with_capacity(search_results.len()); - let mut status_ids = Vec::with_capacity(search_results.len()); + let mut data = Vec::with_capacity(search_results.len()); for result in search_results { let (thread, _) = thread_from_stored_thread( result.thread, fallback_provider.as_str(), &self.config.cwd, ); - status_ids.push(thread.id.clone()); - results.push((thread, result.snippet)); + data.push(ThreadSearchResult { + thread, + snippet: result.snippet, + }); } - let statuses = self - .thread_watch_manager - .loaded_statuses_for_threads(status_ids) - .await; - let data = results - .into_iter() - .map(|(mut thread, snippet)| { - if let Some(status) = statuses.get(&thread.id) { - thread.status = status.clone(); - } - ThreadSearchResult { thread, snippet } - }) - .collect(); + + enrich_loaded_threads( + &self.thread_manager, + &self.thread_watch_manager, + data.as_mut_slice(), + |result| &mut result.thread, + ) + .await; Ok(ThreadSearchResponse { data, diff --git a/codex-rs/app-server/src/thread_status.rs b/codex-rs/app-server/src/thread_status.rs index 35a5921066..b4a3802e81 100644 --- a/codex-rs/app-server/src/thread_status.rs +++ b/codex-rs/app-server/src/thread_status.rs @@ -116,14 +116,15 @@ impl ThreadWatchManager { pub(crate) async fn loaded_statuses_for_threads( &self, - thread_ids: Vec, + thread_ids: impl IntoIterator, ) -> HashMap { let state = self.state.lock().await; thread_ids .into_iter() - .map(|thread_id| { - let status = state.loaded_status_for_thread(&thread_id); - (thread_id, status) + .filter_map(|thread_id| { + state + .status_for(&thread_id) + .map(|status| (thread_id, status)) }) .collect() } @@ -641,15 +642,22 @@ mod tests { } #[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(); manager.upsert_thread(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 .loaded_statuses_for_threads(vec![ INTERACTIVE_THREAD_ID.to_string(), NON_INTERACTIVE_THREAD_ID.to_string(), + UNTRACKED_THREAD_ID.to_string(), ]) .await; @@ -663,6 +671,7 @@ mod tests { statuses.get(NON_INTERACTIVE_THREAD_ID), Some(&ThreadStatus::NotLoaded), ); + assert_eq!(statuses.get(UNTRACKED_THREAD_ID), None); } #[tokio::test] diff --git a/codex-rs/app-server/tests/suite/v2/thread_list.rs b/codex-rs/app-server/tests/suite/v2/thread_list.rs index ab54970e6e..956a048754 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_list.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_list.rs @@ -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_with_source; 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::rollout_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::ThreadListCwdFilter; 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::ThreadSortKey; use codex_app_server_protocol::ThreadSourceKind; @@ -31,10 +34,13 @@ use codex_core::ARCHIVED_SESSIONS_SUBDIR; use codex_git_utils::GitSha; use codex_protocol::ThreadId; use codex_protocol::protocol::GitInfo as CoreGitInfo; +use codex_protocol::protocol::MultiAgentVersion; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::RolloutLine; use codex_protocol::protocol::SessionSource as CoreSessionSource; 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_utils_absolute_path::test_support::PathExt; use core_test_support::responses; @@ -136,7 +142,7 @@ async fn list_threads_for_relation( archived: None, section_id: None, cwd: None, - use_state_db_only: false, + use_state_db_only: true, search_term: None, parent_thread_id, ancestor_thread_id, @@ -1193,6 +1199,208 @@ async fn thread_list_empty_source_kinds_defaults_to_interactive_only() -> Result 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::>(), + 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::>(), + 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::>(), + expected_subagents + ); + assert_eq!(response.next_cursor, None); + + Ok(()) +} + #[tokio::test] async fn thread_list_filters_by_source_kind_subagent_thread_spawn() -> Result<()> { let codex_home = TempDir::new()?; diff --git a/codex-rs/app-server/tests/suite/v2/turn_start.rs b/codex-rs/app-server/tests/suite/v2/turn_start.rs index 3d0be58c54..44de5a425d 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -3415,6 +3415,44 @@ async fn direct_input_to_multi_agent_v2_subagent_is_rejected() -> Result<()> { }) .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 .send_turn_start_request(TurnStartParams { thread_id: child_thread_id.clone(),