Smooth transitions between TUI reasoning headings (#64202)

## Why

Streaming reasoning summaries can replace the status heading before the
current line finishes, making fast updates hard to read.

## What changed

With shimmer active, sample the latest usable reasoning heading every
3.5 seconds while letting the visible line finish as its text arrives.
Fade out the previous heading and reveal the next one across the visible
terminal columns. Retry messages still appear immediately, and reduced
motion and unsupported terminals keep the static display.

Use the same prepared frame for layout and rendering so the status row
can reflow when the heading changes.

## Testing

Cover chunks that finish one heading and start another before a draw,
delayed frames, and split Markdown bold markers. Snapshot the transition
in light and dark themes and verify that hook status text reflows at the
fade boundary.

GitOrigin-RevId: 63c579602f030f461ac81c4841106b29755710b1
This commit is contained in:
Felipe Coury
2026-11-26 19:16:52 +00:00
committed by copyberry
parent d7ebabf7b7
commit 58cb1ccf8d
16 changed files with 490 additions and 111 deletions
+9 -1
View File
@@ -281,6 +281,7 @@ pub(crate) use chat_composer::ShellPrefixHandling;
pub(crate) use chat_composer_history::HistoryEntry;
use crate::status_indicator_widget::StatusDetailsCapitalization;
use crate::status_indicator_widget::StatusHeader;
use crate::status_indicator_widget::StatusIndicatorWidget;
#[cfg(test)]
pub(crate) use experimental_features_view::ExperimentalFeatureItem;
@@ -731,6 +732,10 @@ impl BottomPane {
self.status.as_ref()
}
pub(crate) fn status_widget_mut(&mut self) -> Option<&mut StatusIndicatorWidget> {
self.status.as_mut()
}
pub(crate) fn status_elapsed(&self) -> Option<Duration> {
self.is_task_running
.then(|| self.status_timer.elapsed_at(Instant::now()))
@@ -1167,6 +1172,9 @@ impl BottomPane {
fn pre_draw_tick_at(&mut self, now: Instant) {
self.composer.sync_popups();
self.maybe_show_delayed_prompts_at(now);
if let Some(status) = &mut self.status {
status.prepare_frame(now);
}
self.tick_active_view(now);
self.schedule_active_view_frame();
}
@@ -1371,7 +1379,7 @@ impl BottomPane {
/// was updated and requested a redraw.
pub(crate) fn update_status(
&mut self,
header: String,
header: impl Into<StatusHeader>,
details: Option<String>,
details_capitalization: StatusDetailsCapitalization,
details_max_lines: usize,
+3 -2
View File
@@ -252,6 +252,7 @@ use crate::status::RateLimitSnapshotDisplay;
use crate::status::remote_connection::RemoteConnectionStatus;
use crate::status_indicator_widget::STATUS_DETAILS_DEFAULT_MAX_LINES;
use crate::status_indicator_widget::StatusDetailsCapitalization;
use crate::status_indicator_widget::StatusHeader;
use crate::text_formatting::truncate_text;
use crate::tui::FrameRequester;
mod activity_groups;
@@ -679,8 +680,8 @@ pub(crate) struct ChatWidget {
interrupts: InterruptManager,
// Accumulates the current reasoning block text to extract a header
reasoning_buffer: String,
// Caches the first completed bold header so later deltas do not rescan the whole block.
reasoning_header: Option<String>,
// Keep the last usable heading through tools and empty reasoning items.
reasoning_header: Option<StatusHeader>,
// Preserves reasoning-summary part boundaries for transcript-only recording.
reasoning_summary_parts: Vec<String>,
status_state: StatusState,
@@ -39,7 +39,7 @@ pub(super) fn on_metadata(chat: &mut ChatWidget, notification: TurnModerationMet
chat.clear_safety_buffering();
chat.bottom_pane.ensure_status_indicator();
chat.set_status_header(
"I can’t help with this request. Preparing alternative suggestions…".into(),
"I can’t help with this request. Preparing alternative suggestions…".to_owned(),
);
}
}
@@ -16,7 +16,7 @@ impl ChatWidget {
/// requested a redraw.
pub(super) fn set_status(
&mut self,
header: String,
header: impl Into<StatusHeader>,
details: Option<String>,
details_capitalization: StatusDetailsCapitalization,
details_max_lines: usize,
@@ -27,12 +27,12 @@ impl ChatWidget {
&& self.status_state.retry_status_header.is_none()
{
(
compaction::COMPACTION_HEADER.to_string(),
compaction::COMPACTION_HEADER.to_string().into(),
Some(compaction::COMPACTION_DETAILS.to_string()),
STATUS_DETAILS_DEFAULT_MAX_LINES,
)
} else {
(header, details, details_max_lines)
(header.into(), details, details_max_lines)
};
let details = details
.filter(|details| !details.is_empty())
@@ -46,7 +46,7 @@ impl ChatWidget {
}
});
self.status_state.set_status(StatusIndicatorState {
header: header.clone(),
header: header.text.clone(),
details: details.clone(),
details_max_lines,
});
@@ -75,7 +75,7 @@ impl ChatWidget {
/// Convenience wrapper around [`Self::set_status`];
/// updates the status indicator header and clears any existing details, returning whether the
/// visible status indicator requested a redraw.
pub(super) fn set_status_header(&mut self, header: String) -> bool {
pub(super) fn set_status_header(&mut self, header: impl Into<StatusHeader>) -> bool {
self.set_status(
header,
/*details*/ None,
+27 -27
View File
@@ -13,24 +13,23 @@ fn streamed_message_matches_completed(streamed: &str, completed: &str) -> bool {
streamed == completed || streamed.strip_suffix('\n') == Some(completed)
}
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 {
/// Finish the visible line and remember the latest one for the next sample.
fn refresh_reasoning_heading(&mut self) -> bool {
let item_id = self.status_state.reasoning_item_id.as_deref();
let part = self.reasoning_summary_parts.len();
if let Some(row) = self.bottom_pane.status_widget_mut() {
row.extend_reasoning(item_id, part, &self.reasoning_buffer);
}
if let Some(heading) = StatusHeader::from_summary(item_id, part, &self.reasoning_buffer)
&& self.reasoning_header.as_ref() != Some(&heading)
{
self.reasoning_header = Some(heading);
return true;
}
false
}
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)
@@ -54,8 +53,7 @@ impl ChatWidget {
{
return;
}
self.reasoning_header =
latest_summary_line(&self.reasoning_buffer).or(self.reasoning_header.take());
self.refresh_reasoning_heading();
if let Some(header) = self.reasoning_header.clone() {
self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Thinking;
self.set_status_header(header);
@@ -457,28 +455,28 @@ impl ChatWidget {
return;
}
self.reasoning_header =
latest_summary_line(&self.reasoning_buffer).or(self.reasoning_header.take());
let Some(header) = self.reasoning_header.as_deref() else {
let changed = self.refresh_reasoning_heading();
let Some(header) = &self.reasoning_header else {
// No usable summary has arrived yet.
return;
};
let status = &self.status_state.current_status;
if self.status_state.terminal_title_status_kind == TerminalTitleStatusKind::Thinking
&& status.header == header
if !changed
&& self.status_state.terminal_title_status_kind == TerminalTitleStatusKind::Thinking
&& status.header == header.text
&& status.details.is_none()
&& status.details_max_lines == STATUS_DETAILS_DEFAULT_MAX_LINES
&& self
.bottom_pane
.status_widget()
.is_none_or(|status| status.header() == header)
.is_none_or(|status| status.header() == header.text)
{
return;
}
// Update the shimmer header to the extracted reasoning chunk header.
let header = header.to_string();
let header = header.clone();
self.status_state.terminal_title_status_kind = TerminalTitleStatusKind::Thinking;
if !self.set_status_header(header) {
self.request_redraw();
@@ -491,11 +489,13 @@ impl ChatWidget {
self.reasoning_summary_parts
.push(std::mem::take(&mut self.reasoning_buffer));
}
let item_id = self.status_state.reasoning_item_id.as_deref();
self.reasoning_header = self
.reasoning_summary_parts
.iter()
.enumerate()
.rev()
.find_map(|part| latest_summary_line(part))
.find_map(|(index, part)| StatusHeader::from_summary(item_id, index, part))
.or(self.reasoning_header.take());
if !self.reasoning_summary_parts.is_empty() {
let reasoning_parts = std::mem::take(&mut self.reasoning_summary_parts);
@@ -33,6 +33,66 @@ fn complete(chat: &mut ChatWidget, id: &str) {
);
}
fn assert_heading(chat: &mut ChatWidget, start: Instant, times_ms: &[u64], expected: &str) {
let row = chat.bottom_pane.status_widget_mut().unwrap();
for &ms in times_ms {
let frame = row.render_heading_at(start + Duration::from_millis(ms));
assert_eq!(frame, expected, "at {ms} ms");
}
}
#[tokio::test]
async fn finishes_the_visible_heading_when_the_next_heading_arrives_before_a_draw() {
for chunks in [
&["ing files", "\nRunning tests"][..],
&["ing files\nRunning tests"],
// A second line with the same prefix is still a distinct heading.
&["ing files\nReading files", " again", "\nRunning tests"],
] {
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", "Starting");
delta(&mut chat, "first", "\nRead");
let start = Instant::now();
assert_heading(&mut chat, start, &[0], "Read");
for chunk in chunks {
delta(&mut chat, "first", chunk);
}
assert_eq!(
chat.bottom_pane.status_widget().unwrap().header(),
"Running tests"
);
// The first draw after the tick is 30 ms late. The second tick is still at 7000 ms.
assert_heading(&mut chat, start, &[32, 3499, 3530], "Reading files");
delta(&mut chat, "first", "\nEditing");
assert_heading(&mut chat, start, &[4270, 6999], "Running tests");
delta(&mut chat, "first", "\nTesting");
assert_heading(&mut chat, start, &[7000], "Running tests");
assert_heading(&mut chat, start, &[7740], "Testing");
delta(&mut chat, "first", "\nFinishing");
chat.on_stream_error("Reconnecting".into(), /*additional_details*/ None);
assert_heading(&mut chat, start, &[7800, 11000], "Reconnecting");
}
}
#[tokio::test]
async fn a_split_bold_opener_waits_for_the_heading_text() {
let (mut chat, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
chat.on_task_started();
handle_agent_reasoning_started(&mut chat, "first");
let start = Instant::now();
for (ms, chunk) in [(0, "*"), (32, "*Reading files*")] {
delta(&mut chat, "first", chunk);
assert_heading(&mut chat, start, &[ms], "Working");
}
// Repeating Working between draws should preserve the handoff from that label.
chat.restore_reasoning_status_header();
delta(&mut chat, "first", "*");
assert_heading(&mut chat, start, &[64], "Working");
assert_heading(&mut chat, start, &[1000], "Reading files");
}
#[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;
@@ -5392,13 +5392,16 @@ async fn reasoning_delta_redraws_when_latest_usable_line_changes() {
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"));
assert_eq!(
chat.reasoning_header.as_ref().unwrap().text,
"Checking files"
);
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.reasoning_header.as_ref().unwrap().text,
"Preparing a response"
);
chat.on_agent_reasoning_delta("".to_string());
assert!(matches!(
@@ -5423,7 +5426,10 @@ async fn reasoning_delta_does_not_double_schedule_visible_status_redraw() {
chat.on_agent_reasoning_delta("**Checking files**".to_string());
assert_eq!(chat.reasoning_header.as_deref(), Some("Checking files"));
assert_eq!(
chat.reasoning_header.as_ref().unwrap().text,
"Checking files"
);
assert!(draw_rx.try_recv().is_ok());
assert!(matches!(
draw_rx.try_recv(),
+9 -1
View File
@@ -107,6 +107,7 @@ async fn persisted_default_loads_and_renders_without_animation() -> anyhow::Resu
use crate::app_event_sender::AppEventSender;
use crate::legacy_core::config::ConfigBuilder;
use crate::render::renderable::Renderable;
use crate::status_indicator_widget::StatusHeader;
use crate::status_indicator_widget::StatusIndicatorWidget;
use crate::status_indicator_widget::StatusTimer;
use crate::tui::FrameRequester;
@@ -135,7 +136,14 @@ async fn persisted_default_loads_and_renders_without_animation() -> anyhow::Resu
config.animations,
Default::default(),
);
status.update_header("Reading the terminal output".into());
status.update_header(
StatusHeader::from_summary(
/*item_id*/ None,
/*part*/ 0,
"Reading the terminal output",
)
.unwrap(),
);
let mut timer = StatusTimer::default();
timer.pause_at(std::time::Instant::now());
let mut terminal = Terminal::new(TestBackend::new(/*width*/ 60, /*height*/ 1))?;
@@ -6,6 +6,9 @@ expression: headers
[
Span::from("שלום עולם").dim(),
],
[
Span::from("Checking שלום").dim(),
],
[
Span::from("Checking ש\u{5b8}\u{5c1}לו\u{5b9}ם (test.rs) 123").dim(),
],
@@ -9,17 +9,24 @@ dark Working 1350ms: [128, 128, 128, 128, 144, 198, 238]
dark Working 3600ms: [128, 128, 128, 128, 128, 128, 128]
dark Working 5100ms: [128, 156, 212, 240, 212, 156, 128]
dark Preparing bootstrap diagnostics 0ms: [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]
dark Preparing bootstrap diagnostics 850ms: [128, 128, 128, 132, 175, 226, 237, 198, 145, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]
dark Preparing bootstrap diagnostics 1100ms: [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 159, 213, 240, 213, 159, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]
dark Preparing bootstrap diagnostics 1350ms: [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 145, 198, 237, 226, 175, 132, 128, 128, 128]
dark Preparing bootstrap diagnostics 850ms: [153, 174, 196, 217, 232, 239, 237, 227, 209, 188, 165, 146, 133, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]
dark Preparing bootstrap diagnostics 1100ms: [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 131, 143, 161, 184, 206, 224, 236, 239, 234, 220, 200, 178, 156, 139, 129, 128, 128, 128, 128]
dark Preparing bootstrap diagnostics 1350ms: [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 135, 150, 171, 193, 214]
dark Preparing bootstrap diagnostics 3600ms: [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]
dark Preparing bootstrap diagnostics 5100ms: [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 159, 213, 240, 213, 159, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]
dark Preparing bootstrap diagnostics 5100ms: [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 131, 143, 161, 184, 206, 224, 236, 239, 234, 220, 200, 178, 156, 139, 129, 128, 128, 128, 128]
dark 界é界 0ms: [128, 128, 128]
dark 界é界 850ms: [198, 129, 128]
dark 界é界 1100ms: [184, 240, 184]
dark 界é界 1350ms: [128, 129, 198]
dark 界é界 3600ms: [128, 128, 128]
dark 界é界 5100ms: [184, 240, 184]
dark handoff 0ms: "Working" [128]
dark handoff 50ms: "Working" [72]
dark handoff 160ms: "Re " [217, 94, 16, 16, 16, 16, 16, 16, 16, 16, 16]
dark handoff 370ms: "Reading " [128, 128, 136, 181, 228, 170, 52, 16, 16, 16, 16]
dark handoff 740ms: "Reading e\u{301}界🧪" [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 186]
dark handoff 1000ms: "Reading e\u{301}界🧪" [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]
dark handoff 4370ms: "Reading e\u{301}界🧪" [128, 128, 136, 181, 228, 237, 199, 148, 128, 128, 128]
light Working 0ms: [128, 128, 128, 128, 128, 128, 128]
light Working 850ms: [17, 57, 111, 128, 128, 128, 128]
light Working 1100ms: [128, 100, 44, 16, 44, 100, 128]
@@ -27,14 +34,21 @@ light Working 1350ms: [128, 128, 128, 128, 111, 57, 17]
light Working 3600ms: [128, 128, 128, 128, 128, 128, 128]
light Working 5100ms: [128, 100, 44, 16, 44, 100, 128]
light Preparing bootstrap diagnostics 0ms: [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]
light Preparing bootstrap diagnostics 850ms: [128, 128, 128, 123, 80, 29, 18, 57, 110, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]
light Preparing bootstrap diagnostics 1100ms: [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 127, 96, 42, 16, 42, 96, 127, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]
light Preparing bootstrap diagnostics 1350ms: [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 110, 57, 18, 29, 80, 123, 128, 128, 128]
light Preparing bootstrap diagnostics 850ms: [102, 81, 59, 38, 23, 16, 18, 28, 46, 67, 90, 109, 122, 127, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]
light Preparing bootstrap diagnostics 1100ms: [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 124, 112, 94, 72, 49, 31, 19, 16, 21, 35, 55, 77, 99, 116, 126, 128, 128, 128, 128]
light Preparing bootstrap diagnostics 1350ms: [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 127, 120, 105, 84, 62, 41]
light Preparing bootstrap diagnostics 3600ms: [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]
light Preparing bootstrap diagnostics 5100ms: [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 127, 96, 42, 16, 42, 96, 127, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]
light Preparing bootstrap diagnostics 5100ms: [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 124, 112, 94, 72, 49, 31, 19, 16, 21, 35, 55, 77, 99, 116, 126, 128, 128, 128, 128]
light 界é界 0ms: [128, 128, 128]
light 界é界 850ms: [57, 126, 128]
light 界é界 1100ms: [72, 16, 72]
light 界é界 1350ms: [128, 126, 57]
light 界é界 3600ms: [128, 128, 128]
light 界é界 5100ms: [72, 16, 72]
light handoff 0ms: "Working" [128]
light handoff 50ms: "Working" [184]
light handoff 160ms: "Re " [38, 161, 240, 240, 240, 240, 240, 240, 240, 240, 240]
light handoff 370ms: "Reading " [128, 128, 119, 74, 27, 85, 203, 240, 240, 240, 240]
light handoff 740ms: "Reading e\u{301}界🧪" [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 69]
light handoff 1000ms: "Reading e\u{301}界🧪" [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128]
light handoff 4370ms: "Reading e\u{301}界🧪" [128, 128, 119, 74, 27, 18, 56, 107, 128, 128, 128]
+79 -16
View File
@@ -37,6 +37,8 @@ use crate::width::display_width;
use crate::wrapping::RtOptions;
use crate::wrapping::word_wrap_lines;
mod header;
pub(crate) use header::StatusHeader;
mod timer;
pub(crate) use timer::StatusTimer;
@@ -46,6 +48,14 @@ use summary_shimmer::summary_shimmer;
pub(crate) const STATUS_DETAILS_DEFAULT_MAX_LINES: usize = 3;
const DETAILS_PREFIX: &str = " └ ";
const HEADING_INTERVAL: Duration = Duration::from_millis(/*millis*/ 3500);
#[derive(Clone, Debug)]
struct HeaderSample {
header: StatusHeader,
outgoing: Option<String>,
next_sample: Option<Instant>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum StatusDetailsCapitalization {
@@ -57,8 +67,10 @@ pub(crate) enum StatusDetailsCapitalization {
#[derive(Clone, Debug)]
pub(crate) struct StatusIndicatorWidget {
/// Animated header text (defaults to "Working").
header: String,
header: StatusHeader,
header_started_at: Instant,
prepared_at: Option<Instant>,
sample: Option<HeaderSample>,
details: Option<String>,
details_max_lines: usize,
/// Optional suffix rendered after the elapsed/interrupt segment.
@@ -99,8 +111,10 @@ impl StatusIndicatorWidget {
effects: codex_config::types::TuiEffects,
) -> Self {
Self {
header: String::from("Working"),
header: String::from("Working").into(),
header_started_at: Instant::now(),
prepared_at: None,
sample: None,
details: None,
details_max_lines: STATUS_DETAILS_DEFAULT_MAX_LINES,
inline_message: None,
@@ -123,12 +137,66 @@ impl StatusIndicatorWidget {
self.effects = tui.effects;
}
fn shimmer_motion(&self) -> MotionMode {
MotionMode::from_animations_enabled(self.animations_enabled && self.effects.shimmer)
}
/// Use the same heading and transition time for layout and painting.
pub(crate) fn prepare_frame(&mut self, now: Instant) {
self.prepared_at = Some(now);
if self.shimmer_motion() == MotionMode::Reduced
|| summary_shimmer::palette(self.header()).is_none()
{
self.sample = None;
return;
}
let sample = self.sample.get_or_insert_with(|| HeaderSample {
header: self.header.clone(),
outgoing: None,
next_sample: None,
});
let due = sample.next_sample.unwrap_or(now);
if !self.header.is_reasoning() || now < due {
return;
}
// Keep the first heading's clock even when a frame is drawn late.
let late = (now.duration_since(due).as_nanos() % HEADING_INTERVAL.as_nanos()) as u64;
sample.next_sample = Some(now + HEADING_INTERVAL - Duration::from_nanos(late));
if sample.header != self.header {
let previous = std::mem::replace(&mut sample.header, self.header.clone());
if previous.text != self.header.text {
sample.outgoing = Some(previous.text);
self.header_started_at = now;
}
}
}
fn header_spans(&self, now: Instant, columns: usize) -> Vec<Span<'static>> {
summary_shimmer(
self.header(),
now.saturating_duration_since(self.header_started_at),
self.shimmer_motion(),
columns,
self.sample.as_ref(),
)
}
/// Update the animated header label (left of the brackets).
pub(crate) fn update_header(&mut self, header: String) {
if self.header != header {
self.header = header;
pub(crate) fn update_header(&mut self, header: impl Into<StatusHeader>) {
let header = header.into();
if !header.is_reasoning() && self.header != header {
self.sample = None;
}
if self.sample.is_none() && self.header.text != header.text {
self.header_started_at = Instant::now();
}
self.header = header;
}
pub(crate) fn extend_reasoning(&mut self, item_id: Option<&str>, part: usize, summary: &str) {
if let Some(sample) = &mut self.sample {
sample.header.extend(item_id, part, summary);
}
}
/// Update the details text shown below the header.
@@ -166,7 +234,7 @@ impl StatusIndicatorWidget {
}
pub(crate) fn header(&self) -> &str {
&self.header
&self.header.text
}
#[cfg(test)]
@@ -224,7 +292,7 @@ impl StatusIndicator<'_> {
// wide Unicode characters, remapped interrupt hints, and elapsed-time text.
fn lines(&self, width: u16) -> Vec<Line<'static>> {
let row = self.row;
let now = Instant::now();
let now = row.prepared_at.unwrap_or_else(Instant::now);
let elapsed_duration = self.timer.display_started_at.map_or_else(
|| self.timer.elapsed_at(now),
|started_at| now.saturating_duration_since(started_at),
@@ -232,23 +300,18 @@ impl StatusIndicator<'_> {
let pretty_elapsed = fmt_elapsed_compact(elapsed_duration.as_secs());
let progress =
MotionMode::from_animations_enabled(row.animations_enabled && row.effects.progress);
let shimmer =
MotionMode::from_animations_enabled(row.animations_enabled && row.effects.shimmer);
let mut spans = Vec::with_capacity(5);
let mut label_columns = usize::from(width);
if let Some(indicator) = activity_indicator(
Some(self.timer.last_resume_at),
progress,
ReducedMotionIndicator::Hidden,
) {
label_columns = label_columns.saturating_sub(indicator.width() + 1);
spans.push(indicator);
spans.push(" ".into());
}
spans.extend(summary_shimmer(
&row.header,
now.saturating_duration_since(row.header_started_at),
shimmer,
));
spans.extend(row.header_spans(now, label_columns));
if !spans.is_empty() {
spans.push(" ".into());
}
@@ -306,7 +369,7 @@ impl Renderable for StatusIndicator<'_> {
let interval_ms = if self.row.animations_enabled
&& (self.row.effects.progress
|| (self.row.effects.shimmer
&& !contains_rtl_or_arabic_number(&self.row.header)))
&& !contains_rtl_or_arabic_number(self.row.header())))
{
32
} else {
@@ -5,6 +5,76 @@ use crate::app_event::AppEvent;
use crate::terminal_palette::with_test_default_colors;
use crate::terminal_probe::DefaultColors;
impl StatusIndicatorWidget {
pub(crate) fn render_heading_at(&mut self, now: Instant) -> String {
with_test_default_colors(
DefaultColors {
fg: (240, 240, 240),
bg: (16, 16, 16),
},
|| {
self.prepare_frame(now);
Line::from(self.header_spans(now, /*columns*/ 80)).to_string()
},
)
}
}
#[test]
fn hook_status_reflows_at_the_prepared_frame() {
with_test_default_colors(
DefaultColors {
fg: (240, 240, 240),
bg: (16, 16, 16),
},
|| {
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
let mut row = StatusIndicatorWidget::new(
AppEventSender::new(tx),
FrameRequester::test_dummy(),
/*animations_enabled*/ true,
codex_config::types::TuiEffects {
progress: false,
..Default::default()
},
);
row.set_interrupt_hint_visible(/*visible*/ false);
row.update_hook_status_message(Some("running hook".into()));
// The wall clock has crossed the fade boundary before either draw.
let start = Instant::now() - Duration::from_secs(/*secs*/ 1);
let timer = StatusTimer {
last_resume_at: start,
..Default::default()
};
row.prepare_frame(start);
row.update_header(
StatusHeader::from_summary(
/*item_id*/ None,
/*part*/ 0,
"Checking dependencies",
)
.unwrap(),
);
row.prepare_frame(start);
let width = 30;
let frames = [(99, 1), (100, 2), (1000, 2)].map(|(ms, expected_height)| {
row.prepare_frame(start + Duration::from_millis(ms));
let height = row.with_timer(&timer).desired_height(width);
pretty_assertions::assert_eq!(height, expected_height, "at {ms} ms");
let mut terminal =
ratatui::Terminal::new(ratatui::backend::TestBackend::new(width, height))
.unwrap();
terminal
.draw(|f| row.with_timer(&timer).render(f.area(), f.buffer_mut()))
.unwrap();
format!("{ms} ms\n{}", terminal.backend())
});
insta::assert_snapshot!(frames.join("\n"));
},
);
}
#[test]
fn shimmer_and_progress_are_independent_and_obey_master_switch() {
with_test_default_colors(
@@ -0,0 +1,73 @@
//! Status text and, for reasoning, the source line that can still extend it.
use std::borrow::Cow;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct StatusHeader {
pub(crate) text: String,
source: Option<ReasoningLine>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct ReasoningLine {
item_id: Option<String>,
part: usize,
start: usize,
}
impl From<String> for StatusHeader {
fn from(text: String) -> Self {
Self { text, source: None }
}
}
impl StatusHeader {
pub(crate) fn from_summary(item_id: Option<&str>, part: usize, summary: &str) -> Option<Self> {
let mut start = summary.len();
summary.split_inclusive('\n').rev().find_map(|line| {
start -= line.len();
Some(Self {
text: heading_text(line)?.into_owned(),
source: Some(ReasoningLine {
item_id: item_id.map(str::to_owned),
part,
start,
}),
})
})
}
pub(super) fn is_reasoning(&self) -> bool {
self.source.is_some()
}
/// Read through the end of this line even when a chunk contains the next one too.
pub(super) fn extend(&mut self, item_id: Option<&str>, part: usize, summary: &str) {
if let Some(line) = &self.source
&& line.item_id.as_deref() == item_id
&& line.part == part
&& let Some((prefix, tail)) = summary.split_at_checked(line.start)
&& (prefix.is_empty() || prefix.ends_with('\n'))
&& let Some(text) = tail.lines().next().and_then(heading_text)
&& let Some(suffix) = text.strip_prefix(self.text.as_str())
{
self.text.push_str(suffix);
}
}
}
fn heading_text(raw: &str) -> Option<Cow<'_, str>> {
let line = raw.trim().trim_start_matches('#').trim();
if matches!(line, "" | "*" | "<" | "<!" | "<!-") || line.starts_with("<!--") {
return None;
}
let Some(stripped) = line.strip_prefix("**") else {
return Some(line.into());
};
let (bold, trailing) = stripped.split_once("**")?;
match (bold, trailing) {
("", "") => None,
(bold, "") => Some(bold.into()),
_ => Some(format!("{bold}{trailing}").into()),
}
}
@@ -0,0 +1,14 @@
---
source: tui/src/status_indicator_widget/effects_tests.rs
expression: "frames.join(\"\\n\")"
---
99 ms
"Working (0s) · running hook "
100 ms
"Ch (0s) "
" └ running hook "
1000 ms
"Checking dependencies (1s) "
" └ running hook "
+60 -30
View File
@@ -1,70 +1,100 @@
//! Smooth, whole-grapheme status shimmer with the desktop's cadenced sweep.
//!
//! Only brightness changes: the moving band uses the terminal foreground, while
//! the remaining text blends halfway into the background. The wave spans at
//! least six terminal columns so short labels do not flash one letter at a time.
//! New headers wait 600 ms, then sweep for one second every four seconds.
//! Unknown palettes use static dim text instead of a stepped animation.
//! Paint a glimmer across the visible terminal cells of a status heading.
//! On a handoff, fade the outgoing text before revealing the new heading
//! during its first sweep. Later sweeps only change its brightness.
use std::time::Duration;
use ratatui::buffer::CellWidth;
use ratatui::style::Style;
use ratatui::text::Span;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use super::HeaderSample;
use crate::color::blend;
use crate::line_truncation::span_width;
use crate::motion::MotionMode;
use crate::terminal_palette::StdoutColorLevel;
use crate::terminal_palette::default_bg;
use crate::terminal_palette::default_fg;
use crate::terminal_palette::default_colors;
use crate::terminal_palette::effective_stdout_color_level;
use crate::terminal_palette::rgb_color;
use crate::text_formatting::contains_rtl_or_arabic_number;
// Match the desktop app's thinking and reasoning header timings.
const START_DELAY: Duration = Duration::from_millis(/*millis*/ 600);
const SWEEP_SECONDS: f64 = 1.0;
const INTERVAL_SECONDS: f64 = 4.0;
const FADE_SECONDS: f64 = 0.1;
const REVEAL_SECONDS: f64 = 0.74;
const SOFT_EDGE_COLUMNS: f64 = 2.0;
pub(crate) fn summary_shimmer(
pub(super) fn summary_shimmer(
text: &str,
elapsed: Duration,
motion: MotionMode,
columns: usize,
sample: Option<&HeaderSample>,
) -> Vec<Span<'static>> {
if motion == MotionMode::Reduced {
return vec![text.to_owned().into()];
}
// Per-grapheme color updates redraw individual terminal cells and break native bidi
// rendering. Keep bidi-sensitive headers as one stable span in logical order.
if contains_rtl_or_arabic_number(text) {
return vec![Span::styled(text.to_owned(), Style::default().dim())];
}
let (StdoutColorLevel::TrueColor, Some(fg), Some(bg)) =
(effective_stdout_color_level(), default_fg(), default_bg())
else {
let text = sample.map_or(text, |s| &s.header.text);
let Some((fg, bg)) = palette(text) else {
return vec![Span::styled(text.to_owned(), Style::default().dim())];
};
let width = text.width() as f64;
let half_width = (width * 0.1).max(/*other*/ 3.0);
let sweep =
(elapsed.saturating_sub(START_DELAY).as_secs_f64() % INTERVAL_SECONDS).min(SWEEP_SECONDS);
let position = sweep / SWEEP_SECONDS * (width + 2.0 * half_width) - half_width;
let (sweep_time, reveal) = if let Some(outgoing) = sample.and_then(|s| s.outgoing.as_ref()) {
let seconds = elapsed.as_secs_f64();
if seconds < FADE_SECONDS {
let alpha = 0.5 * (1.0 - seconds / FADE_SECONDS);
let style = Style::default().fg(rgb_color(blend(fg, bg, alpha as f32)));
return vec![Span::styled(outgoing.clone(), style)];
}
(elapsed, (1.08 * seconds / REVEAL_SECONDS - 0.08).min(1.0))
} else {
(elapsed.saturating_sub(START_DELAY), 1.0)
};
let width = span_width(&Span::raw(text)).min(columns) as f64;
// Keep a broad band on short labels and scale it to the visible cells on long ones.
let half_width = (width * 0.25).max(/*other*/ 3.0);
let edge = reveal * (width + SOFT_EDGE_COLUMNS);
let sweep = (sweep_time.as_secs_f64() % INTERVAL_SECONDS).min(SWEEP_SECONDS);
// Desktop moves the center from -25% to 150%. Let the minimum-width
// band travel far enough to clear both ends even on a short label.
let travel = (1.75 * width).max(width + 2.0 * half_width);
let position = sweep / SWEEP_SECONDS * travel - half_width;
let mut column = 0.0;
text.graphemes(/*is_extended*/ true)
.map(|grapheme| {
let glyph_width = grapheme.width() as f64;
let center = column + glyph_width / 2.0;
column += glyph_width;
let glyph_width = grapheme.cell_width();
let center = column + f64::from(glyph_width) / 2.0;
column += f64::from(glyph_width);
let distance = ((center - position).abs() / half_width).min(/*other*/ 1.0);
let intensity = 0.5 * (1.0 + (std::f64::consts::PI * distance).cos());
let alpha = (0.5 + 0.5 * intensity) as f32;
let opacity = ((edge - center) / SOFT_EDGE_COLUMNS).clamp(0.0, 1.0);
let content = if opacity == 0.0 {
// Color emoji and terminal contrast correction ignore matching fg and bg.
" ".repeat(usize::from(glyph_width))
} else {
grapheme.to_owned()
};
let alpha = ((0.5 + 0.5 * intensity) * opacity) as f32;
let style = Style::default().fg(rgb_color(blend(fg, bg, alpha)));
Span::styled(grapheme.to_owned(), style)
Span::styled(content, style)
})
.collect()
}
type Rgb = (u8, u8, u8);
pub(super) fn palette(text: &str) -> Option<(Rgb, Rgb)> {
// Per-cell color updates break native bidirectional rendering.
if contains_rtl_or_arabic_number(text)
|| effective_stdout_color_level() != StdoutColorLevel::TrueColor
{
return None;
}
let colors = default_colors()?;
Some((colors.fg?, colors.bg))
}
#[cfg(test)]
#[path = "summary_shimmer_tests.rs"]
mod tests;
+45 -16
View File
@@ -4,6 +4,20 @@ use pretty_assertions::assert_eq;
use crate::terminal_palette::with_test_default_colors;
use crate::terminal_probe::DefaultColors;
fn summary_shimmer(text: &str, elapsed: Duration, motion: MotionMode) -> Vec<Span<'static>> {
super::summary_shimmer(text, elapsed, motion, usize::MAX, /*sample*/ None)
}
fn levels(spans: &[Span<'_>]) -> Vec<u8> {
spans
.iter()
.map(|span| match span.style.fg {
Some(ratatui::style::Color::Rgb(level, _, _)) => level,
color => panic!("expected interpolated RGB, got {color:?}"),
})
.collect()
}
#[test]
fn rtl_headers_remain_stable_during_the_sweep() {
with_test_default_colors(
@@ -15,15 +29,24 @@ fn rtl_headers_remain_stable_during_the_sweep() {
let mut headers = Vec::new();
for text in [
"שלום עולם",
"Checking שלום",
"Checking שָׁלוֹם (test.rs) 123",
"Checking lines ١٢-٣٤",
"مرحبا",
] {
let initial = summary_shimmer(text, Duration::ZERO, MotionMode::Animated);
let sweep = summary_shimmer(
text,
// A chunk can finish the visible line and start an English heading.
let sample = HeaderSample {
header: text.to_owned().into(),
outgoing: None,
next_sample: None,
};
let sweep = super::summary_shimmer(
"Running tests",
Duration::from_millis(/*millis*/ 1100),
MotionMode::Animated,
usize::MAX,
Some(&sample),
);
assert_eq!(initial, sweep);
assert_eq!(
@@ -62,16 +85,28 @@ fn short_and_long_labels_sweep_smoothly_in_both_themes() {
for ms in [0, 850, 1100, 1350, 3600, 5100] {
let spans =
summary_shimmer(text, Duration::from_millis(ms), MotionMode::Animated);
let levels = spans
.iter()
.map(|span| match span.style.fg {
Some(ratatui::style::Color::Rgb(level, _, _)) => level,
color => panic!("expected interpolated RGB, got {color:?}"),
})
.collect::<Vec<_>>();
let levels = levels(&spans);
frames.push(format!("{theme} {text} {ms}ms: {levels:?}"));
}
}
let text = "Reading e\u{301}界🧪";
let sample = HeaderSample {
header: text.to_owned().into(),
outgoing: Some("Working".into()),
next_sample: None,
};
for ms in [0, 50, 160, 370, 740, 1000, 4370] {
let spans = super::summary_shimmer(
text,
Duration::from_millis(ms),
MotionMode::Animated,
/*columns*/ 20,
Some(&sample),
);
let levels = levels(&spans);
let label = ratatui::text::Line::from(spans).to_string();
frames.push(format!("{theme} handoff {ms}ms: {label:?} {levels:?}"));
}
});
}
insta::assert_snapshot!(frames.join("\n"));
@@ -90,13 +125,7 @@ fn working_has_overlapping_highlights_without_frame_to_frame_flashes() {
for ms in (0..=5600).step_by(/*step*/ 32) {
let spans =
summary_shimmer("Working", Duration::from_millis(ms), MotionMode::Animated);
let brightness = spans
.iter()
.map(|span| match span.style.fg {
Some(ratatui::style::Color::Rgb(r, _, _)) => r,
color => panic!("expected interpolated RGB, got {color:?}"),
})
.collect::<Vec<_>>();
let brightness = levels(&spans);
if brightness.iter().any(|value| *value > 220) {
assert!(brightness.iter().filter(|value| **value > 160).count() >= 2);
}