Clear stale turn and review state when the TUI resumes (#64236)

## Why

Persisted history can still show a turn as in progress after its task
has stopped. A review interrupted by a crash can also lack an exit
event, leaving the resumed TUI in review mode.

## What changed

- Treat in-progress turns as interrupted when legacy or anchored resume
  history reports a non-active thread. Preserve in-progress turns on
  unanchored pages, which can include a turn started after the status
  was read.
- Reconcile buffered thread status updates during resume. An idle update
  clears activity restored from history while preserving newer live
  turns and retaining elapsed time for a later completion event.
- Reset review state when replay reaches an interrupted turn and end
  review mode at the same boundary when backtracking.

## Testing

Extend resume and replay coverage for stale and live turns, buffered
idle updates, and elapsed time when completion arrives after idle.

GitOrigin-RevId: ac46b271e86960e7e7b7e81d1c45f7ef655118fa
This commit is contained in:
Eric Traut
2026-11-27 01:14:33 +00:00
committed by copyberry
parent ad0ab3d832
commit bee5dc55ac
14 changed files with 178 additions and 26 deletions
+1 -1
View File
@@ -586,6 +586,7 @@ impl App {
)
});
store.set_session(session, turns);
store.rebase_buffer_after_session_refresh();
if let Some((active, latest, evicted, reasoning)) = live_turn {
store.active_turn_id = active;
store.latest_turn_id = latest;
@@ -599,7 +600,6 @@ impl App {
}
store.replay_may_have_output |= replay_may_have_output;
store.merge_recap_progress(recap_progress);
store.rebase_buffer_after_session_refresh();
live_attached
}
@@ -213,6 +213,7 @@ async fn reconnect_daemon_command_center_after_socket_replacement_without_a_conv
restored_previous.clone().unwrap()
};
if changed_child_permissions && thread.id != child.to_string() {
thread.status = ThreadStatus::Active { active_flags: Vec::new() };
thread.turns = vec![test_turn("saved", TurnStatus::InProgress, Vec::new())];
}
let (approval, sandbox) = if changed_child_permissions && thread.id != child.to_string() {
@@ -48,6 +48,17 @@ impl ThreadEventStore {
.buffered_agent_message_delta_bytes
.saturating_add(delta.delta.len());
}
// Also reconcile notifications buffered while resume was fetching history.
if let ThreadBufferedEvent::Notification(notification) = &event
&& let ServerNotification::ThreadStatusChanged(status) = notification.as_ref()
&& status.status == codex_app_server_protocol::ThreadStatus::Idle
&& self.turns.last().is_some_and(|turn| {
turn.status == codex_app_server_protocol::TurnStatus::InProgress
&& self.active_turn_id() == Some(turn.id.as_str())
})
{
self.clear_active_turn_id();
}
self.buffer.push_back(event);
self.evict_overflowing_events();
}
+45 -2
View File
@@ -192,8 +192,19 @@ impl ThreadEventStore {
.map(|prefix| self.buffer.split_off(prefix.min(self.buffer.len())));
self.buffer.retain_mut(Self::event_survives_session_refresh);
self.buffered_agent_message_delta_bytes = 0;
for event in tail.into_iter().flatten() {
self.push_buffered_event(event);
if let Some(tail) = tail {
// Status broadcasts can predate the subscription. Only replay the latest
// status against the snapshot, even if we missed the newer TurnStarted.
let is_status = |event: &ThreadBufferedEvent| {
matches!(event, ThreadBufferedEvent::Notification(n)
if matches!(n.as_ref(), ServerNotification::ThreadStatusChanged(_)))
};
let latest = tail.iter().rposition(is_status);
for (index, event) in tail.into_iter().enumerate() {
if Some(index) == latest || !is_status(&event) {
self.push_buffered_event(event);
}
}
}
}
@@ -976,6 +987,38 @@ mod tests {
let mut refreshed_store = ThreadEventStore::new(/*capacity*/ 8);
refreshed_store.set_session(session, turns);
assert_eq!(refreshed_store.active_turn_id(), Some("turn-2"));
let status = |status| {
ServerNotification::ThreadStatusChanged(
codex_app_server_protocol::ThreadStatusChangedNotification {
thread_id: thread_id.to_string(),
status,
},
)
};
let idle = status(codex_app_server_protocol::ThreadStatus::Idle);
// Before subscription we can see both broadcasts but miss turn-2's start.
refreshed_store.attachment_prefix = Some(0);
refreshed_store.push_notification(idle.clone());
refreshed_store.push_notification(status(
codex_app_server_protocol::ThreadStatus::Active {
active_flags: Vec::new(),
},
));
refreshed_store.set_turns(store.turns.clone());
refreshed_store.rebase_buffer_after_session_refresh();
assert_eq!(refreshed_store.active_turn_id(), Some("turn-2"));
assert_eq!(refreshed_store.snapshot().events.len(), 1);
// Idle can also arrive after subscription before the history is installed.
refreshed_store.attachment_prefix = Some(0);
refreshed_store.push_notification(idle.clone());
refreshed_store.set_turns(store.turns);
refreshed_store.rebase_buffer_after_session_refresh();
assert_eq!(refreshed_store.active_turn_id(), None);
refreshed_store.push_notification(turn_started_notification(thread_id, "turn-3"));
refreshed_store.push_notification(idle);
assert_eq!(refreshed_store.active_turn_id(), Some("turn-3"));
}
#[test]
+2 -7
View File
@@ -1330,12 +1330,7 @@ impl App {
session.thread_name.clone_from(&update.thread_name);
}
let previous_pending_status = guard.side_parent_pending_status();
let turn_stopped = match &notification {
ServerNotification::TurnCompleted(notification) => {
guard.active_turn_id() == Some(notification.turn.id.as_str())
}
_ => false,
};
let was_running = guard.active_turn_id().is_some();
let notification = if guard.active {
guard.push_notification_ref(&notification);
Some(notification)
@@ -1383,7 +1378,7 @@ impl App {
notification,
previous_pending_status,
guard.side_parent_pending_status(),
turn_stopped,
was_running && guard.active_turn_id().is_none(),
)
};
if is_turn_started {
+3
View File
@@ -713,6 +713,9 @@ pub(crate) fn backtrack_revert_before_turn_id(
}
return Ok(before_turn_id);
}
if turn.status == TurnStatus::Interrupted {
review_mode = false;
}
}
bail!("the selected prompt was not found in the persisted thread");
}
+44 -8
View File
@@ -134,6 +134,7 @@ use codex_app_server_protocol::ThreadSource;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
use codex_app_server_protocol::ThreadStartSource;
use codex_app_server_protocol::ThreadStatus;
use codex_app_server_protocol::ThreadStatusChangedNotification;
use codex_app_server_protocol::ThreadUnarchiveParams;
use codex_app_server_protocol::ThreadUnarchiveResponse;
@@ -144,6 +145,7 @@ use codex_app_server_protocol::TurnInterruptParams;
use codex_app_server_protocol::TurnInterruptResponse;
use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::TurnStartResponse;
use codex_app_server_protocol::TurnStatus;
use codex_app_server_protocol::TurnSteerParams;
use codex_app_server_protocol::TurnSteerResponse;
use codex_app_server_protocol::UserInput;
@@ -3174,11 +3176,24 @@ async fn started_thread_from_start_response(
}
async fn started_thread_from_resume_response(
response: ThreadResumeResponse,
mut response: ThreadResumeResponse,
local_settings: &LocalSettings,
cwd_convention: Option<PathConvention>,
) -> Result<AppServerStartedThread> {
let blocks_direct_input = thread_blocks_direct_input(&response.thread);
// Replay and interrupt routing both infer the active turn from hydrated history.
// Match the server's interrupted-turn fallback when that history outlives the task.
// An unanchored page can include a turn started after the resume status was read.
if (response.thread.history_mode == ThreadHistoryMode::Legacy
|| response.turns_backwards_cursor.is_some())
&& !matches!(response.thread.status, ThreadStatus::Active { .. })
{
for turn in &mut response.thread.turns {
if turn.status == TurnStatus::InProgress {
turn.status = TurnStatus::Interrupted;
}
}
}
let session =
thread_session_state_from_thread_resume_response(&response, local_settings, cwd_convention)
.await
@@ -3480,9 +3495,7 @@ mod tests {
use app_test_support::create_fake_rollout;
use codex_app_server_protocol::ThreadItem;
use codex_app_server_protocol::ThreadItemsListCursor;
use codex_app_server_protocol::ThreadStatus;
use codex_app_server_protocol::Turn;
use codex_app_server_protocol::TurnStatus;
use codex_features::Feature;
use codex_protocol::config_types::ReasoningSummary;
use codex_protocol::config_types::ServiceTier;
@@ -5325,7 +5338,7 @@ mod tests {
let thread_id = ThreadId::new();
let forked_from_id = ThreadId::new();
let read_only_profile = PermissionProfile::read_only();
let response = ThreadResumeResponse {
let mut response = ThreadResumeResponse {
disabled_plugin_ids: Vec::new(),
thread: codex_app_server_protocol::Thread {
originator: None,
@@ -5380,6 +5393,12 @@ mod tests {
}],
},
),
ThreadItem::untimed(
codex_app_server_protocol::ThreadItemPayload::EnteredReviewMode {
id: "review-1".to_string(),
review: "current changes".to_string(),
},
),
ThreadItem::untimed(
codex_app_server_protocol::ThreadItemPayload::AgentMessage {
moderation: None,
@@ -5392,7 +5411,7 @@ mod tests {
},
),
],
status: TurnStatus::Completed,
status: TurnStatus::InProgress,
error: None,
started_at: None,
completed_at: None,
@@ -5455,14 +5474,19 @@ mod tests {
response.instruction_source_path_uris()
);
assert_eq!(started.session.permission_profile, read_only_profile);
assert_eq!(started.turns.len(), 1);
assert_eq!(started.turns[0], response.thread.turns[0]);
let mut interrupted = response.thread.turns[0].clone();
interrupted.status = TurnStatus::Interrupted;
assert_eq!(started.turns, vec![interrupted]);
assert!(!started.blocks_direct_input);
// The first prompt after resume must preserve the server's restored mode.
let (mut chat, _sender, _events, mut commands) =
crate::chatwidget::tests::helpers::make_chatwidget_manual_with_sender().await;
chat.handle_thread_session(started.session);
chat.replay_thread_turns(
started.turns,
crate::chatwidget::ReplayKind::ResumeInitialMessages,
);
insta::assert_snapshot!(
"resumed_plan_mode",
crate::chatwidget::tests::helpers::normalize_snapshot_paths(
@@ -5492,6 +5516,9 @@ mod tests {
.build()
.await
.expect("config should build");
response.thread.status = ThreadStatus::Active {
active_flags: Vec::new(),
};
let started = started_thread_from_resume_response(
response.clone(),
&LocalSettings::from(&embedded_config),
@@ -5499,10 +5526,11 @@ mod tests {
)
.await
.expect("embedded resume response should map");
assert_eq!(started.turns, response.thread.turns);
assert_eq!(started.session.permission_profile, read_only_profile);
let mut thread = response.thread.clone();
let mut empty_roots_response = response;
let mut empty_roots_response = response.clone();
empty_roots_response.runtime_workspace_roots = Vec::new();
let server_cwd = r"/\repo";
empty_roots_response.cwd = LegacyAppPathString::from_string(server_cwd);
@@ -5525,6 +5553,7 @@ mod tests {
// Cloud can filter every item in its newest page while older prompts remain.
thread.history_mode = ThreadHistoryMode::Paginated;
thread.status = ThreadStatus::Idle;
let mut turn = thread.turns.pop().unwrap();
let prompt = turn.items.remove(0);
turn.items.clear();
@@ -5572,6 +5601,13 @@ mod tests {
)
.await
.expect("Cloud history should load past a hidden page");
// Activation was idle, but the unanchored Cloud page includes a live turn.
response.thread = thread.clone();
let started =
started_thread_from_resume_response(response, &settings, /*cwd_convention*/ None)
.await
.unwrap();
assert_eq!(started.turns, thread.turns);
let cells = crate::thread_transcript::thread_to_transcript_cells(
thread,
crate::thread_transcript::RawReasoningVisibility::Hidden,
@@ -450,9 +450,9 @@ impl AppServerSession {
.wrap_err("invalid thread id in bounded history response")?;
if thread.history_mode == ThreadHistoryMode::Legacy {
if thread.turns.is_empty() {
thread.turns = Box::pin(self.thread_read(thread_id, /*include_turns*/ true))
.await?
.turns;
let latest = Box::pin(self.thread_read(thread_id, /*include_turns*/ true)).await?;
thread.status = latest.status;
thread.turns = latest.turns;
}
self.history_pagination.entry(thread_id).or_default();
return Ok(());
+3 -3
View File
@@ -1212,7 +1212,8 @@ impl ChatWidget {
Some(info.total_token_usage.tokens_in_context_window())
}
fn restore_pre_review_token_info(&mut self) {
fn reset_review_mode(&mut self) {
self.review.is_review_mode = false;
if let Some(saved) = self.review.pre_review_token_info.take() {
match saved {
Some(info) => self.apply_token_info(info),
@@ -1357,8 +1358,7 @@ impl ChatWidget {
self.flush_answer_stream_with_separator();
self.flush_interrupt_queue();
self.flush_active_cell();
self.review.is_review_mode = false;
self.restore_pre_review_token_info();
self.reset_review_mode();
self.add_to_history(history_cell::new_review_status_line(
"<< Code review finished >>".to_string(),
));
+10 -1
View File
@@ -10,10 +10,19 @@ impl ChatWidget {
replay_kind: Option<ReplayKind>,
) -> Option<history_cell::FinalMessageSeparator> {
let live = replay_kind.is_none();
let elapsed = if live {
self.turn_lifecycle
.elapsed_at_idle
.take_if(|(id, _)| *id == turn.id)
.map(|(_, elapsed)| elapsed)
.or_else(|| self.bottom_pane.status_elapsed())
} else {
None
};
history_cell::FinalMessageSeparator::from_turn_once(
turn,
&mut self.turn_lifecycle.rendered_completion_turn_ids,
self.bottom_pane.status_elapsed().filter(|_| live),
elapsed,
live.then(Local::now),
)
.filter(|cell| self.local_settings.transcript_mode.is_owned() || cell.has_timing())
+18 -1
View File
@@ -101,6 +101,24 @@ impl ChatWidget {
ServerNotification::ThreadSettingsUpdated(notification) => {
self.apply_thread_settings(notification, replay_kind);
}
ServerNotification::ThreadStatusChanged(notification) => {
// Idle has no turn ID. Only retire activity restored from history;
// a newer live turn must finish through its own completion event.
if notification.status == codex_app_server_protocol::ThreadStatus::Idle
&& self.turn_lifecycle.agent_turn_running
&& self.turn_lifecycle.running_from_history
{
self.turn_lifecycle.elapsed_at_idle = self
.turn_lifecycle
.last_turn_id
.clone()
.zip(self.bottom_pane.status_elapsed());
self.reset_review_mode();
self.turn_lifecycle.finish();
self.update_task_running_state();
self.request_redraw();
}
}
ServerNotification::TurnStarted(notification) => {
self.turn_lifecycle.has_turn_history = true;
if self
@@ -405,7 +423,6 @@ impl ChatWidget {
| ServerNotification::GatewayOAuthChanged(_)
| ServerNotification::AccountRateLimitsUpdated(_)
| ServerNotification::ThreadStarted(_)
| ServerNotification::ThreadStatusChanged(_)
| ServerNotification::ThreadReadStateChanged(_)
| ServerNotification::ThreadSectionChanged(_)
| ServerNotification::ThreadReverted(_)
+5
View File
@@ -197,6 +197,7 @@ impl ChatWidget {
self.turn_lifecycle.last_turn_id = Some(turn_id.clone());
self.last_non_retry_error = None;
self.on_replayed_task_started(started_at);
self.turn_lifecycle.running_from_history = true;
}
let trailing_reasoning_id = (status == TurnStatus::InProgress)
.then(|| items.last())
@@ -256,6 +257,10 @@ impl ChatWidget {
} else {
status
};
// A crash can leave a review start in history without the corresponding exit.
if status == TurnStatus::Interrupted {
self.reset_review_mode();
}
if status == TurnStatus::InProgress {
self.status_state.reasoning_resume_turn_id = Some(turn_id.clone());
}
@@ -1805,6 +1805,31 @@ async fn replayed_in_progress_turn_marks_task_running() {
std::iter::from_fn(|| rx.try_recv().ok())
.all(|event| !matches!(event, AppEvent::Exit(_)))
);
let input = chat.capture_thread_input_state();
chat.restore_reconnected_input(input, &[]);
replay_entered_review_mode(&mut chat, "current changes");
let idle = ServerNotification::ThreadStatusChanged(
codex_app_server_protocol::ThreadStatusChangedNotification {
thread_id: chat.thread_id.unwrap().to_string(),
status: codex_app_server_protocol::ThreadStatus::Idle,
},
);
chat.bottom_pane
.reset_status_timer(std::time::Duration::from_secs(/*secs*/ 125));
chat.handle_server_notification(idle.clone(), /*replay_kind*/ None);
assert!(!chat.bottom_pane.is_task_running());
super::helpers::handle_turn_completed(&mut chat, "turn-1", /*duration_ms*/ None);
let completion = drain_insert_history(&mut rx)
.into_iter()
.map(|lines| lines_to_single_string(&lines))
.collect::<String>();
assert!(completion.contains("Worked for 2m 5s"), "{completion}");
handle_turn_started(&mut chat, "turn-2");
chat.handle_server_notification(idle, /*replay_kind*/ None);
assert!(chat.bottom_pane.is_task_running());
}
}
}
@@ -19,6 +19,8 @@ pub(super) struct TurnLifecycleState {
pub(super) sleep_inhibitor: SleepInhibitor,
/// Tracks whether codex-core currently considers an agent turn to be in progress.
pub(super) agent_turn_running: bool,
pub(super) running_from_history: bool,
pub(super) elapsed_at_idle: Option<(String, std::time::Duration)>,
pub(super) last_turn_id: Option<String>,
pub(super) steer_hint: SteerHint,
/// A live or restored turn makes the parent available for side-chat creation.
@@ -37,6 +39,8 @@ impl TurnLifecycleState {
Self {
sleep_inhibitor: SleepInhibitor::new(prevent_idle_sleep),
agent_turn_running: false,
running_from_history: false,
elapsed_at_idle: None,
last_turn_id: None,
steer_hint: SteerHint::Hidden,
has_turn_history: false,
@@ -51,6 +55,7 @@ impl TurnLifecycleState {
pub(super) fn start(&mut self, now: Instant) {
self.steer_hint = SteerHint::Hidden;
self.agent_turn_running = true;
self.running_from_history = false;
self.goal_status_active_turn_started_at = Some(now);
self.sleep_inhibitor.set_turn_running(/*turn_running*/ true);
}
@@ -58,6 +63,7 @@ impl TurnLifecycleState {
pub(super) fn finish(&mut self) {
self.steer_hint = SteerHint::Hidden;
self.agent_turn_running = false;
self.running_from_history = false;
self.goal_status_active_turn_started_at = None;
self.sleep_inhibitor
.set_turn_running(/*turn_running*/ false);
@@ -77,6 +83,7 @@ impl TurnLifecycleState {
pub(super) fn reset_thread(&mut self) {
self.finish();
self.last_turn_id = None;
self.elapsed_at_idle = None;
self.has_turn_history = false;
self.admitted_turn_id = None;
self.budget_limited_turn_ids.clear();