travelagent 1.11.1

Agent-first TUI code review tool
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
use chrono::{DateTime, Utc};
use ratatui::{
    Frame,
    layout::Rect,
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Paragraph},
};

use crate::app::{App, DiffSource, InputMode, Message, MessageType};
use crate::theme::Theme;
use crate::ui::styles;

/// Format a duration since `earlier` as a short relative string for the
/// status bar. Resolutions: seconds (<60), minutes (<60m), hours (<24h),
/// days otherwise. Returns e.g. "2m ago", "15s ago", "3h ago", "just now".
pub fn format_relative_time(earlier: DateTime<Utc>, now: DateTime<Utc>) -> String {
    let delta = now.signed_duration_since(earlier);
    let secs = delta.num_seconds();
    if secs < 0 {
        // Clock skew or future timestamp — treat as "just now".
        return "just now".to_string();
    }
    if secs < 5 {
        return "just now".to_string();
    }
    if secs < 60 {
        return format!("{secs}s ago");
    }
    let minutes = delta.num_minutes();
    if minutes < 60 {
        return format!("{minutes}m ago");
    }
    let hours = delta.num_hours();
    if hours < 24 {
        return format!("{hours}h ago");
    }
    let days = delta.num_days();
    format!("{days}d ago")
}

pub fn build_message_span(message: Option<&Message>, theme: &Theme) -> (Span<'static>, usize) {
    if let Some(msg) = message {
        let (fg, bg) = match msg.message_type {
            MessageType::Info => (theme.message_info_fg, theme.message_info_bg),
            MessageType::Warning => (theme.message_warning_fg, theme.message_warning_bg),
            MessageType::Error => (theme.message_error_fg, theme.message_error_bg),
        };
        let content = format!(" {} ", msg.content);
        let width = content.len();
        (
            Span::styled(
                content,
                Style::default().fg(fg).bg(bg).add_modifier(Modifier::BOLD),
            ),
            width,
        )
    } else {
        (Span::raw(""), 0)
    }
}

/// Render the agent flash breadcrumb with a style that's visually distinct
/// from regular info messages. We reuse the info palette but add a REVERSED
/// modifier so it pops against a backdrop of other info-styled indicators
/// (tour mode, AI summary badge) that already use the info theme colors.
pub fn build_flash_span(text: &str, theme: &Theme) -> (Span<'static>, usize) {
    let content = format!(" {text} ");
    let width = content.len();
    (
        Span::styled(
            content,
            Style::default()
                .fg(theme.message_info_fg)
                .bg(theme.message_info_bg)
                .add_modifier(Modifier::BOLD | Modifier::REVERSED),
        ),
        width,
    )
}

pub fn build_right_aligned_spans<'a>(
    mut left_spans: Vec<Span<'a>>,
    message_span: Span<'a>,
    message_width: usize,
    total_width: usize,
) -> Vec<Span<'a>> {
    let left_width: usize = left_spans.iter().map(|s| s.content.len()).sum();
    let padding_width = total_width.saturating_sub(left_width + message_width);
    let padding = Span::raw(" ".repeat(padding_width));

    left_spans.push(padding);
    if message_width > 0 {
        left_spans.push(message_span);
    }
    left_spans
}

