mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Clear stale transcript history when switching threads (#43994)
## Why History events queued by the previous thread can repopulate the transcript after a thread switch, mixing old content into the new thread's replay. ## What changed - Reset the transcript immediately and queue another reset before replaying the new thread, covering both snapshot switches and app-server thread replacement. - Leave the alternate screen when resetting, and pause terminal event handling until queued resets finish. - Process queued resets even when the transport is offline. ## Testing Add regression tests for both switch paths, including queued history, an open transcript overlay, and a disconnect before replay events are handled. Snapshot the replacement transcript to verify it contains only the new thread's content. GitOrigin-RevId: b68b07fb10ff35e908c2c184f80859dda637f977
This commit is contained in:
1 parent
721f46a07a
commit
b831057106
8 files changed
+185
-1
No files matched your search
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
+14
@@ -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
|
||||
@@ -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,
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user