feat(tui): restore output-free cancelled prompts (#25316)

## TL;DR

When you press Esc or Ctrl+C after sending a prompt but before any
output was rendering, it restores the last composer and the message.

## Summary

Cancelling a prompt immediately after submission should behave like
returning to edit that prompt, not like discarding the user's draft.
Today, pressing `Esc` or `Ctrl+C` before Codex responds leaves the
submitted prompt in the transcript and returns an empty composer,
forcing the user to recall or retype it.

When an interrupted turn has not produced substantive visible output,
restore its submitted prompt directly into the composer and roll back
that latest turn. This also covers the first prompt in a fresh thread,
before the TUI has retained a local user-history cell. The restored
draft keeps its text, image attachments, and active collaboration mode
so it can be edited and resubmitted in place.

Restoration is intentionally suppressed once the turn has produced
user-visible activity such as assistant output, tool work, hooks, or
patches. A transient thinking status does not make the prompt
ineligible. Rollback also rebuilds terminal scrollback from the retained
transcript cells so repeated cancellations and terminal resizes do not
duplicate history.

## How to Test

1. Start the TUI with `cargo run -p codex-cli --bin codex`.
2. In a fresh thread, submit the first prompt and press `Esc` before
Codex emits substantive output. Confirm that the prompt returns to the
composer for editing and its submitted transcript row is removed.
3. Repeat with `Ctrl+C`, then repeat after at least one completed turn.
Confirm the same behavior.
4. Submit a prompt, wait for assistant output or tool activity, then
cancel. Confirm that the transcript remains intact and the prompt is not
restored into the composer.
5. Cancel several output-free prompts and resize the terminal between
attempts. Confirm that the startup banner, tip, and transcript history
do not duplicate in scrollback.

Targeted tests:
- `just test -p codex-tui cancelled_turn_edit_restores_prompt`
- `just test -p codex-tui
output_free_interrupted_turn_requests_prompt_restore`
- `just test -p codex-tui
visible_output_prevents_cancelled_turn_prompt_restore`
- `just test -p codex-tui
thinking_status_keeps_cancelled_turn_prompt_restore_eligible`
- `just test -p codex-tui
patch_activity_prevents_cancelled_turn_prompt_restore`

The full `just test -p codex-tui` run completed with `2746` passing
tests and two unrelated existing guardian feature-flag failures. `just
argument-comment-lint` remains blocked locally by the existing Bazel
LLVM `compiler-rt` sanitizer-header glob failure; the touched Rust diff
was manually audited for positional literal comments.
This commit is contained in:
Felipe Coury authored and GitHub committed 2026-06-01 11:49:14 -03:00
1 parent 4eded02f52
commit c0ea566bb5
28 files changed
+329 -46

No files matched your search

@@ -240,6 +240,7 @@ impl ChatWidget {
}
pub(crate) fn handle_command_execution_started_now(&mut self, item: ThreadItem) {
self.record_visible_turn_activity();
let ThreadItem::CommandExecution {
id,
command,
@@ -182,6 +182,7 @@ impl ChatWidget {
forked_from: None,
interrupted_turn_notice_mode: InterruptedTurnNoticeMode::Default,
input_queue: InputQueueState::default(),
cancel_edit: CancelEditState::default(),
chat_keymap,
queued_message_edit_hint_binding,
show_welcome_banner: is_first_run,
@@ -7,6 +7,7 @@ use super::*;
impl ChatWidget {
pub(super) fn on_hook_started(&mut self, run: codex_app_server_protocol::HookRunSummary) {
self.record_visible_turn_activity();
self.flush_answer_stream_with_separator();
self.flush_completed_hook_output();
match self.active_hook_cell.as_mut() {
+40 -1
View File
@@ -3,6 +3,38 @@
use super::*;
impl ChatWidget {
pub(super) fn record_cancel_edit_candidate(&mut self, prompt: UserMessage) {
self.cancel_edit.prompt = Some(prompt);
self.cancel_edit.eligible = true;
self.cancel_edit.armed = false;
}
pub(super) fn record_visible_turn_activity(&mut self) {
self.cancel_edit.eligible = false;
self.cancel_edit.armed = false;
}
pub(super) fn arm_cancel_edit(&mut self) {
self.cancel_edit.armed = self.cancel_edit.eligible
&& self.cancel_edit.prompt.is_some()
&& self.bottom_pane.composer_is_empty()
&& self.input_queue.pending_steers.is_empty()
&& !self.has_queued_follow_up_messages()
&& !self.active_side_conversation;
}
fn take_armed_cancel_edit_prompt(&mut self, reason: TurnAbortReason) -> Option<UserMessage> {
(reason == TurnAbortReason::Interrupted
&& self.cancel_edit.armed
&& self.cancel_edit.eligible)
.then(|| self.cancel_edit.prompt.take())
.flatten()
}
pub(super) fn clear_cancel_edit(&mut self) {
self.cancel_edit = CancelEditState::default();
}
pub(crate) fn set_initial_user_message_submit_suppressed(&mut self, suppressed: bool) {
self.suppress_initial_user_message_submit = suppressed;
}
@@ -104,12 +136,15 @@ impl ChatWidget {
/// When there are queued user messages, restore them into the composer
/// separated by newlines rather than auto-submitting the next one.
pub(super) fn on_interrupted_turn(&mut self, reason: TurnAbortReason) {
let cancelled_prompt = self.take_armed_cancel_edit_prompt(reason);
// Finalize, log a gentle prompt, and clear running state.
self.finalize_turn();
let send_pending_steers_immediately =
self.input_queue.submit_pending_steers_after_interrupt;
self.input_queue.submit_pending_steers_after_interrupt = false;
if self.interrupted_turn_notice_mode != InterruptedTurnNoticeMode::Suppress {
if cancelled_prompt.is_none()
&& self.interrupted_turn_notice_mode != InterruptedTurnNoticeMode::Suppress
{
if send_pending_steers_immediately {
self.add_to_history(history_cell::new_info_event(
"Model interrupted to submit steer instructions.".to_owned(),
@@ -143,6 +178,10 @@ impl ChatWidget {
self.restore_user_message_to_composer(combined);
}
self.refresh_pending_input_preview();
if let Some(prompt) = cancelled_prompt {
self.app_event_tx
.send(AppEvent::RestoreCancelledTurn(prompt));
}
self.request_redraw();
}
@@ -389,6 +389,16 @@ impl ChatWidget {
self.refresh_pending_input_preview();
}
if render_in_history {
self.record_cancel_edit_candidate(UserMessage {
text: text.clone(),
local_images: local_images.clone(),
remote_image_urls: remote_image_urls.clone(),
text_elements: text_elements.clone(),
mention_bindings: mention_bindings.clone(),
});
}
// Show replayable user content in conversation history.
let display_user_message = render_in_history.then(|| {
user_message_display_for_history(
+2 -2
View File
@@ -375,7 +375,7 @@ impl ChatWidget {
self.quit_shortcut_key = None;
self.bottom_pane.clear_quit_shortcut_hint();
self.pause_active_goal_for_interrupt();
self.submit_op(AppCommand::interrupt());
self.submit_op(AppCommand::interrupt_and_restore_prompt_if_no_output());
} else {
self.request_quit_without_confirmation();
}
@@ -393,7 +393,7 @@ impl ChatWidget {
if self.is_cancellable_work_active() {
self.pause_active_goal_for_interrupt();
self.submit_op(AppCommand::interrupt());
self.submit_op(AppCommand::interrupt_and_restore_prompt_if_no_output());
}
}
+6
View File
@@ -111,6 +111,9 @@ impl ChatWidget {
if self.active_mode_kind() != ModeKind::Plan {
return;
}
if !delta.is_empty() {
self.record_visible_turn_activity();
}
if !self.transcript.plan_item_active {
self.transcript.plan_item_active = true;
self.transcript.plan_delta_buffer.clear();
@@ -370,6 +373,9 @@ impl ChatWidget {
#[inline]
pub(super) fn handle_streaming_delta(&mut self, delta: String) {
if !delta.is_empty() {
self.record_visible_turn_activity();
}
if self.stream_controller.is_none() {
// Before starting an agent stream, flush any active exec cell group.
self.flush_unified_exec_wait_streak();
@@ -7,6 +7,7 @@ use codex_protocol::permissions::FileSystemSandboxEntry;
use codex_protocol::permissions::FileSystemSpecialPath;
use codex_protocol::permissions::NetworkSandboxPolicy;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use std::collections::VecDeque;
#[tokio::test]
@@ -926,6 +927,69 @@ async fn empty_enter_during_task_does_not_queue() {
assert!(chat.input_queue.queued_user_messages.is_empty());
}
#[tokio::test]
async fn output_free_interrupted_turn_requests_prompt_restore() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
let prompt = UserMessage::from("revise this prompt");
chat.record_cancel_edit_candidate(prompt.clone());
handle_turn_started(&mut chat, "turn-1");
chat.submit_op(AppCommand::interrupt_and_restore_prompt_if_no_output());
assert_matches!(
op_rx.try_recv(),
Ok(Op::Interrupt {
behavior: crate::app_command::InterruptBehavior::RestorePromptIfNoOutput,
})
);
handle_turn_interrupted(&mut chat, "turn-1");
assert_matches!(rx.try_recv(), Ok(AppEvent::RestoreCancelledTurn(restored)) if restored == prompt);
}
#[tokio::test]
async fn visible_output_prevents_cancelled_turn_prompt_restore() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.record_cancel_edit_candidate(UserMessage::from("revise this prompt"));
handle_turn_started(&mut chat, "turn-1");
chat.on_agent_message_delta("visible output".to_string());
chat.submit_op(AppCommand::interrupt_and_restore_prompt_if_no_output());
handle_turn_interrupted(&mut chat, "turn-1");
while let Ok(event) = rx.try_recv() {
assert!(!matches!(event, AppEvent::RestoreCancelledTurn(_)));
}
}
#[tokio::test]
async fn thinking_status_keeps_cancelled_turn_prompt_restore_eligible() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
let prompt = UserMessage::from("revise this prompt");
chat.record_cancel_edit_candidate(prompt.clone());
handle_turn_started(&mut chat, "turn-1");
chat.on_agent_reasoning_delta("**Thinking**".to_string());
chat.submit_op(AppCommand::interrupt_and_restore_prompt_if_no_output());
handle_turn_interrupted(&mut chat, "turn-1");
assert_matches!(rx.try_recv(), Ok(AppEvent::RestoreCancelledTurn(restored)) if restored == prompt);
}
#[tokio::test]
async fn patch_activity_prevents_cancelled_turn_prompt_restore() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.record_cancel_edit_candidate(UserMessage::from("revise this prompt"));
handle_turn_started(&mut chat, "turn-1");
chat.on_patch_apply_begin(HashMap::new());
chat.submit_op(AppCommand::interrupt_and_restore_prompt_if_no_output());
handle_turn_interrupted(&mut chat, "turn-1");
while let Ok(event) = rx.try_recv() {
assert!(!matches!(event, AppEvent::RestoreCancelledTurn(_)));
}
}
#[tokio::test]
async fn pending_steer_esc_does_not_steal_vim_insert_escape() {
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
@@ -949,7 +1013,7 @@ async fn pending_steer_esc_does_not_steal_vim_insert_escape() {
chat.handle_key_event(esc);
match op_rx.try_recv() {
Ok(Op::Interrupt) => {}
Ok(Op::Interrupt { .. }) => {}
other => panic!("expected Op::Interrupt, got {other:?}"),
}
assert!(chat.input_queue.submit_pending_steers_after_interrupt);
@@ -975,7 +1039,7 @@ async fn pending_steer_interrupt_uses_remapped_binding() {
chat.handle_key_event(KeyEvent::new(KeyCode::F(12), KeyModifiers::NONE));
match op_rx.try_recv() {
Ok(Op::Interrupt) => {}
Ok(Op::Interrupt { .. }) => {}
other => panic!("expected Op::Interrupt, got {other:?}"),
}
assert!(chat.input_queue.submit_pending_steers_after_interrupt);
+1 -1
View File
@@ -208,7 +208,7 @@ pub(super) fn next_submit_op(op_rx: &mut tokio::sync::mpsc::UnboundedReceiver<Op
pub(super) fn next_interrupt_op(op_rx: &mut tokio::sync::mpsc::UnboundedReceiver<Op>) {
loop {
match op_rx.try_recv() {
Ok(Op::Interrupt) => return,
Ok(Op::Interrupt { .. }) => return,
Ok(_) => continue,
Err(TryRecvError::Empty) => panic!("expected interrupt op but queue was empty"),
Err(TryRecvError::Disconnected) => panic!("expected interrupt op but channel closed"),
@@ -1351,7 +1351,7 @@ async fn streaming_final_answer_keeps_task_running_state() {
chat.handle_key_event(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
match op_rx.try_recv() {
Ok(Op::Interrupt) => {}
Ok(Op::Interrupt { .. }) => {}
other => panic!("expected Op::Interrupt, got {other:?}"),
}
assert!(!chat.bottom_pane.quit_shortcut_hint_visible());
@@ -1384,7 +1384,7 @@ async fn ctrl_c_interrupt_pauses_active_goal_turn() {
chat.handle_key_event(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
match op_rx.try_recv() {
Ok(Op::Interrupt) => {}
Ok(Op::Interrupt { .. }) => {}
other => panic!("expected Op::Interrupt, got {other:?}"),
}
assert_matches!(
@@ -7,10 +7,12 @@ use super::*;
impl ChatWidget {
pub(super) fn on_patch_apply_begin(&mut self, changes: HashMap<PathBuf, FileChange>) {
self.record_visible_turn_activity();
self.add_to_history(history_cell::new_patch_event(changes, &self.config.cwd));
}
pub(super) fn on_view_image_tool_call(&mut self, path: AbsolutePathBuf) {
self.record_visible_turn_activity();
self.flush_answer_stream_with_separator();
self.add_to_history(history_cell::new_view_image_tool_call(
path,
@@ -20,6 +22,7 @@ impl ChatWidget {
}
pub(super) fn on_image_generation_begin(&mut self) {
self.record_visible_turn_activity();
self.flush_answer_stream_with_separator();
}
@@ -63,6 +66,7 @@ impl ChatWidget {
}
pub(super) fn on_web_search_begin(&mut self, call_id: String) {
self.record_visible_turn_activity();
self.flush_answer_stream_with_separator();
self.flush_active_cell();
self.transcript.active_cell = Some(Box::new(history_cell::new_active_web_search_call(
@@ -109,6 +113,7 @@ impl ChatWidget {
}
pub(super) fn on_collab_agent_tool_call(&mut self, item: ThreadItem) {
self.record_visible_turn_activity();
let ThreadItem::CollabAgentToolCall {
id, tool, status, ..
} = &item
@@ -153,6 +158,7 @@ impl ChatWidget {
}
pub(crate) fn handle_mcp_tool_call_started_now(&mut self, item: ThreadItem) {
self.record_visible_turn_activity();
let ThreadItem::McpToolCall {
id,
server,
@@ -7,6 +7,7 @@ use super::*;
impl ChatWidget {
pub(super) fn on_exec_approval_request(&mut self, _id: String, ev: ExecApprovalRequestEvent) {
self.record_visible_turn_activity();
let ev2 = ev.clone();
self.defer_or_handle(
|q| q.push_exec_approval(ev),
@@ -19,6 +20,7 @@ impl ChatWidget {
_id: String,
ev: ApplyPatchApprovalRequestEvent,
) {
self.record_visible_turn_activity();
let ev2 = ev.clone();
self.defer_or_handle(
|q| q.push_apply_patch_approval(ev),
@@ -256,6 +258,7 @@ impl ChatWidget {
request_id: AppServerRequestId,
params: McpServerElicitationRequestParams,
) {
self.record_visible_turn_activity();
let request_id2 = request_id.clone();
let params2 = params.clone();
self.defer_or_handle(
@@ -265,6 +268,7 @@ impl ChatWidget {
}
pub(super) fn on_request_user_input(&mut self, ev: ToolRequestUserInputParams) {
self.record_visible_turn_activity();
let ev2 = ev.clone();
self.defer_or_handle(
|q| q.push_user_input(ev),
@@ -273,6 +277,7 @@ impl ChatWidget {
}
pub(super) fn on_request_permissions(&mut self, ev: RequestPermissionsEvent) {
self.record_visible_turn_activity();
let ev2 = ev.clone();
self.defer_or_handle(
|q| q.push_request_permissions(ev),
@@ -317,6 +317,7 @@ impl ChatWidget {
self.stream_controller = None;
self.plan_stream_controller = None;
self.status_state.pending_status_indicator_restore = false;
self.clear_cancel_edit();
self.request_status_line_branch_refresh();
self.request_status_line_git_summary_refresh();
self.maybe_show_pending_rate_limit_prompt();
+5 -5
View File
@@ -25,16 +25,16 @@ use super::ChatWidget;
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct UserMessage {
pub(super) text: String,
pub(super) local_images: Vec<LocalImageAttachment>,
pub(crate) text: String,
pub(crate) local_images: Vec<LocalImageAttachment>,
/// Remote image attachments represented as URLs (for example data URLs)
/// provided by app-server clients.
///
/// Unlike `local_images`, these are not created by TUI image attach/paste
/// flows. The TUI can restore and remove them while editing/backtracking.
pub(super) remote_image_urls: Vec<String>,
pub(super) text_elements: Vec<TextElement>,
pub(super) mention_bindings: Vec<MentionBinding>,
pub(crate) remote_image_urls: Vec<String>,
pub(crate) text_elements: Vec<TextElement>,
pub(crate) mention_bindings: Vec<MentionBinding>,
}
#[derive(Clone, Debug, PartialEq)]