pub fn render_header(frame: &mut Frame, app: &App, area: Rect) {
    let theme = &app.theme;
    let vcs_type = &app.vcs_info.vcs_type;
    let branch = app.vcs_info.branch_name.as_deref().unwrap_or("detached");

    let title = " trv - Code Review ".to_string();
    let vcs_info = format!("[{vcs_type}:{branch}] ");

    // Show diff source info
    let source_info = match &app.diff_source {
        DiffSource::WorkingTree => String::new(),
        DiffSource::Staged => "[staged] ".to_string(),
        DiffSource::Unstaged => "[unstaged] ".to_string(),
        DiffSource::StagedAndUnstaged => "[staged + unstaged] ".to_string(),
        DiffSource::CommitRange(commits) => {
            if commits.len() == 1 {
                format!("[commit {}] ", &commits[0][..7.min(commits[0].len())])
            } else {
                match app.commit_select.selection_range {
                    Some((start, end)) if end - start + 1 < app.inline_selector.commits.len() => {
                        format!(
                            "[{}/{} commits] ",
                            end - start + 1,
                            app.inline_selector.commits.len()
                        )
                    }
                    _ => format!("[{} commits] ", commits.len()),
                }
            }
        }
        DiffSource::StagedUnstagedAndCommits(commits) => {
            if commits.len() == 1 {
                format!(
                    "[staged + unstaged + commit {}] ",
                    &commits[0][..7.min(commits[0].len())]
                )
            } else {
                format!("[staged + unstaged + {} commits] ", commits.len())
            }
        }
        DiffSource::Remote { pr_number, .. } => {
            format!("[PR #{pr_number}] ")
        }
    };

    let progress = format!("{}/{} reviewed ", app.reviewed_count(), app.file_count());

    let title_span = Span::styled(title, styles::header_style(theme));
    let vcs_span = Span::styled(vcs_info, Style::default().fg(theme.fg_secondary));
    let source_span = Span::styled(source_info, Style::default().fg(theme.diff_hunk_header));
    let progress_span = Span::styled(
        progress,
        if app.reviewed_count() == app.file_count() {
            styles::reviewed_style(theme)
        } else {
            styles::pending_style(theme)
        },
    );

    let (update_span, update_width) = if let Some(ref info) = app.update_info {
        if info.update_available {
            let text = format!(" v{} available ", info.latest_version);
            let width = text.len();
            (
                Span::styled(
                    text,
                    Style::default()
                        .fg(theme.update_badge_fg)
                        .bg(theme.update_badge_bg)
                        .add_modifier(Modifier::BOLD),
                ),
                width,
            )
        } else if info.is_ahead {
            let text = format!(" unreleased v{} ", info.current_version);
            let width = text.len();
            (
                Span::styled(
                    text,
                    Style::default()
                        .fg(theme.update_badge_fg)
                        .bg(theme.update_badge_bg)
                        .add_modifier(Modifier::BOLD),
                ),
                width,
            )
        } else {
            (Span::raw(""), 0)
        }
    } else {
        (Span::raw(""), 0)
    };

    let left_spans = vec![title_span, vcs_span, source_span, progress_span];
    let left_width: usize = left_spans.iter().map(|s| s.content.len()).sum();
    let total_width = area.width as usize;
    let padding_width = total_width.saturating_sub(left_width + update_width);

    let mut spans = left_spans;
    spans.push(Span::raw(" ".repeat(padding_width)));
    if update_width > 0 {
        spans.push(update_span);
    }

    let line = Line::from(spans);

    let header = Paragraph::new(line)
        .style(styles::status_bar_style(theme))
        .block(Block::default());

    frame.render_widget(header, area);
}

