Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Make TUI turn interrupts nonblocking (#35000)

Eric Traut62ba648136c7
diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs
index 7d70bd1d9b..f9cb758eaa 100644
--- a/codex-rs/tui/src/app/tests.rs
+++ b/codex-rs/tui/src/app/tests.rs
@@ -6921,6 +6921,7 @@ async fn interrupt_without_active_turn_is_treated_as_handled() {
app.enqueue_primary_thread_session(started.session, started.turns)
.await
.expect("primary thread should be registered");
+ app.backtrack.primed = true;
let op = AppCommand::interrupt();
let handled = Box::pin(app.try_submit_active_thread_op_via_app_server(
@@ -6932,6 +6933,7 @@ async fn interrupt_without_active_turn_is_treated_as_handled() {
.expect("interrupt submission should not fail");
assert_eq!(handled, true);
+ assert!(!app.backtrack.primed);
})
.await;
}
diff --git a/codex-rs/tui/src/app/tests/safety_buffering.rs b/codex-rs/tui/src/app/tests/safety_buffering.rs
index f6fb2e21a6..901b26467f 100644
--- a/codex-rs/tui/src/app/tests/safety_buffering.rs
+++ b/codex-rs/tui/src/app/tests/safety_buffering.rs
@@ -149,6 +149,121 @@ async fn wait_for_turn_completed(
}
}
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn active_turn_interrupt_is_nonblocking_and_coalesces_repeated_requests() -> Result<()> {
+ let (chunks, release_response) =
+ gated_response_chunks("interrupt-response", ev_completed("interrupt-response"));
+ let (server, _completions) = start_streaming_sse_server(vec![chunks]).await;
+ let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await;
+ let codex_home = tempdir()?;
+ std::fs::write(
+ codex_home.path().join("config.toml"),
+ format!(
+ r#"
+model = "{CURRENT_MODEL}"
+model_provider = "{MODEL_PROVIDER_ID}"
+
+[model_providers.{MODEL_PROVIDER_ID}]
+name = "Interrupt test"
+base_url = "{}/v1"
+wire_api = "responses"
+request_max_retries = 0
+stream_max_retries = 0
+"#,
+ server.uri()
+ ),
+ )?;
+ app.config.codex_home = codex_home.path().to_path_buf().abs();
+ app.config.sqlite_home = codex_home.path().to_path_buf();
+ app.config.model = Some(CURRENT_MODEL.to_string());
+ app.config.model_provider_id = MODEL_PROVIDER_ID.to_string();
+ app.config.model_provider = ModelProviderInfo {
+ name: "Interrupt test".to_string(),
+ base_url: Some(format!("{}/v1", server.uri())),
+ request_max_retries: Some(0),
+ stream_max_retries: Some(0),
+ ..ModelProviderInfo::default()
+ };
+
+ let mut tui = crate::tui::test_support::make_test_tui()?;
+ let mut app_server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
+ let started = app_server.start_thread(&app.config).await?;
+ let thread_id = started.session.thread_id;
+ app.replace_chat_widget_with_app_server_thread(
+ &mut tui,
+ started,
+ ThreadAttachPresentation::SessionLineage,
+ /*initial_user_message*/ None,
+ )
+ .await?;
+ while app_event_rx.try_recv().is_ok() {}
+
+ submit_prompt(&mut app, "Keep this turn running until interrupted");
+ let turn = next_user_turn_event(&mut app_event_rx);
+ app.submit_thread_op(&mut app_server, thread_id, turn)
+ .await?;
+ let turn_id = next_turn_started(&mut app, &mut app_server, thread_id).await;
+ drive_until_request_count(
+ &mut app,
+ &mut app_server,
+ &server,
+ /*expected_request_count*/ 1,
+ )
+ .await;
+
+ let interrupt = AppCommand::interrupt();
+ assert!(
+ app.try_submit_active_thread_op_via_app_server(&mut app_server, thread_id, &interrupt)
+ .await?
+ );
+ let AppServerRequestId::Integer(next_request_id) = app_server.next_request_id() else {
+ unreachable!("embedded app-server request IDs are integers");
+ };
+ assert!(
+ app.try_submit_active_thread_op_via_app_server(&mut app_server, thread_id, &interrupt)
+ .await?
+ );
+ assert_eq!(
+ app_server.next_request_id(),
+ AppServerRequestId::Integer(next_request_id + 1)
+ );
+ {
+ let store = app.thread_event_channels[&thread_id].store.lock().await;
+ assert_eq!(store.active_turn_id.as_deref(), Some(turn_id.as_str()));
+ assert_eq!(
+ store.pending_interrupt_turn_id.as_deref(),
+ Some(turn_id.as_str())
+ );
+ }
+
+ while app_event_rx.try_recv().is_ok() {}
+ app.handle_thread_event_now(ThreadBufferedEvent::Notification(
+ ServerNotification::Warning(WarningNotification {
+ thread_id: Some(thread_id.to_string()),
+ message: "event handled while interrupt is pending".to_string(),
+ }),
+ ));
+ assert!(matches!(
+ app_event_rx.try_recv(),
+ Ok(AppEvent::InsertHistoryCell(_))
+ ));
+
+ wait_for_turn_completed(&mut app, &mut app_server, thread_id).await;
+ assert_eq!(
+ app.thread_event_channels[&thread_id]
+ .store
+ .lock()
+ .await
+ .pending_interrupt_turn_id,
+ None
+ );
+
+ let _ = release_response.send(());
+ app_server.shutdown().await?;
+ server.shutdown().await;
+ Ok(())
+}
+
async fn drive_until_request_count(
app: &mut App,
app_server: &mut AppServerSession,
diff --git a/codex-rs/tui/src/app/thread_events.rs b/codex-rs/tui/src/app/thread_events.rs
index f2e0682f57..27472880f3 100644
--- a/codex-rs/tui/src/app/thread_events.rs
+++ b/codex-rs/tui/src/app/thread_events.rs
@@ -45,6 +45,7 @@ pub(super) struct ThreadEventStore {
pub(super) buffer: VecDeque<ThreadBufferedEvent>,
pub(super) pending_interactive_replay: PendingInteractiveReplayState,
pub(super) active_turn_id: Option<String>,
+ pub(super) pending_interrupt_turn_id: Option<String>,
pub(super) input_state: Option<ThreadInputState>,
pub(super) capacity: usize,
pub(super) active: bool,
@@ -69,6 +70,7 @@ impl ThreadEventStore {
buffer: VecDeque::new(),
pending_interactive_replay: PendingInteractiveReplayState::default(),
active_turn_id: None,
+ pending_interrupt_turn_id: None,
input_state: None,
capacity,
active: false,
@@ -120,13 +122,17 @@ impl ThreadEventStore {
ServerNotification::TurnStarted(turn) => {
self.active_turn_id = Some(turn.turn.id.clone());
}
- ServerNotification::TurnCompleted(turn)
- if self.active_turn_id.as_deref() == Some(turn.turn.id.as_str()) =>
- {
- self.active_turn_id = None;
+ ServerNotification::TurnCompleted(turn) => {
+ if self.active_turn_id.as_deref() == Some(turn.turn.id.as_str()) {
+ self.active_turn_id = None;
+ }
+ if self.pending_interrupt_turn_id.as_deref() == Some(turn.turn.id.as_str()) {
+ self.pending_interrupt_turn_id = None;
+ }
}
ServerNotification::ThreadClosed(_) => {
self.active_turn_id = None;
+ self.pending_interrupt_turn_id = None;
}
_ => {}
}
diff --git a/codex-rs/tui/src/app/thread_routing.rs b/codex-rs/tui/src/app/thread_routing.rs
index 9149d3192a..d060666a22 100644
--- a/codex-rs/tui/src/app/thread_routing.rs
+++ b/codex-rs/tui/src/app/thread_routing.rs
@@ -8,6 +8,9 @@ use super::session_lifecycle::ThreadAttachPresentation;
use super::*;
use crate::chatwidget::ThreadInputStateRestoreMode;
use crate::session_resume::read_session_model;
+use codex_app_server_protocol::TurnInterruptParams;
+use codex_app_server_protocol::TurnInterruptResponse;
+use codex_app_server_protocol::WarningNotification;
impl App {
pub(super) async fn shutdown_current_thread(&mut self, app_server: &mut AppServerSession) {
@@ -567,41 +570,71 @@ impl App {
) -> Result<bool> {
match op {
AppCommand::Interrupt => {
- if let Some(turn_id) = self.active_turn_id_for_thread(thread_id).await {
- let mut interrupt_turn_id = turn_id;
- for retried_after_turn_mismatch in [false, true] {
- match app_server
- .turn_interrupt(thread_id, interrupt_turn_id.clone())
- .await
- {
- Ok(()) => return Ok(true),
- Err(error) if !retried_after_turn_mismatch => {
- let Some(actual_turn_id) = active_turn_interrupt_race(&error)
- else {
- return Err(error).wrap_err("turn/interrupt failed in TUI");
+ let mut turn_id = self
+ .active_turn_id_for_thread(thread_id)
+ .await
+ .unwrap_or_default();
+ let (thread_event_tx, thread_event_store) = {
+ let channel = self.ensure_thread_channel(thread_id);
+ (channel.sender.clone(), Arc::clone(&channel.store))
+ };
+ self.reset_backtrack_state();
+ if !turn_id.is_empty() {
+ let mut store = thread_event_store.lock().await;
+ if store.pending_interrupt_turn_id.as_deref() == Some(turn_id.as_str()) {
+ return Ok(true);
+ }
+ store.pending_interrupt_turn_id = Some(turn_id.clone());
+ }
+ let request_handle = app_server.request_handle();
+ let request_ids = [app_server.next_request_id(), app_server.next_request_id()];
+ tokio::spawn(async move {
+ for (attempt, request_id) in request_ids.into_iter().enumerate() {
+ let result = request_handle
+ .request_typed::<TurnInterruptResponse>(ClientRequest::TurnInterrupt {
+ request_id,
+ params: TurnInterruptParams {
+ thread_id: thread_id.to_string(),
+ turn_id: turn_id.clone(),
+ },
+ })
+ .await;
+
+ match result {
+ Ok(_) => break,
+ Err(error) => {
+ if attempt == 0
+ && let Some(actual_turn_id) = active_turn_interrupt_race(&error)
+ && actual_turn_id != turn_id
+ {
+ thread_event_store.lock().await.pending_interrupt_turn_id =
+ Some(actual_turn_id.clone());
+ turn_id = actual_turn_id;
+ continue;
+ }
+ tracing::warn!(error = %error, "turn/interrupt failed in TUI");
+ let notification =
+ ServerNotification::Warning(WarningNotification {
+ thread_id: Some(thread_id.to_string()),
+ message: format!("Failed to interrupt turn: {error}"),
+ });
+ let should_send = {
+ let mut store = thread_event_store.lock().await;
+ store.push_notification_ref(&notification);
+ store.active
};
- if actual_turn_id == interrupt_turn_id {
- return Err(error).wrap_err("turn/interrupt failed in TUI");
+ if should_send
+ && let Err(error) = thread_event_tx
+ .send(ThreadBufferedEvent::Notification(notification))
+ .await
+ {
+ tracing::warn!(error = %error, "thread event channel closed");
}
- // Review flows can swap the active turn before the TUI processes
- // the corresponding notification. Retry once with the
- // server-reported turn id so Ctrl+C/Esc do not fatally exit on that
- // stale cache, but let lifecycle notifications own the cached
- // active turn id.
- interrupt_turn_id = actual_turn_id;
- }
- Err(error) => {
- return Err(error).wrap_err("turn/interrupt failed in TUI");
+ break;
}
}
}
- unreachable!("interrupt retry loop should return");
- } else {
- app_server
- .startup_interrupt(thread_id)
- .await
- .wrap_err("turn/interrupt failed in TUI")?;
- }
+ });
Ok(true)
}
AppCommand::UserTurn {
diff --git a/codex-rs/tui/src/app_server_session.rs b/codex-rs/tui/src/app_server_session.rs
index 487778ca6c..81b38697da 100644
--- a/codex-rs/tui/src/app_server_session.rs
+++ b/codex-rs/tui/src/app_server_session.rs
@@ -1271,7 +1271,7 @@ impl AppServerSession {
self.client.request_handle()
}
- fn next_request_id(&mut self) -> RequestId {
+ pub(crate) fn next_request_id(&mut self) -> RequestId {
let request_id = self.next_request_id;
self.next_request_id += 1;
RequestId::Integer(request_id)