Honor the system clock preference in TUI completion timestamps (#46845)

## Why

Completion timestamps always used a 12-hour clock, even when the host preferred 24-hour time.

## What changed

- Detect the clock preference from native settings on macOS and Windows, and from `LC_ALL`, `LC_TIME`, then `LANG` on Linux with glibc.
- Render completion times in the detected format, such as `14:32` instead of `2:32 PM`, for both live turns and restored history.
- Cache detection without changing the process locale, and retain 12-hour output when the preference cannot be determined. Recognize standard `C` and `POSIX` locales as 24-hour on Linux and Android.

## Testing

Add tests for locale precedence, unavailable locales, and clock pattern parsing, plus snapshot coverage for 24-hour timestamps with dates and line wrapping. Update completion timestamp normalization to handle both clock formats.

GitOrigin-RevId: eb338e67de627cbb992de16058884ece2b4b9ff7
This commit is contained in:
Eric Traut
2026-09-20 16:52:02 +00:00
committed by copyberry
parent 15312c326c
commit 79ef00ded1
12 changed files with 408 additions and 29 deletions
+1
View File
@@ -4847,6 +4847,7 @@ dependencies = [
"lazy_static",
"libc",
"objc2-app-kit",
"objc2-foundation",
"pathdiff",
"pretty_assertions",
"pulldown-cmark",
+2
View File
@@ -142,6 +142,7 @@ libc = { workspace = true }
[target.'cfg(target_os = "macos")'.dependencies]
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSAccessibility", "NSWorkspace"] }
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSDateFormatter", "NSFormatter", "NSLocale", "NSString"] }
[target.'cfg(target_os = "linux")'.dependencies]
# Keep the same executor features as the credential store, which also uses zbus.
@@ -151,6 +152,7 @@ zbus = "4.4.0"
which = { workspace = true }
windows-sys = { version = "0.52", features = [
"Win32_Foundation",
"Win32_Globalization",
"Win32_Security",
"Win32_Storage_FileSystem",
"Win32_System_Console",
@@ -176,7 +176,12 @@ async fn older_pagination_completion_footers_follow_answers_without_overlap_dupl
.join("\n"),
);
}
insta::assert_snapshot!(snapshots.join("\n\n--- next overlapping page ---\n\n"));
// Canonicalize the fixture's afternoon clock while retaining minute differences.
let afternoon_clock = regex_lite::Regex::new(r"at 14:(\d\d)").unwrap();
insta::assert_snapshot!(afternoon_clock.replace_all(
&snapshots.join("\n\n--- next overlapping page ---\n\n"),
"at 2:$1 PM",
));
app_server.shutdown().await?;
proxy.await??;
Ok(())
+3 -1
View File
@@ -46,7 +46,9 @@ impl ChatWidget {
/*runtime_metrics*/ None,
);
Some(match completed_at {
Some(completed_at) => cell.with_completed_at(completed_at),
Some(completed_at) => {
cell.with_completed_at(completed_at, crate::clock_format::ClockFormat::system())
}
None => cell,
})
}
@@ -1,6 +1,7 @@
//! Exercises completion metadata through live notifications and restored turn history.
use super::*;
use crate::clock_format::ClockFormat;
use chrono::Local;
use chrono::TimeZone;
use pretty_assertions::assert_eq;
@@ -56,7 +57,10 @@ fn saved_completion_label() -> String {
Local
.timestamp_opt(COMPLETED_AT, /*nsecs*/ 0)
.unwrap()
.format("%b %-d, %Y at %-I:%M %p")
.format(&format!(
"%b %-d, %Y at {}",
ClockFormat::system().time_format()
))
.to_string()
}
@@ -109,7 +113,7 @@ async fn completion_live_applies_duration_threshold_and_preserves_timestamp_fall
let time = if completed_at.is_some() {
saved_completion_label()
} else {
time.format("%-I:%M %p").to_string()
time.format(ClockFormat::system().time_format()).to_string()
};
format!("{prefix}{time}")
});
@@ -192,7 +196,11 @@ async fn completion_replay_waits_for_older_turn_items_to_load() {
let older_time = Local
.timestamp_opt(older_completed_at, /*nsecs*/ 0)
.unwrap()
.format("%b %-d, %Y at %-I:%M %p");
.format(&format!(
"%b %-d, %Y at {}",
ClockFormat::system().time_format()
))
.to_string();
assert_eq!(
completion_labels(&mut rx),
format!("Worked for 2m 5s · {older_time}"),
@@ -245,14 +253,19 @@ fn completion_snapshot_normalization_preserves_clock_only_message_lines() {
transcript
);
let footer =
history_cell::FinalMessageSeparator::new(Some(3_723), /*runtime_metrics*/ None)
.with_completed_at(Local.timestamp_opt(COMPLETED_AT, /*nsecs*/ 0).unwrap());
assert_eq!(
normalize_completion_timestamps(
&footer,
lines_to_single_string(&footer.display_lines(/*width*/ 80))
),
" Worked for [duration] · [completion time]\n"
);
for clock_format in [ClockFormat::TwelveHour, ClockFormat::TwentyFourHour] {
let footer =
history_cell::FinalMessageSeparator::new(Some(3_723), /*runtime_metrics*/ None)
.with_completed_at(
Local.timestamp_opt(COMPLETED_AT, /*nsecs*/ 0).unwrap(),
clock_format,
);
assert_eq!(
normalize_completion_timestamps(
&footer,
lines_to_single_string(&footer.display_lines(/*width*/ 80))
),
" Worked for [duration] · [completion time]\n"
);
}
}
+1 -1
View File
@@ -1861,7 +1861,7 @@ pub(crate) fn normalize_completion_timestamps(
}
static COMPLETION_FOOTER: std::sync::LazyLock<regex_lite::Regex> = std::sync::LazyLock::new(
|| {
regex_lite::Regex::new(r"(?m)^(?P<indent>[ \t]*)(?P<duration>Worked for (?:[0-9]+h )?(?:[0-9]+m )?[0-9]+s · )?(?:[A-Z][a-z]{2} [0-9]{1,2}(?:, [0-9]{4})? at )?[0-9]{1,2}:[0-9]{2} (?:AM|PM)(?P<padding>[ \t]*)$")
regex_lite::Regex::new(r"(?m)^(?P<indent>[ \t]*)(?P<duration>Worked for (?:[0-9]+h )?(?:[0-9]+m )?[0-9]+s · )?(?:[A-Z][a-z]{2} [0-9]{1,2}(?:, [0-9]{4})? at )?[0-9]{1,2}:[0-9]{2}(?: (?:AM|PM))?(?P<padding>[ \t]*)$")
.expect("valid completion footer pattern")
},
);
+191
View File
@@ -0,0 +1,191 @@
//! Detects the TUI host's clock preference once. Unknown preferences preserve 12-hour output;
//! detection never changes the process locale or runs while rendering a history cell.
use std::sync::OnceLock;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ClockFormat {
TwelveHour,
TwentyFourHour,
}
impl ClockFormat {
pub(crate) fn system() -> Self {
static FORMAT: OnceLock<ClockFormat> = OnceLock::new();
*FORMAT.get_or_init(|| detect().unwrap_or(Self::TwelveHour))
}
pub(crate) fn time_format(self) -> &'static str {
match self {
Self::TwelveHour => "%-I:%M %p",
Self::TwentyFourHour => "%H:%M",
}
}
}
#[cfg(any(target_os = "linux", target_os = "android", test))]
fn time_locale(
mut get: impl FnMut(&str) -> Option<std::ffi::OsString>,
) -> Option<std::ffi::OsString> {
["LC_ALL", "LC_TIME", "LANG"]
.into_iter()
.find_map(|name| get(name).filter(|value| !value.is_empty()))
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn detect() -> Option<ClockFormat> {
let locale = time_locale(|name| std::env::var_os(name))?;
detect_time_locale(locale.to_str()?)
}
#[cfg(any(target_os = "linux", target_os = "android", test))]
fn detect_time_locale(locale: &str) -> Option<ClockFormat> {
if matches!(locale, "C" | "POSIX" | "C.UTF-8" | "C.utf8") {
return Some(ClockFormat::TwentyFourHour);
}
#[cfg(all(target_os = "linux", target_env = "gnu"))]
{
let name = std::ffi::CString::new(locale).ok()?;
// SAFETY: name is NUL-terminated, the mask is valid, and a null base creates
// an independent locale. Its borrowed pattern is read before freeing it.
unsafe {
let locale = libc::newlocale(libc::LC_TIME_MASK, name.as_ptr(), std::ptr::null_mut());
if locale.is_null() {
return None;
}
let pattern = libc::nl_langinfo_l(libc::T_FMT, locale);
let result = if pattern.is_null() {
None
} else {
parse_strftime(std::ffi::CStr::from_ptr(pattern).to_bytes())
};
libc::freelocale(locale);
result
}
}
// musl and bionic can return C patterns for unsupported locales. Do not
// mistake that fallback for the user's actual clock preference.
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
None
}
#[cfg(any(all(target_os = "linux", target_env = "gnu"), test))]
fn parse_strftime(pattern: &[u8]) -> Option<ClockFormat> {
let mut chars = pattern.iter().copied().peekable();
let mut twelve = false;
let mut twenty_four = false;
while let Some(ch) = chars.next() {
if ch != b'%' {
continue;
}
while chars
.next_if(|ch| matches!(ch, b'_' | b'-' | b'0' | b'^' | b'#') || ch.is_ascii_digit())
.is_some()
{}
chars.next_if(|ch| matches!(ch, b'E' | b'O'));
match chars.next()? {
b'I' | b'l' | b'r' => twelve = true,
b'H' | b'k' | b'R' | b'T' => twenty_four = true,
b'%' | b'M' | b'S' | b'p' | b'P' | b'Z' | b'z' | b'n' | b't' => {}
// In particular, do not recurse into %X or %c.
_ => return None,
}
}
match (twelve, twenty_four) {
(true, false) => Some(ClockFormat::TwelveHour),
(false, true) => Some(ClockFormat::TwentyFourHour),
_ => None,
}
}
#[cfg(target_os = "macos")]
fn detect() -> Option<ClockFormat> {
use objc2_foundation::NSDateFormatter;
use objc2_foundation::NSLocale;
use objc2_foundation::NSString;
let locale = NSLocale::currentLocale();
let pattern = NSDateFormatter::dateFormatFromTemplate_options_locale(
&NSString::from_str("j"),
/*opts*/ 0,
Some(&locale),
)?;
parse_native_pattern(&pattern.to_string(), "hHKk")
}
#[cfg(windows)]
fn detect() -> Option<ClockFormat> {
use windows_sys::Win32::Globalization::GetLocaleInfoEx;
use windows_sys::Win32::Globalization::LOCALE_SSHORTTIME;
// SAFETY: the first call queries the size; the second receives a writable
// buffer of that size. A null locale name selects the user's default locale,
// and user overrides remain enabled.
let pattern = unsafe {
let length = GetLocaleInfoEx(
std::ptr::null(),
LOCALE_SSHORTTIME,
std::ptr::null_mut(),
/*cchdata*/ 0,
);
if length <= 1 {
return None;
}
let mut buffer = vec![0; length as usize];
let written = GetLocaleInfoEx(
std::ptr::null(),
LOCALE_SSHORTTIME,
buffer.as_mut_ptr(),
length,
);
if written <= 1 {
return None;
}
String::from_utf16(&buffer[..written as usize - 1]).ok()?
};
parse_native_pattern(&pattern, "hH")
}
#[cfg(any(target_os = "macos", windows, test))]
fn parse_native_pattern(pattern: &str, hour_symbols: &str) -> Option<ClockFormat> {
let mut quoted = false;
let mut twelve = false;
let mut twenty_four = false;
for ch in pattern.chars() {
if ch == '\'' {
// Two adjacent apostrophes restore the quote state, representing
// a literal apostrophe in both native pattern syntaxes.
quoted = !quoted;
} else if !quoted {
if ch == ';' {
break; // Windows lists the preferred pattern first.
}
if hour_symbols.contains(ch) {
match ch {
'h' | 'K' => twelve = true,
'H' | 'k' => twenty_four = true,
_ => return None,
}
}
}
}
match (quoted, twelve, twenty_four) {
(false, true, false) => Some(ClockFormat::TwelveHour),
(false, false, true) => Some(ClockFormat::TwentyFourHour),
_ => None,
}
}
#[cfg(not(any(
target_os = "linux",
target_os = "android",
target_os = "macos",
windows
)))]
fn detect() -> Option<ClockFormat> {
None
}
#[cfg(test)]
#[path = "clock_format_tests.rs"]
mod tests;
+99
View File
@@ -0,0 +1,99 @@
//! Preference precedence and native pattern parsing without changing host settings.
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn time_locale_uses_first_nonempty_setting() {
for (values, expected) in [
(
[Some("C"), Some("en_US.UTF-8"), Some("de_DE.UTF-8")],
Some("C"),
),
(
[Some(""), Some("C.UTF-8"), Some("en_US.UTF-8")],
Some("C.UTF-8"),
),
([None, Some(""), Some("C.utf8")], Some("C.utf8")),
([Some("invalid"), Some("C"), None], Some("invalid")),
([None, Some(""), None], None),
] {
let environment = ["LC_ALL", "LC_TIME", "LANG"].into_iter().zip(values);
assert_eq!(
time_locale(|name| environment
.clone()
.find(|(key, _)| *key == name)
.unwrap()
.1
.map(Into::into)),
expected.map(std::ffi::OsString::from),
);
}
}
#[test]
fn standard_locales_and_unavailable_locales() {
for locale in ["C", "POSIX", "C.UTF-8", "C.utf8"] {
assert_eq!(
detect_time_locale(locale),
Some(ClockFormat::TwentyFourHour)
);
}
for locale in [
"codex_missing_locale",
"C.codex_missing_encoding",
"invalid\0locale",
] {
assert_eq!(detect_time_locale(locale), None);
}
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
assert_eq!(detect_time_locale("de_DE.UTF-8"), None);
}
#[test]
fn strftime_hour_fields_determine_the_clock() {
for (pattern, expected) in [
("%I:%M:%S %p", Some(ClockFormat::TwelveHour)),
("%l:%M %P", Some(ClockFormat::TwelveHour)),
("%r", Some(ClockFormat::TwelveHour)),
("%H:%M:%S", Some(ClockFormat::TwentyFourHour)),
("%k:%M", Some(ClockFormat::TwentyFourHour)),
("%R", Some(ClockFormat::TwentyFourHour)),
("%T %Z", Some(ClockFormat::TwentyFourHour)),
("%%I %_2OH:%M", Some(ClockFormat::TwentyFourHour)),
("%%H %-I:%M", Some(ClockFormat::TwelveHour)),
("%H %I", None),
("%H %X", None),
("%H %", None),
("%H %Q", None),
("%p", None),
("%%H", None),
("", None),
] {
assert_eq!(parse_strftime(pattern.as_bytes()), expected, "{pattern}");
}
}
#[test]
fn native_patterns_ignore_literals_and_use_the_first_alternative() {
for (pattern, symbols, expected) in [
("h:mm tt", "hH", Some(ClockFormat::TwelveHour)),
("HH:mm", "hH", Some(ClockFormat::TwentyFourHour)),
("h 'H; o''clock' a", "hHKk", Some(ClockFormat::TwelveHour)),
("'h' HH:mm;h:mm tt", "hH", Some(ClockFormat::TwentyFourHour)),
("h:mm tt;HH:mm", "hH", Some(ClockFormat::TwelveHour)),
("K a", "hHKk", Some(ClockFormat::TwelveHour)),
("kk", "hHKk", Some(ClockFormat::TwentyFourHour)),
("K HH:mm", "hH", Some(ClockFormat::TwentyFourHour)),
("h 'unterminated", "hH", None),
("h HH", "hH", None),
("'HH' mm", "hH", None),
("", "hH", None),
] {
assert_eq!(
parse_native_pattern(pattern, symbols),
expected,
"{pattern}"
);
}
}
+19 -7
View File
@@ -1,6 +1,7 @@
//! Subtle completion timestamps, elapsed durations, and runtime metrics for transcript history.
use super::*;
use crate::clock_format::ClockFormat;
use chrono::DateTime;
use chrono::Datelike;
use chrono::Local;
@@ -9,7 +10,7 @@ use chrono::NaiveDate;
/// Completion metadata shown after the assistant's final response.
///
/// 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.
/// Times use the host's clock preference; other local days include the date and other years 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;
@@ -20,6 +21,7 @@ pub struct FinalMessageSeparator {
runtime_metrics: Option<RuntimeMetricsSummary>,
completed_at: Option<DateTime<Local>>,
display_date: NaiveDate,
clock_format: ClockFormat,
}
impl FinalMessageSeparator {
/// Creates completion metadata using the protocol turn duration when available.
@@ -32,11 +34,17 @@ impl FinalMessageSeparator {
runtime_metrics,
completed_at: None,
display_date: Local::now().date_naive(),
clock_format: ClockFormat::TwelveHour,
}
}
pub(crate) fn with_completed_at(mut self, completed_at: DateTime<Local>) -> Self {
pub(crate) fn with_completed_at(
mut self,
completed_at: DateTime<Local>,
clock_format: ClockFormat,
) -> Self {
self.completed_at = Some(completed_at);
self.clock_format = clock_format;
self
}
@@ -64,14 +72,18 @@ impl FinalMessageSeparator {
label_parts.push(format!("Worked for {elapsed}"));
}
if let Some(completed_at) = self.completed_at {
let format = if completed_at.date_naive() == today {
"%-I:%M %p"
let date_format = if completed_at.date_naive() == today {
""
} else if completed_at.year() == today.year() {
"%b %-d at %-I:%M %p"
"%b %-d at "
} else {
"%b %-d, %Y at %-I:%M %p"
"%b %-d, %Y at "
};
label_parts.push(completed_at.format(format).to_string());
label_parts.push(format!(
"{}{}",
completed_at.format(date_format),
completed_at.format(self.clock_format.time_format()),
));
}
if let Some(metrics_label) = self.runtime_metrics.and_then(runtime_metrics_label) {
label_parts.push(metrics_label);
@@ -33,7 +33,7 @@ fn completion_label_shows_duration_only_above_sixty_seconds() {
.into_iter()
.map(|elapsed_seconds| {
FinalMessageSeparator::new(elapsed_seconds, /*runtime_metrics*/ None)
.with_completed_at(completed_at)
.with_completed_at(completed_at, ClockFormat::TwelveHour)
.label(completed_at.date_naive())
.expect("completion label")
})
@@ -57,7 +57,7 @@ fn completion_label_includes_date_when_viewed_on_another_day() {
/*elapsed_seconds*/ Some(125),
/*runtime_metrics*/ None,
)
.with_completed_at(completed_at);
.with_completed_at(completed_at, ClockFormat::TwelveHour);
let tomorrow = completed_at.date_naive().succ_opt().expect("next day");
insta::assert_snapshot!(cell.label(tomorrow).expect("completion label"), @"Worked for 2m 5s · Sep 6 at 2:32 PM");
@@ -70,7 +70,7 @@ 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)
.with_completed_at(completed_at, ClockFormat::TwelveHour)
.label(completed_at.date_naive())
.expect("completion label")
});
@@ -81,6 +81,39 @@ fn completion_uses_twelve_hour_time_at_midnight_noon_and_afternoon() {
");
}
#[test]
fn completion_uses_twenty_four_hour_time_with_dates_and_wrapping() {
let today = completed_at().date_naive();
let tomorrow = today.succ_opt().unwrap();
let next_year = today.with_year(/*year*/ 2001).unwrap();
let mut labels = Vec::new();
for hour in [0, 12, 23] {
let completed_at = completed_at()
.with_hour(hour)
.unwrap()
.with_minute(/*min*/ 25)
.unwrap();
let mut cell = FinalMessageSeparator::new(Some(125), /*runtime_metrics*/ None)
.with_completed_at(completed_at, ClockFormat::TwentyFourHour);
for date in [today, tomorrow, next_year] {
labels.push(cell.label(date).unwrap());
}
cell.display_date = next_year;
labels.push(
cell.display_lines(/*width*/ 24)
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join("\n"),
);
assert_eq!(
cell.raw_lines(),
vec![Line::from(cell.label(next_year).unwrap())]
);
}
insta::assert_snapshot!(labels.join("\n"));
}
#[test]
fn completion_without_metadata_has_no_visible_or_raw_lines() {
let cell =
@@ -104,7 +137,7 @@ fn completion_wraps_metadata_and_preserves_unwrapped_raw_text() {
/*elapsed_seconds*/ Some(125),
/*runtime_metrics*/ None,
)
.with_completed_at(completed_at())
.with_completed_at(completed_at(), ClockFormat::TwelveHour)
.with_runtime_metrics(Some(RuntimeMetricsSummary {
tool_calls: RuntimeMetricTotals {
count: 3,
@@ -135,7 +168,7 @@ fn completion_wraps_metadata_and_preserves_unwrapped_raw_text() {
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()),
.with_completed_at(completed_at(), ClockFormat::TwelveHour),
);
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 1,
@@ -160,7 +193,7 @@ 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);
.with_completed_at(completed_at, ClockFormat::TwelveHour);
cell.display_date = completed_at.date_naive();
insta::assert_snapshot!(cell.display_lines(/*width*/ 80)[0].to_string(), @" 2:32 PM");
@@ -0,0 +1,20 @@
---
source: tui/src/history_cell/separators_tests.rs
assertion_line: 101
expression: "labels.join(\"\\n\")"
---
Worked for 2m 5s · 00:25
Worked for 2m 5s · Sep 6 at 00:25
Worked for 2m 5s · Sep 6, 2000 at 00:25
Worked for 2m 5s · Sep
6, 2000 at 00:25
Worked for 2m 5s · 12:25
Worked for 2m 5s · Sep 6 at 12:25
Worked for 2m 5s · Sep 6, 2000 at 12:25
Worked for 2m 5s · Sep
6, 2000 at 12:25
Worked for 2m 5s · 23:25
Worked for 2m 5s · Sep 6 at 23:25
Worked for 2m 5s · Sep 6, 2000 at 23:25
Worked for 2m 5s · Sep
6, 2000 at 23:25
+1
View File
@@ -121,6 +121,7 @@ mod cli;
mod clipboard_copy;
mod clipboard_html;
mod clipboard_paste;
mod clock_format;
mod collaboration_modes;
mod color;
mod config_update;