Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Preserve streamed answers when subagents finish (#46867)

Felipe Courye29eceb75131
diff --git a/codex-rs/tui/src/chatwidget/interrupts.rs b/codex-rs/tui/src/chatwidget/interrupts.rs
index 5021d03698..fdd27a414e 100644
--- a/codex-rs/tui/src/chatwidget/interrupts.rs
+++ b/codex-rs/tui/src/chatwidget/interrupts.rs
@@ -1,4 +1,6 @@
-//! Queue prompt overlays and deferred tool activity while another interrupt is visible.
+//! Defer prompt overlays and tool activity until assistant streams finish.
+//!
+//! Turn termination settles background activity without opening queued prompts.
use std::collections::VecDeque;
@@ -93,6 +95,21 @@ impl InterruptManager {
self.queue.push_back(QueuedInterrupt::ItemCompleted(item));
}
+ /// Settle background activity at turn end without opening queued prompts.
+ pub(crate) fn flush_activity(&mut self, chat: &mut ChatWidget) {
+ let mut pending_prompts = VecDeque::new();
+ while let Some(queued) = self.queue.pop_front() {
+ match queued {
+ QueuedInterrupt::ItemStarted(item) => chat.handle_queued_item_started_now(item),
+ QueuedInterrupt::ItemCompleted(item) => {
+ chat.handle_queued_item_completed_now(item);
+ }
+ prompt => pending_prompts.push_back(prompt),
+ }
+ }
+ self.queue = pending_prompts;
+ }
+
pub(crate) fn remove_resolved_prompt(&mut self, request: &ResolvedAppServerRequest) -> bool {
if !self.has_pending_prompt() {
return false;
diff --git a/codex-rs/tui/src/chatwidget/streaming.rs b/codex-rs/tui/src/chatwidget/streaming.rs
index f91322007a..3c907a584a 100644
--- a/codex-rs/tui/src/chatwidget/streaming.rs
+++ b/codex-rs/tui/src/chatwidget/streaming.rs
@@ -526,6 +526,12 @@ impl ChatWidget {
self.interrupts = mgr;
}
+ pub(super) fn flush_interrupt_activity(&mut self) {
+ let mut mgr = std::mem::take(&mut self.interrupts);
+ mgr.flush_activity(self);
+ self.interrupts = mgr;
+ }
+
/// Move a lifecycle payload into the interrupt queue or its immediate handler.
#[inline]
pub(super) fn defer_or_handle<T>(
diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs
index e12b20257d..d3edcf3133 100644
--- a/codex-rs/tui/src/chatwidget/tests.rs
+++ b/codex-rs/tui/src/chatwidget/tests.rs
@@ -297,6 +297,8 @@ mod startup_submission_tests;
mod status_and_layout;
mod status_command_tests;
mod status_surface_previews;
+#[path = "tests/subagent_activity_tests.rs"]
+mod subagent_activity;
mod terminal_title;
#[path = "tests/tool_activity_tests.rs"]
mod tool_activity_tests;
diff --git a/codex-rs/tui/src/chatwidget/tests/dynamic_activity_tests.rs b/codex-rs/tui/src/chatwidget/tests/dynamic_activity_tests.rs
index cbb2e27d64..72edc6cac4 100644
--- a/codex-rs/tui/src/chatwidget/tests/dynamic_activity_tests.rs
+++ b/codex-rs/tui/src/chatwidget/tests/dynamic_activity_tests.rs
@@ -114,6 +114,21 @@ async fn owned_dynamic_activity_updates_the_retained_row_after_config_refresh()
async fn turn_finalization_drains_lifecycle_queue_before_interrupting_remaining_calls() {
let (mut chat, mut events, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
drain_insert_history(&mut events);
+ chat.interrupts.push_user_input(ToolRequestUserInputParams {
+ thread_id: "thread-1".to_string(),
+ turn_id: "turn-1".to_string(),
+ item_id: "question-1".to_string(),
+ questions: vec![ToolRequestUserInputQuestion {
+ id: "scope".to_string(),
+ header: "Scope".to_string(),
+ question: "Which change should I review?".to_string(),
+ is_other: false,
+ is_secret: false,
+ options: None,
+ }],
+ is_blocking: true,
+ auto_resolution_ms: None,
+ });
chat.interrupts
.push_item_started(dynamic_item("completed", DynamicToolCallStatus::InProgress));
chat.interrupts
@@ -123,6 +138,8 @@ async fn turn_finalization_drains_lifecycle_queue_before_interrupting_remaining_
DynamicToolCallStatus::InProgress,
));
chat.finalize_turn();
+ assert!(chat.interrupts.has_pending_prompt());
+ assert!(!chat.bottom_pane.has_active_view());
let cells = std::iter::from_fn(|| events.try_recv().ok())
.filter_map(|event| match event {
AppEvent::InsertHistoryCell(cell)
diff --git a/codex-rs/tui/src/chatwidget/tests/subagent_activity_tests.rs b/codex-rs/tui/src/chatwidget/tests/subagent_activity_tests.rs
new file mode 100644
index 0000000000..2266b3d0c6
--- /dev/null
+++ b/codex-rs/tui/src/chatwidget/tests/subagent_activity_tests.rs
@@ -0,0 +1,229 @@
+//! Subagent notifications must preserve one authoritative answer across streaming boundaries.
+
+use super::*;
+use pretty_assertions::assert_eq;
+
+const PREFIX: &str = "The top is PR #42.\n\n";
+const SUFFIX: &str = "Branch: feature/rollout.";
+const ACTIVITY: &str = "• Completed `/root/stack_tip`\n";
+
+#[derive(Debug, PartialEq, Eq)]
+enum FinalizedEvent {
+ Answer(String),
+ History(String),
+}
+
+fn complete_subagent(chat: &mut ChatWidget, id: &str) {
+ let item = AppServerThreadItem::SubAgentActivity {
+ id: id.to_string(),
+ kind: codex_app_server_protocol::SubAgentActivityKind::Completed,
+ agent_thread_id: ThreadId::new().to_string(),
+ agent_path: "/root/stack_tip".to_string(),
+ };
+ for notification in [
+ ServerNotification::ItemStarted(ItemStartedNotification {
+ thread_id: "thread-1".to_string(),
+ turn_id: "turn-1".to_string(),
+ started_at_ms: 0,
+ item: item.clone(),
+ }),
+ ServerNotification::ItemCompleted(ItemCompletedNotification {
+ thread_id: "thread-1".to_string(),
+ turn_id: "turn-1".to_string(),
+ completed_at_ms: 0,
+ item,
+ }),
+ ] {
+ chat.handle_server_notification(notification, /*replay_kind*/ None);
+ }
+}
+
+/// Inspect publication order, excluding provisional stream cells and completion timestamps.
+fn drain_finalized_transcript(
+ rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
+) -> (Vec<FinalizedEvent>, String) {
+ let mut events = Vec::new();
+ let mut rendered = Vec::new();
+ while let Ok(event) = rx.try_recv() {
+ match event {
+ AppEvent::ConsolidateAgentMessage {
+ source,
+ cwd,
+ inline_visualization_context,
+ ..
+ } => {
+ let cell = history_cell::AgentMarkdownCell::new_with_inline_visualizations(
+ source.clone(),
+ &cwd,
+ inline_visualization_context,
+ );
+ rendered.push(lines_to_single_string(&cell.display_lines(/*width*/ 80)));
+ events.push(FinalizedEvent::Answer(source));
+ }
+ AppEvent::InsertHistoryCell(cell)
+ if !cell.as_any().is::<history_cell::AgentMessageCell>()
+ && !cell.as_any().is::<history_cell::FinalMessageSeparator>() =>
+ {
+ let text = lines_to_single_string(&cell.display_lines(/*width*/ 80));
+ rendered.push(text.clone());
+ events.push(FinalizedEvent::History(text));
+ }
+ _ => {}
+ }
+ }
+ (events, rendered.join("\n"))
+}
+
+#[tokio::test]
+async fn subagent_completion_preserves_stream_and_authoritative_answer() {
+ let answer = format!("{PREFIX}{SUFFIX}");
+ for (before_activity, after_activity) in [
+ // The reported session: all deltas precede activity, then the answer item completes.
+ (answer.as_str(), ""),
+ // The same activity can arrive before the remaining answer deltas.
+ (PREFIX, SUFFIX),
+ // Authoritative completion must still repair a dropped final delta.
+ (PREFIX, ""),
+ ] {
+ let (mut chat, mut rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
+ handle_turn_started(&mut chat, "turn-1");
+ handle_agent_message_delta(&mut chat, before_activity);
+ chat.run_commit_tick();
+
+ complete_subagent(&mut chat, "activity-1");
+ assert!(chat.stream_controller.is_some());
+ assert!(!chat.interrupts.is_empty());
+ assert_eq!(
+ drain_finalized_transcript(&mut rx),
+ (Vec::new(), String::new())
+ );
+
+ if !after_activity.is_empty() {
+ handle_agent_message_delta(&mut chat, after_activity);
+ }
+ complete_assistant_message(&mut chat, "msg-1", &answer, Some(MessagePhase::FinalAnswer));
+ handle_turn_completed(&mut chat, "turn-1", /*duration_ms*/ None);
+
+ let (events, rendered) = drain_finalized_transcript(&mut rx);
+ assert_eq!(
+ events,
+ vec![
+ FinalizedEvent::Answer(answer.clone()),
+ FinalizedEvent::History(ACTIVITY.to_string()),
+ ],
+ );
+ assert!(chat.interrupts.is_empty());
+ assert_eq!(
+ chat.transcript.last_agent_markdown.as_deref(),
+ Some(answer.as_str())
+ );
+ insta::allow_duplicates! {
+ insta::assert_snapshot!(rendered, @"
+ • The top is PR #42.
+
+ Branch: feature/rollout.
+
+ • Completed `/root/stack_tip`
+ ");
+ }
+ }
+}
+
+#[tokio::test]
+async fn interrupted_answer_flushes_queued_subagent_activity() {
+ let (mut chat, mut rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
+ handle_turn_started(&mut chat, "turn-1");
+ handle_agent_message_delta(&mut chat, PREFIX);
+ chat.run_commit_tick();
+ complete_subagent(&mut chat, "activity-1");
+ assert!(!chat.interrupts.is_empty());
+
+ handle_turn_interrupted(&mut chat, "turn-1");
+
+ let (events, _rendered) = drain_finalized_transcript(&mut rx);
+ assert_eq!(events.len(), 3);
+ assert_eq!(
+ &events[..2],
+ &[
+ FinalizedEvent::Answer(PREFIX.trim_end().to_string()),
+ FinalizedEvent::History(ACTIVITY.to_string()),
+ ],
+ );
+ let FinalizedEvent::History(interrupted) = &events[2] else {
+ panic!("expected interruption notice after the answer and subagent activity");
+ };
+ assert!(interrupted.starts_with("■ Conversation interrupted"));
+ assert!(chat.interrupts.is_empty());
+ assert!(chat.stream_controller.is_none());
+}
+
+#[tokio::test]
+async fn terminal_turn_drains_subagents_without_opening_queued_questions() {
+ for status in [AppServerTurnStatus::Completed, AppServerTurnStatus::Failed] {
+ let (mut chat, mut rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
+ handle_turn_started(&mut chat, "turn-1");
+ handle_agent_message_delta(&mut chat, PREFIX);
+ chat.run_commit_tick();
+ chat.on_request_user_input(ToolRequestUserInputParams {
+ thread_id: "thread-1".to_string(),
+ turn_id: "turn-1".to_string(),
+ item_id: "question-1".to_string(),
+ questions: vec![ToolRequestUserInputQuestion {
+ id: "scope".to_string(),
+ header: "Scope".to_string(),
+ question: "Which change should I review?".to_string(),
+ is_other: false,
+ is_secret: false,
+ options: None,
+ }],
+ is_blocking: true,
+ auto_resolution_ms: None,
+ });
+ complete_subagent(&mut chat, "activity-1");
+ assert!(chat.interrupts.has_pending_prompt());
+ assert!(!chat.bottom_pane.has_active_view());
+
+ let mut expected = vec![
+ FinalizedEvent::Answer(PREFIX.trim_end().to_string()),
+ FinalizedEvent::History(ACTIVITY.to_string()),
+ ];
+ let error = (status == AppServerTurnStatus::Failed).then(|| {
+ expected.push(FinalizedEvent::History(
+ "■ stream disconnected\n".to_string(),
+ ));
+ AppServerTurnError {
+ message: "stream disconnected".to_string(),
+ misalignment: None,
+ codex_error_info: None,
+ additional_details: None,
+ }
+ });
+ // There is no final answer item; turn termination must settle the stream and activity.
+ chat.handle_server_notification(
+ ServerNotification::TurnCompleted(TurnCompletedNotification {
+ thread_id: "thread-1".to_string(),
+ turn: app_server_turn("turn-1", status, /*duration_ms*/ None, error),
+ }),
+ /*replay_kind*/ None,
+ );
+ assert_eq!(drain_finalized_transcript(&mut rx).0, expected);
+ assert!(chat.interrupts.has_pending_prompt());
+ assert!(!chat.bottom_pane.has_active_view());
+ assert!(!chat.turn_lifecycle.agent_turn_running);
+ assert!(chat.stream_controller.is_none());
+
+ // Another child may finish after the parent stops, while the old question remains queued.
+ complete_subagent(&mut chat, "activity-2");
+ assert_eq!(
+ drain_finalized_transcript(&mut rx).0,
+ vec![FinalizedEvent::History(ACTIVITY.to_string())],
+ );
+ assert!(!chat.bottom_pane.has_active_view());
+ assert!(chat.interrupts.remove_resolved_prompt(
+ &crate::app::app_server_requests::ResolvedAppServerRequest::UserInput {
+ call_id: "question-1".to_string(),
+ },
+ ));
+ assert!(chat.interrupts.is_empty());
+ }
+}
diff --git a/codex-rs/tui/src/chatwidget/tool_lifecycle.rs b/codex-rs/tui/src/chatwidget/tool_lifecycle.rs
index e8ca99efa0..135aabca87 100644
--- a/codex-rs/tui/src/chatwidget/tool_lifecycle.rs
+++ b/codex-rs/tui/src/chatwidget/tool_lifecycle.rs
@@ -143,6 +143,21 @@ impl ChatWidget {
}
pub(super) fn on_sub_agent_activity(&mut self, item: ThreadItem) {
+ // Background agents can finish while the parent answer is still streaming.
+ // Keep that stream intact until its authoritative message completion.
+ // After the turn stops, leftover prompts must not hold up late activity.
+ if !self.turn_lifecycle.agent_turn_running && self.stream_controller.is_none() {
+ self.handle_sub_agent_activity_now(item);
+ } else {
+ self.defer_or_handle(
+ item,
+ InterruptManager::push_item_completed,
+ Self::handle_sub_agent_activity_now,
+ );
+ }
+ }
+
+ fn handle_sub_agent_activity_now(&mut self, item: ThreadItem) {
if let Some(cell) = multi_agents::sub_agent_activity_history_cell(&item) {
self.on_collab_event(cell);
}
@@ -300,6 +315,7 @@ impl ChatWidget {
item @ ThreadItem::FileChange { .. } => self.handle_file_change_completed_now(item),
item @ ThreadItem::McpToolCall { .. } => self.handle_mcp_tool_call_completed_now(item),
item @ ThreadItem::DynamicToolCall { .. } => self.handle_dynamic_tool_item_now(item),
+ item @ ThreadItem::SubAgentActivity { .. } => self.handle_sub_agent_activity_now(item),
_ => {}
}
}
diff --git a/codex-rs/tui/src/chatwidget/turn_runtime.rs b/codex-rs/tui/src/chatwidget/turn_runtime.rs
index 92835275ba..d473394efe 100644
--- a/codex-rs/tui/src/chatwidget/turn_runtime.rs
+++ b/codex-rs/tui/src/chatwidget/turn_runtime.rs
@@ -143,7 +143,7 @@ impl ChatWidget {
self.transcript.saw_copy_source_this_turn = false;
// If a stream is currently active, finalize it.
self.flush_answer_and_plan_streams();
- self.flush_interrupt_queue();
+ self.flush_interrupt_activity();
self.finish_dynamic_activity();
self.flush_unified_exec_wait_streak();
self.flush_completed_tool_activity();
@@ -313,7 +313,7 @@ impl ChatWidget {
/// and should continue to drive the bottom-pane running indicator while it is in progress.
pub(super) fn finalize_turn(&mut self) {
self.flush_answer_and_plan_streams();
- self.flush_interrupt_queue();
+ self.flush_interrupt_activity();
self.finish_dynamic_activity();
if self.status_state.reasoning_resume_turn_id.is_some() {
self.on_agent_reasoning_final();