Show completion timestamps after successful TUI turns (#43558)

## What changed

Replace horizontal turn separators with dim completion metadata after the final answer, including plain conversational answers. Show local completion times such as `done 2:32 PM`, adding the date for other days and the year for other years. Retain `Worked for` durations above sixty seconds and runtime metrics, and wrap metadata on narrow terminals.

Restore saved completion metadata when resuming conversations or loading older history. Keep each footer after its turn's items and deduplicate it across repeated notifications and overlapping pages. Only live completions fall back to the current time when a saved timestamp is unavailable. Failed, interrupted, and in-progress turns do not receive success footers.

Avoid submitting queued input or emitting completion notifications while replaying history.

## Testing

Add unit and snapshot coverage for timestamp formatting, duration thresholds, muted styling, narrow layouts, live and replayed completions, missing metadata, and pagination boundaries with overlapping pages.

GitOrigin-RevId: 308c35c6720720da43c9a391aa5a68c1b231c9a5
This commit is contained in:
Felipe Coury authored and copyberry committed 2026-09-07 19:01:08 +00:00
1 parent 769a6a5bcd
commit 333c41eef6
42 files changed
+1112 -202

No files matched your search

+83 -47
View File
@@ -1,19 +1,28 @@
//! Turn separators and runtime-metrics labels for transcript history.
//! Subtle completion timestamps, elapsed durations, and runtime metrics for transcript history.
use super::*;
use chrono::DateTime;
use chrono::Datelike;
use chrono::Local;
use chrono::NaiveDate;
#[derive(Debug)]
/// A visual divider between turns, optionally showing how long the assistant "worked for".
/// Completion metadata shown after the assistant's final response.
///
/// This separator is only emitted for turns that performed concrete work (e.g., running commands,
/// applying patches, making MCP tool calls), so purely conversational turns do not show an empty
/// divider.
/// The timestamp records when the turn actually finished, including when restored from history.
/// Times use a twelve-hour clock; other local days include the date and other years include the year.
/// Durations are shown only above sixty seconds; shorter turns still show their timestamp.
/// Absent metadata occupies no transcript rows.
/// The display date is fixed at construction so crossing midnight cannot invalidate cached heights;
/// restoring the conversation constructs new cells and refreshes whether the timestamp needs a date.
#[derive(Debug)]
pub struct FinalMessageSeparator {
elapsed_seconds: Option<u64>,
runtime_metrics: Option<RuntimeMetricsSummary>,
completed_at: Option<DateTime<Local>>,
display_date: NaiveDate,
}
impl FinalMessageSeparator {
/// Creates a separator; completed turns should pass protocol turn duration when available.
/// Creates completion metadata using the protocol turn duration when available.
pub(crate) fn new(
elapsed_seconds: Option<u64>,
runtime_metrics: Option<RuntimeMetricsSummary>,
@@ -21,58 +30,85 @@ impl FinalMessageSeparator {
Self {
elapsed_seconds,
runtime_metrics,
completed_at: None,
display_date: Local::now().date_naive(),
}
}
pub(crate) fn with_completed_at(mut self, completed_at: DateTime<Local>) -> Self {
self.completed_at = Some(completed_at);
self
}
pub(crate) fn with_runtime_metrics(
mut self,
runtime_metrics: Option<RuntimeMetricsSummary>,
) -> Self {
self.runtime_metrics = runtime_metrics;
self
}
fn label(&self, today: NaiveDate) -> Option<String> {
let mut label_parts = Vec::new();
if let Some(elapsed_seconds) = self.elapsed_seconds.filter(|seconds| *seconds > 60) {
let hours = elapsed_seconds / 3_600;
let minutes = (elapsed_seconds % 3_600) / 60;
let seconds = elapsed_seconds % 60;
let elapsed = if hours > 0 {
format!("{hours}h {minutes}m {seconds}s")
} else if minutes > 0 {
format!("{minutes}m {seconds}s")
} else {
format!("{seconds}s")
};
label_parts.push(format!("Worked for {elapsed}"));
}
if let Some(completed_at) = self.completed_at {
let format = if completed_at.date_naive() == today {
"done %-I:%M %p"
} else if completed_at.year() == today.year() {
"done %b %-d at %-I:%M %p"
} else {
"done %b %-d, %Y at %-I:%M %p"
};
label_parts.push(completed_at.format(format).to_string());
}
if let Some(metrics_label) = self.runtime_metrics.and_then(runtime_metrics_label) {
label_parts.push(metrics_label);
}
(!label_parts.is_empty()).then(|| label_parts.join(" · "))
}
}
impl HistoryCell for FinalMessageSeparator {
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
let mut label_parts = Vec::new();
if let Some(elapsed_seconds) = self
.elapsed_seconds
.filter(|seconds| *seconds > 60)
.map(crate::status_indicator_widget::fmt_elapsed_compact)
{
label_parts.push(format!("Worked for {elapsed_seconds}"));
if width == 0 {
return Vec::new();
}
if let Some(metrics_label) = self.runtime_metrics.and_then(runtime_metrics_label) {
label_parts.push(metrics_label);
}
if label_parts.is_empty() {
return vec![Line::from_iter(["─".repeat(width as usize).dim()])];
}
let label = format!("─ {} ─", label_parts.join(" • "));
let (label, _suffix, label_width) = take_prefix_by_width(&label, width as usize);
vec![
Line::from_iter([
label,
"─".repeat((width as usize).saturating_sub(label_width)),
])
.dim(),
]
self.label(self.display_date)
.map(|label| {
let indent = if width > 2 { " " } else { "" };
let options = textwrap::Options::new(usize::from(width))
.initial_indent(indent)
.subsequent_indent(indent);
textwrap::wrap(&label, options)
.into_iter()
.map(|line| Line::from(line.into_owned()).dim())
.collect()
})
.unwrap_or_default()
}
fn raw_lines(&self) -> Vec<Line<'static>> {
let mut label_parts = Vec::new();
if let Some(elapsed_seconds) = self
.elapsed_seconds
.filter(|seconds| *seconds > 60)
.map(crate::status_indicator_widget::fmt_elapsed_compact)
{
label_parts.push(format!("Worked for {elapsed_seconds}"));
}
if let Some(metrics_label) = self.runtime_metrics.and_then(runtime_metrics_label) {
label_parts.push(metrics_label);
}
if label_parts.is_empty() {
Vec::new()
} else {
vec![Line::from(label_parts.join(" • "))]
}
self.label(self.display_date)
.map(|label| vec![Line::from(label)])
.unwrap_or_default()
}
}
#[cfg(test)]
#[path = "separators_tests.rs"]
mod tests;
pub(crate) fn runtime_metrics_label(summary: RuntimeMetricsSummary) -> Option<String> {
let mut parts = Vec::new();
if summary.tool_calls.count > 0 {
@@ -0,0 +1,168 @@
//! Completion metadata rendering, date selection, and muted styling coverage.
use super::*;
use chrono::NaiveDateTime;
use chrono::TimeZone;
use chrono::Timelike;
use codex_otel::RuntimeMetricTotals;
use pretty_assertions::assert_eq;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
fn completed_at() -> DateTime<Local> {
let datetime = NaiveDateTime::parse_from_str("2000-09-06 14:32:00", "%Y-%m-%d %H:%M:%S")
.expect("valid completion time");
Local
.from_local_datetime(&datetime)
.single()
.expect("unambiguous completion time")
}
#[test]
fn completion_label_shows_duration_only_above_sixty_seconds() {
let completed_at = completed_at();
let labels = [
None,
Some(0),
Some(12),
Some(60),
Some(61),
Some(125),
Some(3_605),
]
.into_iter()
.map(|elapsed_seconds| {
FinalMessageSeparator::new(elapsed_seconds, /*runtime_metrics*/ None)
.with_completed_at(completed_at)
.label(completed_at.date_naive())
.expect("completion label")
})
.collect::<Vec<_>>();
insta::assert_snapshot!(labels.join("\n"), @"
done 2:32 PM
done 2:32 PM
done 2:32 PM
done 2:32 PM
Worked for 1m 1s · done 2:32 PM
Worked for 2m 5s · done 2:32 PM
Worked for 1h 0m 5s · done 2:32 PM
");
}
#[test]
fn completion_label_includes_date_when_viewed_on_another_day() {
let completed_at = completed_at();
let cell = FinalMessageSeparator::new(
/*elapsed_seconds*/ Some(125),
/*runtime_metrics*/ None,
)
.with_completed_at(completed_at);
let tomorrow = completed_at.date_naive().succ_opt().expect("next day");
insta::assert_snapshot!(cell.label(tomorrow).expect("completion label"), @"Worked for 2m 5s · done Sep 6 at 2:32 PM");
let next_year = tomorrow.with_year(/*year*/ 2001).expect("valid next year");
insta::assert_snapshot!(cell.label(next_year).expect("completion label"), @"Worked for 2m 5s · done Sep 6, 2000 at 2:32 PM");
}
#[test]
fn completion_uses_twelve_hour_time_at_midnight_noon_and_afternoon() {
let labels = [0, 12, 15].map(|hour| {
let completed_at = completed_at().with_hour(hour).expect("valid hour");
FinalMessageSeparator::new(/*elapsed_seconds*/ None, /*runtime_metrics*/ None)
.with_completed_at(completed_at)
.label(completed_at.date_naive())
.expect("completion label")
});
insta::assert_snapshot!(labels.join("\n"), @"
done 12:32 AM
done 12:32 PM
done 3:32 PM
");
}
#[test]
fn completion_without_metadata_has_no_visible_or_raw_lines() {
let cell =
FinalMessageSeparator::new(/*elapsed_seconds*/ None, /*runtime_metrics*/ None);
assert_eq!(cell.display_lines(/*width*/ 80), Vec::<Line>::new());
assert_eq!(cell.raw_lines(), Vec::<Line>::new());
}
#[test]
fn completion_without_timestamp_retains_known_elapsed_duration() {
let cell = FinalMessageSeparator::new(
/*elapsed_seconds*/ Some(125),
/*runtime_metrics*/ None,
);
insta::assert_snapshot!(cell.raw_lines()[0].to_string(), @"Worked for 2m 5s");
}
#[test]
fn completion_wraps_metadata_and_preserves_unwrapped_raw_text() {
let cell = FinalMessageSeparator::new(
/*elapsed_seconds*/ Some(125),
/*runtime_metrics*/ None,
)
.with_completed_at(completed_at())
.with_runtime_metrics(Some(RuntimeMetricsSummary {
tool_calls: RuntimeMetricTotals {
count: 3,
duration_ms: 2_450,
},
..RuntimeMetricsSummary::default()
}));
let lines = cell.display_lines(/*width*/ 24);
let rendered = lines.iter().map(ToString::to_string).collect::<Vec<_>>();
insta::assert_snapshot!(rendered.join("\n"), @"
Worked for 2m 5s ·
done Sep 6, 2000 at
2:32 PM · Local tools:
3 calls (2.5s)
");
insta::assert_snapshot!(cell.raw_lines()[0].to_string(), @"Worked for 2m 5s · done Sep 6, 2000 at 2:32 PM · Local tools: 3 calls (2.5s)");
for width in [0, 1, 5, 24] {
assert!(
cell.display_lines(width)
.iter()
.all(|line| line.width() <= usize::from(width))
);
}
}
#[test]
fn completion_renders_with_dim_default_colors() {
let cell: Box<dyn HistoryCell> = Box::new(
FinalMessageSeparator::new(/*elapsed_seconds*/ None, /*runtime_metrics*/ None)
.with_completed_at(completed_at()),
);
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 1,
);
let mut buffer = Buffer::empty(area);
cell.render(area, &mut buffer);
let text_width = cell.display_lines(area.width)[0].width();
let styles = (0..text_width)
.map(|x| {
let rendered = &buffer[(x as u16, 0)];
(rendered.fg, rendered.bg, rendered.modifier)
})
.collect::<Vec<_>>();
assert_eq!(
styles,
vec![(Color::Reset, Color::Reset, Modifier::DIM); text_width]
);
}
#[test]
fn completion_rendering_uses_the_captured_display_date() {
let completed_at = completed_at();
let mut cell =
FinalMessageSeparator::new(/*elapsed_seconds*/ None, /*runtime_metrics*/ None)
.with_completed_at(completed_at);
cell.display_date = completed_at.date_naive();
insta::assert_snapshot!(cell.display_lines(/*width*/ 80)[0].to_string(), @" done 2:32 PM");
assert_eq!(cell.raw_lines(), vec![Line::from("done 2:32 PM")]);
}
+2 -2
View File
@@ -598,7 +598,7 @@ fn unified_exec_interaction_cell_renders_wait() {
}
#[test]
fn final_message_separator_hides_short_worked_label_and_includes_runtime_metrics() {
fn final_message_separator_preserves_runtime_metrics_for_short_turns() {
let summary = RuntimeMetricsSummary {
tool_calls: RuntimeMetricTotals {
count: 3,
@@ -633,7 +633,7 @@ fn final_message_separator_hides_short_worked_label_and_includes_runtime_metrics
let rendered = render_lines(&cell.display_lines(/*width*/ 600));
assert_eq!(rendered.len(), 1);
assert!(!rendered[0].contains("Worked for"));
assert!(rendered[0].starts_with(" Local tools:"));
assert!(rendered[0].contains("Local tools: 3 calls (2.5s)"));
assert!(rendered[0].contains("Inference: 2 calls (1.2s)"));
assert!(rendered[0].contains("WebSocket: 1 events send (700ms)"));