From 00696090d65a747848e0a40661e1da8badb1f146 Mon Sep 17 00:00:00 2001 From: Anton Panasenko Date: Mon, 23 Nov 2026 18:33:35 +0000 Subject: [PATCH] Preserve slash command selection across TUI connection changes (#63419) ## Why Going offline can change the slash command menu while a user is choosing a command. With `/ex` typed and `/export` selected, a disconnect could move the highlight to `/exit` and cause Enter to quit Codex. ## What changed - Keep the same command highlighted when it remains in the menu. If it disappears, clear the selection and prevent submission from falling back to the draft. Restore the cursor, selection, and popup dismissal on reconnect. - Honor configured submit chords in restricted slash command menus and prevent Tab from queuing the draft there. - When users try to report an issue offline, scroll to the latest transcript entry to show the thread ID and prompt them to reconnect and retry. ## Testing Add regression coverage for the `/export` to `/exit` case, popup state after reconnect, offline Tab and submit chords, Vim command submission, and thread ID visibility while scrolled back. GitOrigin-RevId: 8143534f9d40e77a389d80d1dff3db993e194a23 --- codex-rs/tui/src/app/event_dispatch.rs | 3 +- .../src/app/tests/active_reconnect_tests.rs | 25 +++++ .../tui/src/app/tests/disconnect_tests.rs | 21 ---- codex-rs/tui/src/app/tests/key_chords.rs | 24 +++++ .../app/tests/local_command_scroll_tests.rs | 34 +++++++ codex-rs/tui/src/bottom_pane/chat_composer.rs | 26 +++-- .../bottom_pane/chat_composer/reconnect.rs | 60 ++++++++++- .../chat_composer/reconnect_tests.rs | 99 ++++++++++++++++++- .../bottom_pane/chat_composer/slash_input.rs | 9 +- ...ect__tests__disconnected_command_menu.snap | 2 +- codex-rs/tui/src/bottom_pane/command_popup.rs | 87 ++++++++-------- codex-rs/tui/src/bottom_pane/mod.rs | 1 + codex-rs/tui/src/chatwidget/input_restore.rs | 6 ++ codex-rs/tui/src/chatwidget/questions.rs | 1 + .../chatwidget/tests/composer_submission.rs | 51 ++++++++++ codex-rs/tui/src/chatwidget/user_messages.rs | 1 + codex-rs/tui/src/keymap/chords.rs | 2 +- 17 files changed, 371 insertions(+), 81 deletions(-) diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index c2efb3f692..76d51c91d5 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -96,9 +96,10 @@ impl App { || "Thread ID unavailable.".to_string(), |id| format!("Thread ID {id}"), ); + self.transcript_view.jump_to_latest(); self.chat_widget.add_info_message( thread, - Some("Reconnect to send feedback or save a ZIP.".into()), + Some("Reconnect and retry /feedback.".into()), ); return Ok(AppRunControl::Continue); } diff --git a/codex-rs/tui/src/app/tests/active_reconnect_tests.rs b/codex-rs/tui/src/app/tests/active_reconnect_tests.rs index 0f85ec35bb..21743ff01c 100644 --- a/codex-rs/tui/src/app/tests/active_reconnect_tests.rs +++ b/codex-rs/tui/src/app/tests/active_reconnect_tests.rs @@ -568,6 +568,16 @@ async fn reconnect_reconciles_offscreen_pending_profile_before_restoring_permiss let mut session = crate::start_embedded_app_server_for_picker(&app.config).await?; let mut tui = crate::tui::test_support::make_test_tui()?; app.begin_reconnect(); + // The displayed thread is editing /config when the connection returns. + for ch in "/co".chars() { + app.handle_tui_event( + &mut tui, + &mut session, + TuiEvent::Key(KeyCode::Char(ch).into()), + ) + .await?; + } + assert!(render_bottom_popup(&app.chat_widget, /*width*/ 80).contains("› /config")); let connected = reconnect( session.backend_id(), app.app_server_target.clone(), @@ -588,6 +598,21 @@ async fn reconnect_reconciles_offscreen_pending_profile_before_restoring_permiss ) .await?; assert!(app.pending_server_profiles.contains_key(&primary)); + // Replay replaces the widget. Tab must still complete /config even though + // /compact now sorts first. + let menu = render_bottom_popup(&app.chat_widget, /*width*/ 80); + let choices = menu + .lines() + .filter(|line| line.contains("/compact") || line.contains("/config")) + .map(str::trim_end) + .collect::>(); + assert_snapshot!(choices.join("\n"), @r" + /compact summarize conversation to prevent hitting the context limit + › /config configure Codex preferences + "); + app.handle_tui_event(&mut tui, &mut session, TuiEvent::Key(KeyCode::Tab.into())) + .await?; + assert_eq!(app.chat_widget.composer_text_with_pending(), "/config "); app.select_agent_thread(&mut tui, &mut session, primary) .await?; diff --git a/codex-rs/tui/src/app/tests/disconnect_tests.rs b/codex-rs/tui/src/app/tests/disconnect_tests.rs index a2105b1685..016153f1b1 100644 --- a/codex-rs/tui/src/app/tests/disconnect_tests.rs +++ b/codex-rs/tui/src/app/tests/disconnect_tests.rs @@ -220,27 +220,6 @@ async fn lost_mutation_reply_preserves_work_without_resubmitting() -> Result<()> AppRunControl::Exit(ExitReason::UserRequested) )); } - for ch in "/feedback".chars() { - app.handle_tui_event( - &mut tui, - &mut session, - TuiEvent::Key(KeyCode::Char(ch).into()), - ) - .await?; - } - app.handle_tui_event(&mut tui, &mut session, TuiEvent::Key(KeyCode::Enter.into())) - .await?; - while let Ok(event) = events.try_recv() { - app.handle_event(&mut tui, &mut session, event).await?; - } - let guidance = lines_to_single_string( - &app.transcript_cells - .last() - .unwrap() - .display_lines(/*width*/ 120), - ); - assert_snapshot!(guidance.replace(&id.to_string(), ""), @"• Thread ID Reconnect to send feedback or save a ZIP."); - for command in ["/exit", "/quit", "/q"] { app.chat_widget .restore_user_message_to_composer(command.into()); diff --git a/codex-rs/tui/src/app/tests/key_chords.rs b/codex-rs/tui/src/app/tests/key_chords.rs index 8f9a854681..9087aea880 100644 --- a/codex-rs/tui/src/app/tests/key_chords.rs +++ b/codex-rs/tui/src/app/tests/key_chords.rs @@ -302,6 +302,30 @@ async fn completed_global_chords_toggle_output_and_request_external_editor() -> Ok(()) } +#[tokio::test] +async fn disconnected_command_popup_accepts_the_composer_submit_chord() -> Result<()> { + let (mut app, mut events, _ops) = make_test_app_with_channels().await; + let mut server = start_config_write_test_app_server(&app).await?; + let mut tui = crate::tui::test_support::make_test_tui()?; + let config = toml::from_str("[composer]\nsubmit = 'ctrl-x enter'")?; + app.keymap = RuntimeKeymap::from_config(&config).expect("valid submit chord"); + app.chat_widget.apply_keymap_update(config, &app.keymap); + app.reconnect.offline = true; + for ch in "/warnings".chars() { + press(&mut app, &mut tui, &mut server, KeyCode::Char(ch).into()).await?; + } + press(&mut app, &mut tui, &mut server, ctrl('x')).await?; + assert!(app.key_chord_matcher.is_pending()); + assert_eq!(app.chat_widget.composer_text_with_pending(), "/warnings"); + press(&mut app, &mut tui, &mut server, KeyCode::Enter.into()).await?; + assert!( + std::iter::from_fn(|| events.try_recv().ok()) + .any(|event| matches!(event, AppEvent::OpenWarnings)) + ); + server.shutdown().await?; + Ok(()) +} + #[tokio::test] async fn composer_submit_chord_works_with_slash_argument_popup() -> Result<()> { let (mut app, mut tui, mut app_server) = chord_app().await?; diff --git a/codex-rs/tui/src/app/tests/local_command_scroll_tests.rs b/codex-rs/tui/src/app/tests/local_command_scroll_tests.rs index 504a26b4fd..786f6bf322 100644 --- a/codex-rs/tui/src/app/tests/local_command_scroll_tests.rs +++ b/codex-rs/tui/src/app/tests/local_command_scroll_tests.rs @@ -47,6 +47,40 @@ fn submit_local_command(app: &mut App, command: &str) { assert_eq!(app.chat_widget.composer_text_with_pending(), ""); } +#[tokio::test] +async fn disconnected_feedback_reveals_the_thread_id_from_older_history() -> Result<()> { + let (mut app, mut events, _ops) = make_test_app_with_channels().await; + let mut tui = crate::tui::test_support::make_test_tui()?; + let mut server = start_config_write_test_app_server(&app).await?; + tui.set_owned_screen(/*owned*/ true)?; + let id = ThreadId::new(); + app.active_thread_id = Some(id); + app.reconnect.offline = true; + hold_older_history(&mut app, &mut tui); + for ch in "/feedback".chars() { + app.handle_tui_event( + &mut tui, + &mut server, + TuiEvent::Key(KeyCode::Char(ch).into()), + ) + .await?; + } + app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Enter.into())) + .await?; + while let Ok(event) = events.try_recv() { + app.handle_event(&mut tui, &mut server, event).await?; + } + let visible = crate::app::owned_transcript::tests::buffer_text(&transcript_buffer(&mut app)); + insta::assert_snapshot!(visible.replace(&id.to_string(), ""), @" + older 5 + + • Thread ID Reconnect and retry /feedback. + "); + tui.set_owned_screen(/*owned*/ false)?; + server.shutdown().await?; + Ok(()) +} + #[tokio::test] async fn settings_pickers_preserve_the_reading_anchor_through_open_and_close() -> Result<()> { let (mut app, mut events, _op_rx) = make_test_app_with_channels().await; diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 8869397783..fb524fb27b 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -195,7 +195,9 @@ //! Exports and local display commands (`/title` and `/statusline`) also accept arguments. //! //! While disconnected, `handle_restricted_key` keeps the draft editable without submission. -//! The slash popup supports navigation, Tab and submission of local commands. +//! The slash popup supports navigation and configured submit keys for local commands. +//! Tab completes without queuing. A connection change keeps the same selection or leaves +//! the menu unselected if the command disappears. //! Local commands include `/warnings`, `/config`, `/rc` (alias `/remote`, including `stop`), //! `/feedback` (thread ID and reconnection guidance), `/quit`, and `/exit`. Searching for //! other commands shows that they require a server connection. `?` becomes literal input. @@ -432,6 +434,7 @@ mod passive_hints; mod paste_input; mod popup_state; mod reconnect; +pub(crate) use reconnect::DisconnectedCommandState; pub(crate) use reconnect::RestrictedInputMode; mod edit_history; mod slash_argument; @@ -1181,7 +1184,14 @@ impl ChatComposer { } else { KeymapContextSet::default() }; - return if matches!(self.popups.active, ActivePopup::Argument(_)) { + let restricted_command = matches!(self.popups.active, ActivePopup::Command(_)) + && matches!( + self.popups.restricted_input_mode, + Some( + RestrictedInputMode::Disconnected | RestrictedInputMode::UnavailableThread + ) + ); + return if matches!(self.popups.active, ActivePopup::Argument(_)) || restricted_command { contexts.with_composer_submit() } else { contexts @@ -1663,7 +1673,8 @@ impl ChatComposer { self.current_cursor() } - fn history_navigation_cursor(&self) -> usize { + /// Treat Vim's final block cursor as the end of the draft. + fn logical_cursor(&self) -> usize { if self.draft.is_bash_mode && self.draft.textarea.cursor() == 0 { 0 } else if self.draft.textarea.is_vim_normal_mode() @@ -3720,10 +3731,9 @@ impl ChatComposer { }; if history_up_pressed || history_down_pressed { if self.draft.textarea.mouse_selection_range().is_none() - && self.history.should_handle_navigation( - &self.current_text(), - self.history_navigation_cursor(), - ) + && self + .history + .should_handle_navigation(&self.current_text(), self.logical_cursor()) { let replace_entry = if history_up_pressed { self.history.navigate_up(&self.app_event_tx) @@ -4077,7 +4087,7 @@ impl ChatComposer { if self.draft.is_bash_mode || self .history - .should_handle_navigation(&self.current_text(), self.history_navigation_cursor()) + .should_handle_navigation(&self.current_text(), self.logical_cursor()) { if self.popups.current_file_query.is_some() { self.app_event_tx diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/reconnect.rs b/codex-rs/tui/src/bottom_pane/chat_composer/reconnect.rs index 3bd7d58df2..66e29f2e91 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/reconnect.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/reconnect.rs @@ -1,4 +1,5 @@ //! Restricted editing retains drafts and limits slash dispatch to local commands. +//! A reconnect can replace the composer. Preserve the slash selection with the draft. //! Unavailable threads also allow recovery and other local commands. //! Connected unavailable threads retain the empty-prompt agents shortcut. //! Paste Enter handling is shared with normal submission so buffered newlines survive both paths. @@ -8,6 +9,44 @@ //! Offline draft edits also consume the Astra sparkle opportunity before rendering. use super::*; +use crate::bottom_pane::BottomPane; + +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct DisconnectedCommandState { + cursor: usize, + selected: Option, + dismissed: Option, +} + +impl BottomPane { + pub(crate) fn disconnected_command_state(&self) -> Option { + let composer = &self.composer; + if composer.popups.restricted_input_mode != Some(RestrictedInputMode::Disconnected) + || composer.draft.is_bash_mode + || !composer.draft.textarea.text().starts_with('/') + { + return None; + } + Some(DisconnectedCommandState { + cursor: composer.logical_cursor(), + selected: match &composer.popups.active { + ActivePopup::Command(popup) => popup.current_item(), + _ => None, + }, + dismissed: composer.popups.dismissed_command_token.clone(), + }) + } + + pub(crate) fn restore_disconnected_command(&mut self, state: DisconnectedCommandState) { + self.composer.popups.active = ActivePopup::None; + self.composer.popups.dismissed_command_token = state.dismissed; + self.set_composer_cursor(state.cursor); + if let ActivePopup::Command(popup) = &mut self.composer.popups.active { + // An absent selection matters too, e.g. when the cursor split the name offline. + popup.restore_selection(state.selected); + } + } +} #[derive(Clone, Copy, PartialEq, Eq)] pub(crate) enum RestrictedInputMode { @@ -33,12 +72,11 @@ impl ChatComposer { let was_disconnected = self.popups.restricted_input_mode == Some(RestrictedInputMode::Disconnected); self.popups.restricted_input_mode = mode; - // Command popups cache their catalog. Rebuild it on a connection change, keeping - // the selection across keys and redraws that use the same catalog. - if was_disconnected != (mode == Some(RestrictedInputMode::Disconnected)) - && matches!(self.popups.active, ActivePopup::Command(_)) + let disconnected = mode == Some(RestrictedInputMode::Disconnected); + if was_disconnected != disconnected + && let ActivePopup::Command(popup) = &mut self.popups.active { - self.popups.active = ActivePopup::None; + popup.set_disconnected(disconnected); self.sync_restricted_slash_popup(); } // Reconcile a popup opened before the routing mode changed, before Tab can accept it. @@ -216,6 +254,9 @@ impl ChatComposer { self.sync_restricted_slash_popup(); return result; } + if submit && popup.blocks_submit_fallback() { + return InputResult::None; + } if !submit && (matches!(key.code, KeyCode::Up | KeyCode::Down | KeyCode::Esc) || matches!( @@ -246,6 +287,15 @@ impl ChatComposer { { let input = self.slash_input(); let text = self.draft.textarea.text(); + // A partial name under the cursor hides the popup offline. Don't + // dispatch the full draft in place of the previously highlighted row. + if mode == RestrictedInputMode::Disconnected + && let Some((_, tail)) = + slash_input::command_under_cursor(text, self.logical_cursor()) + && tail.starts_with(|ch: char| !ch.is_whitespace()) + { + return InputResult::None; + } let command = input .bare_command(text) .or_else(|| input.inline_command(text).map(|command| command.command)) diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/reconnect_tests.rs b/codex-rs/tui/src/bottom_pane/chat_composer/reconnect_tests.rs index a6aadeb68e..ade1373992 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/reconnect_tests.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/reconnect_tests.rs @@ -320,11 +320,28 @@ fn unavailable_thread_vim_escape_and_search_keep_popup_closed() { } } +#[test] +fn disconnected_vim_submit_after_escape_dispatches_the_complete_command() { + let (mut composer, _) = new_test_composer(); + composer.enable_vim_in_insert_mode(); + let mode = RestrictedInputMode::Disconnected; + for ch in "/feedback".chars() { + composer.handle_restricted_key(KeyCode::Char(ch).into(), mode); + } + composer.handle_restricted_key(KeyCode::Esc.into(), mode); + composer.sync_popups(); + assert!(composer.draft.textarea.is_vim_normal_mode()); + assert_eq!( + composer.handle_restricted_key(KeyCode::Enter.into(), mode), + InputResult::Command(SlashCommand::Feedback) + ); +} + #[test] fn disconnected_menu_keeps_its_selection_across_redraws_and_restores_the_catalog() { let (mut composer, _) = new_test_composer(); - composer.set_text_content("/".into(), Vec::new(), Vec::new()); let mode = RestrictedInputMode::Disconnected; + composer.handle_restricted_key(KeyCode::Char('/').into(), mode); for key in [KeyCode::Down, KeyCode::Down, KeyCode::Up] { composer.handle_restricted_key(key.into(), mode); composer.set_restricted_input_mode(Some(mode)); @@ -367,6 +384,86 @@ fn disconnected_menu_keeps_its_selection_across_redraws_and_restores_the_catalog ); } +#[test] +fn disconnected_popup_never_retargets_export_to_exit() { + let (mut composer, _) = new_test_composer(); + composer.set_text_content("/ex".into(), Vec::new(), Vec::new()); + composer.handle_key_event(KeyCode::Down.into()); + let ActivePopup::Command(popup) = &composer.popups.active else { + panic!("expected command popup"); + }; + assert_eq!( + popup.selected_item(), + Some(CommandItem::Builtin(SlashCommand::Export)) + ); + + let mode = RestrictedInputMode::Disconnected; + // Enter can arrive before the first offline frame. + assert_eq!( + composer.handle_restricted_key(KeyCode::Enter.into(), mode), + InputResult::None + ); + composer.sync_popups(); + composer.handle_restricted_key(KeyCode::Tab.into(), mode); + assert_eq!(composer.current_text(), "/ex"); + composer.handle_restricted_key(KeyCode::Down.into(), mode); + assert_eq!( + composer.handle_restricted_key(KeyCode::Enter.into(), mode), + InputResult::Command(SlashCommand::Exit) + ); +} + +#[test] +fn disconnected_popup_does_not_submit_the_draft_when_the_cursor_splits_the_name() { + let (mut composer, _) = new_test_composer(); + composer.set_text_content("/exit".into(), Vec::new(), Vec::new()); + // Filter on the prefix before the cursor, while the full draft is a valid command. + for key in [KeyCode::End, KeyCode::Left, KeyCode::Left, KeyCode::Down] { + composer.handle_key_event(key.into()); + } + let ActivePopup::Command(popup) = &composer.popups.active else { + panic!("expected command popup"); + }; + assert_eq!( + popup.selected_item(), + Some(CommandItem::Builtin(SlashCommand::Export)) + ); + assert_eq!( + composer.handle_restricted_key(KeyCode::Enter.into(), RestrictedInputMode::Disconnected), + InputResult::None + ); + assert_eq!(composer.current_text(), "/exit"); + composer.handle_restricted_key(KeyCode::End.into(), RestrictedInputMode::Disconnected); + assert_eq!( + composer.handle_restricted_key(KeyCode::Enter.into(), RestrictedInputMode::Disconnected), + InputResult::Command(SlashCommand::Exit) + ); +} + +#[test] +fn disconnected_popup_requires_navigation_when_the_selection_disappears() { + let (mut composer, _) = new_test_composer(); + composer.set_text_content("/".into(), Vec::new(), Vec::new()); + let mode = RestrictedInputMode::Disconnected; + composer.handle_restricted_key(KeyCode::Null.into(), mode); + composer.sync_popups(); + assert_eq!( + composer.handle_restricted_key(KeyCode::Enter.into(), mode), + InputResult::None + ); + assert_eq!( + composer.handle_key_event(KeyCode::Enter.into()).0, + InputResult::None + ); + composer.handle_restricted_key(KeyCode::Down.into(), mode); + composer.set_restricted_input_mode(/*mode*/ None); + composer.sync_popups(); + assert_eq!( + composer.handle_key_event(KeyCode::Enter.into()).0, + InputResult::Command(SlashCommand::Config) + ); +} + #[test] fn disconnected_input_dispatches_local_config_command() { let (mut composer, _) = new_test_composer(); diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/slash_input.rs b/codex-rs/tui/src/bottom_pane/chat_composer/slash_input.rs index 8783f8ea2f..5140fa6d12 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/slash_input.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/slash_input.rs @@ -334,7 +334,7 @@ impl ChatComposer { if has_visible_items && !has_selectable_item { return (InputResult::None, true); } - if self.is_task_running { + if self.is_task_running && mode == SlashPopupInputMode::Normal { return self.handle_submission(/*should_queue*/ true); } (InputResult::None, true) @@ -422,7 +422,10 @@ impl ChatComposer { true, ); } - // Fallback to default newline handling if no command selected. + // A selection lost on disconnect must not submit the raw draft after reconnect. + if popup.blocks_submit_fallback() { + return (InputResult::None, true); + } self.handle_key_event_without_popup(key_event) } input => self.handle_input_basic(input), @@ -562,7 +565,7 @@ pub(super) fn command_popup_filter_text(first_line: &str, cursor: usize) -> Opti /// If the cursor is currently within a slash command on the first line, /// extract the command fragment before the cursor and the rest of the line after it. -fn command_under_cursor(first_line: &str, cursor: usize) -> Option<(&str, &str)> { +pub(super) fn command_under_cursor(first_line: &str, cursor: usize) -> Option<(&str, &str)> { if !first_line.starts_with('/') { return None; } diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__reconnect__tests__disconnected_command_menu.snap b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__reconnect__tests__disconnected_command_menu.snap index bb98e4fe9e..b8bd303bf9 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__reconnect__tests__disconnected_command_menu.snap +++ b/codex-rs/tui/src/bottom_pane/chat_composer/snapshots/codex_tui__bottom_pane__chat_composer__reconnect__tests__disconnected_command_menu.snap @@ -6,7 +6,7 @@ expression: terminal.backend() "› /rc manage remote control for the local background server " " /warnings view retained warnings and diagnostic details " " /exit exit Codex " -" /feedback show the thread ID and how to send feedback " +" /feedback show the current thread ID " " " "› / " " " diff --git a/codex-rs/tui/src/bottom_pane/command_popup.rs b/codex-rs/tui/src/bottom_pane/command_popup.rs index e6854d61bc..0e23ecef2c 100644 --- a/codex-rs/tui/src/bottom_pane/command_popup.rs +++ b/codex-rs/tui/src/bottom_pane/command_popup.rs @@ -34,7 +34,7 @@ pub(crate) enum CommandItem { pub(crate) struct CommandPopup { disconnected: bool, - command_filter: String, + command_filter: Option, commands: Vec, side_conversation_active: bool, state: ScrollState, @@ -98,7 +98,7 @@ impl CommandPopup { .collect(); Self { disconnected: flags.disconnected, - command_filter: String::new(), + command_filter: None, commands, side_conversation_active: flags.side_conversation_active, state: ScrollState::new(), @@ -106,40 +106,37 @@ impl CommandPopup { } } - /// Update the filter string based on the current composer text. The text - /// passed in is expected to start with a leading '/'. Everything after the - /// *first* '/' on the *first* line becomes the active filter that is used - /// to narrow down the list of available commands. + /// Changing availability can reorder or hide rows. Never retarget a pending Enter. + pub(crate) fn set_disconnected(&mut self, disconnected: bool) { + let selected = self.current_item(); + self.disconnected = disconnected; + self.restore_selection(selected); + } + + pub(super) fn restore_selection(&mut self, selected: Option) { + let items = self.filtered_items(); + self.state.reset(); + self.state.selected_idx = items + .iter() + .position(|item| Some(item) == selected.as_ref()); + self.state.ensure_visible(items.len(), MAX_POPUP_ROWS); + } + + /// Only a new filter selects the first match. Redraws must also preserve + /// an empty selection if the previously highlighted command disappeared. pub(crate) fn on_composer_text_change(&mut self, text: String) { - let first_line = text.lines().next().unwrap_or(""); - let previous_filter = self.command_filter.clone(); - - if let Some(stripped) = first_line.strip_prefix('/') { - // Extract the *first* token (sequence of non-whitespace - // characters) after the slash so that `/clear something` still - // shows the help for `/clear`. - let token = stripped.trim_start(); - let cmd_token = token.split_whitespace().next().unwrap_or(""); - - // Update the filter keeping the original case (commands are all - // lower-case for now but this may change in the future). - self.command_filter = cmd_token.to_string(); - } else { - // The composer no longer starts with '/'. Reset the filter so the - // popup shows the *full* command list if it is still displayed - // for some reason. - self.command_filter.clear(); + let filter = text + .lines() + .next() + .and_then(|line| line.strip_prefix('/')) + .and_then(|rest| rest.split_whitespace().next()) + .unwrap_or_default(); + if self.command_filter.as_deref() == Some(filter) { + return; } - - if self.command_filter != previous_filter { - self.state.reset(); - } - - // Reset or clamp selected index based on new filtered list. - let matches_len = self.filtered_items().len(); - self.state.clamp_selection(matches_len); - self.state - .ensure_visible(matches_len, MAX_POPUP_ROWS.min(matches_len)); + self.command_filter = Some(filter.to_owned()); + self.state.reset(); + self.state.clamp_selection(self.filtered_items().len()); } /// Determine the preferred height of the popup for a given width. @@ -160,7 +157,7 @@ impl CommandPopup { /// paired with optional highlight indices. Preserves the original /// presentation order for built-ins and prompts. fn filtered(&self) -> Vec<(CommandItem, Option>)> { - let filter = self.command_filter.trim(); + let filter = self.command_filter.as_deref().unwrap_or_default(); let mut out: Vec<(CommandItem, Option>)> = Vec::new(); if filter.is_empty() { for command in self.commands.iter() { @@ -219,6 +216,13 @@ impl CommandPopup { self.filtered().into_iter().map(|(c, _)| c).collect() } + /// With no actionable selection, don't reinterpret a disabled offline row + /// or a lost highlight as a request to submit the underlying draft. + pub(crate) fn blocks_submit_fallback(&self) -> bool { + (self.disconnected || self.state.selected_idx.is_none()) + && !self.filtered_items().is_empty() + } + fn rows_from_matches( &self, matches: Vec<(CommandItem, Option>)>, @@ -230,7 +234,7 @@ impl CommandPopup { let name = format!("/{}", item.command()); let description = match item { CommandItem::Builtin(SlashCommand::Feedback) if self.disconnected => { - "show the thread ID and how to send feedback" + "show the current thread ID" } CommandItem::Builtin(SlashCommand::Daybreak) => self .daybreak_command_description @@ -284,12 +288,15 @@ impl CommandPopup { .ensure_visible(matches_len, MAX_POPUP_ROWS.min(matches_len)); } - /// Return currently selected command, if any. - pub(crate) fn selected_item(&self) -> Option { - let matches = self.filtered_items(); + /// Remember the row even if it is temporarily disabled. + pub(super) fn current_item(&self) -> Option { self.state .selected_idx - .and_then(|idx| matches.get(idx).cloned()) + .and_then(|idx| self.filtered_items().into_iter().nth(idx)) + } + + pub(crate) fn selected_item(&self) -> Option { + self.current_item() .filter(|item| self.unavailable_reason(item).is_none()) } diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index f93c762f84..303ed492bb 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -273,6 +273,7 @@ pub(crate) use chat_composer::ChatComposer; pub(crate) use chat_composer::ChatComposerConfig; pub(crate) use chat_composer::ClipboardPasteTarget; pub(crate) use chat_composer::ComposerDraftSnapshot; +pub(crate) use chat_composer::DisconnectedCommandState; pub(crate) use chat_composer::InputResult; pub(crate) use chat_composer::KillBufferSnapshot; pub(crate) use chat_composer::QueuedInputAction; diff --git a/codex-rs/tui/src/chatwidget/input_restore.rs b/codex-rs/tui/src/chatwidget/input_restore.rs index cc62cd2e72..0d0cdc4481 100644 --- a/codex-rs/tui/src/chatwidget/input_restore.rs +++ b/codex-rs/tui/src/chatwidget/input_restore.rs @@ -679,6 +679,7 @@ impl ChatWidget { let ThreadComposerState { text, shell_mode: _, + disconnected_command, local_images, remote_image_urls, text_elements, @@ -699,6 +700,9 @@ impl ChatWidget { }, ); self.bottom_pane.set_composer_pending_pastes(pending_pastes); + if let Some(command) = disconnected_command { + self.bottom_pane.restore_disconnected_command(command); + } } fn composer_state_from_user_message( @@ -715,6 +719,7 @@ impl ChatWidget { ThreadComposerState { text, shell_mode: None, + disconnected_command: None, local_images, remote_image_urls, text_elements, @@ -728,6 +733,7 @@ impl ChatWidget { let draft = self.bottom_pane.composer_recovery_snapshot(); let composer = ThreadComposerState { text: draft.text, + disconnected_command: self.bottom_pane.disconnected_command_state(), // A disabled shell composer also treats a leading bang literally. shell_mode: Some(draft.shell_mode.unwrap_or(false)), text_elements: draft.text_elements, diff --git a/codex-rs/tui/src/chatwidget/questions.rs b/codex-rs/tui/src/chatwidget/questions.rs index 08a93dc06e..d87dc84138 100644 --- a/codex-rs/tui/src/chatwidget/questions.rs +++ b/codex-rs/tui/src/chatwidget/questions.rs @@ -198,6 +198,7 @@ impl ChatWidget { self.restore_composer_state(ThreadComposerState { text: main.text, shell_mode: None, + disconnected_command: None, text_elements: main.text_elements, local_images: main.local_images, remote_image_urls: main.remote_image_urls, diff --git a/codex-rs/tui/src/chatwidget/tests/composer_submission.rs b/codex-rs/tui/src/chatwidget/tests/composer_submission.rs index db5ffe023a..7a81f440db 100644 --- a/codex-rs/tui/src/chatwidget/tests/composer_submission.rs +++ b/codex-rs/tui/src/chatwidget/tests/composer_submission.rs @@ -13,6 +13,57 @@ use codex_protocol::permissions::NetworkSandboxPolicy; use pretty_assertions::assert_eq; use std::collections::VecDeque; +#[tokio::test] +async fn disconnected_tab_keeps_exact_exit_out_of_the_queue() { + let (mut chat, _events, _ops) = make_chatwidget_manual(/*model_override*/ None).await; + chat.on_task_started(); + chat.queue_user_message("already queued".to_string().into()); + chat.pause_for_disconnect(); + assert!(chat.bottom_pane.is_task_running()); + chat.apply_external_edit("/exit".into()); + chat.handle_restricted_key(KeyCode::Tab.into(), RestrictedInputMode::Disconnected); + assert_eq!(chat.queued_user_message_texts(), ["already queued"]); + assert_eq!(chat.composer_text_with_pending(), "/exit"); +} + +#[tokio::test] +async fn reconnect_keeps_a_split_command_unselected_in_the_new_widget() { + let (mut chat, _events, _ops) = make_chatwidget_manual(/*model_override*/ None).await; + chat.apply_external_edit("/exit".into()); + for key in [KeyCode::End, KeyCode::Left, KeyCode::Left, KeyCode::Down] { + chat.handle_key_event(key.into()); + } + chat.handle_restricted_key(KeyCode::Null.into(), RestrictedInputMode::Disconnected); + let mut input = chat.capture_thread_input_state().expect("offline draft"); + input.reconnect_pending = true; + + let (mut restored, _events, _ops) = make_chatwidget_manual(/*model_override*/ None).await; + restored.restore_reconnected_input(Some(input), &[]); + restored.handle_key_event(KeyCode::Enter.into()); + assert_eq!( + ( + restored.composer_text_with_pending(), + restored.bottom_pane.composer_cursor() + ), + ("/exit".to_owned(), "/ex".len()) + ); +} + +#[tokio::test] +async fn reconnect_keeps_a_dismissed_command_popup_closed() { + let (mut chat, _events, _ops) = make_chatwidget_manual(/*model_override*/ None).await; + chat.apply_external_edit("/config".into()); + chat.handle_restricted_key(KeyCode::Esc.into(), RestrictedInputMode::Disconnected); + let mut input = chat.capture_thread_input_state().expect("offline draft"); + input.reconnect_pending = true; + + let (mut restored, _events, _ops) = make_chatwidget_manual(/*model_override*/ None).await; + restored.restore_reconnected_input(Some(input), &[]); + assert!(restored.bottom_pane.no_modal_or_popup_active()); + restored.handle_key_event(KeyCode::Enter.into()); + assert!(restored.has_active_view()); +} + #[tokio::test] async fn reconnect_queues_enter_and_resumes_ordinary_next_turn_submission() { let (mut chat, mut events, _operations) = make_chatwidget_manual(/*model_override*/ None).await; diff --git a/codex-rs/tui/src/chatwidget/user_messages.rs b/codex-rs/tui/src/chatwidget/user_messages.rs index 9963b63b0c..b98636ba75 100644 --- a/codex-rs/tui/src/chatwidget/user_messages.rs +++ b/codex-rs/tui/src/chatwidget/user_messages.rs @@ -134,6 +134,7 @@ pub(super) enum QueueDrain { pub(super) struct ThreadComposerState { pub(super) text: String, pub(super) shell_mode: Option, + pub(super) disconnected_command: Option, pub(super) local_images: Vec, pub(super) remote_image_urls: Vec, pub(super) text_elements: Vec, diff --git a/codex-rs/tui/src/keymap/chords.rs b/codex-rs/tui/src/keymap/chords.rs index 2d55a92d64..10b5671a37 100644 --- a/codex-rs/tui/src/keymap/chords.rs +++ b/codex-rs/tui/src/keymap/chords.rs @@ -71,7 +71,7 @@ const COMPOSER_SUBMIT: u64 = 1 << 33; const TRANSCRIPT_BROWSING: u64 = 1 << 14; impl KeymapContextSet { - /// Retain submission while an argument suggestion is open. + /// Retain submission without enabling other composer shortcuts in a popup. pub(crate) const fn with_composer_submit(self) -> Self { Self(self.0 | COMPOSER_SUBMIT) }