pub fn render_status_bar(frame: &mut Frame, app: &App, area: Rect) {
    let theme = &app.theme;

    // In command/search mode, show the input on the left (vim-style)
    let left_spans = if matches!(
        app.nav.input_mode,
        InputMode::Command | InputMode::Search | InputMode::CommandPalette
    ) {
        let prefix = match app.nav.input_mode {
            InputMode::Search => "/",
            _ => ":",
        };
        let buffer: &str = match app.nav.input_mode {
            InputMode::Search => &app.search_buffer,
            _ => app.palette.buffer(),
        };
        let command_text = format!("{prefix}{buffer}");
        vec![Span::styled(
            command_text,
            Style::default().fg(theme.fg_primary),
        )]
    } else {
        let mode_str = match app.nav.input_mode {
            InputMode::Normal => {
                // In live review mode, replace NORMAL with LIVE and append
                // the last refresh timestamp (if any) so the human knows
                // when the watcher last tripped a rescan.
                if app.live.active {
                    match app.live.last_refresh_at {
                        Some(ts) => {
                            let stamp = ts.format("%H:%M:%S");
                            if let Some(count) = app.pending_count {
                                format!(" LIVE {count} · {stamp} ")
                            } else {
                                format!(" LIVE · {stamp} ")
                            }
                        }
                        None => {
                            if let Some(count) = app.pending_count {
                                format!(" LIVE {count} ")
                            } else {
                                " LIVE ".to_string()
                            }
                        }
                    }
                } else if let Some(count) = app.pending_count {
                    format!(" NORMAL {count} ")
                } else {
                    " NORMAL ".to_string()
                }
            }
            InputMode::Command => " COMMAND ".to_string(),
            InputMode::Search => " SEARCH ".to_string(),
            InputMode::Comment => " COMMENT ".to_string(),
            InputMode::Help => " HELP ".to_string(),
            InputMode::Confirm => " CONFIRM ".to_string(),
            InputMode::CommitSelect => " SELECT ".to_string(),
            InputMode::VisualSelect => {
                if let Some((range, _)) = app.get_visual_selection() {
                    if range.is_single() {
                        format!(" VISUAL L{} ", range.start)
                    } else {
                        format!(" VISUAL L{}-L{} ", range.start, range.end)
                    }
                } else {
                    " VISUAL ".to_string()
                }
            }
            InputMode::ReviewSubmit => " REVIEW ".to_string(),
            InputMode::CommandPalette => " COMMAND ".to_string(),
            InputMode::ReactionPicker => " REACTION ".to_string(),
            InputMode::CommentTemplatePicker => " TEMPLATE ".to_string(),
            InputMode::MentalModelEdit => " MENTAL MODEL ".to_string(),
        };

        let mode_span = Span::styled(mode_str, styles::mode_style(theme));

        let hints = match app.nav.input_mode {
            InputMode::Normal => {
                " j,k (scroll)  r (reviewed)  c (comment)  \\ (files)  <,> (resize)  ? (help)  : (commands) "
            }
            InputMode::Command => " Enter (execute)  Esc (cancel) ",
            InputMode::Search => " Enter (search)  Esc (cancel) ",
            InputMode::Comment => " Ctrl-S (save)  Esc (cancel) ",
            InputMode::Help => " q,?,Esc (close) ",
            InputMode::Confirm => " y (yes)  n (no) ",
            InputMode::CommitSelect => {
                " j,k (navigate)  Space (select)  Enter (confirm)  Esc (back)  q (quit) "
            }
            InputMode::VisualSelect => " j,k (extend)  c,Enter (comment)  Esc,V (cancel) ",
            InputMode::ReviewSubmit => {
                if app.remote().is_some_and(|r| r.review_body_editing) {
                    " Type body text  Esc (back to verdict)  Ctrl+S (submit) "
                } else {
                    " j,k (verdict)  Enter (edit body)  Ctrl+S (submit)  Esc (cancel) "
                }
            }
            InputMode::CommandPalette => " Enter (execute)  Esc (cancel)  j,k (navigate) ",
            InputMode::ReactionPicker => {
                " \u{2190}/\u{2192} (move)  Enter (select)  1-8 (quick)  Esc (cancel) "
            }
            InputMode::CommentTemplatePicker => " Enter (insert)  Esc (cancel)  j,k (navigate) ",
            InputMode::MentalModelEdit => {
                " Tab (next field)  Shift+Tab (prev)  Ctrl+S (save)  Esc (cancel) "
            }
        };
        let hints_span = Span::styled(hints, Style::default().fg(theme.fg_secondary));

        let dirty_indicator = if app.dirty {
            Span::styled(" [modified] ", Style::default().fg(theme.pending))
        } else {
            Span::raw("")
        };

        // When in tour mode, show the current stop + a truncated summary so
        // both human and agent can see where they are. Appends
        // `threshold=N risk=M` so the human sees the active aggressiveness
        // and the current stop's risk at a glance.
        let tour_indicator = if let Some(tour) = app.tour.plan.as_ref()
            && let Some(stop) = tour.current()
        {
            let n = tour.stops.len();
            let i = tour.index + 1;
            let summary = stop.summary.trim();
            let short = if summary.chars().count() > 40 {
                let mut s: String = summary.chars().take(39).collect();
                s.push('');
                s
            } else {
                summary.to_string()
            };
            let batched = if stop.is_batched() {
                format!(" ({} commits)", stop.commit_ids.len())
            } else {
                String::new()
            };
            let threshold = tour.threshold.as_u8();
            let risk = stop.risk.as_u8();
            Span::styled(
                format!(" Tour {i}/{n}{batched} threshold={threshold} risk={risk}: {short} "),
                Style::default()
                    .fg(theme.message_info_fg)
                    .bg(theme.message_info_bg)
                    .add_modifier(Modifier::BOLD),
            )
        } else {
            Span::raw("")
        };

        // Triage counts appear whenever any tour comment has been triaged, so
        // the human can see agent progress at a glance. Persists past tour_end.
        let triage_indicator = {
            let (live, obsolete, moved) = app.tour_triage_counts();
            if live + obsolete + moved > 0 {
                Span::styled(
                    format!(" · {live}L {obsolete}O {moved}M "),
                    Style::default().fg(theme.fg_secondary),
                )
            } else {
                Span::raw("")
            }
        };

        // Phase I3b: `[blind]` badge shown while `--blind-tests` /
        // `:blind` is filtering paths out of the diff view. Reviewers
        // pair this with `:unblind` when they're ready to see the
        // hidden files. Dim so it doesn't fight with the more urgent
        // status segments.
        let blind_indicator = if app.blind_mode {
            Span::styled(" [blind] ", Style::default().fg(theme.fg_secondary))
        } else {
            Span::raw("")
        };

        // Phase I1a + I6 + I5-2b: `[spar: L/N]` badge shown while
        // Sparring Review mode is active. `N` is the count of active
        // (non-resolved) specs; `L` is the number currently linked
        // to a generated test per the most recent `scan_spec_links`
        // pass. When every active spec is linked we swap to `N✓`
        // so the reviewer sees "everything's addressed" at a glance.
        // Reconciling counts land once the test-runner integration
        // (I4c-3) fills in `SparringStatus::Reconciling`.
        let spar_indicator = if app.spar_mode {
            let n = app.engine.session().spec_count();
            let label = if n == 0 {
                " [spar] ".to_string()
            } else {
                let linked = app
                    .spec_statuses
                    .values()
                    .filter(|s| matches!(s, travelagent_core::sparring::SparringStatus::Linked))
                    .count();
                if linked >= n {
                    format!(" [spar: {n}✓] ")
                } else {
                    format!(" [spar: {linked}/{n}] ")
                }
            };
            Span::styled(label, Style::default().fg(theme.fg_secondary))
        } else {
            Span::raw("")
        };

        // MCP listener badge. Persistent so the human always knows the
        // PID an agent should attach to (no need to read `:mcp-on`'s
        // transient status message).
        //
        //   [mcp:<pid>]              listening, no peers attached (dim)
        //   [mcp:<pid> · N peers]    one or more agents attached (bold accent)
        //   [mcp:draining]           :mcp-off in progress, finishing in-flight
        //                            calls before close (warning hue)
        //
        // Hidden entirely when the listener is off — the absence is the
        // signal. PID comes from std::process::id() since the listener
        // always lives in the running trv's own process.
        let mcp_indicator = if app.mcp_listener.is_draining() {
            Span::styled(
                " [mcp:draining] ",
                Style::default()
                    .fg(theme.pending)
                    .add_modifier(Modifier::BOLD),
            )
        } else if app.mcp_listener.is_on() {
            let pid = std::process::id();
            let peers = app.mcp_peer_count();
            if peers > 0 {
                Span::styled(
                    format!(
                        " [mcp:{pid} · {peers} peer{}] ",
                        if peers == 1 { "" } else { "s" }
                    ),
                    Style::default()
                        .fg(theme.message_info_fg)
                        .bg(theme.message_info_bg)
                        .add_modifier(Modifier::BOLD),
                )
            } else {
                Span::styled(
                    format!(" [mcp:{pid}] "),
                    Style::default().fg(theme.fg_secondary),
                )
            }
        } else {
            Span::raw("")
        };

        // AI summary badge: orange `[AI!]` when a new summary is unread, dim
        // `[AI]` once the user has seen it. Empty when no summary is loaded.
        let ai_summary_indicator = if app.ai.summary.is_some() {
            if app.ai.unread {
                Span::styled(
                    " [AI!] ",
                    Style::default()
                        .fg(theme.pending)
                        .add_modifier(Modifier::BOLD),
                )
            } else {
                Span::styled(" [AI] ", Style::default().fg(theme.fg_secondary))
            }
        } else {
            Span::raw("")
        };

        // Last completed review indicator: shows the wall-clock time of the
        // last successful submit/export. When the PR has advanced past the
        // SHA captured at submit time, an `[reviewed@old]` stale marker is
        // shown instead. Both fields live on the session so they survive
        // a session reload.
        let last_review_indicator = if let Some(ts) = app.engine.session().last_review_submitted_at
        {
            let current_sha = app
                .remote()
                .and_then(|r| r.pr_metadata.as_ref().map(|m| m.head_sha.as_str()));
            let recorded_sha = app.engine.session().last_review_sha.as_deref();
            let is_stale = matches!(
                (recorded_sha, current_sha),
                (Some(rec), Some(cur)) if rec != cur
            );
            if is_stale {
                Span::styled(
                    " [reviewed@old] ".to_string(),
                    Style::default().fg(theme.fg_dim),
                )
            } else {
                let label = ts.format("%H:%M");
                Span::styled(
                    format!(" [reviewed: {label}] "),
                    Style::default().fg(theme.reviewed),
                )
            }
        } else {
            Span::raw("")
        };

        // Cursor-ownership indicator: `📌 pinned` when the human has locked
        // their viewport against agent navigation. When a ghost also exists
        // (agent tried to navigate while pinned), append the ghost's
        // file basename so the human sees "where the agent is looking"
        // without having to press Ctrl+G. Empty in the default follow mode.
        let pin_indicator = if app.viewport_pinned {
            let body = if let Some(g) = app.agent_ghost.as_ref() {
                let base = match g.path.rsplit_once('/') {
                    Some((_, tail)) if !tail.is_empty() => tail,
                    _ => g.path.as_str(),
                };
                format!(" \u{1f4cc} pinned · \u{1f440} agent: {base} ")
            } else {
                " \u{1f4cc} pinned ".to_string()
            };
            Span::styled(
                body,
                Style::default()
                    .fg(theme.message_info_fg)
                    .bg(theme.message_info_bg)
                    .add_modifier(Modifier::BOLD),
            )
        } else {
            Span::raw("")
        };

        // Order matters: the status bar is a single non-wrapping line that
        // clips at the right edge on narrow terminals. Priority, left→right:
        //   1. mode + compact state badges (incl. `[mcp:<pid>]`) — always shown
        //   2. the keybinding `hints` menu — kept on screen (the user relies on
        //      it; it's the same prose as `?`)
        //   3. the long `tour_indicator` LAST — it's the only genuinely long,
        //      lower-priority segment, so it's the first thing to clip when
        //      space is tight (and its summary is already capped at 40 chars).
        // This keeps both the PID indicator and the menu visible; only the
        // tour banner shortens on a narrow terminal.
        vec![
            mode_span,
            dirty_indicator,
            mcp_indicator,
            ai_summary_indicator,
            spar_indicator,
            blind_indicator,
            pin_indicator,
            last_review_indicator,
            hints_span,
            triage_indicator,
            tour_indicator,
        ]
    };

    // Append remote-mode indicators (last refresh, rate limit) before the
    // right-aligned message so they float to the right edge when there's no
    // active message.
    let mut left_spans = left_spans;
    if let Some(r) = app.remote()
        && matches!(app.diff_source, DiffSource::Remote { .. })
    {
        if let Some(ts) = r.last_refreshed_at {
            let rel = format_relative_time(ts, chrono::Utc::now());
            left_spans.push(Span::styled(
                format!(" last: {rel} "),
                Style::default().fg(theme.fg_secondary),
            ));
        }
        if let Some(remaining) = r.rate_limit_remaining
            && remaining < 1000
        {
            left_spans.push(Span::styled(
                format!(" rl: {remaining} "),
                Style::default()
                    .fg(theme.message_warning_fg)
                    .bg(theme.message_warning_bg)
                    .add_modifier(Modifier::BOLD),
            ));
        }
    }

    // Build message span and create right-aligned layout. Errors win over
    // agent flashes (they're more important); otherwise the transient
    // agent-originated breadcrumb supersedes normal info/warning messages
    // so the human sees *why* their cursor just jumped.
    let show_error = matches!(
        app.message.as_ref().map(|m| &m.message_type),
        Some(MessageType::Error)
    );
    let (message_span, message_width) =
        if !show_error && let Some(flash_text) = app.current_flash_text() {
            build_flash_span(flash_text, theme)
        } else {
            build_message_span(app.message.as_ref(), theme)
        };
    let total_width = area.width as usize;
    let spans = build_right_aligned_spans(left_spans, message_span, message_width, total_width);

    let line = Line::from(spans);

    let status = Paragraph::new(line)
        .style(styles::status_bar_style(theme))
        .block(Block::default());

    frame.render_widget(status, area);
}

