From a66312f2e9d680866ec73f21e03933c6261d9d8a Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Mon, 23 Nov 2026 19:56:47 +0000 Subject: [PATCH] Resolve subagent nicknames in TUI transcripts (#63444) ## Why Live and replayed tool calls can show raw thread IDs when subagent metadata hasn't arrived yet, making it harder to tell which agents were spawned or are being waited on. ## What changed Look up missing nicknames in the background and refresh tool-call rows in the active transcript and parked panes as metadata arrives. Use archived subagent metadata to label older rows while keeping archived threads out of the agent picker. ## Testing Add regression coverage for replayed spawn rows and live wait rows when metadata arrives late, including a subagent that closes during the lookup. Extend picker coverage to verify that archived metadata is cached. GitOrigin-RevId: 47a5f585d6ebc1b0d9ac49020efeaf6c1b205198 --- codex-rs/tui/src/app/agent_picker.rs | 107 ++++++++++++++- codex-rs/tui/src/app/event_dispatch.rs | 3 +- codex-rs/tui/src/app/history_pagination.rs | 7 +- .../tui/src/app/sidebar_agent_status_tests.rs | 2 +- codex-rs/tui/src/app/tests.rs | 48 ++----- .../src/app/tests/agents_navigation_tests.rs | 123 ++++++++++++++++++ codex-rs/tui/src/app/thread_routing.rs | 3 + codex-rs/tui/src/app_event.rs | 3 +- codex-rs/tui/src/chatwidget.rs | 2 +- codex-rs/tui/src/multi_agents.rs | 23 +++- codex-rs/tui/src/multi_agents_history.rs | 90 +++++++++++++ 11 files changed, 356 insertions(+), 55 deletions(-) create mode 100644 codex-rs/tui/src/multi_agents_history.rs diff --git a/codex-rs/tui/src/app/agent_picker.rs b/codex-rs/tui/src/app/agent_picker.rs index c3b42a87d0..777503ab29 100644 --- a/codex-rs/tui/src/app/agent_picker.rs +++ b/codex-rs/tui/src/app/agent_picker.rs @@ -6,6 +6,7 @@ use super::app_server_event_targets::server_notification_thread_target; use super::sidebar_subagents::PendingLink; use super::*; use crate::app_event::AgentPickerThreadRefresh; +use crate::multi_agents::CollabHistoryCell; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::SortDirection; use codex_app_server_protocol::ThreadListParams; @@ -19,6 +20,66 @@ const AGENT_PICKER_PAGE_SIZE: u32 = 100; const AGENT_PICKER_MAX_THREADS: usize = 1_000; impl App { + pub(super) fn prepare_collab_history( + &mut self, + app_server: &AppServerSession, + cell: &mut dyn HistoryCell, + ) { + let Some(cell) = cell.as_any_mut().downcast_mut::() else { + return; + }; + // A refresh can finish between queuing and inserting a history cell. + if let Some(updated) = cell.refreshed(|id| self.chat_widget.collab_agent_metadata(id)) { + *cell = updated; + } + if !self.reconnect.offline + && let Some(root) = self.primary_thread_id + && cell.needs_names() + && (self.initial_history_replay_buffer.is_some() + || !self.agent_navigation.queue_picker_refresh(root)) + { + self.refresh_agent_picker_threads(app_server, root); + } + } + + pub(super) fn refresh_collab_history(&mut self) { + let mut changed = false; + let focused = (&mut self.transcript_cells, &mut self.transcript_view, true); + let parked = self + .side_companions + .values_mut() + .map(|pane| (&mut pane.cells, &mut pane.view, false)); + for (cells, view, is_focused) in std::iter::once(focused).chain(parked) { + for index in 0..cells.len() { + let Some(updated) = cells[index] + .as_any() + .downcast_ref::() + .and_then(|cell| { + cell.refreshed(|id| self.chat_widget.collab_agent_metadata(id)) + }) + else { + continue; + }; + let replacement: Arc = Arc::new(updated); + let range = index..index + 1; + view.replace_range(cells, range.clone(), &replacement); + if is_focused { + // Update pending output without rewriting scrollback already handed to the terminal. + self.native_history + .consolidate(&cells[range.clone()], &replacement); + if let Some(Overlay::Transcript(overlay)) = &mut self.overlay { + overlay.consolidate_cells(range, Arc::clone(&replacement)); + } + } + cells[index] = replacement; + changed = true; + } + } + if changed { + self.chat_widget.request_redraw(); + } + } + pub(super) fn refresh_agent_picker_threads( &mut self, app_server: &AppServerSession, @@ -79,11 +140,17 @@ impl App { .collect(); listed += page_threads.len(); if archived { - refresh.archived_thread_ids.extend( - page_threads - .into_iter() - .filter_map(|thread| ThreadId::from_string(&thread.id).ok()), - ); + for thread in page_threads { + if let Ok(id) = ThreadId::from_string(&thread.id) { + refresh.archived_threads.insert( + id, + crate::multi_agents::AgentMetadata { + agent_nickname: thread.agent_nickname, + agent_role: thread.agent_role, + }, + ); + } + } } else { refresh.threads.extend(page_threads); } @@ -153,7 +220,18 @@ impl App { let is_running = matches!(thread.status, ThreadStatus::Active { .. }); let update_liveness = previous.is_none() || !is_running; let is_closed = !live && matches!(thread.status, ThreadStatus::NotLoaded); - if !is_closed && previous.is_some_and(|entry| entry.is_closed) { + if !is_closed && let Some(closed) = previous.filter(|entry| entry.is_closed) { + // The child may have closed while discovery was in flight. Its name is + // still useful, even though the list cannot reopen it. + if closed.agent_nickname.is_none() && thread.agent_nickname.is_some() { + let role = closed.agent_role.clone().or(thread.agent_role); + self.upsert_agent_picker_thread( + thread_id, + thread.agent_nickname, + role, + /*is_closed*/ true, + ); + } continue; } let agent_path = crate::app_server_session::source_agent_path(&thread.source); @@ -176,7 +254,21 @@ impl App { self.seed_discovered_sidebar_agent(root, thread_id, &thread.status); } } - for thread_id in refresh.archived_thread_ids { + for (thread_id, metadata) in refresh.archived_threads { + // Archived children can label old rows without joining the picker. + if metadata.agent_nickname.is_some() + && self + .chat_widget + .collab_agent_metadata(thread_id) + .agent_nickname + .is_none() + { + self.chat_widget.set_collab_agent_metadata( + thread_id, + metadata.agent_nickname, + metadata.agent_role, + ); + } if !completion.visibility_changed_threads.contains(&thread_id) { self.update_agent_picker_thread_visibility( thread_id, @@ -186,6 +278,7 @@ impl App { } self.agent_navigation.prune_untracked_picker_exclusions(); + self.refresh_collab_history(); self.refresh_agent_picker(); if completion.follow_up_requested { self.refresh_agent_picker_threads(app_server, root); diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 126bcb8df0..d618d0f65d 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -1252,7 +1252,8 @@ impl App { self.transcript_view.jump_to_latest(); tui.frame_requester().schedule_frame(); } - AppEvent::InsertHistoryCell(cell) => { + AppEvent::InsertHistoryCell(mut cell) => { + self.prepare_collab_history(app_server, cell.as_mut()); self.insert_history_cell(tui, cell); } AppEvent::TurnTipReady { thread_id, turn_id } => { diff --git a/codex-rs/tui/src/app/history_pagination.rs b/codex-rs/tui/src/app/history_pagination.rs index 977191fead..dd370e7316 100644 --- a/codex-rs/tui/src/app/history_pagination.rs +++ b/codex-rs/tui/src/app/history_pagination.rs @@ -128,7 +128,7 @@ impl App { pane.cells.as_slice() }); let split_insertion = split_image_insertion(existing, split_turn); - let (cells, split_images) = self.project_older_history_cells( + let (mut cells, split_images) = self.project_older_history_cells( items, &turns, &hidden_item_ids, @@ -137,6 +137,11 @@ impl App { visibility, split_insertion.is_some(), ); + for cell in &mut cells { + if let Some(cell) = Arc::get_mut(cell) { + self.prepare_collab_history(app_server, cell); + } + } if let Some(pane) = self.side_companions.get_mut(&thread_id).filter(|_| parked) { let images = split_insertion.and_then(|index| { if split_images.is_empty() { diff --git a/codex-rs/tui/src/app/sidebar_agent_status_tests.rs b/codex-rs/tui/src/app/sidebar_agent_status_tests.rs index afabcbf7b9..eb869b9491 100644 --- a/codex-rs/tui/src/app/sidebar_agent_status_tests.rs +++ b/codex-rs/tui/src/app/sidebar_agent_status_tests.rs @@ -280,7 +280,7 @@ async fn active_discovery_supersedes_restored_completion() -> color_eyre::Result request, Ok(crate::app_event::AgentPickerThreadRefresh { threads: vec![thread, completed_thread, failed_thread], - archived_thread_ids: HashSet::new(), + ..Default::default() }), ) .is_none() diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 2876c31c88..496af0b42a 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -2259,43 +2259,6 @@ async fn token_usage_update_refreshes_status_line_with_runtime_context_window() } } -#[tokio::test] -async fn collab_receiver_notification_caches_thread_without_app_server_read() { - let mut app = make_test_app().await; - let receiver_thread_id = - ThreadId::from_string("00000000-0000-0000-0000-000000000123").expect("valid thread id"); - - app.handle_thread_event_now(ThreadBufferedEvent::Notification(Box::new( - ServerNotification::ItemStarted(ItemStartedNotification::new( - ThreadId::new().to_string(), - "turn-1".to_string(), - ThreadItemPayload::CollabAgentToolCall { - id: "wait-1".to_string(), - tool: codex_app_server_protocol::CollabAgentTool::Wait, - status: codex_app_server_protocol::CollabAgentToolCallStatus::InProgress, - sender_thread_id: ThreadId::new().to_string(), - receiver_thread_ids: vec![receiver_thread_id.to_string()], - prompt: None, - model: None, - reasoning_effort: None, - agents_states: HashMap::new(), - }, - /*started_at_ms*/ 0, - )), - ))); - - assert_eq!( - app.agent_navigation.get(&receiver_thread_id), - Some(&AgentPickerThreadEntry { - agent_nickname: None, - agent_role: None, - agent_path: None, - is_running: false, - is_closed: false, - }) - ); -} - #[tokio::test] async fn collab_receiver_notification_does_not_cache_not_found_thread() { let mut app = make_test_app().await; @@ -2389,6 +2352,11 @@ async fn archived_untracked_threads_do_not_appear_in_agent_picker() -> Result<() ); app.thread_event_channels .insert(archived_thread_id, ThreadEventChannel::new(/*capacity*/ 1)); + let unloaded = ThreadId::new(); + let metadata = crate::multi_agents::AgentMetadata { + agent_nickname: Some("Kepler".into()), + agent_role: Some("explorer".into()), + }; let request_id = app .agent_navigation .begin_picker_refresh(primary_thread_id) @@ -2400,11 +2368,15 @@ async fn archived_untracked_threads_do_not_appear_in_agent_picker() -> Result<() request_id, Ok(crate::app_event::AgentPickerThreadRefresh { threads: Vec::new(), - archived_thread_ids: std::collections::HashSet::from([archived_thread_id]), + archived_threads: HashMap::from([ + (archived_thread_id, Default::default()), + (unloaded, metadata.clone()), + ]), }), ) .is_none() ); + assert_eq!(app.chat_widget.collab_agent_metadata(unloaded), metadata); assert_eq!( app.thread_event_channels[&archived_thread_id].attachment(), ThreadEventAttachment::ReplayOnly diff --git a/codex-rs/tui/src/app/tests/agents_navigation_tests.rs b/codex-rs/tui/src/app/tests/agents_navigation_tests.rs index 1a9963d642..34cf389ca9 100644 --- a/codex-rs/tui/src/app/tests/agents_navigation_tests.rs +++ b/codex-rs/tui/src/app/tests/agents_navigation_tests.rs @@ -581,3 +581,126 @@ fn thread_links_navigate_and_missing_threads_preserve_the_draft() -> Result<()> .join() .expect("thread-link navigation test panicked") } + +#[tokio::test] +async fn collab_history_resolves_replayed_and_live_names_in_background() -> Result<()> { + let (mut app, mut rx, _ops) = Box::pin(make_test_app_with_channels()).await; + let root = ThreadId::new(); + let receiver_thread_id = ThreadId::from_string( + &app_test_support::create_fake_parented_rollout_with_source( + app.config.codex_home.as_path(), + "2026-01-01T00-00-01", + "2026-01-01T00:00:01Z", + "Child", + Some(&app.config.model_provider_id), + /*git_info*/ None, + RolloutSessionSource::SubAgent(SubAgentSource::ThreadSpawn { + parent_thread_id: root, + depth: 1, + agent_path: None, + agent_nickname: Some("Kepler".into()), + agent_role: Some("explorer".into()), + }), + root.into(), + root, + ) + .expect("create child rollout"), + )?; + let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?; + let mut tui = crate::tui::test_support::make_test_tui()?; + app.primary_thread_id = Some(root); + + let call = |id: &str, tool, status| ThreadItemPayload::CollabAgentToolCall { + id: id.to_string(), + tool, + status, + sender_thread_id: root.to_string(), + receiver_thread_ids: vec![receiver_thread_id.to_string()], + prompt: None, + model: None, + reasoning_effort: None, + agents_states: HashMap::new(), + }; + let spawn = call( + "spawn-1", + codex_app_server_protocol::CollabAgentTool::SpawnAgent, + codex_app_server_protocol::CollabAgentToolCallStatus::Completed, + ); + app.chat_widget.replay_thread_turns( + vec![test_turn("saved-turn", TurnStatus::Completed, vec![spawn])], + ReplayKind::ResumeInitialMessages, + ); + let completion = loop { + let event = tokio::time::timeout(Duration::from_secs(/*secs*/ 5), rx.recv()) + .await? + .expect("app event channel"); + if matches!(event, AppEvent::AgentPickerThreadsLoaded { .. }) { + break event; + } + Box::pin(app.handle_event(&mut tui, &mut server, event)).await?; + }; + let mut parked = SideCompanion::empty(app.config.cwd.to_path_buf()); + parked.cells = app.transcript_cells.clone(); + let parked_id = ThreadId::new(); + app.side_companions.insert(parked_id, parked); + // The wait is queued before the name arrives, but inserted after the lookup completes. + app.handle_thread_event_now(ThreadBufferedEvent::Notification(Box::new( + ServerNotification::ItemStarted(ItemStartedNotification::new( + root.to_string(), + "turn-1".to_string(), + call( + "wait-1", + codex_app_server_protocol::CollabAgentTool::Wait, + codex_app_server_protocol::CollabAgentToolCallStatus::InProgress, + ), + /*started_at_ms*/ 0, + )), + ))); + + assert_eq!( + app.agent_navigation.get(&receiver_thread_id), + Some(&AgentPickerThreadEntry { + agent_nickname: None, + agent_role: None, + agent_path: None, + is_running: false, + is_closed: false, + }) + ); + app.enqueue_thread_notification( + receiver_thread_id, + thread_closed_notification(receiver_thread_id), + ) + .await?; + Box::pin(app.handle_event(&mut tui, &mut server, completion)).await?; + assert!( + app.agent_navigation + .get(&receiver_thread_id) + .unwrap() + .is_closed + ); + drain_app_events(&mut app, &mut tui, &mut server, &mut rx).await?; + let text = |lines: Vec| { + lines + .iter() + .map(rendered_line_text) + .collect::>() + .join("\n") + }; + let transcript = text(app.render_transcript_lines_for_reflow(/*width*/ 80).lines); + insta::assert_snapshot!(transcript, @r" + • Spawned Kepler [explorer] + + • Waiting for Kepler [explorer] + "); + assert_eq!( + text(app.side_companions[&parked_id].cells[0].transcript_hyperlink_lines(/*width*/ 80)), + "• Spawned Kepler [explorer]" + ); + assert_eq!( + text(tui.pending_history_lines_for_test()), + format!("• Spawned {receiver_thread_id}\n\n• Waiting for Kepler [explorer]") + ); + server.shutdown().await?; + Ok(()) +} diff --git a/codex-rs/tui/src/app/thread_routing.rs b/codex-rs/tui/src/app/thread_routing.rs index 47acb41b3a..50f70a313a 100644 --- a/codex-rs/tui/src/app/thread_routing.rs +++ b/codex-rs/tui/src/app/thread_routing.rs @@ -1272,6 +1272,9 @@ impl App { started.thread.agent_role.clone(), /*is_closed*/ false, ); + if started.thread.agent_nickname.is_some() { + self.refresh_collab_history(); + } self.agent_navigation.set_agent_path( thread_id, crate::app_server_session::source_agent_path(&started.thread.source), diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 463d3a1bb3..a91de01430 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -298,7 +298,8 @@ pub(crate) struct AgentsOverviewThreadRefresh { #[derive(Debug, Default)] pub(crate) struct AgentPickerThreadRefresh { pub(crate) threads: Vec, - pub(crate) archived_thread_ids: std::collections::HashSet, + pub(crate) archived_threads: + std::collections::HashMap, } /// Source-backed replacement for the outgoing widget's width-bound streaming rows. diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 07c3f65b8e..481c07fe0e 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -996,7 +996,7 @@ impl ChatWidget { } /// Returns the cached metadata for a thread, defaulting to empty if none has been registered. - fn collab_agent_metadata(&self, thread_id: ThreadId) -> AgentMetadata { + pub(crate) fn collab_agent_metadata(&self, thread_id: ThreadId) -> AgentMetadata { self.collab_agent_metadata .get(&thread_id) .cloned() diff --git a/codex-rs/tui/src/multi_agents.rs b/codex-rs/tui/src/multi_agents.rs index b019a97fb0..c2ddfcdc7b 100644 --- a/codex-rs/tui/src/multi_agents.rs +++ b/codex-rs/tui/src/multi_agents.rs @@ -4,6 +4,11 @@ //! picker entries, and the fast-switch keyboard shortcuts. Higher-level coordination, such as //! deciding which thread becomes active or when a thread closes, stays in [`crate::app::App`]. +#[path = "multi_agents_history.rs"] +mod history; +pub(crate) use history::CollabHistoryCell; +pub(crate) use history::tool_call_history_cell; + use crate::history_cell::LabeledToolCell; use crate::history_cell::WebHyperlinkHistoryCell; use crate::style::accent_color; @@ -63,6 +68,15 @@ pub(crate) struct AgentMetadata { pub(crate) agent_role: Option, } +impl AgentMetadata { + fn nickname(&self) -> Option<&str> { + self.agent_nickname + .as_deref() + .map(str::trim) + .filter(|name| !name.is_empty()) + } +} + #[derive(Clone, Copy)] struct AgentLabel<'a> { thread_id: Option, @@ -204,7 +218,7 @@ pub(crate) fn spawn_request_summary(item: &ThreadItemPayload) -> Option, mut agent_metadata: impl FnMut(ThreadId) -> AgentMetadata, @@ -508,7 +522,7 @@ fn parse_thread_id(thread_id: &str) -> Option { fn agent_label(thread_id: ThreadId, metadata: &AgentMetadata) -> AgentLabel<'_> { AgentLabel { thread_id: Some(thread_id), - nickname: metadata.agent_nickname.as_deref(), + nickname: metadata.nickname(), role: metadata.agent_role.as_deref(), } } @@ -520,8 +534,7 @@ fn agent_label_line(agent: AgentLabel<'_>) -> HyperlinkLine { } fn append_agent(line: &mut HyperlinkLine, agent: AgentLabel<'_>) { - let nickname = agent.nickname.map(str::trim).filter(|n| !n.is_empty()); - let name = if let Some(nickname) = nickname { + let name = if let Some(nickname) = agent.nickname { nickname.to_string().bold() } else if let Some(id) = agent.thread_id { Span::from(id.to_string()) @@ -950,7 +963,7 @@ mod tests { fn resume_cell( status: CollabAgentToolCallStatus, agent_status: CollabAgentStatus, - ) -> LabeledToolCell { + ) -> CollabHistoryCell { let sender_thread_id = ThreadId::from_string("00000000-0000-0000-0000-000000000001") .expect("valid sender thread id"); let robie_id = ThreadId::from_string("00000000-0000-0000-0000-000000000002") diff --git a/codex-rs/tui/src/multi_agents_history.rs b/codex-rs/tui/src/multi_agents_history.rs new file mode 100644 index 0000000000..b546893d04 --- /dev/null +++ b/codex-rs/tui/src/multi_agents_history.rs @@ -0,0 +1,90 @@ +//! Keep the source of unnamed collab rows until background thread discovery can label them. + +use super::*; +use crate::history_cell::HistoryCell; + +#[derive(Debug)] +pub(crate) struct CollabHistoryCell { + rendered: LabeledToolCell, + unresolved: Option>, +} + +#[derive(Debug)] +struct Unresolved { + item: ThreadItemPayload, + spawn_request: Option, + missing: Vec, +} + +pub(crate) fn tool_call_history_cell( + item: &ThreadItemPayload, + cached_spawn_request: Option<&SpawnRequestSummary>, + metadata: impl Fn(ThreadId) -> AgentMetadata, +) -> Option { + let ThreadItemPayload::CollabAgentToolCall { agents_states, .. } = item else { + return None; + }; + let mut missing = Vec::new(); + let rendered = render_tool_call(item, cached_spawn_request, |id| { + let agent = metadata(id); + if agent.nickname().is_none() + && agents_states + .get(&id.to_string()) + .is_none_or(|s| s.status != CollabAgentStatus::NotFound) + { + missing.push(id); + } + agent + })?; + let unresolved = (!missing.is_empty()).then(|| { + Box::new(Unresolved { + item: item.clone(), + spawn_request: cached_spawn_request.cloned(), + missing, + }) + }); + Some(CollabHistoryCell { + rendered, + unresolved, + }) +} + +impl CollabHistoryCell { + pub(crate) fn needs_names(&self) -> bool { + self.unresolved.is_some() + } + + pub(crate) fn refreshed(&self, metadata: impl Fn(ThreadId) -> AgentMetadata) -> Option { + let source = self.unresolved.as_ref()?; + if !source + .missing + .iter() + .any(|id| metadata(*id).nickname().is_some()) + { + return None; + } + tool_call_history_cell(&source.item, source.spawn_request.as_ref(), metadata) + } +} + +impl HistoryCell for CollabHistoryCell { + fn tool_call_labels(&self) -> Vec { + self.rendered.tool_call_labels() + } + + fn display_lines(&self, width: u16) -> Vec> { + self.rendered.display_lines(width) + } + + fn display_hyperlink_lines(&self, width: u16) -> Vec { + self.rendered.display_hyperlink_lines(width) + } + + fn transcript_hyperlink_lines(&self, width: u16) -> Vec { + self.rendered.transcript_hyperlink_lines(width) + } + + fn raw_lines(&self) -> Vec> { + self.rendered.raw_lines() + } +}