Show streaming reasoning summaries in the TUI status row (#43921)

## What changed

- Update the status heading from the latest usable reasoning line and retain it through tool activity and empty reasoning items. Keep completed reasoning in the expanded transcript only.
- Restore active reasoning after resume, thread switches, and session refreshes, including when earlier events have left the replay buffer.
- Default new embedded TUI threads to `model_reasoning_summary = "detailed"`, honoring explicit summary settings. Keep `concurrent_reasoning_summaries` opt-in and disable it when summaries are `none`.
- Persist the request's captured reasoning summary setting in context updates and local and remote compaction checkpoints.
- Animate status text with a smooth, grapheme-aware shimmer that respects terminal colors and reduced motion.

## Testing

Add regression coverage for reasoning status updates, transcript visibility, resume and buffered replay, outbound summary configuration, and summary settings across all three compaction modes. Add shimmer snapshots and checks for smooth brightness changes and Unicode grapheme preservation.

GitOrigin-RevId: 725c7de20f23166d7a3da6daeca617add5cbc600
This commit is contained in:
Felipe Coury authored and copyberry committed 2026-09-08 21:41:02 +00:00
1 parent 78932f4493
commit 9ec33e1926
45 files changed
+1798 -90

No files matched your search

+47 -11
View File
@@ -15,6 +15,11 @@ impl ChatWidget {
return;
}
if replay_kind != Some(ReplayKind::ResumeInitialMessages)
&& !self.recover_resumed_reasoning(&notification)
{
return;
}
let was_replaying_turn_completion = self.thread_usage.replaying_turn_completion;
self.thread_usage.replaying_turn_completion = replay_kind.is_some();
let from_replay = replay_kind.is_some();
@@ -98,7 +103,9 @@ impl ChatWidget {
if !self.is_realtime_delegated_reasoning_item(
&notification.turn_id,
&notification.item_id,
) {
) && self.status_state.reasoning_item_id.as_deref()
== Some(&notification.item_id)
{
self.on_agent_reasoning_delta(notification.delta);
}
}
@@ -108,6 +115,7 @@ impl ChatWidget {
&notification.turn_id,
&notification.item_id,
)
&& self.status_state.reasoning_item_id.as_deref() == Some(&notification.item_id)
{
self.on_agent_reasoning_delta(notification.delta);
}
@@ -116,7 +124,9 @@ impl ChatWidget {
if !self.is_realtime_delegated_reasoning_item(
&notification.turn_id,
&notification.item_id,
) {
) && self.status_state.reasoning_item_id.as_deref()
== Some(&notification.item_id)
{
self.on_reasoning_section_break();
}
}
@@ -334,6 +344,20 @@ impl ChatWidget {
| ServerNotification::ThreadProjectUpdated(_) => {}
ServerNotification::ContextCompacted(_) => {}
}
// Tool and hook activity can recreate a hidden row with its default
// heading. Restore the selected status before that row is rendered.
if self
.bottom_pane
.status_widget()
.is_some_and(|status| status.header() != self.status_state.current_status.header)
{
self.bottom_pane.update_status(
self.status_state.current_status.header.clone(),
self.status_state.current_status.details.clone(),
StatusDetailsCapitalization::Preserve,
self.status_state.current_status.details_max_lines,
);
}
self.thread_usage.replaying_turn_completion = was_replaying_turn_completion;
}
@@ -461,16 +485,22 @@ impl ChatWidget {
ThreadItem::AgentMessage { id, .. } if replay_kind.is_none() => {
self.is_realtime_delegated_agent_item(&notification.turn_id, &id);
}
ThreadItem::Reasoning { id, .. }
ThreadItem::Reasoning { id, .. } => {
if replay_kind.is_none()
&& !self.is_realtime_delegated_reasoning_turn(&notification.turn_id) =>
{
// A later voice handoff can steer this turn without making an
// already-started typed reasoning item private.
self.realtime_conversation
.agent_items
.entry((notification.turn_id.clone(), id))
.or_insert(realtime::RealtimeAgentItemOrigin::Typed);
&& !self.is_realtime_delegated_reasoning_turn(&notification.turn_id)
{
// A later voice handoff can steer this turn without making an
// already-started typed reasoning item private.
self.realtime_conversation
.agent_items
.entry((notification.turn_id.clone(), id.clone()))
.or_insert(realtime::RealtimeAgentItemOrigin::Typed);
}
if !matches!(replay_kind, Some(ReplayKind::ResumeInitialMessages))
&& !self.is_realtime_delegated_reasoning_item(&notification.turn_id, &id)
{
self.on_reasoning_item_started(id);
}
}
ThreadItem::ContextCompaction { id }
if !matches!(replay_kind, Some(ReplayKind::ResumeInitialMessages)) =>
@@ -552,6 +582,12 @@ impl ChatWidget {
{
self.add_async_questions(id, questions);
}
if replay_kind.is_none()
&& let ThreadItem::Reasoning { id, .. } = &notification.item
&& self.status_state.reasoning_item_id.as_ref() != Some(id)
{
return;
}
match notification.item {
item @ ThreadItem::CommandExecution { .. } => self.on_command_execution_completed(item),
item => self.handle_thread_item(
@@ -338,6 +338,12 @@ async fn delegated_reasoning_never_enters_live_history() {
}
}
assert!(!chat.is_realtime_delegated_reasoning_turn(turn_id));
let typed_reasoning = ThreadItem::Reasoning {
id: "typed-reasoning".into(),
summary: vec!["ordinary summary".into()],
content: Vec::new(),
};
start_item(&mut chat, thread_id, "typed-turn", typed_reasoning.clone());
chat.handle_server_notification(
ServerNotification::ReasoningSummaryTextDelta(ReasoningSummaryTextDeltaNotification {
thread_id: thread_id.to_string(),
@@ -348,16 +354,7 @@ async fn delegated_reasoning_never_enters_live_history() {
}),
/*replay_kind*/ None,
);
complete_item(
&mut chat,
thread_id,
"typed-turn",
ThreadItem::Reasoning {
id: "typed-reasoning".into(),
summary: vec!["ordinary summary".into()],
content: Vec::new(),
},
);
complete_item(&mut chat, thread_id, "typed-turn", typed_reasoning);
let rendered = std::iter::from_fn(|| events.try_recv().ok())
.filter_map(|event| match event {
AppEvent::InsertHistoryCell(cell) => Some(
+133 -4
View File
@@ -1,11 +1,95 @@
//! Thread replay rendering for `ChatWidget`.
//!
//! This module rehydrates turns and items into transcript state while avoiding
//! live-only side effects.
//! live-only side effects. An in-progress snapshot does not carry reasoning completion
//! state: keep its trailing reasoning provisional until live events identify the next item.
use super::*;
impl ChatWidget {
/// Restores the active typed reasoning item after a thread switch or session refresh.
/// Its completion carries the full summary if the bounded event buffer lost earlier deltas.
pub(crate) fn restore_active_reasoning_item(
&mut self,
started: codex_app_server_protocol::ItemStartedNotification,
parts: Option<(Vec<String>, Vec<String>)>,
) {
let turn_id = started.turn_id;
let id = started.item.id().to_string();
self.realtime_conversation
.agent_items
.entry((turn_id, id.clone()))
.or_insert(realtime::RealtimeAgentItemOrigin::Typed);
self.on_reasoning_item_started(id);
self.status_state.reasoning_recovered_after_refresh = true;
if let Some((summary, content)) = parts {
let reasoning_parts = summary.into_iter().chain(
self.config
.show_raw_agent_reasoning
.then_some(content)
.into_iter()
.flatten(),
);
for (index, delta) in reasoning_parts.enumerate() {
if index > 0 {
self.on_reasoning_section_break();
}
self.on_agent_reasoning_delta(delta);
}
}
}
/// The first reasoning update after resume can arrive without an item/started event.
/// Returns false for unrelated reasoning while waiting for the resumed turn's first update.
pub(super) fn recover_resumed_reasoning(&mut self, notification: &ServerNotification) -> bool {
let Some(resumed_turn_id) = self.status_state.reasoning_resume_turn_id.clone() else {
return true;
};
let (turn_id, item_id) = match notification {
ServerNotification::ReasoningSummaryTextDelta(delta) => {
(&delta.turn_id, &delta.item_id)
}
ServerNotification::ReasoningTextDelta(delta) => (&delta.turn_id, &delta.item_id),
ServerNotification::ReasoningSummaryPartAdded(part) => (&part.turn_id, &part.item_id),
ServerNotification::ItemCompleted(
codex_app_server_protocol::ItemCompletedNotification {
turn_id,
item: ThreadItem::Reasoning { id, .. },
..
},
) => (turn_id, id),
ServerNotification::ItemStarted(item)
if resumed_turn_id == item.turn_id
&& !matches!(item.item, ThreadItem::UserMessage { .. })
&& self.status_state.reasoning_item_id.as_deref() != Some(item.item.id()) =>
{
// A new item closes a trailing snapshot that was already complete at resume.
self.on_agent_reasoning_final();
return true;
}
_ => return true,
};
if resumed_turn_id != *turn_id
|| self.is_realtime_delegated_reasoning_item(turn_id, item_id)
{
return false;
}
self.restore_active_reasoning_item(
codex_app_server_protocol::ItemStartedNotification {
thread_id: self.thread_id.map(|id| id.to_string()).unwrap_or_default(),
turn_id: turn_id.clone(),
item: ThreadItem::Reasoning {
id: item_id.clone(),
summary: Vec::new(),
content: Vec::new(),
},
started_at_ms: 0,
},
/*parts*/ None,
);
true
}
/// Flush prior activity before live or replayed assistant text.
pub(super) fn prepare_assistant_message(&mut self) {
self.flush_unified_exec_wait_streak();
@@ -59,6 +143,13 @@ impl ChatWidget {
self.last_non_retry_error = None;
self.on_task_started();
}
let trailing_reasoning_id = (status == TurnStatus::InProgress)
.then(|| items.last())
.flatten()
.and_then(|item| match item {
ThreadItem::Reasoning { id, .. } => Some(id.clone()),
_ => None,
});
let mut replaying_delegation = false;
for item in items {
if matches!(&item, ThreadItem::UserMessage { content, .. }
@@ -74,13 +165,38 @@ impl ChatWidget {
if hidden_nested_review_turn && matches!(item, ThreadItem::UserMessage { .. }) {
continue;
}
self.replay_thread_item(item, turn_id.clone(), replay_kind);
if trailing_reasoning_id.as_deref() == Some(item.id())
&& let ThreadItem::Reasoning {
id,
summary,
content,
} = item
{
self.restore_active_reasoning_item(
codex_app_server_protocol::ItemStartedNotification {
thread_id: self.thread_id.map(|id| id.to_string()).unwrap_or_default(),
turn_id: turn_id.clone(),
item: ThreadItem::Reasoning {
id,
summary: Vec::new(),
content: Vec::new(),
},
started_at_ms: 0,
},
Some((summary, content)),
);
} else {
self.replay_thread_item(item, turn_id.clone(), replay_kind);
}
}
let status = if hidden_nested_review_turn {
TurnStatus::Completed
} else {
status
};
if status == TurnStatus::InProgress {
self.status_state.reasoning_resume_turn_id = Some(turn_id.clone());
}
// A resolved historical precaution must not clear the restored draft or input queue.
if Some(&turn_id) != latest_turn_id.as_ref()
&& error.as_ref().is_some_and(|error| {
@@ -201,9 +317,22 @@ impl ChatWidget {
}
ThreadItem::Plan { text, .. } => self.on_plan_item_completed(text),
ThreadItem::Reasoning {
summary, content, ..
id,
summary,
content,
} => {
if from_replay {
let recover_completion = self.status_state.reasoning_recovered_after_refresh
&& (!summary.is_empty()
|| (self.config.show_raw_agent_reasoning && !content.is_empty()));
if from_replay || recover_completion {
if from_replay {
self.on_reasoning_item_started(id);
} else {
// A refreshed snapshot can omit the active item and its earlier deltas.
// Reconcile with the complete item before committing the transcript.
self.reasoning_buffer.clear();
self.reasoning_summary_parts.clear();
}
let reasoning_parts = summary.into_iter().chain(
self.config
.show_raw_agent_reasoning
@@ -0,0 +1,5 @@
---
source: tui/src/chatwidget/tests/reasoning_status_tests.rs
expression: terminal.backend()
---
"• Preparing evidence report (42s • esc …"
@@ -0,0 +1,5 @@
---
source: tui/src/chatwidget/tests/reasoning_status_tests.rs
expression: terminal.backend()
---
"• Preparing evidence report (42s • esc to interrupt) · 1 background terminal ru…"
@@ -1,9 +1,10 @@
---
source: tui/src/chatwidget/tests/status_and_layout.rs
assertion_line: 4833
expression: normalized_backend_snapshot(terminal.backend())
---
" "
"• Checking files (0s • esc to interrupt) · 1 background terminal running · /ps …"
"• Checking files and preparing a response (0s • esc to interrupt) · 1 backgroun…"
" "
" "
"› Ask Codex to do anything "
@@ -110,6 +110,12 @@ impl PendingGuardianReviewStatus {
#[derive(Debug)]
pub(super) struct StatusState {
/// Only the active reasoning item may update the streamed heading.
pub(super) reasoning_item_id: Option<String>,
/// An in-progress snapshot can omit the start of its next live reasoning update.
pub(super) reasoning_resume_turn_id: Option<String>,
/// A restored stream may have missed earlier deltas; use its complete item at finalization.
pub(super) reasoning_recovered_after_refresh: bool,
pub(super) compaction: Option<super::compaction::ActiveCompaction>,
pub(super) current_status: StatusIndicatorState,
pub(super) pending_guardian_review_status: PendingGuardianReviewStatus,
@@ -122,6 +128,9 @@ pub(super) struct StatusState {
impl Default for StatusState {
fn default() -> Self {
Self {
reasoning_item_id: None,
reasoning_resume_turn_id: None,
reasoning_recovered_after_refresh: false,
compaction: None,
current_status: StatusIndicatorState::working(),
pending_guardian_review_status: PendingGuardianReviewStatus::default(),
+63 -13
View File
@@ -5,15 +5,56 @@
use super::*;
impl ChatWidget {
pub(super) fn restore_reasoning_status_header(&mut self) {
if self.reasoning_header.is_none() {
self.reasoning_header = extract_first_bold(&self.reasoning_buffer);
fn latest_summary_line(text: &str) -> Option<String> {
text.lines().rev().find_map(|line| {
let line = line.trim();
if line.is_empty() || line.starts_with("<!--") {
return None;
}
let line = line.trim_start_matches('#').trim();
let line = if let Some(stripped) = line.strip_prefix("**") {
let (bold, trailing) = stripped.split_once("**")?;
format!("{bold}{trailing}")
} else {
line.to_string()
};
(!line.is_empty()).then_some(line)
})
}
impl ChatWidget {
pub(super) fn on_reasoning_item_started(&mut self, id: String) {
if self.status_state.reasoning_resume_turn_id.take().is_some()
&& self.status_state.reasoning_item_id.as_ref() != Some(&id)
{
self.on_agent_reasoning_final();
}
if self.status_state.reasoning_item_id.as_ref() == Some(&id) {
return;
}
self.status_state.reasoning_item_id = Some(id);
self.status_state.reasoning_recovered_after_refresh = false;
self.reasoning_buffer.clear();
self.reasoning_summary_parts.clear();
self.restore_reasoning_status_header();
}
pub(super) fn restore_reasoning_status_header(&mut self) {
if self.safety_buffering_is_waiting()
|| self.unified_exec_wait_streak.is_some()
|| self.status_state.compaction.is_some()
|| !self.status_state.pending_guardian_review_status.is_empty()
{
return;
}
self.reasoning_header =
latest_summary_line(&self.reasoning_buffer).or(self.reasoning_header.take());
if let Some(header) = self.reasoning_header.clone() {
self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Thinking;
self.set_status_header(header);
} else if self.bottom_pane.is_task_running() {
} else if self.bottom_pane.is_task_running()
|| self.status_state.current_status.is_guardian_review()
{
self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Working;
self.set_status_header(String::from("Working"));
}
@@ -230,9 +271,7 @@ impl ChatWidget {
}
pub(super) fn on_agent_reasoning_delta(&mut self, delta: String) {
// For reasoning deltas, do not stream to history. Accumulate the
// current reasoning block and extract the first bold element
// (between **/**) as the chunk header. Show this header as status.
// Accumulate the current reasoning block for history and activity text.
self.reasoning_buffer.push_str(&delta);
if self.safety_buffering_is_waiting() {
@@ -244,11 +283,14 @@ impl ChatWidget {
return;
}
if self.reasoning_header.is_none() {
self.reasoning_header = extract_first_bold(&self.reasoning_buffer);
if !self.status_state.pending_guardian_review_status.is_empty() {
return;
}
self.reasoning_header =
latest_summary_line(&self.reasoning_buffer).or(self.reasoning_header.take());
let Some(header) = self.reasoning_header.as_deref() else {
// Fallback while we don't yet have a bold header: leave existing header as-is.
// No usable summary has arrived yet.
return;
};
@@ -279,13 +321,22 @@ impl ChatWidget {
self.reasoning_summary_parts
.push(std::mem::take(&mut self.reasoning_buffer));
}
self.reasoning_header = self
.reasoning_summary_parts
.iter()
.rev()
.find_map(|part| latest_summary_line(part))
.or(self.reasoning_header.take());
if !self.reasoning_summary_parts.is_empty() {
let reasoning_parts = std::mem::take(&mut self.reasoning_summary_parts);
let cell = history_cell::new_reasoning_summary_block(reasoning_parts, &self.config.cwd);
self.add_boxed_history(cell);
}
self.reasoning_buffer.clear();
self.reasoning_header = None;
// Keep the last useful summary through tools and later empty items.
self.status_state.reasoning_item_id = None;
self.status_state.reasoning_resume_turn_id = None;
self.status_state.reasoning_recovered_after_refresh = false;
self.reasoning_summary_parts.clear();
self.request_redraw();
}
@@ -296,7 +347,6 @@ impl ChatWidget {
self.reasoning_summary_parts
.push(std::mem::take(&mut self.reasoning_buffer));
}
self.reasoning_header = None;
}
pub(super) fn on_stream_error(&mut self, message: String, additional_details: Option<String>) {
+2
View File
@@ -267,6 +267,8 @@ mod plugin_catalog;
mod popups_and_settings;
#[path = "tests/rate_limit_recovery_tests.rs"]
mod rate_limit_recovery_tests;
#[path = "tests/reasoning_status_tests.rs"]
mod reasoning_status_tests;
#[path = "tests/replay_render_tests.rs"]
mod replay_render_tests;
mod review_mode;
@@ -532,7 +532,30 @@ pub(super) fn handle_agent_message_delta(chat: &mut ChatWidget, delta: impl Into
);
}
pub(super) fn handle_agent_reasoning_started(chat: &mut ChatWidget, id: impl Into<String>) {
chat.handle_server_notification(
ServerNotification::ItemStarted(ItemStartedNotification {
thread_id: thread_id(chat),
turn_id: chat
.turn_lifecycle
.last_turn_id
.clone()
.unwrap_or_else(|| "turn-1".to_string()),
started_at_ms: 0,
item: AppServerThreadItem::Reasoning {
id: id.into(),
summary: Vec::new(),
content: Vec::new(),
},
}),
/*replay_kind*/ None,
);
}
pub(super) fn handle_agent_reasoning_delta(chat: &mut ChatWidget, delta: impl Into<String>) {
if chat.status_state.reasoning_item_id.is_none() {
handle_agent_reasoning_started(chat, "reasoning-1");
}
chat.handle_server_notification(
ServerNotification::ReasoningSummaryTextDelta(ReasoningSummaryTextDeltaNotification {
thread_id: thread_id(chat),
@@ -550,6 +573,9 @@ pub(super) fn handle_agent_reasoning_delta(chat: &mut ChatWidget, delta: impl In
}
pub(super) fn handle_agent_reasoning_final(chat: &mut ChatWidget) {
if chat.status_state.reasoning_item_id.is_none() {
handle_agent_reasoning_started(chat, "reasoning-1");
}
chat.handle_server_notification(
ServerNotification::ItemCompleted(ItemCompletedNotification {
thread_id: thread_id(chat),
@@ -1386,6 +1386,8 @@ async fn live_reasoning_summary_is_not_rendered_twice_when_item_completes() {
);
let _ = drain_insert_history(&mut rx);
handle_agent_reasoning_started(&mut chat, "reasoning-1");
chat.handle_server_notification(
ServerNotification::ReasoningSummaryTextDelta(ReasoningSummaryTextDeltaNotification {
thread_id: "thread-1".to_string(),
@@ -1443,6 +1445,8 @@ async fn live_reasoning_summary_drops_empty_parts_without_losing_content() {
);
let _ = drain_insert_history(&mut rx);
handle_agent_reasoning_started(&mut chat, "reasoning-1");
for (summary_index, delta) in [
(0, "**Plan**\n\ndone"),
(1, "**Checking tests**\n\n<!-- -->"),
@@ -0,0 +1,317 @@
//! Reasoning activity retains the latest usable line through empty items and status-row replacement.
use super::*;
use pretty_assertions::assert_eq;
fn delta(chat: &mut ChatWidget, id: &str, text: &str) {
chat.handle_server_notification(
ServerNotification::ReasoningSummaryTextDelta(ReasoningSummaryTextDeltaNotification {
thread_id: "thread-1".to_string(),
turn_id: "turn-1".to_string(),
item_id: id.to_string(),
delta: text.to_string(),
summary_index: 0,
}),
/*replay_kind*/ None,
);
}
fn complete(chat: &mut ChatWidget, id: &str) {
chat.handle_server_notification(
ServerNotification::ItemCompleted(ItemCompletedNotification {
thread_id: "thread-1".to_string(),
turn_id: "turn-1".to_string(),
completed_at_ms: 0,
item: AppServerThreadItem::Reasoning {
id: id.to_string(),
summary: Vec::new(),
content: Vec::new(),
},
}),
/*replay_kind*/ None,
);
}
#[tokio::test]
async fn reasoning_status_accepts_bold_text_with_a_plain_suffix() {
let (mut chat, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
chat.on_task_started();
handle_agent_reasoning_started(&mut chat, "reasoning");
delta(&mut chat, "reasoning", "**Checking tests");
let before_close = chat
.bottom_pane
.status_widget()
.unwrap()
.header()
.to_string();
delta(&mut chat, "reasoning", "**: running suite");
let after_close = chat
.bottom_pane
.status_widget()
.unwrap()
.header()
.to_string();
insta::assert_debug_snapshot!(vec![before_close, after_close], @r###"
[
"Working",
"Checking tests: running suite",
]
"###);
}
#[tokio::test]
async fn reasoning_status_tracks_items_and_restores_after_tool_activity() {
let (mut chat, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
chat.on_task_started();
let mut headers = Vec::new();
let capture = |chat: &ChatWidget, headers: &mut Vec<String>| {
headers.push(
chat.bottom_pane
.status_widget()
.expect("running status")
.header()
.to_string(),
);
};
handle_agent_reasoning_started(&mut chat, "first");
delta(&mut chat, "first", "**Researching backend");
capture(&chat, &mut headers);
delta(&mut chat, "first", " freshness**");
capture(&chat, &mut headers);
complete(&mut chat, "first");
delta(&mut chat, "first", "**Late old header**");
capture(&chat, &mut headers);
// A tool recreates the row after streamed commentary has hidden it.
chat.bottom_pane.hide_status_indicator();
begin_unified_exec_startup(&mut chat, "tool-1", "process-1", "sleep 2");
capture(&chat, &mut headers);
handle_agent_reasoning_started(&mut chat, "second");
capture(&chat, &mut headers);
chat.handle_server_notification(
ServerNotification::ReasoningSummaryPartAdded(
codex_app_server_protocol::ReasoningSummaryPartAddedNotification {
thread_id: "thread-1".to_string(),
turn_id: "turn-1".to_string(),
item_id: "first".to_string(),
summary_index: 1,
},
),
/*replay_kind*/ None,
);
complete(&mut chat, "first");
delta(&mut chat, "first", "**Stale heading**");
delta(&mut chat, "second", "No summary heading is available.");
capture(&chat, &mut headers);
delta(&mut chat, "second", "\n**Preparing evidence report**");
capture(&chat, &mut headers);
insta::assert_debug_snapshot!(headers);
let mut timer = crate::status_indicator_widget::StatusTimer::default();
timer.pause_at(std::time::Instant::now());
timer.reset(std::time::Duration::from_secs(/*secs*/ 42));
for width in [80, 40] {
let mut terminal =
ratatui::Terminal::new(ratatui::backend::TestBackend::new(width, /*height*/ 1))
.expect("terminal");
terminal
.draw(|frame| {
chat.bottom_pane
.status_widget()
.expect("running status")
.with_timer(&timer)
.render(frame.area(), frame.buffer_mut());
})
.expect("render reasoning status");
assert_chatwidget_snapshot!(
format!("reasoning_activity_row_{width}"),
terminal.backend()
);
}
chat.on_interrupted_turn(TurnAbortReason::Interrupted);
delta(&mut chat, "second", "**After interruption**");
assert_eq!(chat.status_state.reasoning_item_id, None);
assert_eq!(chat.reasoning_header, None);
assert!(!chat.bottom_pane.status_indicator_visible());
chat.on_task_started();
assert_eq!(
chat.bottom_pane.status_widget().unwrap().header(),
"Working"
);
}
#[tokio::test]
async fn voice_handoff_preserves_typed_reasoning_and_ignores_private_items() {
let (mut chat, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
chat.on_task_started();
handle_agent_reasoning_started(&mut chat, "typed");
delta(&mut chat, "typed", "**Checking repository**");
chat.remember_realtime_delegated_reasoning_turn("turn-1");
handle_agent_reasoning_started(&mut chat, "private");
delta(&mut chat, "private", "**Private voice reasoning**");
complete(&mut chat, "private");
assert_eq!(
chat.status_state.reasoning_item_id.as_deref(),
Some("typed")
);
assert_eq!(
chat.bottom_pane.status_widget().unwrap().header(),
"Checking repository"
);
delta(&mut chat, "typed", "\n**Verifying changes**");
assert_eq!(
chat.bottom_pane.status_widget().unwrap().header(),
"Verifying changes"
);
complete(&mut chat, "typed");
assert_eq!(chat.status_state.reasoning_item_id, None);
}
#[tokio::test]
async fn reasoning_status_preserves_an_explicit_wait_and_restores_the_heading() {
let (mut chat, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
chat.on_task_started();
chat.status_state
.pending_guardian_review_status
.start_or_update("review-1".to_string(), "Checking a command".to_string());
chat.set_status_header("Reviewing approval request".to_string());
handle_agent_reasoning_started(&mut chat, "first");
delta(&mut chat, "first", "**Choosing the missing-data fix**");
complete(&mut chat, "first");
assert_eq!(
chat.bottom_pane.status_widget().unwrap().header(),
"Reviewing approval request"
);
chat.status_state
.pending_guardian_review_status
.finish("review-1");
chat.restore_reasoning_status_header();
assert_eq!(
chat.bottom_pane.status_widget().unwrap().header(),
"Choosing the missing-data fix"
);
}
#[tokio::test]
async fn reasoning_status_replay_retains_last_usable_heading() {
let (mut chat, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
chat.on_task_started();
for (id, summary, expected) in [
(
"first",
vec!["**First heading**".to_string()],
"First heading",
),
(
"second",
vec!["**Second heading**".to_string()],
"Second heading",
),
("third", Vec::new(), "Second heading"),
] {
chat.handle_thread_item(
AppServerThreadItem::Reasoning {
id: id.to_string(),
summary,
content: Vec::new(),
},
"turn-1".to_string(),
ThreadItemRenderSource::Replay(ReplayKind::ThreadSnapshot),
);
assert_eq!(chat.bottom_pane.status_widget().unwrap().header(), expected);
}
}
#[tokio::test]
async fn reasoning_status_accepts_plain_lines_and_ignores_empty_sections() {
let (mut chat, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
chat.on_task_started();
handle_agent_reasoning_started(&mut chat, "first");
delta(
&mut chat,
"first",
"# Checking files\n<!-- progress -->\nPreparing response",
);
assert_eq!(
chat.bottom_pane.status_widget().unwrap().header(),
"Preparing response"
);
complete(&mut chat, "first");
handle_agent_reasoning_started(&mut chat, "second");
delta(&mut chat, "second", "<!-- no public update -->");
assert_eq!(
chat.bottom_pane.status_widget().unwrap().header(),
"Preparing response"
);
delta(&mut chat, "second", "\n**Verifying results**");
assert_eq!(
chat.bottom_pane.status_widget().unwrap().header(),
"Verifying results"
);
}
#[tokio::test]
async fn completed_reasoning_stays_in_expanded_transcript_for_live_and_replay() {
let mut renders = Vec::new();
for replay in [false, true] {
let (mut chat, mut rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
chat.on_task_started();
for (id, summary) in [
("first", "**Inspecting repository structure**"),
("second", "Mapping the app structure"),
(
"third",
"**Tracing terminal components**\n\nThe playback clock preserves elapsed time.",
),
] {
if replay {
chat.handle_thread_item(
AppServerThreadItem::Reasoning {
id: id.to_string(),
summary: vec![summary.to_string()],
content: Vec::new(),
},
"turn-1".to_string(),
ThreadItemRenderSource::Replay(ReplayKind::ThreadSnapshot),
);
} else {
handle_agent_reasoning_started(&mut chat, id);
delta(&mut chat, id, summary);
complete(&mut chat, id);
}
}
let mut compact = Vec::new();
let mut expanded = Vec::new();
while let Ok(event) = rx.try_recv() {
if let AppEvent::InsertHistoryCell(cell) = event {
compact.extend(cell.display_lines(/*width*/ 80));
expanded.extend(cell.transcript_lines(/*width*/ 80));
assert!(cell.raw_lines().is_empty());
}
}
let rendered = format!(
"Compact history:\n{}\nLive status:\n{}\nExpanded transcript:\n{}",
ratatui::text::Text::from(compact),
chat.bottom_pane.status_widget().unwrap().header(),
ratatui::text::Text::from(expanded),
);
renders.push(rendered);
}
assert_eq!(renders[0], renders[1]);
insta::assert_snapshot!(renders[0], @r"
Compact history:
Live status:
The playback clock preserves elapsed time.
Expanded transcript:
• Inspecting repository structure
• Mapping the app structure
• The playback clock preserves elapsed time.
");
}
@@ -0,0 +1,14 @@
---
source: tui/src/chatwidget/tests/reasoning_status_tests.rs
assertion_line: 84
expression: headers
---
[
"Working",
"Researching backend freshness",
"Researching backend freshness",
"Researching backend freshness",
"Researching backend freshness",
"No summary heading is available.",
"Preparing evidence report",
]
@@ -4744,29 +4744,29 @@ async fn regular_commit_tick_clears_orphaned_plan_stream_tail() {
}
#[tokio::test]
async fn reasoning_delta_redraws_only_when_header_becomes_visible() {
async fn reasoning_delta_redraws_when_latest_usable_line_changes() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
let (frame_requester, mut draw_rx) = FrameRequester::test_channel();
chat.frame_requester = frame_requester;
chat.on_agent_reasoning_delta("still looking".to_string());
chat.on_agent_reasoning_delta("**Checking".to_string());
assert!(matches!(
draw_rx.try_recv(),
Err(tokio::sync::mpsc::error::TryRecvError::Empty)
));
assert_eq!(chat.reasoning_header, None);
chat.on_agent_reasoning_delta(" **Checking".to_string());
assert!(matches!(
draw_rx.try_recv(),
Err(tokio::sync::mpsc::error::TryRecvError::Empty)
));
chat.on_agent_reasoning_delta(" files**".to_string());
assert!(draw_rx.try_recv().is_ok());
assert_eq!(chat.reasoning_header.as_deref(), Some("Checking files"));
chat.on_agent_reasoning_delta(" and preparing a response".to_string());
chat.on_agent_reasoning_delta("\nPreparing a response".to_string());
assert!(draw_rx.try_recv().is_ok());
assert_eq!(
chat.reasoning_header.as_deref(),
Some("Preparing a response")
);
chat.on_agent_reasoning_delta("".to_string());
assert!(matches!(
draw_rx.try_recv(),
Err(tokio::sync::mpsc::error::TryRecvError::Empty)
@@ -4813,7 +4813,7 @@ async fn reasoning_delta_restores_recreated_status_indicator_header() {
.bottom_pane
.status_widget()
.expect("status indicator should be recreated");
assert_eq!(status.header(), "Working");
assert_eq!(status.header(), "Checking files");
chat.on_agent_reasoning_delta(" and preparing a response".to_string());
@@ -4821,7 +4821,7 @@ async fn reasoning_delta_restores_recreated_status_indicator_header() {
.bottom_pane
.status_widget()
.expect("status indicator should remain visible");
assert_eq!(status.header(), "Checking files");
assert_eq!(status.header(), "Checking files and preparing a response");
let width: u16 = 80;
let height = chat.desired_height(width);
+2 -2
View File
@@ -142,12 +142,12 @@ impl ChatWidget {
status.details_max_lines,
);
} else if self.status_state.current_status.is_guardian_review() {
self.set_status_header(String::from("Working"));
self.restore_reasoning_status_header();
}
} else if self.status_state.pending_guardian_review_status.is_empty()
&& self.status_state.current_status.is_guardian_review()
{
self.set_status_header(String::from("Working"));
self.restore_reasoning_status_header();
}
if ev.status == GuardianAssessmentStatus::Approved {
@@ -103,6 +103,8 @@ impl ChatWidget {
self.reasoning_summary_parts.clear();
self.reasoning_buffer.clear();
self.reasoning_header = None;
self.status_state.reasoning_item_id = None;
self.status_state.reasoning_resume_turn_id = None;
self.set_ambient_pet_notification(
crate::pets::PetNotificationKind::Running,
/*body*/ None,
@@ -116,6 +118,9 @@ impl ChatWidget {
completion: Option<history_cell::FinalMessageSeparator>,
from_replay: bool,
) {
if self.status_state.reasoning_resume_turn_id.is_some() {
self.on_agent_reasoning_final();
}
self.input_queue.submit_pending_steers_after_interrupt = false;
let sanitized_last_agent_message = last_agent_message.as_deref().map(|message| {
parse_assistant_markdown(message, self.config.cwd.as_path()).visible_markdown
@@ -174,6 +179,9 @@ impl ChatWidget {
// Mark task stopped and request redraw now that all content is in history.
self.clear_context_compaction();
self.status_state.pending_status_indicator_restore = false;
self.status_state.reasoning_item_id = None;
self.status_state.reasoning_resume_turn_id = None;
self.reasoning_header = None;
self.input_queue.user_turn_pending_start = false;
self.clear_active_hook_cell();
self.clear_guardian_review_status();
@@ -314,6 +322,12 @@ impl ChatWidget {
/// This does not clear MCP startup tracking, because MCP startup can overlap with turn cleanup
/// and should continue to drive the bottom-pane running indicator while it is in progress.
pub(super) fn finalize_turn(&mut self) {
if self.status_state.reasoning_resume_turn_id.is_some() {
self.on_agent_reasoning_final();
}
self.status_state.reasoning_item_id = None;
self.status_state.reasoning_resume_turn_id = None;
self.reasoning_header = None;
self.clear_context_compaction();
self.clear_safety_buffering();
// Drop preview-only stream tail content on any termination path before