#[cfg(test)]
mod tests {
    use super::*;

    fn test_message(message_type: MessageType) -> Message {
        Message {
            content: "hello".to_string(),
            message_type,
        }
    }

    #[test]
    fn should_style_info_message_using_theme_fields() {
        let theme = Theme::dark();
        let (span, width) = build_message_span(Some(&test_message(MessageType::Info)), &theme);
        assert_eq!(span.style.fg, Some(theme.message_info_fg));
        assert_eq!(span.style.bg, Some(theme.message_info_bg));
        assert_eq!(width, " hello ".len());
    }

    #[test]
    fn should_return_empty_span_when_message_is_none() {
        let theme = Theme::dark();
        let (span, width) = build_message_span(None, &theme);
        assert_eq!(span.content.as_ref(), "");
        assert_eq!(width, 0);
    }

    #[test]
    fn should_style_warning_message_using_theme_fields() {
        let theme = Theme::dark();
        let (span, _) = build_message_span(Some(&test_message(MessageType::Warning)), &theme);
        assert_eq!(span.style.fg, Some(theme.message_warning_fg));
        assert_eq!(span.style.bg, Some(theme.message_warning_bg));
    }

    #[test]
    fn should_style_error_message_using_theme_fields() {
        let theme = Theme::dark();
        let (span, _) = build_message_span(Some(&test_message(MessageType::Error)), &theme);
        assert_eq!(span.style.fg, Some(theme.message_error_fg));
        assert_eq!(span.style.bg, Some(theme.message_error_bg));
    }

