From ef9f3d022aff6bd087c640392dc8608743aa411d Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Fri, 18 Sep 2026 23:29:27 +0000 Subject: [PATCH] Allow recovery commands when the current thread is unavailable (#46566) ## Why An unavailable thread blocked slash commands even while the server remained connected, preventing users from starting or resuming a conversation and accessing local commands. ## What changed - Allow explicitly supported recovery and local commands, including `/new`, `/clear`, `/resume`, `/status`, and `/copy`, through configured submit keys when the current thread is unavailable. - Keep other drafts and attachments intact, require commands to occupy a single line, and expand collapsed pastes without dispatching them on the same keypress. Disconnected input remains restricted to editing. - Clear stale review and MCP startup activity and recover prompts awaiting turn start into the retained input queue so recovery commands can proceed. ## Testing Add composer and app tests for command routing, custom submit bindings, blocked draft preservation, paste expansion, and `/new` and `/clear` creating writable sessions despite stale activity. GitOrigin-RevId: 2f5589d615276eb50c69490829dc042bba3f12a9 --- codex-rs/tui/src/app.rs | 12 +- codex-rs/tui/src/app/input.rs | 3 +- codex-rs/tui/src/app/reconnect.rs | 6 +- codex-rs/tui/src/app/tests.rs | 2 + ...nds__unavailable_thread_local_command.snap | 5 + .../app/tests/unavailable_commands_tests.rs | 199 ++++++++++++++++++ codex-rs/tui/src/bottom_pane/chat_composer.rs | 6 +- .../bottom_pane/chat_composer/reconnect.rs | 37 +++- .../chat_composer/reconnect_tests.rs | 133 +++++++++++- .../chat_composer/sparkle_tests.rs | 35 +-- codex-rs/tui/src/bottom_pane/mod.rs | 17 +- codex-rs/tui/src/chatwidget/reconnect.rs | 32 ++- .../chatwidget/tests/composer_submission.rs | 11 +- .../src/chatwidget/tests/questions_tests.rs | 16 +- codex-rs/tui/src/slash_command.rs | 20 ++ 15 files changed, 492 insertions(+), 42 deletions(-) create mode 100644 codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__unavailable_commands__unavailable_thread_local_command.snap create mode 100644 codex-rs/tui/src/app/tests/unavailable_commands_tests.rs diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index cb86b5ccd4..e27f50e93f 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -33,6 +33,7 @@ use crate::bottom_pane::FeedbackAudience; use crate::bottom_pane::McpElicitationApprovalRequest; use crate::bottom_pane::McpServerElicitationFormRequest; use crate::bottom_pane::PermissionsApprovalRequest; +use crate::bottom_pane::RestrictedInputMode; use crate::bottom_pane::SelectionItem; use crate::bottom_pane::SelectionViewParams; use crate::bottom_pane::popup_consts::standard_popup_hint_line; @@ -890,7 +891,8 @@ impl App { if self.reconnect.presentation == reconnect::ReconnectPresentation::Overview { self.chat_widget.handle_disconnected_view_key(*key); } else { - self.chat_widget.handle_disconnected_key(*key); + self.chat_widget + .handle_restricted_key(*key, RestrictedInputMode::Disconnected); } return Ok(AppRunControl::Continue); } @@ -935,10 +937,10 @@ impl App { && self.reconnect.presentation == reconnect::ReconnectPresentation::Conversation { - self.chat_widget.handle_disconnected_key(KeyEvent::new( - KeyCode::Null, - KeyModifiers::NONE, - )); + self.chat_widget.handle_restricted_key( + KeyEvent::new(KeyCode::Null, KeyModifiers::NONE), + RestrictedInputMode::Disconnected, + ); } } TuiEvent::Draw | TuiEvent::Resume | TuiEvent::Resize(_) | TuiEvent::FocusGained => { diff --git a/codex-rs/tui/src/app/input.rs b/codex-rs/tui/src/app/input.rs index 7a6de1e70e..ec3ba30ef4 100644 --- a/codex-rs/tui/src/app/input.rs +++ b/codex-rs/tui/src/app/input.rs @@ -457,7 +457,8 @@ impl App { } if self.should_handle_unavailable_thread_key(key_event) { - self.chat_widget.handle_disconnected_key(key_event); + self.chat_widget + .handle_restricted_key(key_event, RestrictedInputMode::UnavailableThread); return; } diff --git a/codex-rs/tui/src/app/reconnect.rs b/codex-rs/tui/src/app/reconnect.rs index aff846153e..61edae1dc9 100644 --- a/codex-rs/tui/src/app/reconnect.rs +++ b/codex-rs/tui/src/app/reconnect.rs @@ -217,8 +217,10 @@ impl App { } ReconnectPresentation::Overview } else { - self.chat_widget - .handle_disconnected_key(KeyEvent::new(KeyCode::Null, KeyModifiers::NONE)); + self.chat_widget.handle_restricted_key( + KeyEvent::new(KeyCode::Null, KeyModifiers::NONE), + RestrictedInputMode::Disconnected, + ); ReconnectPresentation::Conversation }; self.chat_widget.pause_for_disconnect(); diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 9b8b3892d4..e1b9b516d3 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -48,6 +48,8 @@ mod pagination_completion_tests; mod patch_approval_tests; #[path = "tests/permission_selection_tests.rs"] mod permission_selection_tests; +#[path = "tests/unavailable_commands_tests.rs"] +mod unavailable_commands; #[path = "tests/permission_shortcuts_tests.rs"] mod permission_shortcuts_tests; diff --git a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__unavailable_commands__unavailable_thread_local_command.snap b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__unavailable_commands__unavailable_thread_local_command.snap new file mode 100644 index 0000000000..014aacecb4 --- /dev/null +++ b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__unavailable_commands__unavailable_thread_local_command.snap @@ -0,0 +1,5 @@ +--- +source: tui/src/app/tests/unavailable_commands_tests.rs +expression: "history.replace(&app.config.cwd.display().to_string(), \"/project\")" +--- +• Current working directory: /project diff --git a/codex-rs/tui/src/app/tests/unavailable_commands_tests.rs b/codex-rs/tui/src/app/tests/unavailable_commands_tests.rs new file mode 100644 index 0000000000..79d23085ff --- /dev/null +++ b/codex-rs/tui/src/app/tests/unavailable_commands_tests.rs @@ -0,0 +1,199 @@ +//! Recovery commands remain usable when only the current conversation is unavailable. + +use super::active_reconnect::drain_history; +use super::*; +use pretty_assertions::assert_eq; + +#[tokio::test] +async fn unavailable_thread_routes_local_and_recovery_commands() -> Result<()> { + let (mut app, mut events, mut ops) = make_test_app_with_channels().await; + let id = ThreadId::new(); + app.active_thread_id = Some(id); + app.primary_thread_id = Some(id); + app.app_server_target = AppServerTarget::Remote { + endpoint: crate::resolve_remote_addr("ws://127.0.0.1:1")?, + }; + app.chat_widget + .handle_thread_session(test_thread_session(id, app.config.cwd.to_path_buf())); + app.ensure_thread_channel(id).mark_replay_only(); + app.chat_widget + .restore_user_message_to_composer("pending input".into()); + app.chat_widget.handle_key_event(KeyCode::Enter.into()); + app.chat_widget + .restore_user_message_to_composer("keep queued input".into()); + app.chat_widget.handle_key_event(KeyCode::Tab.into()); + assert_eq!( + app.chat_widget.queued_user_message_texts(), + vec!["keep queued input"] + ); + app.chat_widget.pause_unavailable_thread(); + assert_eq!( + app.chat_widget.queued_user_message_texts(), + vec!["pending input", "keep queued input"] + ); + app.chat_widget + .set_local_worktree_operations(/*enabled*/ false); + let mut session = start_config_write_test_app_server(&app).await?; + let mut tui = crate::tui::test_support::make_test_tui()?; + while events.try_recv().is_ok() {} + while ops.try_recv().is_ok() {} + + for command in [ + "/new", + "/clear recovery", + "/resume", + "/agents", + "/subagents", + "/raw on", + "/quit", + "/exit", + ] { + app.chat_widget + .restore_user_message_to_composer(command.into()); + app.handle_tui_event(&mut tui, &mut session, TuiEvent::Key(KeyCode::Enter.into())) + .await?; + let mut dispatched = false; + while let Ok(event) = events.try_recv() { + dispatched |= matches!((command, &event), + ("/clear recovery", AppEvent::ClearUi { name: Some(name) }) if name == "recovery" + ); + dispatched |= matches!( + (command, &event), + ("/new", AppEvent::NewSession { name: None }) + | ("/resume", AppEvent::OpenResumePicker) + | ("/agents", AppEvent::OpenAgentsOverview) + | ("/subagents", AppEvent::OpenAgentPicker) + | ("/raw on", AppEvent::RawOutputModeChanged { enabled: true }) + | ("/quit" | "/exit", AppEvent::Exit(_)) + ); + } + assert!(dispatched, "{command}"); + assert!(ops.try_recv().is_err(), "{command}"); + } + + app.chat_widget + .restore_user_message_to_composer("/pwd".into()); + app.handle_tui_event(&mut tui, &mut session, TuiEvent::Key(KeyCode::Enter.into())) + .await?; + let history = drain_history(&mut app, &mut tui, &mut session, &mut events).await?; + assert!(history.contains("Current working directory:")); + assert_snapshot!( + "unavailable_thread_local_command", + history.replace(&app.config.cwd.display().to_string(), "/project") + ); + + app.chat_widget + .restore_user_message_to_composer("/status".into()); + app.handle_tui_event(&mut tui, &mut session, TuiEvent::Key(KeyCode::Enter.into())) + .await?; + let history = drain_history(&mut app, &mut tui, &mut session, &mut events).await?; + assert!(history.contains("Model:"), "{history}"); + assert!(app.chat_widget.composer_is_empty()); + assert!(ops.try_recv().is_err()); + + let input = app.chat_widget.capture_thread_input_state(); + app.chat_widget + .restore_user_message_to_composer("/copy".into()); + app.handle_tui_event(&mut tui, &mut session, TuiEvent::Key(KeyCode::Enter.into())) + .await?; + app.handle_tui_event(&mut tui, &mut session, TuiEvent::Key(KeyCode::Esc.into())) + .await?; + while let Ok(event) = events.try_recv() { + assert!(!matches!(event, AppEvent::CodexOp(_))); + app.handle_event(&mut tui, &mut session, event).await?; + } + assert_eq!(app.chat_widget.capture_thread_input_state(), input); + assert!(ops.try_recv().is_err()); + + for offline in [false, true] { + app.reconnect.offline = offline; + for draft in if offline { + vec!["/new", "/clear", "/status"] + } else { + vec!["keep my draft", "/review", "/rename changed"] + } { + app.handle_tui_event( + &mut tui, + &mut session, + TuiEvent::Key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL)), + ) + .await?; + app.chat_widget + .restore_user_message_to_composer(draft.into()); + app.handle_tui_event(&mut tui, &mut session, TuiEvent::Key(KeyCode::Enter.into())) + .await?; + assert_eq!(app.chat_widget.composer_text_with_pending(), draft); + assert!(events.try_recv().is_err()); + assert!(ops.try_recv().is_err()); + } + } + session.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn unavailable_thread_new_and_clear_start_a_writable_session() -> Result<()> { + for (command, activity) in ["/new", "/clear"] + .into_iter() + .flat_map(|command| ["idle", "review", "mcp"].map(|activity| (command, activity))) + { + let (mut app, mut events, _) = make_test_app_with_channels().await; + let id = ThreadId::new(); + app.active_thread_id = Some(id); + app.primary_thread_id = Some(id); + app.app_server_target = AppServerTarget::Remote { + endpoint: crate::resolve_remote_addr("ws://127.0.0.1:1")?, + }; + app.chat_widget + .handle_thread_session(test_thread_session(id, app.config.cwd.to_path_buf())); + app.ensure_thread_channel(id).mark_replay_only(); + match activity { + "review" => app.chat_widget.replay_thread_turns( + vec![test_turn( + "review", + TurnStatus::InProgress, + vec![ThreadItem::EnteredReviewMode { + id: "review-start".into(), + review: "changes against main".into(), + }], + )], + ReplayKind::ResumeInitialMessages, + ), + "mcp" => app.chat_widget.handle_server_notification( + ServerNotification::McpServerStatusUpdated(McpServerStatusUpdatedNotification { + thread_id: Some(id.to_string()), + name: "slow".into(), + status: McpServerStartupState::Starting, + error: None, + failure_reason: None, + }), + /*replay_kind*/ None, + ), + _ => {} + } + app.chat_widget.pause_unavailable_thread(); + app.chat_widget + .set_local_worktree_operations(/*enabled*/ false); + let mut session = start_config_write_test_app_server(&app).await?; + let mut tui = crate::tui::test_support::make_test_tui()?; + while events.try_recv().is_ok() {} + app.chat_widget + .restore_user_message_to_composer(command.into()); + app.handle_tui_event(&mut tui, &mut session, TuiEvent::Key(KeyCode::Enter.into())) + .await?; + while let Ok(event) = events.try_recv() { + if matches!( + event, + AppEvent::NewSession { .. } | AppEvent::ClearUi { .. } + ) { + app.handle_event(&mut tui, &mut session, event).await?; + break; + } + } + let new_id = app.chat_widget.thread_id().expect("new thread"); + assert_ne!(new_id, id, "{command}"); + assert!(!app.thread_unavailable(new_id), "{command}"); + session.shutdown().await?; + } + Ok(()) +} diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index b25d7ac023..b219ad2892 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -122,9 +122,10 @@ //! navigation slash commands remain available so users can leave or manage the view. Transcript //! exports also remain available, including an explicit destination filename. //! -//! During reconnection, `handle_disconnected_key` edits the draft directly without popup dispatch, +//! During reconnection, `handle_restricted_key` edits the draft directly without popup dispatch, //! composer shortcuts, or submission; `?` becomes literal input. Enter and Tab leave the draft -//! intact until reconnection succeeds. +//! intact until reconnection succeeds. When connected but the thread is unavailable, configured +//! submit keys may dispatch explicitly allowed recovery and local commands; other drafts stay put. //! Collapsed pastes expand into editable text so the full draft can be copied before quitting. //! //! # Reasoning Effort Animations @@ -351,6 +352,7 @@ mod inline_input; mod paste_input; mod popup_state; mod reconnect; +pub(crate) use reconnect::RestrictedInputMode; mod slash_input; mod sparkle; mod vim_history; 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 aea6d84580..4f5102bf1c 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/reconnect.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/reconnect.rs @@ -1,9 +1,16 @@ -//! Offline editing retains the draft in place. +//! Restricted editing retains drafts; unavailable threads also allow recovery and local commands. //! Paste Enter handling is shared with normal submission so buffered newlines survive both paths. +//! Recovery commands must occupy one line and be visible before the submit key expands pastes. //! Offline draft edits also consume the Astra sparkle opportunity before rendering. use super::*; +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum RestrictedInputMode { + Disconnected, + UnavailableThread, +} + impl ChatComposer { /// Preserve Enter inside a paste burst without attempting submission. pub(crate) fn handle_paste_enter(&mut self, now: Instant) -> bool { @@ -43,7 +50,11 @@ impl ChatComposer { false } - pub(crate) fn handle_disconnected_key(&mut self, key: KeyEvent) { + pub(crate) fn handle_restricted_key( + &mut self, + key: KeyEvent, + mode: RestrictedInputMode, + ) -> InputResult { self.cancel_history_search(); self.attachments.clear_remote_image_selection(); self.popups.active = ActivePopup::None; @@ -62,6 +73,27 @@ impl ChatComposer { } } } + if mode == RestrictedInputMode::UnavailableThread + && pending_pastes.is_empty() + && matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) + && self.submit_keys.is_pressed(key) + { + let input = self.slash_input(); + let text = self.draft.textarea.text(); + let command = input + .bare_command(text) + .or_else(|| input.inline_command(text).map(|command| command.command)) + .filter(|_| text.trim().lines().count() == 1); + if matches!(command, Some(SlashCommandItem::Builtin(command)) + if command.available_when_thread_unavailable()) + { + return self + .try_dispatch_bare_slash_command() + .or_else(|| self.try_dispatch_slash_command_with_args()) + .unwrap_or(InputResult::None); + } + } + // Enter/Tab and configured submit bindings must never consume the draft offline. // The basic editor reconciles attachments without invoking composer-level shortcuts. if !matches!(key.code, KeyCode::Enter | KeyCode::Tab) @@ -76,6 +108,7 @@ impl ChatComposer { let (result, _) = self.handle_input_basic(key); self.after_sparkle_key(before, &result); } + InputResult::None } } 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 36fb5a4e70..c1f58a8b54 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 @@ -13,7 +13,10 @@ fn reconnect_expands_pastes_preserving_images_and_cursor() { composer.handle_paste(paste); let expanded = composer.current_text_with_pending(); let images = composer.draft_snapshot().local_images; - composer.handle_disconnected_key(KeyEvent::new(KeyCode::Char('!'), KeyModifiers::NONE)); + composer.handle_restricted_key( + KeyEvent::new(KeyCode::Char('!'), KeyModifiers::NONE), + RestrictedInputMode::Disconnected, + ); let draft = composer.draft_snapshot(); assert_eq!( ( @@ -37,7 +40,10 @@ fn reconnect_edit_removes_deleted_attachment_and_paste_metadata() { let (mut composer, _) = new_test_composer(); composer.attach_image(PathBuf::from("local.png")); composer.handle_paste("x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 1)); - composer.handle_disconnected_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL)); + composer.handle_restricted_key( + KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL), + RestrictedInputMode::Disconnected, + ); let draft = composer.draft_snapshot(); assert_eq!( (draft.text, draft.local_images, draft.pending_pastes), @@ -54,7 +60,128 @@ fn reconnect_edit_cancels_history_preview_without_losing_original_draft() { composer.apply_history_search_result(HistorySearchResult::Found(HistoryEntry::new( "history preview".into(), ))); - composer.handle_disconnected_key(KeyEvent::new(KeyCode::Char('!'), KeyModifiers::NONE)); + composer.handle_restricted_key( + KeyEvent::new(KeyCode::Char('!'), KeyModifiers::NONE), + RestrictedInputMode::Disconnected, + ); assert_eq!(composer.current_text(), "original draft!"); assert!(!composer.history_search_active()); } + +#[test] +fn unavailable_thread_dispatches_recovery_and_local_commands() { + for command in [ + SlashCommand::New, + SlashCommand::Clear, + SlashCommand::Resume, + SlashCommand::Agents, + SlashCommand::MultiAgents, + SlashCommand::Quit, + SlashCommand::Exit, + SlashCommand::Status, + SlashCommand::DebugConfig, + SlashCommand::Pwd, + SlashCommand::Rollout, + SlashCommand::Copy, + SlashCommand::Raw, + ] { + let (mut composer, _) = new_test_composer(); + composer.set_text_content(format!("/{}", command.command()), Vec::new(), Vec::new()); + assert_eq!( + composer.handle_restricted_key( + KeyEvent::from(KeyCode::Enter), + RestrictedInputMode::UnavailableThread, + ), + InputResult::Command(command), + ); + assert_eq!(composer.current_text(), ""); + } +} + +#[test] +fn unavailable_thread_dispatches_inline_commands_with_configured_submit_key() { + for (text, command, args) in [ + ("/new recovery", SlashCommand::New, "recovery"), + ("/clear recovery", SlashCommand::Clear, "recovery"), + ("/resume saved", SlashCommand::Resume, "saved"), + ("/raw on", SlashCommand::Raw, "on"), + ] { + let (mut composer, _) = new_test_composer(); + let key = KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL); + composer.submit_keys = vec![key_hint::ctrl(KeyCode::Char('s'))]; + composer.set_text_content(text.into(), Vec::new(), Vec::new()); + assert_eq!( + composer.handle_restricted_key( + KeyEvent::from(KeyCode::Enter), + RestrictedInputMode::UnavailableThread + ), + InputResult::None, + ); + assert_eq!(composer.current_text(), text); + assert_eq!( + composer.handle_restricted_key(key, RestrictedInputMode::UnavailableThread), + InputResult::CommandWithArgs(command, args.into(), Vec::new()), + ); + } +} + +#[test] +fn restricted_input_preserves_blocked_drafts_and_attachments() { + for mode in [ + RestrictedInputMode::Disconnected, + RestrictedInputMode::UnavailableThread, + ] { + for text in [ + "keep my draft", + "!echo hello", + "/review", + "/rename changed", + "/compact", + "/voice", + "/unknown", + "/status extra", + "/status\nkeep my draft", + "/clear recovery\nkeep my draft", + "/new recovery\nkeep my draft", + "/resume saved\nkeep my draft", + ] { + let (mut composer, _) = new_test_composer(); + composer.set_text_content(text.into(), Vec::new(), Vec::new()); + composer.attach_image(PathBuf::from("local.png")); + let before = composer.draft_snapshot(); + for key in [KeyCode::Enter, KeyCode::Tab] { + assert_eq!( + composer.handle_restricted_key(key.into(), mode), + InputResult::None + ); + assert_eq!(composer.draft_snapshot(), before); + } + } + } + for text in ["/status", "/new", "/clear", "/raw on"] { + let (mut composer, _) = new_test_composer(); + composer.set_text_content(text.into(), Vec::new(), Vec::new()); + assert_eq!( + composer + .handle_restricted_key(KeyCode::Enter.into(), RestrictedInputMode::Disconnected), + InputResult::None + ); + assert_eq!(composer.current_text(), text); + } +} + +#[test] +fn unavailable_thread_expands_pasted_commands_without_dispatching() { + let (mut composer, _) = new_test_composer(); + let text = format!("/clear {}", "x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 1)); + composer.handle_paste(text.clone()); + assert_ne!(composer.current_text(), text); + assert_eq!( + composer.handle_restricted_key( + KeyCode::Enter.into(), + RestrictedInputMode::UnavailableThread, + ), + InputResult::None + ); + assert_eq!(composer.current_text(), text); +} 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.rs index 9ba12a09d8..318de06df6 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 @@ -3,6 +3,7 @@ use super::*; use crate::app_event_sender::AppEventSender; use crate::bottom_pane::BottomPaneParams; +use crate::bottom_pane::RestrictedInputMode; use crate::bottom_pane::chat_composer_history::HistoryEntry; use crate::render::renderable::Renderable; use crate::slash_command::SlashCommand; @@ -470,31 +471,37 @@ fn disconnected_sparkle_edits_are_tracked_between_renders() { let initial = draw(&pane.composer, /*width*/ 80, now).0; assert_eq!(dots(&initial).is_empty(), model == "gpt-5.5"); for key in [KeyCode::Null, KeyCode::Enter, KeyCode::Tab] { - pane.handle_disconnected_key(KeyEvent::new(key, KeyModifiers::NONE)); + pane.handle_restricted_key( + KeyEvent::new(key, KeyModifiers::NONE), + RestrictedInputMode::Disconnected, + ); } - pane.handle_disconnected_key(KeyEvent::new_with_kind( - KeyCode::Char('x'), - KeyModifiers::NONE, - crossterm::event::KeyEventKind::Release, - )); + pane.handle_restricted_key( + KeyEvent::new_with_kind( + KeyCode::Char('x'), + KeyModifiers::NONE, + crossterm::event::KeyEventKind::Release, + ), + RestrictedInputMode::Disconnected, + ); assert_eq!(pane.composer.sparkle.draft.get(), SparkleDraft::Untouched); assert_eq!( dots(&draw(&pane.composer, /*width*/ 80, now).0), dots(&initial) ); for ch in input.chars() { - pane.handle_disconnected_key(KeyEvent::new( - KeyCode::Char(ch), - KeyModifiers::NONE, - )); + pane.handle_restricted_key( + KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE), + RestrictedInputMode::Disconnected, + ); } assert_eq!(pane.composer.current_text(), input, "{scenario}"); assert_eq!(pane.composer.sparkle.draft.get(), draft, "{scenario}"); for _ in input.chars() { - pane.handle_disconnected_key(KeyEvent::new( - KeyCode::Backspace, - KeyModifiers::NONE, - )); + pane.handle_restricted_key( + KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE), + RestrictedInputMode::Disconnected, + ); } assert_eq!(pane.composer.current_text(), ""); pane.select_sparkle_model("gpt-6-astra", &enabled()); diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 3aedb4fc50..689ccfef21 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -221,6 +221,7 @@ pub(crate) use chat_composer::ChatComposerConfig; pub(crate) use chat_composer::ComposerDraftSnapshot; pub(crate) use chat_composer::InputResult; pub(crate) use chat_composer::QueuedInputAction; +pub(crate) use chat_composer::RestrictedInputMode; pub(crate) use chat_composer_history::HistoryEntry; pub(crate) use textarea::KillBufferSnapshot; @@ -727,14 +728,19 @@ impl BottomPane { self.push_view(Box::new(modal)); } - /// Edit the draft without invoking popups, submissions, or remote actions. - pub(crate) fn handle_disconnected_key(&mut self, key: KeyEvent) { + /// Preserve restricted drafts, allowing recovery commands only for connected unavailable threads. + pub(crate) fn handle_restricted_key( + &mut self, + key: KeyEvent, + mode: RestrictedInputMode, + ) -> InputResult { self.view_stack.clear(); self.delayed_approval_requests.clear(); self.composer .set_input_enabled(/*enabled*/ true, /*placeholder*/ None); - self.composer.handle_disconnected_key(key); + let result = self.composer.handle_restricted_key(key, mode); self.request_redraw(); + result } /// Forward a key event to the active view or the composer. @@ -2632,7 +2638,10 @@ mod tests { assert_eq!(pane.composer_text(), "ya"); assert!(pane.view_stack.is_empty()); assert_eq!(pane.delayed_approval_requests.len(), 1); - pane.handle_disconnected_key(KeyEvent::new(KeyCode::Null, KeyModifiers::NONE)); + pane.handle_restricted_key( + KeyEvent::new(KeyCode::Null, KeyModifiers::NONE), + RestrictedInputMode::Disconnected, + ); pane.pre_draw_tick_at(Instant::now() + APPROVAL_PROMPT_TYPING_IDLE_DELAY); pane.handle_paste(" kept".into()); assert_eq!(pane.composer_text(), "ya kept"); diff --git a/codex-rs/tui/src/chatwidget/reconnect.rs b/codex-rs/tui/src/chatwidget/reconnect.rs index f6e954fbc3..4eb80b181b 100644 --- a/codex-rs/tui/src/chatwidget/reconnect.rs +++ b/codex-rs/tui/src/chatwidget/reconnect.rs @@ -1,7 +1,9 @@ //! Disconnects preserve editable input but never automatically retry queued submissions. +//! Unavailable threads retain uncertain prompts in recovered queues before clearing activity. use super::realtime::RealtimeConversationPhase; use super::*; +use crate::bottom_pane::RestrictedInputMode; impl ChatWidget { pub(crate) fn pause_for_disconnect(&mut self) { @@ -74,14 +76,33 @@ impl ChatWidget { } self.turn_lifecycle .restore_running(/*running*/ false, Instant::now()); + // Cached activity must not keep recovery commands blocked on an unavailable thread. + self.review.is_review_mode = false; + self.mcp_startup_status = None; + if self.input_queue.user_turn_pending_start + && let Some(prompt) = self.safety_buffering_prompt.take() + { + self.input_queue + .queued_user_messages + .push_front(QueuedUserMessage { + source: self.safety_buffering_source, + ..QueuedUserMessage::from(prompt) + }); + self.input_queue + .queued_user_message_history_records + .push_front(UserMessageHistoryRecord::UserMessageText); + } + self.input_queue.user_turn_pending_start = false; + self.input_queue.recovered_queue = true; self.update_task_running_state(); + self.refresh_pending_input_preview(); } pub(crate) fn handle_disconnected_view_key(&mut self, key: KeyEvent) { self.bottom_pane.handle_key_event(key); } - pub(crate) fn handle_disconnected_key(&mut self, key: KeyEvent) { + pub(crate) fn handle_restricted_key(&mut self, key: KeyEvent, mode: RestrictedInputMode) { if self.external_writer_view { return; } @@ -98,12 +119,15 @@ impl ChatWidget { )); self.input_queue.recovered_queue &= !self.input_queue.pending_steers.is_empty(); } - self.bottom_pane - .handle_disconnected_key(KeyEvent::new(KeyCode::Null, KeyModifiers::NONE)); + self.bottom_pane.handle_restricted_key( + KeyEvent::new(KeyCode::Null, KeyModifiers::NONE), + RestrictedInputMode::Disconnected, + ); self.refresh_pending_input_preview(); self.request_redraw(); } else { - self.bottom_pane.handle_disconnected_key(key); + let result = self.bottom_pane.handle_restricted_key(key, mode); + self.handle_composer_input_result(result, /*had_modal_or_popup*/ false); } } diff --git a/codex-rs/tui/src/chatwidget/tests/composer_submission.rs b/codex-rs/tui/src/chatwidget/tests/composer_submission.rs index facb10b58a..98b85d010b 100644 --- a/codex-rs/tui/src/chatwidget/tests/composer_submission.rs +++ b/codex-rs/tui/src/chatwidget/tests/composer_submission.rs @@ -1,5 +1,6 @@ use super::*; use crate::app_event::ConnectorsSnapshot; +use crate::bottom_pane::RestrictedInputMode; use crate::history_cell::ThreadRecapLoadingCell; use base64::Engine; use codex_app_server_protocol::ImageReference; @@ -1824,11 +1825,17 @@ async fn restore_thread_input_state_applies_running_state_policy() { ); chat.pause_for_disconnect(); - chat.handle_disconnected_key(KeyEvent::new(KeyCode::Up, KeyModifiers::ALT)); + chat.handle_restricted_key( + KeyEvent::new(KeyCode::Up, KeyModifiers::ALT), + RestrictedInputMode::Disconnected, + ); assert!(!chat.has_queued_follow_up_messages()); // Editing the last queued draft must not release the uncertain steer for replay. assert!(chat.capture_thread_input_state().unwrap().recovered_queue); - chat.handle_disconnected_key(KeyEvent::new(KeyCode::Up, KeyModifiers::ALT)); + chat.handle_restricted_key( + KeyEvent::new(KeyCode::Up, KeyModifiers::ALT), + RestrictedInputMode::Disconnected, + ); assert_eq!( chat.composer_text_with_pending(), "submitted history\nqueued history" diff --git a/codex-rs/tui/src/chatwidget/tests/questions_tests.rs b/codex-rs/tui/src/chatwidget/tests/questions_tests.rs index 2db8a938da..fcb5a6cbb0 100644 --- a/codex-rs/tui/src/chatwidget/tests/questions_tests.rs +++ b/codex-rs/tui/src/chatwidget/tests/questions_tests.rs @@ -1,5 +1,6 @@ //! Verify question input delivery, retained drafts, and visible editor behavior. use super::*; +use crate::bottom_pane::RestrictedInputMode; use codex_protocol::items::AsyncUserInputQuestion; use pretty_assertions::assert_eq; @@ -398,12 +399,21 @@ async fn disconnected_questions_remain_editable_without_sending() { let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await; chat.add_async_questions("message", &questions()); chat.pause_for_disconnect(); - chat.handle_disconnected_key(KeyEvent::new(KeyCode::Up, KeyModifiers::ALT)); + chat.handle_restricted_key( + KeyEvent::new(KeyCode::Up, KeyModifiers::ALT), + RestrictedInputMode::Disconnected, + ); chat.bottom_pane.handle_paste("offline draft".into()); - chat.handle_disconnected_key(KeyEvent::from(KeyCode::Enter)); + chat.handle_restricted_key( + KeyEvent::from(KeyCode::Enter), + RestrictedInputMode::Disconnected, + ); assert_eq!(question_count(&chat), 2); assert!(op_rx.try_recv().is_err()); - chat.handle_disconnected_key(KeyEvent::new(KeyCode::Char(']'), KeyModifiers::CONTROL)); + chat.handle_restricted_key( + KeyEvent::new(KeyCode::Char(']'), KeyModifiers::CONTROL), + RestrictedInputMode::Disconnected, + ); assert_eq!(question_count(&chat), 2); } diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index c15edac558..a6fec3c17e 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -209,6 +209,26 @@ impl SlashCommand { matches!(self, SlashCommand::Review) } + /// Commands that do not require a writable current thread. The server must still be connected. + pub(crate) fn available_when_thread_unavailable(self) -> bool { + matches!( + self, + SlashCommand::New + | SlashCommand::Clear + | SlashCommand::Resume + | SlashCommand::Agents + | SlashCommand::MultiAgents + | SlashCommand::Quit + | SlashCommand::Exit + | SlashCommand::Status + | SlashCommand::DebugConfig + | SlashCommand::Pwd + | SlashCommand::Rollout + | SlashCommand::Copy + | SlashCommand::Raw + ) + } + /// Whether this command can be run while a task is in progress. pub fn available_during_task(self) -> bool { match self {