Skip to main content

vtcode_commons/
message_timestamp.rs

1//! Wall-clock timestamps and turn durations for the final agent response of a
2//! turn.
3//!
4//! Each completed turn carries one short local-time footer (e.g. `· 3:12 PM`,
5//! optionally `· 3:12 PM · 13m 24s`) after its final agent message, so the
6//! clock marks the turn's summary point instead of repeating on every
7//! intermediate response. Formatting lives here so the TUI transcript, plain
8//! CLI output, and future desktop/export surfaces share one shape.
9
10use std::time::Duration;
11
12use chrono::{DateTime, Local};
13
14/// Format a local timestamp the way agent footers display it (`3:12 PM`).
15///
16/// Twelve-hour clock without seconds or leading zeros, matching the chat-style
17/// reference. Takes the instant as a parameter so tests stay deterministic.
18pub fn format_message_time(now: DateTime<Local>) -> String {
19    now.format("%-I:%M %p").to_string()
20}
21
22/// Display unit of one elapsed-time tier.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum ElapsedUnit {
25    /// Seconds, used below the one-minute boundary.
26    Seconds,
27    /// Minutes, used below the one-hour boundary.
28    Minutes,
29    /// Hours, used at and above the one-hour boundary.
30    Hours,
31}
32
33impl ElapsedUnit {
34    /// Locale-neutral symbol used by surfaces without an i18n layer.
35    #[must_use]
36    pub const fn as_str(self) -> &'static str {
37        match self {
38            Self::Seconds => "s",
39            Self::Minutes => "m",
40            Self::Hours => "h",
41        }
42    }
43}
44
45/// Decompose an elapsed second count into at most two display tiers
46/// (`(primary, unit, optional remainder)`).
47///
48/// Zero remainder parts are omitted by returning `None`, so each surface only
49/// has to map the units to its own presentation (compact symbols here, locale
50/// catalog keys in the desktop app). Keeping the boundary arithmetic here
51/// means a tier change is made once instead of being mirrored in every renderer.
52#[must_use]
53pub fn elapsed_tiers(seconds: u64) -> (u64, ElapsedUnit, Option<(u64, ElapsedUnit)>) {
54    const MINUTE: u64 = 60;
55    const HOUR: u64 = 3600;
56    if seconds < MINUTE {
57        return (seconds, ElapsedUnit::Seconds, None);
58    }
59    if seconds < HOUR {
60        let rest = seconds % MINUTE;
61        let remainder = (rest != 0).then_some((rest, ElapsedUnit::Seconds));
62        return (seconds / MINUTE, ElapsedUnit::Minutes, remainder);
63    }
64    let rest = (seconds % HOUR) / MINUTE;
65    let remainder = (rest != 0).then_some((rest, ElapsedUnit::Minutes));
66    (seconds / HOUR, ElapsedUnit::Hours, remainder)
67}
68
69/// Format a turn duration the way footers and outcome lines display it.
70///
71/// Compact clock symbols with zero parts omitted: `42s`, `13m 24s`, `1h 5m`.
72/// The desktop app renders the same tiers through its locale catalogs; this
73/// plain-symbol shape serves the CLI surfaces that have no i18n layer.
74#[must_use]
75pub fn format_turn_elapsed(duration: Duration) -> String {
76    let (value, unit, remainder) = elapsed_tiers(duration.as_secs());
77    let mut out = format!("{value}{}", unit.as_str());
78    if let Some((value, unit)) = remainder {
79        out.push(' ');
80        out.push_str(&format!("{value}{}", unit.as_str()));
81    }
82    out
83}
84
85/// Build the full footer line for a turn's final agent response
86/// (`· 3:12 PM`, plus `· 13m 24s` when the caller measured the turn).
87///
88/// The leading middot marks the line as chrome in no-color output where
89/// dimming is unavailable; the elapsed middot keeps both halves one chrome
90/// unit so reflow and tail-matching treat them together.
91pub fn message_timestamp_footer(now: DateTime<Local>, elapsed: Option<Duration>) -> String {
92    match elapsed {
93        Some(duration) => format!("· {} · {}", format_message_time(now), format_turn_elapsed(duration)),
94        None => format!("· {}", format_message_time(now)),
95    }
96}
97
98/// Build the footer for the current local time, without an elapsed half.
99pub fn current_message_timestamp_footer() -> String {
100    message_timestamp_footer(Local::now(), None)
101}
102
103/// Build the footer for the current local time with the measured turn
104/// duration appended when the caller has one.
105pub fn current_message_timestamp_footer_with_elapsed(elapsed: Option<Duration>) -> String {
106    message_timestamp_footer(Local::now(), elapsed)
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use chrono::TimeZone;
113
114    fn local_at(hour: u32, minute: u32) -> DateTime<Local> {
115        Local
116            .with_ymd_and_hms(2026, 11, 2, hour, minute, 0)
117            .single()
118            .expect("fixture timestamp must be unambiguous")
119    }
120
121    #[test]
122    fn formats_afternoon_without_leading_zero() {
123        assert_eq!(format_message_time(local_at(15, 12)), "3:12 PM");
124    }
125
126    #[test]
127    fn formats_single_digit_morning_hour() {
128        assert_eq!(format_message_time(local_at(9, 5)), "9:05 AM");
129    }
130
131    #[test]
132    fn formats_double_digit_morning_hour() {
133        assert_eq!(format_message_time(local_at(11, 55)), "11:55 AM");
134    }
135
136    #[test]
137    fn midnight_is_twelve_am_not_zero() {
138        assert_eq!(format_message_time(local_at(0, 5)), "12:05 AM");
139    }
140
141    #[test]
142    fn noon_is_twelve_pm_not_zero() {
143        assert_eq!(format_message_time(local_at(12, 0)), "12:00 PM");
144    }
145
146    #[test]
147    fn footer_prefixes_time_with_middot() {
148        assert_eq!(message_timestamp_footer(local_at(15, 12), None), "· 3:12 PM");
149    }
150
151    #[test]
152    fn footer_appends_elapsed_after_the_clock() {
153        assert_eq!(message_timestamp_footer(local_at(15, 12), Some(Duration::from_secs(804))), "· 3:12 PM · 13m 24s");
154        assert_eq!(message_timestamp_footer(local_at(15, 12), Some(Duration::from_secs(3900))), "· 3:12 PM · 1h 5m");
155    }
156
157    #[test]
158    fn current_footer_with_elapsed_keeps_one_chrome_unit() {
159        let footer = current_message_timestamp_footer_with_elapsed(Some(Duration::from_secs(59)));
160        let time = footer.strip_prefix("· ").expect("current footer must carry the middot");
161        let mut halves = time.split(" · ");
162        let clock = halves.next().expect("clock half must exist");
163        assert!(clock.contains(':'), "clock half must show clock time: {footer:?}");
164        assert!(clock.ends_with("AM") || clock.ends_with("PM"), "clock half must show meridiem: {footer:?}");
165        assert_eq!(halves.next(), Some("59s"), "elapsed half must follow the clock");
166        assert!(halves.next().is_none(), "footer must stay one clock plus one duration");
167    }
168
169    #[test]
170    fn elapsed_symbols_omit_zero_parts() {
171        assert_eq!(format_turn_elapsed(Duration::from_secs(0)), "0s");
172        assert_eq!(format_turn_elapsed(Duration::from_secs(59)), "59s");
173        assert_eq!(format_turn_elapsed(Duration::from_secs(60)), "1m");
174        assert_eq!(format_turn_elapsed(Duration::from_secs(90)), "1m 30s");
175        assert_eq!(format_turn_elapsed(Duration::from_secs(3600)), "1h");
176        assert_eq!(format_turn_elapsed(Duration::from_secs(3900)), "1h 5m");
177    }
178
179    #[test]
180    fn elapsed_tiers_are_boundary_safe_and_zero_parts_omitted() {
181        use ElapsedUnit as U;
182
183        for (seconds, expected) in [
184            (0, (0, U::Seconds, None)),
185            (59, (59, U::Seconds, None)),
186            (60, (1, U::Minutes, None)),
187            (90, (1, U::Minutes, Some((30, U::Seconds)))),
188            (3599, (59, U::Minutes, Some((59, U::Seconds)))),
189            (3600, (1, U::Hours, None)),
190            (3900, (1, U::Hours, Some((5, U::Minutes)))),
191            (86_400, (24, U::Hours, None)),
192        ] {
193            assert_eq!(elapsed_tiers(seconds), expected, "{seconds}s");
194        }
195    }
196
197    #[test]
198    fn current_footer_has_footer_shape() {
199        let footer = current_message_timestamp_footer();
200        let time = footer.strip_prefix("· ").expect("current footer must carry the middot");
201        assert!(time.contains(':'), "current footer must show clock time: {footer:?}");
202        assert!(time.ends_with("AM") || time.ends_with("PM"), "current footer must show meridiem: {footer:?}");
203    }
204}