    #[test]
    fn build_flash_span_uses_info_palette_with_reversed_modifier() {
        // Lock in the "visually distinct from normal info messages" contract:
        // the flash must still use the info theme colors, but it adds the
        // REVERSED modifier so it stands out against other info-styled bits
        // of the status bar (tour indicator, AI badge) that already share
        // the same palette.
        let theme = Theme::dark();
        let (span, width) = build_flash_span("\u{1f916} agent: jumped to foo.rs", &theme);

        assert!(span.content.contains("agent: jumped to foo.rs"));
        assert_eq!(width, span.content.len());
        assert_eq!(span.style.fg, Some(theme.message_info_fg));
        assert_eq!(span.style.bg, Some(theme.message_info_bg));
        assert!(span.style.add_modifier.contains(Modifier::BOLD));
        assert!(span.style.add_modifier.contains(Modifier::REVERSED));
    }

    #[test]
    fn format_relative_time_under_five_seconds_reads_just_now() {
        let now = chrono::Utc::now();
        let earlier = now - chrono::Duration::seconds(2);
        assert_eq!(format_relative_time(earlier, now), "just now");
    }

    #[test]
    fn format_relative_time_seconds() {
        let now = chrono::Utc::now();
        let earlier = now - chrono::Duration::seconds(30);
        assert_eq!(format_relative_time(earlier, now), "30s ago");
    }

