Lightweight coding agent that runs in your terminal
Rust
Preserve history search during background draft recovery (#47423)
Ian MacLeod3032b387fa20
diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rsindex 041ee1bffa..158c39f1c7 100644--- a/codex-rs/tui/src/bottom_pane/chat_composer.rs+++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs@@ -73,7 +73,9 @@//! draft capture cancels previews, and restoration resets traversal.//! Ctrl+R searches history in the footer and previews matches in the composer.//! Typing and pasting edit the active search query, including large pastes and image paths.-//! Enter accepts the preview; Esc restores the original draft.+//! Background recovery updates the saved prompt without changing the query or visible preview.+//! Esc or Ctrl+C restores that prompt, including recovered answers and interrupted input.+//! Enter accepts a matching preview and discards the saved prompt; without a match, search stays open.//! Vim undo/redo snapshots complete drafts and groups direct edits with active Vim transactions.//! An active edit keeps one separately capped snapshot; canceling does not evict committed history.//! Canceled history previews restore history and active commands; accepting another prompt resets them.@@ -1494,9 +1496,10 @@ impl ChatComposer {/// Replace the entire composer content with `text` and reset cursor.///- /// This is the "fresh draft" path: it clears pending paste payloads and- /// mention link targets. Callers restoring a previously submitted draft- /// that must keep sigiled mention target resolution should use+ /// This is the "fresh draft" path: it discards active history search and+ /// clears pending paste payloads and mention link targets. Callers restoring+ /// a previously submitted draft that must keep sigiled mention target+ /// resolution should use/// [`Self::set_text_content_with_mention_bindings`] instead.pub(crate) fn set_text_content(&mut self,@@ -1504,6 +1507,10 @@ impl ChatComposer {text_elements: Vec<TextElement>,local_image_paths: Vec<PathBuf>,) {+ if self.history_search.take().is_some() {+ self.history.reset_navigation();+ self.footer.mode = reset_mode_after_activity(self.footer.mode);+ }self.set_text_content_with_mention_bindings(text,text_elements,@@ -1606,7 +1613,7 @@ impl ChatComposer {text_elements: self.current_text_elements(),local_image_paths: self.attachments.local_image_paths(),remote_image_urls: self.attachments.remote_image_urls(),- mention_bindings: self.snapshot_mention_bindings(),+ mention_bindings: self.mention_bindings(),pending_pastes: self.draft.pending_pastes.clone(),cursor: self.current_cursor(),}@@ -1765,21 +1772,6 @@ impl ChatComposer {self.current_text_elements()}- pub(crate) fn draft_snapshot(&self) -> ComposerDraftSnapshot {- ComposerDraftSnapshot {- text: self.current_text(),- cursor: self.current_cursor(),- text_elements: self.text_elements(),- local_images: self.local_images(),- remote_image_urls: self.remote_image_urls(),- mention_bindings: self.mention_bindings(),- pending_pastes: self.pending_pastes(),- startup_local_history: self.history.startup_local_history().to_vec(),- last_composer_activity_at: None,- sparkle_draft: self.sparkle.draft.get(),- }- }-#[cfg(test)]pub(crate) fn local_image_paths(&self) -> Vec<PathBuf> {self.attachments.local_image_paths()diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/history_search.rs b/codex-rs/tui/src/bottom_pane/chat_composer/history_search.rsindex 9b14b3973f..b5bd3e696e 100644--- a/codex-rs/tui/src/bottom_pane/chat_composer/history_search.rs+++ b/codex-rs/tui/src/bottom_pane/chat_composer/history_search.rs@@ -7,17 +7,23 @@//!//! This module is responsible for the UI-facing lifecycle of a search session: recognizing the//! keys that enter and drive search mode, keeping the footer query separate from the textarea-//! preview, restoring the original draft on cancellation or misses, and translating history search-//! results into composer-visible state. It deliberately does not decide which history entries+//! preview, restoring the saved draft on cancellation, and translating history search results into+//! composer-visible state. It deliberately does not decide which history entries//! match, how duplicate results are skipped, or when persistent history should be fetched; those//! traversal invariants stay with `ChatComposerHistory`.//!//! A search session starts idle with an empty footer query, so opening Ctrl+R never previews the//! latest history entry by itself. Typing or pasting a query restarts traversal from newest to oldest,//! repeated Ctrl+R/Up and Ctrl+S/Down move between unique matches, `Enter` accepts the current-//! preview as an editable draft, and `Esc` or Ctrl+C restores the exact draft that existed before-//! search started. Buffered keys are integrated before that snapshot without reclassifying them as+//! preview as an editable draft, and `Esc` or Ctrl+C restores the saved draft, including background+//! updates since search started. Buffered keys are integrated before that snapshot without reclassifying them as//! an explicit paste. Only accepting a nonempty preview dismisses any unused Astra sparkle opportunity.+//! Background draft updates stay hidden during search. Cancellation restores those updates;+//! accepting a match replaces the saved draft, including any recovered answers.+//! Explicit fresh draft replacements discard the saved draft and end search.++#[path = "history_search_draft.rs"]+mod draft;use std::ops::Range;@@ -49,12 +55,14 @@ use crate::ui_consts::FOOTER_INDENT_COLS;/// Active composer-owned state for one Ctrl+R search interaction.////// The session is created only by [`ChatComposer::begin_history_search`] and is cleared only by-/// accepting, canceling, or replacing the search mode. It stores the original draft and Vim edit-/// state separately from the footer query so transient previews never destroy in-progress content.+/// accepting, canceling, or replacing the search mode. It stores the cancellation draft and Vim+/// edit state separately from the footer query and preview so background edits stay hidden.#[derive(Debug)]pub(super) struct HistorySearchSession {- /// Draft to restore when search is canceled or a query has no match.+ /// Saved draft to restore on cancellation, including background updates.original_draft: ComposerDraft,+ /// Freeze the fallback only when background edits diverge from the saved draft.+ preview_draft: Option<ComposerDraft>,/// Same-draft Vim edits to restore when a temporary preview is canceled.original_vim_history: VimHistory,/// Active and completed Vim commands suspended during temporary draft replacement.@@ -66,6 +74,10 @@ pub(super) struct HistorySearchSession {}impl HistorySearchSession {+ fn preview_draft(&self) -> &ComposerDraft {+ self.preview_draft.as_ref().unwrap_or(&self.original_draft)+ }+/// Renders newlines and tabs as visible markers for the footer and cursor placement./// Matching continues to use the original query.fn display_query(&self) -> String {@@ -75,9 +87,9 @@ impl HistorySearchSession {/// User-visible phase of the active Ctrl+R search session.///-/// Search keeps the footer query and the composer preview separate: `Idle` leaves the original-/// draft untouched, `Searching` waits for persistent history, `Match` previews a found entry, and-/// `NoMatch` restores the original draft while leaving the search input open for more typing.+/// Search keeps the footer query and composer preview separate: `Idle` shows the frozen fallback+/// draft, `Searching` waits for persistent history, `Match` previews a found entry, and `NoMatch`+/// restores the frozen fallback while leaving the search input open for more typing.#[derive(Clone, Debug)]enum HistorySearchStatus {Idle,@@ -87,8 +99,7 @@ enum HistorySearchStatus {}impl ChatComposer {- #[cfg(test)]- pub(super) fn history_search_active(&self) -> bool {+ pub(in crate::bottom_pane) fn history_search_active(&self) -> bool {self.history_search.is_some()}@@ -133,6 +144,7 @@ impl ChatComposer {.textarea.swap_vim_persistent_state(&mut original_vim_state);self.history_search = Some(HistorySearchSession {+ preview_draft: None,original_draft,original_vim_history,original_vim_state,@@ -251,7 +263,7 @@ impl ChatComposer {let Some((query, original_draft)) = self.history_search.as_ref()- .map(|search| (search.query.clone(), search.original_draft.clone()))+ .map(|search| (search.query.clone(), search.preview_draft().clone()))else {return InputResult::None;};@@ -282,7 +294,7 @@ impl ChatComposer {edit(&mut search.query);search.status = HistorySearchStatus::Searching;let query = search.query.clone();- let original_draft = search.original_draft.clone();+ let original_draft = search.preview_draft().clone();self.with_sparkle_history_preview(|composer| composer.restore_draft(original_draft));if query.is_empty() {self.history.reset_search();@@ -350,7 +362,7 @@ impl ChatComposer {let original_draft = self.history_search.as_ref()- .map(|search| search.original_draft.clone());+ .map(|search| search.preview_draft().clone());if let Some(search) = self.history_search.as_mut() {search.status = if matches!(result, HistorySearchResult::NotFound) {HistorySearchStatus::NoMatchdiff --git a/codex-rs/tui/src/bottom_pane/chat_composer/history_search_draft.rs b/codex-rs/tui/src/bottom_pane/chat_composer/history_search_draft.rsnew file mode 100644index 0000000000..8c84217427--- /dev/null+++ b/codex-rs/tui/src/bottom_pane/chat_composer/history_search_draft.rs@@ -0,0 +1,69 @@+//! Read and update the saved composer draft while history search owns the visible preview.+//! Background edits are restored on cancellation and discarded when a history match is accepted.+//! The unchanged fallback preview is copied only before the first background edit.+//! Temporary restores preserve command eligibility; the actual background edit updates it.++use super::super::AttachmentState;+use super::super::ChatComposer;+use super::super::ComposerDraftSnapshot;+use super::super::TextArea;+use super::VimPersistentState;++impl ChatComposer {+ pub(crate) fn draft_snapshot(&self) -> ComposerDraftSnapshot {+ let draft = self.history_search.as_ref().map_or_else(+ || self.snapshot_draft(),+ |search| search.original_draft.clone(),+ );+ let mut attachments = AttachmentState::default();+ let mut textarea = TextArea::new();+ attachments.set_remote_image_urls(draft.remote_image_urls.clone(), &mut textarea);+ attachments.reset_local_images(draft.local_image_paths, &mut textarea);+ ComposerDraftSnapshot {+ text: draft.text,+ cursor: draft.cursor,+ text_elements: draft.text_elements,+ local_images: attachments.local_images(),+ remote_image_urls: draft.remote_image_urls,+ mention_bindings: draft.mention_bindings,+ pending_pastes: draft.pending_pastes,+ startup_local_history: self.history.startup_local_history().to_vec(),+ last_composer_activity_at: None,+ sparkle_draft: self.sparkle.draft.get(),+ }+ }++ /// Apply incoming draft changes behind an active search, preserving its query and preview.+ pub(in crate::bottom_pane) fn edit_stored_draft(&mut self, edit: impl FnOnce(&mut Self)) {+ let Some(mut search) = self.history_search.take() else {+ edit(self);+ return;+ };+ search+ .preview_draft+ .get_or_insert_with(|| search.original_draft.clone());+ let preview = self.snapshot_draft();+ let preview_vim_history = std::mem::take(&mut self.vim_history);+ let mut preview_vim_state = VimPersistentState::default();+ self.draft+ .textarea+ .swap_vim_persistent_state(&mut preview_vim_state);+ self.with_sparkle_history_preview(|composer| composer.restore_draft(search.original_draft));+ self.draft+ .textarea+ .swap_vim_persistent_state(&mut search.original_vim_state);+ self.vim_history = search.original_vim_history;+ edit(self);+ search.original_draft = self.snapshot_draft();+ search.original_vim_history = std::mem::take(&mut self.vim_history);+ self.draft+ .textarea+ .swap_vim_persistent_state(&mut search.original_vim_state);+ self.history_search = Some(search);+ self.with_sparkle_history_preview(|composer| composer.restore_draft(preview));+ self.draft+ .textarea+ .swap_vim_persistent_state(&mut preview_vim_state);+ self.vim_history = preview_vim_history;+ }+}diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/sparkle_tests.rs b/codex-rs/tui/src/bottom_pane/chat_composer/sparkle_tests.rsindex 8e07d16ec3..cecf995bba 100644--- a/codex-rs/tui/src/bottom_pane/chat_composer/sparkle_tests.rs+++ b/codex-rs/tui/src/bottom_pane/chat_composer/sparkle_tests.rs@@ -724,6 +724,7 @@ fn history_search_preserves_a_held_sparkle_command_without_reclassifying_it() {assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Command);pane.handle_paste("history".into());assert_eq!(pane.composer.current_text(), "history prompt");+ pane.set_composer_pending_pastes(Vec::new());assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Command);let searching = draw(&pane.composer, /*width*/ 80, during).0;assert!(dots(&searching).is_empty());@@ -787,16 +788,17 @@ fn cancelling_history_search_preserves_a_typed_command_despite_attachment_previe}#[test]-fn replacing_a_draft_outside_the_history_preview_dismisses_sparkles_during_search() {+fn fresh_draft_replacement_ends_search_and_dismisses_sparkles() {let mut pane = pane();pane.mark_fresh_task_for_sparkle("gpt-5.5", &enabled());pane.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));assert!(pane.composer.history_search_active());pane.composer.set_text_content("external draft".into(), Vec::new(), Vec::new());+ assert!(!pane.composer.history_search_active());assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Dismissed);key(&mut pane, KeyCode::Esc);- assert!(pane.composer.is_empty());+ assert_eq!(pane.composer.current_text(), "external draft");assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Dismissed);}diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/vim_history_tests.rs b/codex-rs/tui/src/bottom_pane/chat_composer/vim_history_tests.rsindex 311e6252d7..1afd87c4fd 100644--- a/codex-rs/tui/src/bottom_pane/chat_composer/vim_history_tests.rs+++ b/codex-rs/tui/src/bottom_pane/chat_composer/vim_history_tests.rs@@ -135,6 +135,29 @@ fn recovered_answers_undo_as_one_vim_edit() {ctrl_r(&mut composer);assert_eq!(composer.draft_snapshot(), after);}++ let mut composer = vim_composer("abc");+ composer+ .history+ .record_local_submission(HistoryEntry::new("archived prompt".into()));+ keys(&mut composer, "x");+ let before = composer.draft_snapshot();+ keys(&mut composer, "d");+ ctrl_r(&mut composer);+ keys(&mut composer, "archive");+ composer.edit_stored_draft(|composer| composer.append_recovered_drafts(&answer));+ assert_eq!(composer.current_text(), "archived prompt");+ assert!(composer.history_search_active());+ escape(&mut composer);+ assert_eq!(+ composer.current_text_with_pending(),+ format!("bc\n{answer}")+ );+ let after = composer.draft_snapshot();+ keys(&mut composer, "u");+ assert_eq!(composer.draft_snapshot(), before);+ ctrl_r(&mut composer);+ assert_eq!(composer.draft_snapshot(), after);}snapshot_composer_state_with_width("recovered_answer_cancels_vim_search",diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rsindex 7ecd259a85..3f16d118e1 100644--- a/codex-rs/tui/src/bottom_pane/mod.rs+++ b/codex-rs/tui/src/bottom_pane/mod.rs@@ -1075,13 +1075,15 @@ impl BottomPane {local_image_paths: Vec<PathBuf>,mention_bindings: Vec<MentionBinding>,) {- self.composer.set_text_content_with_mention_bindings(- text,- text_elements,- local_image_paths,- mention_bindings,- );- self.composer.move_cursor_to_end();+ self.composer.edit_stored_draft(|composer| {+ composer.set_text_content_with_mention_bindings(+ text,+ text_elements,+ local_image_paths,+ mention_bindings,+ );+ composer.move_cursor_to_end();+ });self.request_redraw();}@@ -1150,7 +1152,7 @@ impl BottomPane {}pub(crate) fn composer_pending_pastes(&self) -> Vec<(String, String)> {- self.composer.pending_pastes()+ self.composer.draft_snapshot().pending_pastes}pub(crate) fn apply_external_edit(&mut self, text: String) {@@ -1173,7 +1175,8 @@ impl BottomPane {}pub(crate) fn set_remote_image_urls(&mut self, urls: Vec<String>) {- self.composer.set_remote_image_urls(urls);+ self.composer+ .edit_stored_draft(|composer| composer.set_remote_image_urls(urls));self.request_redraw();}@@ -1188,7 +1191,8 @@ impl BottomPane {}pub(crate) fn set_composer_pending_pastes(&mut self, pending_pastes: Vec<(String, String)>) {- self.composer.set_pending_pastes(pending_pastes);+ self.composer+ .edit_stored_draft(|composer| composer.set_pending_pastes(pending_pastes));self.request_redraw();}diff --git a/codex-rs/tui/src/bottom_pane/questions.rs b/codex-rs/tui/src/bottom_pane/questions.rsindex 55d9c74b97..a507e7cb33 100644--- a/codex-rs/tui/src/bottom_pane/questions.rs+++ b/codex-rs/tui/src/bottom_pane/questions.rs@@ -48,8 +48,7 @@ impl BottomPane {// The question editor closes at turn end; recover its typed answer, not a history preview.questions.composer.cancel_history_search();let drafts = questions.take_pending_drafts();- if !drafts.is_empty() {- self.composer.cancel_history_search();+ if !drafts.is_empty() && !self.composer.history_search_active() {self.composer.flush_pending_input();}Some(drafts)@@ -60,7 +59,8 @@ impl BottomPane {if drafts.is_empty() {return;}- self.composer.append_recovered_drafts(&drafts.join("\n"));+ self.composer+ .edit_stored_draft(|composer| composer.append_recovered_drafts(&drafts.join("\n")));self.request_redraw();}diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__misalignment_turn_end_cleared_composer.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__misalignment_turn_end_cleared_composer.snapnew file mode 100644index 0000000000..37aff5b7ac--- /dev/null+++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__misalignment_turn_end_cleared_composer.snap@@ -0,0 +1,8 @@+---+source: tui/src/chatwidget/tests/misalignment_policy_tests.rs+assertion_line: 236+expression: "normalize_snapshot_paths(render_bottom_popup(&chat, 80))"+---+› Ask Codex to do anything++ esc esc to edit previous messagediff --git a/codex-rs/tui/src/chatwidget/tests/composer_submission.rs b/codex-rs/tui/src/chatwidget/tests/composer_submission.rsindex 95b6ea1a1d..7302a40670 100644--- a/codex-rs/tui/src/chatwidget/tests/composer_submission.rs+++ b/codex-rs/tui/src/chatwidget/tests/composer_submission.rs@@ -210,9 +210,16 @@ async fn rejected_hidden_shell_paste_preserves_colliding_draft_paste() {let draft_payload = format!("draft {}", "y".repeat(1000));chat.handle_paste(draft_payload.clone());chat.set_model("");+ chat.bottom_pane+ .record_replayed_user_message_history(crate::bottom_pane::HistoryEntry::new(+ "earlier prompt".into(),+ ));+ chat.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));+ chat.handle_key_event(KeyEvent::from(KeyCode::Char('e')));handle_turn_completed(&mut chat, "turn-1", /*duration_ms*/ None);chat.set_model(&model);+ chat.handle_key_event(KeyEvent::from(KeyCode::Esc));chat.handle_key_event(KeyEvent::from(KeyCode::Enter));assert_hidden_shell_payload_is_literal(op_rx.try_recv(), format!("{payload}\n{draft_payload}"));diff --git a/codex-rs/tui/src/chatwidget/tests/misalignment_policy_tests.rs b/codex-rs/tui/src/chatwidget/tests/misalignment_policy_tests.rsindex 8f9a249fa2..84b2f8c6e3 100644--- a/codex-rs/tui/src/chatwidget/tests/misalignment_policy_tests.rs+++ b/codex-rs/tui/src/chatwidget/tests/misalignment_policy_tests.rs@@ -178,6 +178,62 @@ async fn misalignment_policy_failure_stops_the_thread_and_renders_once() {assert!(chat.bottom_pane.has_active_view());}+#[tokio::test]+async fn misalignment_turn_end_discards_history_search_and_question_drafts() {+ let (mut chat, _rx, mut ops) = make_chatwidget_manual(/*model_override*/ None).await;+ let thread_id = ThreadId::new();+ chat.thread_id = Some(thread_id);+ handle_turn_started(&mut chat, "turn");+ chat.bottom_pane+ .handle_paste("blocked draft ".repeat(/*n*/ 200));+ chat.bottom_pane+ .set_remote_image_urls(vec!["https://example.com/blocked.png".into()]);+ chat.add_async_questions(+ "question",+ &[codex_protocol::items::AsyncUserInputQuestion {+ title: "Which way?".into(),+ options: None,+ }],+ );+ chat.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::ALT));+ chat.bottom_pane.handle_paste("answer".into());+ chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::ALT));+ chat.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));++ chat.handle_server_notification(+ ServerNotification::TurnCompleted(TurnCompletedNotification {+ thread_id: thread_id.to_string(),+ turn: app_server_turn(+ "turn",+ AppServerTurnStatus::Failed,+ /*duration_ms*/ None,+ Some(AppServerTurnError {+ misalignment: Some(review_details()),+ message: ERROR_MESSAGE.into(),+ codex_error_info: Some(CodexErrorInfo::MisalignmentPolicyViolation),+ additional_details: None,+ }),+ ),+ }),+ /*replay_kind*/ None,+ );++ assert_eq!(chat.capture_thread_input_state().unwrap().composer, None);+ assert_eq!(chat.bottom_pane.question_editor().unanswered_count(), 0);+ chat.clear_misalignment_for_new_turn(+ "acknowledged-turn",+ MisalignmentTurnSource::AcknowledgedContinuation,+ );+ assert!(chat.bottom_pane.no_modal_or_popup_active());+ chat.handle_key_event(KeyEvent::from(KeyCode::Esc));+ assert_eq!(chat.capture_thread_input_state().unwrap().composer, None);+ assert_chatwidget_snapshot!(+ "misalignment_turn_end_cleared_composer",+ normalize_snapshot_paths(render_bottom_popup(&chat, /*width*/ 80))+ );+ assert!(ops.try_recv().is_err());+}+fn review_details() -> codex_app_server_protocol::MisalignmentErrorDetails {codex_app_server_protocol::MisalignmentErrorDetails {error_type: Some("new_category".to_string()),diff --git a/codex-rs/tui/src/chatwidget/tests/question_turn_end_tests.rs b/codex-rs/tui/src/chatwidget/tests/question_turn_end_tests.rsindex ff2ca3ba73..255330f065 100644--- a/codex-rs/tui/src/chatwidget/tests/question_turn_end_tests.rs+++ b/codex-rs/tui/src/chatwidget/tests/question_turn_end_tests.rs@@ -98,6 +98,11 @@ async fn question_turn_end_recovers_collapsed_drafts_on_completion_and_failure()for ch in "main".chars() {chat.handle_key_event(KeyEvent::from(KeyCode::Char(ch)));}+ chat.bottom_pane.record_replayed_user_message_history(+ crate::bottom_pane::HistoryEntry::new("earlier prompt".into()),+ );+ chat.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));+ chat.handle_key_event(KeyEvent::from(KeyCode::Char('e')));if status == AppServerTurnStatus::Failed {chat.input_queue.queued_user_messages@@ -130,6 +135,9 @@ async fn question_turn_end_recovers_collapsed_drafts_on_completion_and_failure()}),/*replay_kind*/ None,);+ assert_eq!(chat.bottom_pane.composer_text(), "earlier prompt");+ assert!(!chat.bottom_pane.no_modal_or_popup_active());+ chat.handle_key_event(KeyEvent::from(KeyCode::Esc));assert_recovered_draft(&mut chat, "main\nanswer");assert!(ops.try_recv().is_err());}@@ -137,29 +145,90 @@ async fn question_turn_end_recovers_collapsed_drafts_on_completion_and_failure()#[tokio::test]async fn question_turn_end_recovers_after_interruption_restores_queued_input() {- let (mut chat, _rx, mut ops) = make_chatwidget_manual(/*model_override*/ None).await;- handle_turn_started(&mut chat, "turn");- chat.bottom_pane.set_disable_paste_burst(/*disabled*/ false);- chat.bottom_pane- .set_composer_text("main draft".into(), Vec::new(), Vec::new());- questions(&mut chat, "question");- chat.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::ALT));- chat.bottom_pane.handle_paste("answer".into());- chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::ALT));- chat.handle_key_event(KeyEvent::from(KeyCode::Char('+')));- chat.input_queue- .queued_user_messages- .push_back(UserMessage::from("queued prompt").into());- chat.input_queue- .pending_steers- .push_back(pending_steer("pending steer"));- handle_turn_interrupted(&mut chat, "turn");- assert_recovered_draft(- &mut chat,- "pending steer\nqueued prompt\nmain draft+\nanswer",- );- assert!(!chat.has_queued_follow_up_messages());- assert!(ops.try_recv().is_err());+ enum MainInput {+ HistoryAccept,+ HistoryCancel,+ BufferedTyping,+ }+ for main_input in [+ MainInput::HistoryAccept,+ MainInput::HistoryCancel,+ MainInput::BufferedTyping,+ ] {+ let (mut chat, _rx, mut ops) = make_chatwidget_manual(/*model_override*/ None).await;+ handle_turn_started(&mut chat, "turn");+ chat.bottom_pane.set_disable_paste_burst(/*disabled*/ false);+ chat.bottom_pane+ .set_composer_text("main draft".into(), Vec::new(), Vec::new());+ questions(&mut chat, "question");+ chat.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::ALT));+ chat.bottom_pane.handle_paste("answer".into());+ chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::ALT));+ let main_draft = match main_input {+ MainInput::HistoryAccept | MainInput::HistoryCancel => {+ chat.bottom_pane.record_replayed_user_message_history(+ crate::bottom_pane::HistoryEntry::new("earlier prompt".into()),+ );+ chat.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));+ chat.handle_key_event(KeyEvent::from(KeyCode::Char('e')));+ assert_eq!(chat.bottom_pane.composer_text(), "earlier prompt");+ if matches!(main_input, MainInput::HistoryAccept) {+ "earlier prompt"+ } else {+ "main draft"+ }+ }+ MainInput::BufferedTyping => {+ chat.handle_key_event(KeyEvent::from(KeyCode::Char('+')));+ "main draft+"+ }+ };+ chat.input_queue+ .queued_user_messages+ .push_back(UserMessage::from("queued prompt").into());+ chat.input_queue+ .pending_steers+ .push_back(pending_steer("pending steer"));+ handle_turn_interrupted(&mut chat, "turn");+ if !matches!(main_input, MainInput::BufferedTyping) {+ assert_eq!(chat.bottom_pane.composer_text(), "earlier prompt");+ assert!(!chat.bottom_pane.no_modal_or_popup_active());+ assert_eq!(+ chat.capture_thread_input_state()+ .unwrap()+ .composer+ .unwrap()+ .text,+ "pending steer\nqueued prompt\nmain draft\nanswer"+ );+ // A query miss and unsuccessful Enter must retain both the search and the answers.+ chat.handle_key_event(KeyEvent::from(KeyCode::Char('z')));+ chat.handle_key_event(KeyEvent::from(KeyCode::Enter));+ assert!(!chat.bottom_pane.no_modal_or_popup_active());+ assert_eq!(chat.bottom_pane.composer_text(), "main draft");+ chat.handle_key_event(KeyEvent::from(KeyCode::Backspace));+ if matches!(main_input, MainInput::HistoryAccept) {+ insta::assert_snapshot!(+ "question_turn_end_keeps_history_search",+ normalize_snapshot_paths(render_bottom_popup(&chat, /*width*/ 80))+ );+ }+ chat.handle_key_event(match main_input {+ MainInput::HistoryAccept => KeyEvent::from(KeyCode::Enter),+ _ => KeyEvent::from(KeyCode::Esc),+ });+ }+ if matches!(main_input, MainInput::HistoryAccept) {+ assert_recovered_draft(&mut chat, "earlier prompt");+ } else {+ assert_recovered_draft(+ &mut chat,+ &format!("pending steer\nqueued prompt\n{main_draft}\nanswer"),+ );+ }+ assert!(!chat.has_queued_follow_up_messages());+ assert!(ops.try_recv().is_err());+ }}fn assert_recovered_draft(chat: &mut ChatWidget, text: &str) {diff --git a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__question_turn_end_tests__question_turn_end_keeps_history_search.snap b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__question_turn_end_tests__question_turn_end_keeps_history_search.snapnew file mode 100644index 0000000000..73904dfd0a--- /dev/null+++ b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__question_turn_end_tests__question_turn_end_keeps_history_search.snap@@ -0,0 +1,8 @@+---+source: tui/src/chatwidget/tests/question_turn_end_tests.rs+assertion_line: 191+expression: "normalize_snapshot_paths(render_bottom_popup(&chat, 80))"+---+› earlier prompt++ reverse-i-search: e enter accept · esc cancel