Let users retry a failed TUI reconnect with Ctrl+R (#63599)

## Why

When automatic reconnect failed in a remote conversation, users had to
relaunch Codex to try again and copy any unsent draft they wanted to keep.

## What changed

Press `Ctrl+R` in an eligible disconnected conversation to start a fresh
reconnect attempt while keeping the draft editable. In Vim mode, the
shortcut works in Insert mode and leaves Normal mode redo intact.

Show the retry shortcut in the chat footer, direct users back to the
conversation from the agents overview, and show a fresh timer only while
a reconnect attempt is running.

Clear stale MCP startup activity on disconnect while preserving the busy
state of an active turn. Check whether a selected slash command is
available before submitting it from the offline completion menu.

## Testing

Extend coverage for retry after timeout, draft preservation, Vim Normal
mode, reconnect status, and offline slash-command handling. Verify that
disconnect clears stale MCP startup activity while an active turn stays
busy.

GitOrigin-RevId: 0742219e891be89a78418c9b8bbc789cd660cec5
This commit is contained in:
Anton Panasenko
2026-11-24 10:02:49 +00:00
committed by copyberry
parent 37aeac06b3
commit 8e757686c1
14 changed files with 234 additions and 38 deletions
+20 -6
View File
@@ -1116,14 +1116,28 @@ impl App {
.active_view_accepts_input_when_disconnected()
&& let TuiEvent::Key(key) = &event
&& matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat)
&& key.modifiers.contains(KeyModifiers::CONTROL)
&& let KeyCode::Char(character) = key.code
&& (character.eq_ignore_ascii_case(&'c')
|| (character.eq_ignore_ascii_case(&'d')
&& self.chat_widget.composer_is_empty()
&& self.chat_widget.no_modal_or_popup_active()))
{
return Ok(AppRunControl::Exit(ExitReason::UserRequested));
if key.modifiers.contains(KeyModifiers::CONTROL)
&& (character.eq_ignore_ascii_case(&'c')
|| (character.eq_ignore_ascii_case(&'d')
&& self.chat_widget.composer_is_empty()
&& self.chat_widget.no_modal_or_popup_active()))
{
return Ok(AppRunControl::Exit(ExitReason::UserRequested));
}
if crate::key_hint::ctrl(KeyCode::Char('r')).is_press(*key)
&& self.overlay.is_none()
&& self.can_retry_reconnect()
&& !self.key_chord_matcher.is_pending()
&& self.chat_widget.accepts_reconnect_shortcut()
&& !self
.chat_widget
.active_view_is(agents_overview::AGENTS_OVERVIEW_VIEW_ID)
{
self.retry_reconnect();
return Ok(AppRunControl::Continue);
}
}
let screen_size = tui.screen_size_for_event(&event)?;
let draws_history = matches!(
+1 -5
View File
@@ -183,11 +183,7 @@ impl App {
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
state.finish_loading();
state.connection_notice = Some(if self.reconnect.failed {
"Reconnect failed — agent list is stale; relaunch to retry"
} else {
"Reconnecting — agent list is stale"
});
state.connection_notice = Some(self.offline_overview_notice());
}
if app_server.thread_params_mode() == crate::app_server_session::ThreadParamsMode::Cloud {
let owner = app_server.backend_id();
+36 -2
View File
@@ -224,12 +224,46 @@ impl App {
) {
self.begin_reconnect();
self.reconnect.failed = true;
self.chat_widget.reconnect_failed();
self.chat_widget.reconnect_failed(/*can_retry*/ false);
return true;
}
self.begin_reconnect_inner(/*preserve_startup_input*/ true)
}
pub(super) fn offline_overview_notice(&self) -> &'static str {
if self.can_retry_reconnect() {
"Reconnect failed — return to the conversation and press Ctrl+R to retry"
} else if self.reconnect.failed {
"Reconnect failed — agent list is stale; relaunch to retry"
} else {
"Reconnecting — agent list is stale"
}
}
pub(super) fn can_retry_reconnect(&self) -> bool {
self.reconnect.offline
&& self.reconnect.failed
&& !matches!(
self.app_server_target,
AppServerTarget::Embedded | AppServerTarget::Cloud
)
&& !matches!(
self.reconnect.presentation,
ReconnectPresentation::Startup(_)
)
&& self.reconnect_thread_id().is_some()
}
// Let the event loop start a fresh bounded attempt without pausing input again.
pub(super) fn retry_reconnect(&mut self) {
self.reconnect.presentation = ReconnectPresentation::Conversation;
self.reconnect.failed = false;
self.chat_widget.show_reconnecting();
if let Ok(mut state) = self.agents_overview.view_state.lock() {
state.connection_notice = Some(self.offline_overview_notice());
}
}
pub(super) fn reconnect_thread_id(&self) -> Option<ThreadId> {
self.current_displayed_thread_id()
}
@@ -339,7 +373,7 @@ impl App {
|| self.reconnect.presentation == ReconnectPresentation::Overview)
&& let Ok(mut state) = self.agents_overview.view_state.lock()
{
state.connection_notice = Some("Reconnecting — agent list is stale");
state.connection_notice = Some(self.offline_overview_notice());
}
if preserve_startup_input {
// Draining admission never reopens. Wait for this connection to close before
+2 -2
View File
@@ -1902,10 +1902,10 @@ See the Codex keymap documentation for supported actions and examples."
}
}
app.reconnect.failed = true;
app.chat_widget.reconnect_failed();
app.chat_widget.reconnect_failed(app.can_retry_reconnect());
app.chat_widget.add_error_message(error.to_string());
if let Ok(mut state) = app.agents_overview.view_state.lock() {
state.connection_notice = Some("Reconnect failed — agent list is stale; relaunch to retry");
state.connection_notice = Some(app.offline_overview_notice());
}
}
}
@@ -683,8 +683,15 @@ async fn reconnect_exhaustion_and_unknown_initial_thread_stay_offline() -> Resul
.err()
.expect("reconnect should time out");
assert_eq!(start.elapsed().as_secs(), 120);
app.active_thread_id = Some(ThreadId::new());
app.begin_reconnect();
app.chat_widget.reconnect_failed();
app.reconnect.failed = true;
let target = std::mem::replace(&mut app.app_server_target, AppServerTarget::Cloud);
assert!(!app.can_retry_reconnect());
app.app_server_target = target;
app.reconnect.presentation = ReconnectPresentation::Overview;
app.chat_widget.reconnect_failed(app.can_retry_reconnect());
app.reconnect.presentation = ReconnectPresentation::Conversation;
assert_snapshot!(
"reconnect_failed",
format!(
@@ -696,6 +703,38 @@ async fn reconnect_exhaustion_and_unknown_initial_thread_stay_offline() -> Resul
)
);
tokio::time::resume();
let mut session = crate::start_embedded_app_server_for_picker(&app.config).await?;
let mut tui = crate::tui::test_support::make_test_tui()?;
app.chat_widget.toggle_vim_mode_and_notify();
for key in [
KeyCode::Esc.into(),
KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL),
KeyCode::Char('d').into(),
KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL),
] {
app.handle_tui_event(&mut tui, &mut session, TuiEvent::Key(key))
.await?;
}
assert!(app.reconnect.failed, "Vim Normal mode owns redo");
app.chat_widget.toggle_vim_mode_and_notify();
app.handle_tui_event(
&mut tui,
&mut session,
TuiEvent::Key(KeyCode::Char('x').into()),
)
.await?;
for key in [
KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL),
KeyEvent::new(KeyCode::Char('\u{0012}'), KeyModifiers::NONE),
] {
app.reconnect.failed = true;
app.chat_widget.reconnect_failed(app.can_retry_reconnect());
app.handle_tui_event(&mut tui, &mut session, TuiEvent::Key(key))
.await?;
assert!(app.is_offline());
assert!(!app.reconnect.failed, "{key:?} should start a retry");
assert_eq!(app.chat_widget.composer_text_with_pending(), "x");
}
Ok(())
}
@@ -19,7 +19,7 @@ use tokio_tungstenite::tungstenite::Message;
pub(super) fn normalize_reconnect_status(popup: &str) -> String {
let status =
regex_lite::Regex::new(r"(?m)^[•◦] (Reconnecting to server…|Reconnect failed — check the endpoint, then relaunch) \([\dhms ]+\)").unwrap();
regex_lite::Regex::new(r"(?m)^[•◦] (Reconnecting to server…) \([\dhms ]+\)").unwrap();
normalize_snapshot_paths(status.replace(popup, "• ${1} (<elapsed>)").into_owned())
}
@@ -1,12 +1,9 @@
---
source: tui/src/app/tests/active_reconnect_tests.rs
expression: "format!(\"{error}\\n{}\", render_bottom_popup(&app.chat_widget, 80))"
expression: "format!(\"{error}\\n{}\",\nsuper::disconnect::normalize_reconnect_status(&render_bottom_popup(&app.chat_widget,\n80)))"
---
Automatic reconnect timed out while connecting to the server.
• Reconnect failed — check the endpoint, then relaunch (<elapsed>)
› Ask Codex to do anything
GPT-5.6-Sol default · /tmp/project
⌃c quit
⌃r reconnect · ⌃c quit
@@ -68,6 +68,10 @@ impl RestrictedInputMode {
}
impl ChatComposer {
pub(crate) fn accepts_reconnect_shortcut(&self) -> bool {
!self.is_vim_enabled() || self.draft.textarea.uses_vim_insert_cursor()
}
pub(crate) fn set_restricted_input_mode(&mut self, mode: Option<RestrictedInputMode>) {
let was_disconnected =
self.popups.restricted_input_mode == Some(RestrictedInputMode::Disconnected);
@@ -243,6 +247,12 @@ impl ChatComposer {
{
return InputResult::None;
}
if submit
&& let CommandItem::Builtin(command) = selected
&& self.reject_slash_command_if_unavailable(&SlashCommandItem::Builtin(command))
{
return InputResult::None;
}
let popup_key = if submit { KeyCode::Enter.into() } else { key };
let result = self
.handle_key_event_with_slash_popup(
@@ -598,3 +598,49 @@ fn disconnected_edit_invalidates_ordinary_redo() {
composer.handle_key_event(KeyEvent::new(KeyCode::F(7), KeyModifiers::SHIFT));
assert_eq!(composer.current_text(), "b");
}
#[test]
fn disconnected_completion_checks_the_full_command_and_task_state() {
let (mut composer, _) = new_test_composer();
let mode = RestrictedInputMode::Disconnected;
composer.handle_paste("/warnings".into());
composer.handle_restricted_key(KeyCode::Left.into(), mode);
composer.handle_restricted_key(KeyCode::End.into(), mode);
assert_eq!(
composer.handle_restricted_key(KeyCode::Enter.into(), mode),
InputResult::Command(SlashCommand::Warnings)
);
composer.set_task_running(/*running*/ true);
composer.handle_paste("/config".into());
assert_eq!(
composer.handle_restricted_key(KeyCode::Enter.into(), mode),
InputResult::None
);
assert_eq!(composer.current_text(), "/config");
}
#[test]
fn disconnected_mid_token_keeps_arguments_and_dispatches_literal_aliases() {
let (mut composer, _) = new_test_composer();
let mode = RestrictedInputMode::Disconnected;
composer.set_text_content("/rc stop".into(), Vec::new(), Vec::new());
composer.draft.textarea.set_cursor(/*pos*/ 2);
assert_eq!(
composer.handle_restricted_key(KeyCode::Tab.into(), mode),
InputResult::None
);
assert_eq!(composer.current_text(), "/rc stop");
composer.set_text_content("/remote".into(), Vec::new(), Vec::new());
composer.draft.textarea.set_cursor(/*pos*/ 2);
assert_eq!(
composer.handle_restricted_key(KeyCode::Tab.into(), mode),
InputResult::None
);
assert_eq!(composer.current_text(), "/remote");
composer.handle_restricted_key(KeyCode::End.into(), mode);
assert_eq!(
composer.handle_restricted_key(KeyCode::Enter.into(), mode),
InputResult::Command(SlashCommand::Rc)
);
}
+4
View File
@@ -1874,6 +1874,10 @@ impl BottomPane {
self.composer.is_empty()
}
pub(crate) fn accepts_reconnect_shortcut(&self) -> bool {
self.composer.accepts_reconnect_shortcut()
}
pub(crate) fn composer_is_vim_enabled(&self) -> bool {
self.composer.is_vim_enabled()
}
+52 -12
View File
@@ -47,16 +47,48 @@ impl ChatWidget {
self.restore_user_message_to_composer(message);
}
}
// Startup notifications from the disconnected transport can no longer
// finish. Only real turn activity should keep local commands busy.
if self.mcp_startup_status.take().is_some() {
self.update_task_running_state();
}
self.show_reconnecting();
self.statusline_disconnected = true;
self.refresh_status_line();
}
pub(crate) fn accepts_reconnect_shortcut(&self) -> bool {
self.bottom_pane.accepts_reconnect_shortcut()
}
pub(crate) fn show_reconnecting(&mut self) {
self.bottom_pane
.set_status_timer_origin(Some(Instant::now()));
self.bottom_pane.ensure_status_indicator();
self.bottom_pane
.set_interrupt_hint_visible(/*visible*/ false);
self.set_status_header("Reconnecting to server…".to_string());
self.set_footer_hint_override(Some(vec![(
self.set_disconnected_footer(/*can_retry*/ false);
}
fn set_disconnected_footer(&mut self, can_retry: bool) {
let mut hints = Vec::new();
if can_retry {
hints.push((
crate::key_hint::ctrl(KeyCode::Char('r')).display_label(),
if self.composer_is_vim_enabled() {
"reconnect in Insert mode"
} else {
"reconnect"
}
.into(),
));
}
hints.push((
crate::key_hint::ctrl(KeyCode::Char('c')).display_label(),
"quit".into(),
)]));
self.statusline_disconnected = true;
self.refresh_status_line();
));
self.set_footer_hint_override(Some(hints));
}
/// Restore local input only after replay, which can otherwise move interrupted queues into the draft.
@@ -249,14 +281,13 @@ impl ChatWidget {
self.refresh_startup_recovery();
return KeyEventAction::None;
}
let startup_key_handled = self.input_queue.startup_submission.is_some()
let had_startup_submission = self.input_queue.startup_submission.is_some();
let startup_key_handled = had_startup_submission
&& !self.startup_submission_has_protected_input()
&& (key.code == KeyCode::Null || self.handle_startup_submission_key(key));
if mode == RestrictedInputMode::Disconnected {
self.set_footer_hint_override(Some(vec![(
crate::key_hint::ctrl(KeyCode::Char('c')).display_label(),
"quit".into(),
)]));
// Cancelling a confirmed startup prompt clears its footer override.
if mode == RestrictedInputMode::Disconnected && had_startup_submission {
self.set_disconnected_footer(/*can_retry*/ false);
}
if startup_key_handled {
return KeyEventAction::None;
@@ -295,8 +326,17 @@ impl ChatWidget {
KeyEventAction::None
}
pub(crate) fn reconnect_failed(&mut self) {
self.set_status_header("Reconnect failed — check the endpoint, then relaunch".into());
pub(crate) fn reconnect_failed(&mut self, can_retry: bool) {
self.bottom_pane
.set_status_timer_origin(/*started_at*/ None);
self.bottom_pane.hide_status_indicator();
self.set_disconnected_footer(can_retry);
if can_retry {
self.add_error_message(
"Automatic reconnect failed. Check the server and press Ctrl+R to retry. Your draft is still editable. Copy it before quitting with Ctrl+C.".into(),
);
return;
}
self.add_error_message(
"Automatic reconnect could not restore this session. Your draft is still editable. Copy it before quitting with Ctrl+C, then reconnect with the same command.".into(),
);
@@ -2,8 +2,6 @@
source: tui/src/chatwidget/tests/composer_submission.rs
expression: "normalize_snapshot_paths(render_bottom_popup(&chat, 80)).replace('◦', \"•\")"
---
• Reconnect failed — check the endpoint, then relaunch (0s)
• Queued follow-up inputs
↳ x
⇧← edit last queued message
@@ -11,4 +9,4 @@ expression: "normalize_snapshot_paths(render_bottom_popup(&chat, 80)).replace('
› describe
GPT-5.6-Sol default · /tmp/project
⌃c quit
⌃r reconnect · ⌃c quit
@@ -3317,8 +3317,13 @@ fn image_preparation_keeps_input_responsive_and_preserves_pending_input() {
assert_eq!(chat.bottom_pane.composer_text(), "earlier\ndescribe\nx");
chat.on_images_prepared(id);
} else if scenario == "disconnect" {
chat.bottom_pane
.reset_status_timer(std::time::Duration::from_secs(/*secs*/ 3600));
chat.pause_for_disconnect();
chat.reconnect_failed();
let reconnecting = render_bottom_popup(&chat, /*width*/ 80);
assert!(reconnecting.contains("Reconnecting to server…"));
assert!(!reconnecting.contains("1h"));
chat.reconnect_failed(/*can_retry*/ true);
assert_eq!(chat.bottom_pane.composer_text(), "describe");
assert_eq!(
chat.bottom_pane.composer_draft_snapshot().local_images,
@@ -977,3 +977,16 @@ async fn app_server_mcp_startup_next_reported_start_reactivates_progress() {
assert!(summary_text.contains("MCP startup incomplete (failed: runtime)"));
assert!(!chat.bottom_pane.is_task_running());
}
#[tokio::test]
async fn disconnect_drops_stale_mcp_activity_but_keeps_an_active_turn_busy() {
for running in [false, true] {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
notify_mcp_status(&mut chat, "slow", McpServerStartupState::Starting);
if running {
handle_turn_started(&mut chat, "turn-1");
}
chat.pause_for_disconnect();
assert_eq!(chat.bottom_pane.is_task_running(), running);
}
}