    #[test]
    fn format_relative_time_minutes() {
        let now = chrono::Utc::now();
        let earlier = now - chrono::Duration::minutes(2);
        assert_eq!(format_relative_time(earlier, now), "2m ago");
    }

    #[test]
    fn format_relative_time_hours() {
        let now = chrono::Utc::now();
        let earlier = now - chrono::Duration::hours(3);
        assert_eq!(format_relative_time(earlier, now), "3h ago");
    }

    #[test]
    fn format_relative_time_days() {
        let now = chrono::Utc::now();
        let earlier = now - chrono::Duration::days(5);
        assert_eq!(format_relative_time(earlier, now), "5d ago");
    }

    #[test]
    fn format_relative_time_clock_skew_treated_as_just_now() {
        let now = chrono::Utc::now();
        let future = now + chrono::Duration::seconds(10);
        assert_eq!(format_relative_time(future, now), "just now");
    }

    #[test]
    fn format_relative_time_hour_and_day_boundary() {
        // Exactly 60 minutes rolls over into "1h ago"; 3600 seconds is the
        // boundary. Similarly 24h becomes "1d ago". Regression guard for the
        // `< 60` / `< 24` comparisons.
        let now = chrono::Utc::now();
        // 59 minutes — last stop in the minutes branch.
        let earlier = now - chrono::Duration::minutes(59);
        assert_eq!(format_relative_time(earlier, now), "59m ago");
        // 60 minutes — crosses into hours.
        let earlier = now - chrono::Duration::minutes(60);
        assert_eq!(format_relative_time(earlier, now), "1h ago");
        // 23 hours stays in the hours branch.
        let earlier = now - chrono::Duration::hours(23);
        assert_eq!(format_relative_time(earlier, now), "23h ago");
        // 24 hours flips to days.
        let earlier = now - chrono::Duration::hours(24);
        assert_eq!(format_relative_time(earlier, now), "1d ago");
    }

    #[test]
    fn format_relative_time_minute_boundary() {
        let now = chrono::Utc::now();
        // Exactly 60 seconds → 1m ago (minutes branch).
        let earlier = now - chrono::Duration::seconds(60);
        assert_eq!(format_relative_time(earlier, now), "1m ago");
        // 59 seconds stays in the seconds branch.
        let earlier = now - chrono::Duration::seconds(59);
        assert_eq!(format_relative_time(earlier, now), "59s ago");
    }
}