diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 45bd82259b..ae551a1fa0 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -65,6 +65,7 @@ use codex_core::git_info::get_git_repo_root; use codex_core::git_info::local_git_branches; use codex_core::mcp::McpManager; use codex_core::models_manager::manager::ModelsManager; +use codex_core::parse_turn_item; use codex_core::plugins::PluginsManager; use codex_core::project_doc::DEFAULT_PROJECT_DOC_FILENAME; use codex_core::skills::model::SkillMetadata; @@ -85,6 +86,7 @@ use codex_protocol::config_types::Settings; #[cfg(target_os = "windows")] use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::items::AgentMessageItem; +use codex_protocol::items::TurnItem; use codex_protocol::models::MessagePhase; use codex_protocol::models::local_image_label_text; use codex_protocol::parse_command::ParsedCommand; @@ -617,16 +619,11 @@ pub(crate) struct ChatWidget { suppress_session_configured_redraw: bool, // User messages queued while a turn is in progress queued_user_messages: VecDeque, - // Nudges deferred while a turn is in progress. + // Nudges already submitted to core but not yet committed into history. // - // Once the current streamed assistant message is done rendering, we - // interrupt the running turn (if needed) and then submit the pending - // nudges as fresh follow-up input. `on_task_complete` still drains this - // queue when the turn finishes naturally before an interrupt is needed. - pending_nudges: VecDeque, - // True after we have requested an automatic interrupt so a pending nudge - // can be submitted as a fresh turn. - pending_nudge_interrupt_requested: bool, + // The bottom pane shows these above queued drafts until core records the + // corresponding user message and emits the matching raw response item. + pending_nudges: VecDeque, // Number of legacy `EventMsg::AgentMessage` events to ignore because the // corresponding `item.completed` already finalized the streamed message. pending_suppressed_legacy_agent_messages: usize, @@ -1498,12 +1495,8 @@ impl ChatWidget { self.unified_exec_wait_streak = None; self.request_redraw(); - if !from_replay { - self.pending_nudge_interrupt_requested = false; - let drained_pending_nudges = self.maybe_send_pending_nudges(); - if !drained_pending_nudges && self.queued_user_messages.is_empty() { - self.maybe_prompt_plan_implementation(); - } + if !from_replay && self.queued_user_messages.is_empty() { + self.maybe_prompt_plan_implementation(); } // Keep this flag for replayed completion events so a subsequent live TurnComplete can // still show the prompt once after thread switch replay. @@ -1790,8 +1783,6 @@ impl ChatWidget { self.add_to_history(history_cell::new_warning_event(message)); self.request_redraw(); - self.pending_nudge_interrupt_requested = false; - self.maybe_send_pending_nudges(); self.maybe_send_next_queued_input(); } @@ -1800,8 +1791,6 @@ impl ChatWidget { self.add_to_history(history_cell::new_error_event(message)); self.request_redraw(); - self.pending_nudge_interrupt_requested = false; - self.maybe_send_pending_nudges(); // After an error ends the turn, try sending the next queued input. self.maybe_send_next_queued_input(); } @@ -1883,27 +1872,19 @@ impl ChatWidget { /// When there are queued user messages, restore them into the composer /// separated by newlines rather than auto‑submitting the next one. fn on_interrupted_turn(&mut self, reason: TurnAbortReason) { - let interrupted_for_pending_nudge = - std::mem::take(&mut self.pending_nudge_interrupt_requested); - let had_pending_nudges = !self.pending_nudges.is_empty(); // Finalize, log a gentle prompt, and clear running state. self.finalize_turn(); if reason == TurnAbortReason::Interrupted { self.clear_unified_exec_processes(); } - if !interrupted_for_pending_nudge && reason != TurnAbortReason::ReviewEnded { + if reason != TurnAbortReason::ReviewEnded { self.add_to_history(history_cell::new_error_event( "Conversation interrupted - tell the model what to do differently. Something went wrong? Hit `/feedback` to report the issue.".to_owned(), )); } - if had_pending_nudges { - self.maybe_send_pending_nudges(); - } - if !interrupted_for_pending_nudge - && let Some(combined) = self.drain_queued_messages_for_restore() - { + if let Some(combined) = self.drain_queued_messages_for_restore() { self.restore_user_message_to_composer(combined); self.refresh_pending_input_preview(); } @@ -2469,9 +2450,6 @@ impl ChatWidget { } // A completed stream indicates non-exec content was just inserted. self.flush_interrupt_queue(); - if self.agent_turn_running { - self.maybe_send_pending_nudges(); - } } #[inline] @@ -2955,7 +2933,6 @@ impl ChatWidget { forked_from: None, queued_user_messages: VecDeque::new(), pending_nudges: VecDeque::new(), - pending_nudge_interrupt_requested: false, pending_suppressed_legacy_agent_messages: 0, queued_message_edit_binding, show_welcome_banner: is_first_run, @@ -3141,7 +3118,6 @@ impl ChatWidget { plan_item_active: false, queued_user_messages: VecDeque::new(), pending_nudges: VecDeque::new(), - pending_nudge_interrupt_requested: false, pending_suppressed_legacy_agent_messages: 0, queued_message_edit_binding, show_welcome_banner: is_first_run, @@ -3308,7 +3284,6 @@ impl ChatWidget { forked_from: None, queued_user_messages: VecDeque::new(), pending_nudges: VecDeque::new(), - pending_nudge_interrupt_requested: false, pending_suppressed_legacy_agent_messages: 0, queued_message_edit_binding, show_welcome_banner: false, @@ -3479,11 +3454,30 @@ impl ChatWidget { else { return; }; - let should_defer_as_pending_nudge = self.is_session_configured() - && (self.is_plan_streaming_in_tui() || self.stream_controller.is_some()); - if should_defer_as_pending_nudge { - self.pending_nudges.push_back(user_message); + let should_preview_as_pending_nudge = self.is_session_configured() + && (self.is_plan_streaming_in_tui() || self.stream_controller.is_some()) + && (!user_message.text.is_empty() + || !user_message.local_images.is_empty() + || !user_message.remote_image_urls.is_empty()) + && user_message.text.strip_prefix('!').is_none() + && ((user_message.local_images.is_empty() + && user_message.remote_image_urls.is_empty()) + || self.current_model_supports_images()); + if should_preview_as_pending_nudge { + self.pending_nudges.push_back( + Self::rendered_user_message_event_from_parts( + user_message.text.clone(), + user_message.text_elements.clone(), + user_message + .local_images + .iter() + .map(|image| image.path.clone()) + .collect(), + user_message.remote_image_urls.clone(), + ), + ); self.refresh_pending_input_preview(); + self.submit_user_message_without_local_history(user_message); } else if self.is_session_configured() { // Submitted is only emitted when steer is enabled. // Reset any reasoning header only when we are actually submitting a turn. @@ -4107,6 +4101,14 @@ impl ChatWidget { } fn submit_user_message(&mut self, user_message: UserMessage) { + self.submit_user_message_internal(user_message, true); + } + + fn submit_user_message_without_local_history(&mut self, user_message: UserMessage) { + self.submit_user_message_internal(user_message, false); + } + + fn submit_user_message_internal(&mut self, user_message: UserMessage, render_in_history: bool) { if !self.is_session_configured() { tracing::warn!("cannot submit user message before session is configured; queueing"); self.queued_user_messages.push_front(user_message); @@ -4305,7 +4307,7 @@ impl ChatWidget { } // Show replayable user content in conversation history. - if !text.is_empty() { + if render_in_history && !text.is_empty() { let local_image_paths = local_images .into_iter() .map(|img| img.path) @@ -4323,7 +4325,7 @@ impl ChatWidget { local_image_paths, remote_image_urls, )); - } else if !remote_image_urls.is_empty() { + } else if render_in_history && !remote_image_urls.is_empty() { self.last_rendered_user_message_event = Some(Self::rendered_user_message_event_from_parts( String::new(), @@ -4557,6 +4559,23 @@ impl ChatWidget { self.on_user_message_event(ev); } } + EventMsg::RawResponseItem(event) => { + if !from_replay + && let Some(TurnItem::UserMessage(item)) = parse_turn_item(&event.item) + && let EventMsg::UserMessage(user_message) = item.as_legacy_event() + { + let rendered = Self::rendered_user_message_event_from_event(&user_message); + if let Some(index) = self + .pending_nudges + .iter() + .position(|pending| pending == &rendered) + { + self.pending_nudges.remove(index); + self.refresh_pending_input_preview(); + self.on_user_message_event(user_message); + } + } + } EventMsg::EnteredReviewMode(review_request) => { self.on_entered_review_mode(review_request, from_replay) } @@ -4587,8 +4606,7 @@ impl ChatWidget { }); } } - EventMsg::RawResponseItem(_) - | EventMsg::ItemStarted(_) + EventMsg::ItemStarted(_) | EventMsg::AgentMessageContentDelta(_) | EventMsg::ReasoningContentDelta(_) | EventMsg::ReasoningRawContentDelta(_) @@ -4613,9 +4631,6 @@ impl ChatWidget { let item = event.item; if let codex_protocol::items::TurnItem::Plan(plan_item) = &item { self.on_plan_item_completed(plan_item.text.clone()); - if !from_replay { - self.maybe_send_pending_nudges(); - } } if let codex_protocol::items::TurnItem::AgentMessage(item) = item { self.on_agent_message_item_completed(item); @@ -4767,28 +4782,6 @@ impl ChatWidget { self.refresh_pending_input_preview(); } - fn maybe_send_pending_nudges(&mut self) -> bool { - if self.stream_controller.is_some() || self.is_plan_streaming_in_tui() { - return false; - } - if self.pending_nudges.is_empty() { - return false; - } - if self.agent_turn_running { - if !self.pending_nudge_interrupt_requested { - self.pending_nudge_interrupt_requested = true; - self.submit_op(Op::Interrupt); - } - return true; - } - self.pending_nudge_interrupt_requested = false; - while let Some(pending_nudge) = self.pending_nudges.pop_front() { - self.submit_user_message(pending_nudge); - } - self.refresh_pending_input_preview(); - true - } - /// Rebuild and update the bottom-pane pending-input preview. fn refresh_pending_input_preview(&mut self) { let messages: Vec = self @@ -4799,7 +4792,7 @@ impl ChatWidget { let pending_nudges: Vec = self .pending_nudges .iter() - .map(|nudge| nudge.text.clone()) + .map(|nudge| nudge.message().to_string()) .collect(); self.bottom_pane .set_pending_input_preview(messages, pending_nudges); diff --git a/codex-rs/tui/src/chatwidget/realtime.rs b/codex-rs/tui/src/chatwidget/realtime.rs index 2970ac4d3a..a599037c1b 100644 --- a/codex-rs/tui/src/chatwidget/realtime.rs +++ b/codex-rs/tui/src/chatwidget/realtime.rs @@ -55,6 +55,12 @@ pub(super) struct RenderedUserMessageEvent { text_elements: Vec, } +impl RenderedUserMessageEvent { + pub(super) fn message(&self) -> &str { + &self.message + } +} + impl ChatWidget { pub(super) fn rendered_user_message_event_from_parts( message: String, diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 7135b011c5..1ff4485013 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -78,6 +78,7 @@ use codex_protocol::protocol::PatchApplyBeginEvent; use codex_protocol::protocol::PatchApplyEndEvent; use codex_protocol::protocol::PatchApplyStatus as CorePatchApplyStatus; use codex_protocol::protocol::RateLimitWindow; +use codex_protocol::protocol::RawResponseItemEvent; use codex_protocol::protocol::ReviewRequest; use codex_protocol::protocol::ReviewTarget; use codex_protocol::protocol::SessionSource; @@ -1709,7 +1710,6 @@ async fn make_chatwidget_manual( startup_tooltip_override: None, queued_user_messages: VecDeque::new(), pending_nudges: VecDeque::new(), - pending_nudge_interrupt_requested: false, pending_suppressed_legacy_agent_messages: 0, queued_message_edit_binding: crate::key_hint::alt(KeyCode::Up), suppress_session_configured_redraw: false, @@ -1758,16 +1758,6 @@ fn next_submit_op(op_rx: &mut tokio::sync::mpsc::UnboundedReceiver) -> Op { } } -fn next_interrupt_op(op_rx: &mut tokio::sync::mpsc::UnboundedReceiver) { - while let Ok(op) = op_rx.try_recv() { - if op == Op::Interrupt { - return; - } - } - - panic!("expected an interrupt op but queue was empty"); -} - fn assert_no_submit_op(op_rx: &mut tokio::sync::mpsc::UnboundedReceiver) { while let Ok(op) = op_rx.try_recv() { assert!( @@ -1842,6 +1832,21 @@ fn drain_insert_history( out } +fn raw_user_message_event(text: &str) -> Event { + let response_item: codex_protocol::models::ResponseItem = + codex_protocol::models::ResponseInputItem::from(vec![UserInput::Text { + text: text.to_string(), + text_elements: Vec::new(), + }]) + .into(); + Event { + id: format!("raw-user-{text}"), + msg: EventMsg::RawResponseItem(RawResponseItemEvent { + item: response_item, + }), + } +} + fn lines_to_single_string(lines: &[ratatui::text::Line<'static>]) -> String { let mut s = String::new(); for line in lines { @@ -3461,7 +3466,7 @@ async fn unified_exec_begin_restores_working_status_snapshot() { #[tokio::test] async fn steer_enter_uses_pending_nudges_while_plan_stream_is_active() { - let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None).await; + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await; chat.thread_id = Some(ThreadId::new()); chat.set_feature_enabled(Feature::CollaborationModes, true); let plan_mask = @@ -3470,6 +3475,7 @@ async fn steer_enter_uses_pending_nudges_while_plan_stream_is_active() { chat.set_collaboration_mask(plan_mask); chat.on_task_started(); chat.on_plan_delta("- Step 1".to_string()); + let _ = drain_insert_history(&mut rx); chat.bottom_pane .set_composer_text("queued submission".to_string(), Vec::new(), Vec::new()); @@ -3479,28 +3485,9 @@ async fn steer_enter_uses_pending_nudges_while_plan_stream_is_active() { assert!(chat.queued_user_messages.is_empty()); assert_eq!(chat.pending_nudges.len(), 1); assert_eq!( - chat.pending_nudges.front().unwrap().text, + chat.pending_nudges.front().unwrap().message(), "queued submission" ); - assert_matches!(op_rx.try_recv(), Err(TryRecvError::Empty)); - - chat.handle_codex_event(Event { - id: "item-plan".into(), - msg: EventMsg::ItemCompleted(ItemCompletedEvent { - thread_id: ThreadId::new(), - turn_id: "turn-1".to_string(), - item: TurnItem::Plan(PlanItem { - id: "plan-1".to_string(), - text: "- Step 1".to_string(), - }), - }), - }); - - next_interrupt_op(&mut op_rx); - - chat.on_interrupted_turn(TurnAbortReason::Interrupted); - - assert!(chat.pending_nudges.is_empty()); match next_submit_op(&mut op_rx) { Op::UserTurn { items, .. } => assert_eq!( items, @@ -3509,13 +3496,21 @@ async fn steer_enter_uses_pending_nudges_while_plan_stream_is_active() { text_elements: Vec::new(), }] ), - other => panic!("expected Op::UserTurn after plan stream completion, got {other:?}"), + other => panic!("expected Op::UserTurn, got {other:?}"), } + assert!(drain_insert_history(&mut rx).is_empty()); + + chat.handle_codex_event(raw_user_message_event("queued submission")); + + assert!(chat.pending_nudges.is_empty()); + let inserted = drain_insert_history(&mut rx); + assert_eq!(inserted.len(), 1); + assert!(lines_to_single_string(&inserted[0]).contains("queued submission")); } #[tokio::test] async fn steer_enter_uses_pending_nudges_while_final_answer_stream_is_active() { - let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None).await; + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await; chat.thread_id = Some(ThreadId::new()); chat.on_task_started(); // Keep the assistant stream open (no commit tick/finalize) to model the repro window: @@ -3532,32 +3527,26 @@ async fn steer_enter_uses_pending_nudges_while_final_answer_stream_is_active() { assert!(chat.queued_user_messages.is_empty()); assert_eq!(chat.pending_nudges.len(), 1); assert_eq!( - chat.pending_nudges.front().unwrap().text, + chat.pending_nudges.front().unwrap().message(), "queued while streaming" ); - assert_no_submit_op(&mut op_rx); - - complete_assistant_message( - &mut chat, - "msg-commentary", - "Final answer line\n", - Some(MessagePhase::Commentary), - ); - - next_interrupt_op(&mut op_rx); - - chat.on_interrupted_turn(TurnAbortReason::Interrupted); - - assert!(chat.pending_nudges.is_empty()); match next_submit_op(&mut op_rx) { Op::UserTurn { .. } => {} - other => panic!("expected Op::UserTurn after message completion, got {other:?}"), + other => panic!("expected Op::UserTurn, got {other:?}"), } + assert!(drain_insert_history(&mut rx).is_empty()); + + chat.handle_codex_event(raw_user_message_event("queued while streaming")); + + assert!(chat.pending_nudges.is_empty()); + let inserted = drain_insert_history(&mut rx); + assert_eq!(inserted.len(), 1); + assert!(lines_to_single_string(&inserted[0]).contains("queued while streaming")); } #[tokio::test] async fn steer_enter_during_final_stream_preserves_follow_up_prompts_in_order() { - let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None).await; + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await; chat.thread_id = Some(ThreadId::new()); chat.on_task_started(); // Simulate "dead mode" repro timing by keeping a final-answer stream active while the @@ -3573,20 +3562,14 @@ async fn steer_enter_during_final_stream_preserves_follow_up_prompts_in_order() assert!(chat.queued_user_messages.is_empty()); assert_eq!(chat.pending_nudges.len(), 2); - assert_eq!(chat.pending_nudges.front().unwrap().text, "first follow-up"); - assert_eq!(chat.pending_nudges.back().unwrap().text, "second follow-up"); - assert_no_submit_op(&mut op_rx); - - complete_assistant_message( - &mut chat, - "msg-commentary", - "Final answer line\n", - Some(MessagePhase::Commentary), + assert_eq!( + chat.pending_nudges.front().unwrap().message(), + "first follow-up" + ); + assert_eq!( + chat.pending_nudges.back().unwrap().message(), + "second follow-up" ); - - next_interrupt_op(&mut op_rx); - - chat.on_interrupted_turn(TurnAbortReason::Interrupted); let first_items = match next_submit_op(&mut op_rx) { Op::UserTurn { items, .. } => items, @@ -3599,8 +3582,6 @@ async fn steer_enter_during_final_stream_preserves_follow_up_prompts_in_order() text_elements: Vec::new(), }] ); - assert!(chat.pending_nudges.is_empty()); - let second_items = match next_submit_op(&mut op_rx) { Op::UserTurn { items, .. } => items, other => panic!("expected Op::UserTurn, got {other:?}"), @@ -3612,12 +3593,30 @@ async fn steer_enter_during_final_stream_preserves_follow_up_prompts_in_order() text_elements: Vec::new(), }] ); + assert!(drain_insert_history(&mut rx).is_empty()); + + chat.handle_codex_event(raw_user_message_event("first follow-up")); + + assert_eq!(chat.pending_nudges.len(), 1); + assert_eq!( + chat.pending_nudges.front().unwrap().message(), + "second follow-up" + ); + let first_insert = drain_insert_history(&mut rx); + assert_eq!(first_insert.len(), 1); + assert!(lines_to_single_string(&first_insert[0]).contains("first follow-up")); + + chat.handle_codex_event(raw_user_message_event("second follow-up")); + assert!(chat.pending_nudges.is_empty()); + let second_insert = drain_insert_history(&mut rx); + assert_eq!(second_insert.len(), 1); + assert!(lines_to_single_string(&second_insert[0]).contains("second follow-up")); } #[tokio::test] -async fn manual_interrupt_flushes_pending_nudges() { - let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None).await; +async fn manual_interrupt_keeps_pending_nudges_pending_until_core_commits_them() { + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await; chat.thread_id = Some(ThreadId::new()); chat.on_task_started(); chat.on_agent_message_delta("Final answer line\n".to_string()); @@ -3630,11 +3629,6 @@ async fn manual_interrupt_flushes_pending_nudges() { chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); assert_eq!(chat.pending_nudges.len(), 1); - assert_no_submit_op(&mut op_rx); - - chat.on_interrupted_turn(TurnAbortReason::Interrupted); - - assert!(chat.pending_nudges.is_empty()); match next_submit_op(&mut op_rx) { Op::UserTurn { items, .. } => assert_eq!( items, @@ -3643,8 +3637,25 @@ async fn manual_interrupt_flushes_pending_nudges() { text_elements: Vec::new(), }] ), - other => panic!("expected Op::UserTurn after manual interrupt, got {other:?}"), + other => panic!("expected Op::UserTurn, got {other:?}"), } + assert!(drain_insert_history(&mut rx).is_empty()); + + chat.on_interrupted_turn(TurnAbortReason::Interrupted); + + assert_eq!(chat.pending_nudges.len(), 1); + assert_eq!( + chat.pending_nudges.front().unwrap().message(), + "queued while streaming" + ); + assert_no_submit_op(&mut op_rx); + + chat.handle_codex_event(raw_user_message_event("queued while streaming")); + + assert!(chat.pending_nudges.is_empty()); + let inserted = drain_insert_history(&mut rx); + assert_eq!(inserted.len(), 2); + assert!(lines_to_single_string(&inserted[1]).contains("queued while streaming")); } #[tokio::test]