Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Clear stale transcript history when switching threads (#43994)

Eric Trautb83105710695
diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs
index 9bc4836332..514ff8c269 100644
--- a/codex-rs/tui/src/app.rs
+++ b/codex-rs/tui/src/app.rs
@@ -584,6 +584,7 @@ pub(crate) struct App {
has_emitted_history_lines: bool,
transcript_reflow: TranscriptReflowState,
initial_history_replay_buffer: Option<InitialHistoryReplayBuffer>,
+ pending_thread_switch_resets: usize,
pub(crate) scrollback_has_older_history: bool,
pub(crate) enhanced_keys_supported: bool,
diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs
index 2c31b48c12..6b01c1bd1d 100644
--- a/codex-rs/tui/src/app/event_dispatch.rs
+++ b/codex-rs/tui/src/app/event_dispatch.rs
@@ -34,6 +34,7 @@ impl App {
&& !matches!(
&event,
AppEvent::InsertHistoryCell(_)
+ | AppEvent::ResetTranscriptForThreadSwitch
| AppEvent::ManagedWorktreeCreated(_)
| AppEvent::AppendMessageHistoryEntry { .. }
| AppEvent::BeginInitialHistoryReplayBuffer
@@ -640,6 +641,10 @@ impl App {
AppEvent::BeginThreadSwitchHistoryReplayBuffer => {
self.begin_thread_switch_history_replay_buffer();
}
+ AppEvent::ResetTranscriptForThreadSwitch => {
+ self.reset_for_thread_switch(tui)?;
+ self.pending_thread_switch_resets -= 1;
+ }
AppEvent::InsertHistoryCell(cell) => {
self.insert_history_cell(tui, cell);
}
diff --git a/codex-rs/tui/src/app/session_lifecycle.rs b/codex-rs/tui/src/app/session_lifecycle.rs
index 6357ce8851..ef3740cdf6 100644
--- a/codex-rs/tui/src/app/session_lifecycle.rs
+++ b/codex-rs/tui/src/app/session_lifecycle.rs
@@ -722,6 +722,9 @@ impl App {
self.chat_widget.set_parent_owned_thread();
}
self.reset_for_thread_switch(tui)?;
+ self.pending_thread_switch_resets += 1;
+ self.app_event_tx
+ .send(AppEvent::ResetTranscriptForThreadSwitch);
self.replay_thread_snapshot(snapshot, resume_restored_queue);
if external_writer {
self.chat_widget.show_external_writer_thread();
@@ -740,6 +743,9 @@ impl App {
}
pub(super) fn reset_for_thread_switch(&mut self, tui: &mut tui::Tui) -> Result<()> {
+ if tui.is_alt_screen_active() {
+ tui.leave_alt_screen()?;
+ }
self.reset_transcript_state_after_clear();
tui.clear_pending_history_lines();
Self::clear_terminal_for_thread_switch(&mut tui.terminal)?;
@@ -1013,6 +1019,10 @@ impl App {
// Initial messages are for freshly attached primary threads only. Thread switches and
// resume/fork flows pass `None` so they cannot replay old history and then auto-submit a new
// user turn by accident.
+ self.reset_for_thread_switch(tui)?;
+ self.pending_thread_switch_resets += 1;
+ self.app_event_tx
+ .send(AppEvent::ResetTranscriptForThreadSwitch);
self.reset_thread_event_state();
let init = self.chatwidget_init_for_forked_or_resumed_thread(
tui,
diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__tests__app_server_thread_replacement_clears_previous_transcript_before_replay-2.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__tests__app_server_thread_replacement_clears_previous_transcript_before_replay-2.snap
new file mode 100644
index 0000000000..4b9aa6a689
--- /dev/null
+++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__tests__app_server_thread_replacement_clears_previous_transcript_before_replay-2.snap
@@ -0,0 +1,14 @@
+---
+source: tui/src/app/tests.rs
+assertion_line: 6350
+expression: rendered
+---
+╭────────────────────────────────────────╮
+│ >_ OpenAI Codex (v0.0.0) │
+│ │
+│ model: gpt-test /model to change │
+│ directory: <thread cwd> │
+╰────────────────────────────────────────╯
+
+
+› Next thread prompt
diff --git a/codex-rs/tui/src/app/startup.rs b/codex-rs/tui/src/app/startup.rs
index 1e73cdba1d..4ce96b87f7 100644
--- a/codex-rs/tui/src/app/startup.rs
+++ b/codex-rs/tui/src/app/startup.rs
@@ -705,6 +705,7 @@ See the Codex keymap documentation for supported actions and examples."
has_emitted_history_lines: false,
transcript_reflow: TranscriptReflowState::default(),
initial_history_replay_buffer: None,
+ pending_thread_switch_resets: 0,
scrollback_has_older_history: false,
commit_animation: None,
status_line_invalid_items_warned: status_line_invalid_items_warned.clone(),
@@ -1080,7 +1081,8 @@ See the Codex keymap documentation for supported actions and examples."
}
AppRunControl::Continue
}
- event = tui_events.next(), if app.reconnect.offline || !block_terminal_input_for_pending_startup_events => {
+ event = tui_events.next(), if app.pending_thread_switch_resets == 0
+ && (app.reconnect.offline || !block_terminal_input_for_pending_startup_events) => {
if let Some(event) = event {
if (matches!(
&event,
diff --git a/codex-rs/tui/src/app/test_support.rs b/codex-rs/tui/src/app/test_support.rs
index f3a912b94b..2748a624b7 100644
--- a/codex-rs/tui/src/app/test_support.rs
+++ b/codex-rs/tui/src/app/test_support.rs
@@ -45,6 +45,7 @@ pub(super) async fn make_test_app() -> App {
has_emitted_history_lines: false,
transcript_reflow: TranscriptReflowState::default(),
initial_history_replay_buffer: None,
+ pending_thread_switch_resets: 0,
scrollback_has_older_history: false,
enhanced_keys_supported: false,
keymap: crate::keymap::RuntimeKeymap::defaults(),
diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs
index 7fde87fc34..5c29e17017 100644
--- a/codex-rs/tui/src/app/tests.rs
+++ b/codex-rs/tui/src/app/tests.rs
@@ -5859,6 +5859,7 @@ async fn make_test_app() -> App {
has_emitted_history_lines: false,
transcript_reflow: TranscriptReflowState::default(),
initial_history_replay_buffer: None,
+ pending_thread_switch_resets: 0,
scrollback_has_older_history: false,
enhanced_keys_supported: false,
keymap: crate::keymap::RuntimeKeymap::defaults(),
@@ -5957,6 +5958,7 @@ pub(super) async fn make_test_app_with_channels() -> (
has_emitted_history_lines: false,
transcript_reflow: TranscriptReflowState::default(),
initial_history_replay_buffer: None,
+ pending_thread_switch_resets: 0,
scrollback_has_older_history: false,
enhanced_keys_supported: false,
keymap: crate::keymap::RuntimeKeymap::defaults(),
@@ -6267,6 +6269,152 @@ fn plain_line_cell(text: impl Into<String>) -> Arc<dyn HistoryCell> {
Arc::new(PlainHistoryCell::new(vec![Line::from(text.into())])) as Arc<dyn HistoryCell>
}
+#[tokio::test]
+async fn app_server_thread_replacement_clears_previous_transcript_before_replay() -> Result<()> {
+ let (mut app, mut events, _op_rx) = make_test_app_with_channels().await;
+ app.local_settings.tui.show_tooltips = false;
+ let previous_thread_id = ThreadId::new();
+ app.enqueue_primary_thread_session(
+ test_thread_session(previous_thread_id, test_path_buf("/tmp/previous")),
+ Vec::new(),
+ )
+ .await?;
+ while events.try_recv().is_ok() {}
+ app.transcript_cells = vec![plain_line_cell("Previous thread transcript")];
+ app.deferred_history_lines = vec![Line::from("Previous pending history").into()];
+ let mut tui = crate::tui::test_support::make_test_tui()?;
+ tui.insert_history_lines(vec![Line::from("Previous pending history")]);
+ app.chat_widget
+ .add_plain_history_lines(vec![Line::from("Previous queued history")]);
+ app.open_transcript_overlay(&mut tui);
+ assert!(tui.is_alt_screen_active());
+
+ let next_thread_id = ThreadId::new();
+ app.replace_chat_widget_with_app_server_thread(
+ &mut tui,
+ AppServerStartedThread {
+ session: test_thread_session(next_thread_id, test_path_buf("/tmp/next")),
+ turns: vec![test_turn(
+ "next-turn",
+ TurnStatus::Completed,
+ vec![ThreadItem::UserMessage {
+ id: "next-user".to_string(),
+ client_id: None,
+ content: vec![AppServerUserInput::Text {
+ text: "Next thread prompt".to_string(),
+ text_elements: Vec::new(),
+ }],
+ }],
+ )],
+ blocks_direct_input: false,
+ task_tools_available: false,
+ },
+ session_lifecycle::ThreadAttachPresentation::SessionLineage,
+ /*initial_user_message*/ None,
+ )
+ .await?;
+
+ assert_eq!(app.chat_widget.thread_id(), Some(next_thread_id));
+ assert!(!tui.is_alt_screen_active());
+ assert!(app.transcript_cells.is_empty());
+ assert!(app.deferred_history_lines.is_empty());
+ let mut app_server = crate::start_embedded_app_server_for_picker(&app.config).await?;
+ // The reset must still run if the transport disconnects before queued events are handled.
+ app.reconnect.offline = true;
+ while let Ok(event) = events.try_recv() {
+ app.handle_event(&mut tui, &mut app_server, event).await?;
+ }
+ let replayed_prompts = app
+ .transcript_cells
+ .iter()
+ .filter_map(|cell| {
+ cell.as_any()
+ .downcast_ref::<UserHistoryCell>()
+ .map(|user| user.message.as_str())
+ })
+ .collect::<Vec<_>>();
+ assert_snapshot!(replayed_prompts.join("\n"), @"Next thread prompt");
+ assert!(app.transcript_cells.iter().all(|cell| {
+ !lines_to_single_string(&cell.display_lines(/*width*/ 80))
+ .contains("Previous queued history")
+ }));
+ let rendered = app
+ .render_transcript_lines_for_reflow(/*width*/ 80)
+ .lines
+ .iter()
+ .map(|line| {
+ let text = rendered_line_text(line);
+ if text.contains("│ directory: ") {
+ "│ directory: <thread cwd> │".to_string()
+ } else {
+ text
+ }
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert!(!rendered.contains("Previous thread transcript"));
+ assert!(!rendered.contains("Previous queued history"));
+ assert_snapshot!(rendered);
+ app_server.shutdown().await?;
+ Ok(())
+}
+
+#[tokio::test]
+async fn snapshot_thread_switch_discards_queued_previous_history() -> Result<()> {
+ let (mut app, mut events, _op_rx) = make_test_app_with_channels().await;
+ app.transcript_cells = vec![plain_line_cell("Previous thread transcript")];
+ app.chat_widget
+ .add_plain_history_lines(vec![Line::from("Previous queued history")]);
+ let mut tui = crate::tui::test_support::make_test_tui()?;
+ let mut app_server = crate::start_embedded_app_server_for_picker(&app.config).await?;
+ let next_thread_id = ThreadId::new();
+ app.render_thread_snapshot(
+ &mut tui,
+ &app_server,
+ next_thread_id,
+ ThreadEventSnapshot {
+ delegated_turns: Vec::new(),
+ session: Some(test_thread_session(
+ next_thread_id,
+ test_path_buf("/tmp/next"),
+ )),
+ turns: vec![test_turn(
+ "next-turn",
+ TurnStatus::Completed,
+ vec![ThreadItem::UserMessage {
+ id: "next-user".to_string(),
+ client_id: None,
+ content: vec![AppServerUserInput::Text {
+ text: "Next thread prompt".to_string(),
+ text_elements: Vec::new(),
+ }],
+ }],
+ )],
+ events: Vec::new(),
+ active_reasoning_item: None,
+ input_state: None,
+ },
+ /*resume_restored_queue*/ false,
+ )?;
+ assert_eq!(app.pending_thread_switch_resets, 1);
+ while let Ok(event) = events.try_recv() {
+ app.handle_event(&mut tui, &mut app_server, event).await?;
+ }
+ assert_eq!(app.pending_thread_switch_resets, 0);
+ let rendered = app
+ .render_transcript_lines_for_reflow(/*width*/ 80)
+ .lines
+ .iter()
+ .map(rendered_line_text)
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert!(!rendered.contains("Previous thread transcript"));
+ assert!(!rendered.contains("Previous queued history"));
+ assert!(rendered.contains("Next thread prompt"));
+ app_server.shutdown().await?;
+ Ok(())
+}
+
fn rendered_line_text(line: &crate::terminal_hyperlinks::HyperlinkLine) -> String {
line.line
.spans
diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs
index 6e481c0a04..9ad0b0b034 100644
--- a/codex-rs/tui/src/app_event.rs
+++ b/codex-rs/tui/src/app_event.rs
@@ -508,6 +508,9 @@ pub(crate) enum AppEvent {
name: Option<String>,
},
+ /// Clear history queued by the previous thread before the new thread's replay events.
+ ResetTranscriptForThreadSwitch,
+
/// Re-render the transcript using the selected scrollback rendering mode.
RawOutputModeChanged {
enabled: bool,