Skip to main content

agentmux_launcher/
splash_core.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Shared startup-splash timeline logic: the row model, event application
5//! with same-tick count-up deferral, a frozen-row finalizer, duration
6//! formatting, and total/other reconciliation — used identically by all
7//! three platform splash renderers (`splash.rs` Windows, `splash_mac.rs`
8//! macOS, `splash_linux/` Linux).
9//!
10//! WHY THIS EXISTS NOW, NOT EARLIER. Before this module, each platform
11//! reimplemented this exact logic from scratch — `splash_mac.rs`'s own doc
12//! comment explained why at the time: "editing two already-working splashes
13//! I cannot build or run to verify" was too risky for the PR that first
14//! needed a macOS stage panel. The predictable result (see
15//! `docs/reports/REPORT_SPLASH_SCREEN_ARCHITECTURE_RETHINK_2026_09_14.md`
16//! §1): the same-tick count-up deferral fix landed only on macOS, the
17//! frozen-row defect (a row whose `End` never arrives stays visually
18//! "running" forever once the render loop stops redrawing on a timer) was
19//! never fixed on ANY platform — including macOS, despite it having the
20//! count-up fix — and total/other reconciliation existed only on macOS, as
21//! a bare unreconciled `"total:"` line on Windows and not at all on Linux.
22//! Three independent implementations meant every fix needed to land three
23//! times, and in practice none of them ever did.
24//!
25//! Platform-specific compositing (Win32 GDI blitting, Cocoa NSTextField
26//! layout, X11/Wayland pixel buffers) stays in each platform's own file —
27//! only the pure logic (no FFI, no windowing, no `Instant` mocking needed)
28//! lives here, which is also what makes it unit-testable without a live
29//! window on any platform, including the two this was written on without
30//! being able to run them.
31
32#[cfg(any(target_os = "windows", target_os = "macos", test))]
33use std::time::Duration;
34use std::time::Instant;
35
36use crate::startup_events::{StartupEvent, StartupStatus};
37
38/// A completed sub-item or stage's outcome: elapsed ms, status, and an
39/// optional short annotation carried over from the originating event.
40pub type Outcome = (u64, StartupStatus, Option<String>);
41
42pub struct SubEntry {
43    pub id: String,
44    pub label: String,
45    pub started_at: Instant,
46    pub done: Option<Outcome>,
47}
48
49pub struct StageEntry {
50    pub stage: &'static str,
51    pub label: &'static str,
52    pub started_at: Instant,
53    pub done: Option<Outcome>,
54    pub subs: Vec<SubEntry>,
55}
56
57/// The `stage` of a row the timeline opens itself when a stage ends and the
58/// next has not begun, so a row is always running between show and dismiss
59/// and the time between stages is measured instead of frozen
60/// (the startup audit in agentmux PR #5218, freeze points F1 and F2).
61pub const GAP_STAGE: &str = "gap";
62
63/// A gap shorter than this is dropped when the next stage begins: it would
64/// only add a row for time nobody waited on.
65pub const GAP_MIN_MS: u64 = 150;
66
67/// The widest stage label the Windows and macOS splashes show whole; longer
68/// ones are cut with "..". Every stage and gap label must fit
69/// (`every_stage_label_fits_the_splash`).
70// Linux's text splash has its own wider column (`splash_linux`).
71#[cfg_attr(target_os = "linux", allow(dead_code))]
72pub const STAGE_LABEL_MAX_CHARS: usize = 16;
73
74/// What runs after `stage` ends and before the next stage reports, as the
75/// gap row's label. `None` after the last stage: nothing follows it.
76pub fn gap_label_after(stage: &str) -> Option<&'static str> {
77    match stage {
78        "paint" => None,
79        "prep" | "migrations" | "prepare" => Some("Starting backend"),
80        "backend" => Some("Starting window"),
81        "host" => Some("Connecting"),
82        "dlopen" => Some("Starting engine"),
83        "cef_init" => Some("Loading the UI"),
84        _ => Some("Waiting"),
85    }
86}
87
88/// Identifies which row a `Begin` event created, so the same-tick deferral
89/// in `apply_tick` can recognize an `End` for a row created in the very same
90/// batch.
91#[derive(PartialEq)]
92enum BeginKey {
93    Stage(&'static str),
94    Sub(&'static str, String),
95}
96
97/// The full timeline: every stage/sub-item seen so far, plus the state the
98/// same-tick deferral needs to carry between calls.
99#[derive(Default)]
100pub struct StageTimeline {
101    pub stages: Vec<StageEntry>,
102    deferred: Vec<StartupEvent>,
103}
104
105impl StageTimeline {
106    pub fn new() -> Self {
107        Self { stages: Vec::new(), deferred: Vec::new() }
108    }
109
110    fn apply_one(&mut self, ev: StartupEvent) {
111        match ev {
112            StartupEvent::StageBegin { stage, label } => {
113                self.close_gap(Instant::now());
114                // A stage that is still running keeps its one row: a retry of the same wait (a main
115                // page that failed to load and is loaded again) is not a new stage.
116                if self.stages.iter().any(|r| r.stage == stage && r.done.is_none()) {
117                    return;
118                }
119                self.stages.push(StageEntry {
120                    stage,
121                    label,
122                    started_at: Instant::now(),
123                    done: None,
124                    subs: Vec::new(),
125                });
126            }
127            StartupEvent::StageEnd { stage, duration_ms, status, detail } => {
128                let open = self.stages.iter().position(|r| r.stage == stage && r.done.is_none());
129                if let Some(i) = open.or_else(|| self.stages.iter().rposition(|r| r.stage == stage)) {
130                    let observed = self.stages[i].started_at.elapsed().as_millis() as u64;
131                    self.stages[i].done = Some((duration_ms, status, detail));
132                    // A stage reported after the fact (macOS `dlopen`: begin and
133                    // end sent together once the work is done) ran during the gap
134                    // before it, so its time is taken back out of that gap.
135                    self.shrink_gap_before(i, duration_ms.saturating_sub(observed));
136                }
137                if self.stages.iter().all(|r| r.done.is_some()) {
138                    if let Some(label) = gap_label_after(stage) {
139                        self.stages.push(StageEntry {
140                            stage: GAP_STAGE,
141                            label,
142                            started_at: Instant::now(),
143                            done: None,
144                            subs: Vec::new(),
145                        });
146                    }
147                }
148            }
149            StartupEvent::SubBegin { stage, id, label } => {
150                if let Some(row) = self.stages.iter_mut().rev().find(|r| r.stage == stage) {
151                    row.subs.push(SubEntry { id, label, started_at: Instant::now(), done: None });
152                }
153            }
154            StartupEvent::SubEnd { stage, id, duration_ms, status, detail } => {
155                if let Some(row) = self.stages.iter_mut().rev().find(|r| r.stage == stage) {
156                    if let Some(sub) = row.subs.iter_mut().rev().find(|s| s.id == id) {
157                        sub.done = Some((duration_ms, status, detail));
158                    }
159                }
160            }
161        }
162    }
163
164    /// Take `ms` out of the closed gap row just before `self.stages[i]`,
165    /// dropping the gap if what remains is under [`GAP_MIN_MS`].
166    fn shrink_gap_before(&mut self, i: usize, ms: u64) {
167        if ms == 0 || i == 0 {
168            return;
169        }
170        let gap = &mut self.stages[i - 1];
171        let Some((gap_ms, _, _)) = gap.done.as_mut() else { return };
172        if gap.stage != GAP_STAGE {
173            return;
174        }
175        *gap_ms = gap_ms.saturating_sub(ms);
176        if *gap_ms < GAP_MIN_MS {
177            self.stages.remove(i - 1);
178        }
179    }
180
181    /// End an open gap row at `at`: keep it with its duration, or drop it if
182    /// it was shorter than [`GAP_MIN_MS`].
183    fn close_gap(&mut self, at: Instant) {
184        let Some(last) = self.stages.last_mut() else { return };
185        if last.stage != GAP_STAGE || last.done.is_some() {
186            return;
187        }
188        let ms = at.saturating_duration_since(last.started_at).as_millis() as u64;
189        if ms < GAP_MIN_MS {
190            self.stages.pop();
191        } else {
192            last.done = Some((ms, StartupStatus::Ok, None));
193        }
194    }
195
196    /// Apply one tick's worth of freshly-drained events, deferring any `End`
197    /// whose matching `Begin` *also* arrived in this same batch to the next
198    /// call — guaranteeing every row spends at least one call (and, since
199    /// every platform's render loop redraws every tick while anything is
200    /// running, at least one paint) in the "running" state before it can
201    /// complete.
202    ///
203    /// Without this, a step whose real work finishes inside a single drain
204    /// interval creates its row already-done — no "running" frame is ever
205    /// painted, so it just snaps to its final value instead of visibly
206    /// counting up
207    /// (`docs/analysis/ANALYSIS_SPLASH_SCREEN_TIMING_2026_07_20.md` §2 first
208    /// diagnosed this; fixed only on macOS at the time — see this module's
209    /// doc comment for why it's here, for every platform, now).
210    ///
211    /// Returns `true` if anything changed (a redraw is warranted).
212    pub fn apply_tick(&mut self, fresh: Vec<StartupEvent>) -> bool {
213        let mut changed = false;
214        let deferred = std::mem::take(&mut self.deferred);
215        for ev in deferred {
216            self.apply_one(ev);
217            changed = true;
218        }
219        let mut began_this_tick: Vec<BeginKey> = Vec::new();
220        for ev in fresh {
221            let defer = match &ev {
222                StartupEvent::StageEnd { stage, .. } => {
223                    began_this_tick.contains(&BeginKey::Stage(stage))
224                }
225                StartupEvent::SubEnd { stage, id, .. } => {
226                    began_this_tick.contains(&BeginKey::Sub(stage, id.clone()))
227                }
228                _ => false,
229            };
230            if defer {
231                self.deferred.push(ev);
232                continue;
233            }
234            match &ev {
235                StartupEvent::StageBegin { stage, .. } => {
236                    began_this_tick.push(BeginKey::Stage(stage));
237                }
238                StartupEvent::SubBegin { stage, id, .. } => {
239                    began_this_tick.push(BeginKey::Sub(stage, id.clone()));
240                }
241                _ => {}
242            }
243            self.apply_one(ev);
244            changed = true;
245        }
246        changed
247    }
248
249    /// Called once, at the moment the splash detects readiness (or its
250    /// safety timeout), for every stage/sub-item still lacking a matching
251    /// `End`. Without this, such a row stays visually "running" (live
252    /// counter, running color) forever once the render loop stops
253    /// redrawing on a timer and switches to redrawing only on-change (or,
254    /// pre-refactor Linux, stops updating entirely once composited for
255    /// dismiss) — the row is drawn once more at the freeze and then never
256    /// again, frozen exactly where it was.
257    ///
258    /// See `docs/reports/REPORT_SPLASH_SCREEN_ARCHITECTURE_RETHINK_2026_09_14.md`
259    /// §2.2 for an already-shipping concrete instance this closes: Windows'
260    /// `first-run-wait` sub-row has no `sub_end` call anywhere in the
261    /// codebase and was frozen "running" for the rest of every boot that
262    /// triggered it, on every platform, including macOS despite macOS
263    /// already having the count-up fix — the two defects are independent.
264    ///
265    /// Reuses `StartupStatus::Warn` rather than adding a new status variant:
266    /// "didn't receive a definitive completion signal before the splash
267    /// dismissed" is itself a real warning-worthy condition, not a third
268    /// rendering concept every platform's color table would need a new arm
269    /// for.
270    ///
271    /// Flushes `self.deferred` first, as genuine completions — NOT as
272    /// abandoned/interrupted work. An entry sitting in `deferred` is a real
273    /// `End` that already arrived; it was only held back one tick so its
274    /// row got at least one "running" paint first (`apply_tick`'s deferral).
275    /// If readiness is detected in that exact same tick, finalizing before
276    /// flushing would discard the row's true, already-known outcome and
277    /// replace it with a synthetic "interrupted" one — wrong, and worse on
278    /// Windows than elsewhere: its dismiss path calls this once and then
279    /// freezes the summary for the whole hold + fade with no further
280    /// `apply_tick` call, so the wrong value would be the only one the user
281    /// ever sees (codex P1 / reagent P1 on PR #3222).
282    pub fn finalize_running(&mut self, at: Instant) {
283        let deferred = std::mem::take(&mut self.deferred);
284        for ev in deferred {
285            self.apply_one(ev);
286        }
287        // A gap open at readiness ran until now: it is real time, not an
288        // interrupted step.
289        self.close_gap(at);
290        for stage in &mut self.stages {
291            if stage.done.is_none() {
292                let ms = at.saturating_duration_since(stage.started_at).as_millis() as u64;
293                stage.done = Some((ms, StartupStatus::Warn, Some("interrupted".to_string())));
294            }
295            for sub in &mut stage.subs {
296                if sub.done.is_none() {
297                    let ms = at.saturating_duration_since(sub.started_at).as_millis() as u64;
298                    sub.done = Some((ms, StartupStatus::Warn, Some("interrupted".to_string())));
299                }
300            }
301        }
302    }
303}
304
305// ── Visible rows: summarize, then keep the latest in view ────────────────────
306
307/// How many of a stage's sub-items are rendered individually. Anything older
308/// collapses into a single tally row.
309///
310/// Two, not one: the newest sub-item is usually the one still running, and
311/// seeing only it gives no sense of progress — the one just finished, with its
312/// real duration, is what tells you the batch is moving. Anything beyond that
313/// is history the user cannot act on, which is exactly the "too many detailed
314/// entries" complaint in
315/// `docs/reports/REPORT_SPLASH_MIGRATION_ROW_OVERFLOW_AND_SUMMARY_2026_09_15.md`.
316pub const SUB_DETAIL_MAX: usize = 2;
317
318/// What one rendered line stands for. Platform renderers match on this and
319/// draw it their own way (GDI text, an `NSTextField` pair, a formatted
320/// string) — the *selection* of what to draw is shared, which is the part
321/// that was wrong in three places independently.
322pub enum RowKind<'a> {
323    Stage(&'a StageEntry),
324    Sub(&'a SubEntry),
325    /// Stands in for sub-items collapsed out of the detail list.
326    /// `done` of `total` sub-items in this stage have completed.
327    SubTally { done: usize, total: usize },
328    /// One line of the end detail of the row above it: why a finished stage
329    /// or sub-item warned or failed (for example "Can't reach the app page:
330    /// ERR_CONNECTION_REFUSED, retrying"). `status` is that row's status, so
331    /// the line is coloured like its time. `indented` is true under a sub-item.
332    Detail { text: String, status: StartupStatus, indented: bool },
333}
334
335pub struct Row<'a> {
336    pub kind: RowKind<'a>,
337}
338
339/// How much room a renderer has for a finished row's end detail: the
340/// characters one line holds, and the most lines one detail may take.
341#[derive(Clone, Copy)]
342pub struct DetailLayout {
343    pub width: usize,
344    pub max_lines: usize,
345}
346
347/// Break `text` into at most `max_lines` lines of at most `width` characters,
348/// at spaces. A word wider than a line is split. When the text does not fit,
349/// the last line ends in ".." (never wider than `width`).
350pub fn wrap_detail(text: &str, width: usize, max_lines: usize) -> Vec<String> {
351    if width < 3 || max_lines == 0 {
352        return Vec::new();
353    }
354    let mut lines: Vec<String> = Vec::new();
355    let mut cur = String::new();
356    let mut cur_len = 0usize;
357    for word in text.split_whitespace() {
358        let mut word: Vec<char> = word.chars().collect();
359        // A word wider than a line fills whole lines until the rest fits.
360        while word.len() > width {
361            if cur_len > 0 {
362                lines.push(std::mem::take(&mut cur));
363                cur_len = 0;
364            }
365            lines.push(word.drain(..width).collect());
366        }
367        if word.is_empty() {
368            continue;
369        }
370        let need = if cur_len == 0 { word.len() } else { cur_len + 1 + word.len() };
371        if need > width {
372            lines.push(std::mem::take(&mut cur));
373            cur_len = 0;
374        }
375        if cur_len > 0 {
376            cur.push(' ');
377            cur_len += 1;
378        }
379        cur.extend(word.iter());
380        cur_len += word.len();
381    }
382    if cur_len > 0 {
383        lines.push(cur);
384    }
385    if lines.len() > max_lines {
386        lines.truncate(max_lines);
387        let last = lines.pop().unwrap_or_default();
388        let last = last.trim_end_matches([',', ';', ':', ' ']);
389        let keep: String = last.chars().take(width - 2).collect();
390        lines.push(format!("{}..", keep.trim_end_matches([',', ';', ':', ' '])));
391    }
392    lines
393}
394
395/// The detail lines to show under a row that ended: only a warn or error
396/// outcome with a detail says anything the time column does not.
397fn detail_rows<'a>(done: &Option<Outcome>, indented: bool, layout: Option<DetailLayout>) -> Vec<Row<'a>> {
398    let (Some(layout), Some((_, status, Some(detail)))) = (layout, done) else { return Vec::new() };
399    if *status == StartupStatus::Ok {
400        return Vec::new();
401    }
402    // Indented rows start two glyphs further right, and have that much less room.
403    let width = if indented { layout.width.saturating_sub(2) } else { layout.width };
404    wrap_detail(detail, width, layout.max_lines)
405        .into_iter()
406        .map(|text| Row { kind: RowKind::Detail { text, status: *status, indented } })
407        .collect()
408}
409
410/// The label for a collapsed-sub-items row. Shared so all three platforms
411/// word it identically.
412pub fn tally_label(done: usize, total: usize) -> String {
413    format!("{done}/{total} done")
414}
415
416/// Flatten `stages` into at most `budget` rows: summarize each stage's older
417/// sub-items into a tally, then — if that still doesn't fit — keep the
418/// **newest** rows rather than the oldest.
419///
420/// The keep-the-newest half is the behavior change. Every platform previously
421/// iterated stages oldest-first and stopped dead at its row cap
422/// (`if row >= MAX_STAGE_ROWS { break }`), so a long sub-item burst filled the
423/// panel with the *earliest* entries and never showed the one currently
424/// running — the opposite of what a progress display is for, and the reason a
425/// slow startup looked frozen rather than busy. See the report above.
426pub fn visible_rows(stages: &[StageEntry], budget: usize, detail: Option<DetailLayout>) -> Vec<Row<'_>> {
427    // One block per stage: its own rows first (the stage row and the lines of
428    // its end detail), then its (summarized) sub rows, each with its own
429    // detail lines. Trimming happens block-wise below — an indented row must
430    // never outlive the stage row it belongs under, nor a detail line the row
431    // it explains.
432    struct Block<'a> {
433        head: Vec<Row<'a>>,
434        units: Vec<Vec<Row<'a>>>,
435    }
436    let mut blocks: Vec<Block<'_>> = Vec::new();
437    for stage in stages {
438        let mut head = vec![Row { kind: RowKind::Stage(stage) }];
439        head.extend(detail_rows(&stage.done, false, detail));
440        let mut units: Vec<Vec<Row<'_>>> = Vec::new();
441        let subs = &stage.subs;
442        let shown = if subs.len() > SUB_DETAIL_MAX {
443            // Counted over ALL of the stage's sub-items, not just the hidden
444            // ones: this is the stage's progress ratio, so it has to keep
445            // rising as the two always-shown items finish too.
446            let done = subs.iter().filter(|s| s.done.is_some()).count();
447            units.push(vec![Row { kind: RowKind::SubTally { done, total: subs.len() } }]);
448            &subs[subs.len() - SUB_DETAIL_MAX..]
449        } else {
450            &subs[..]
451        };
452        for sub in shown {
453            let mut unit = vec![Row { kind: RowKind::Sub(sub) }];
454            unit.extend(detail_rows(&sub.done, true, detail));
455            units.push(unit);
456        }
457        blocks.push(Block { head, units });
458    }
459
460    // Fill from the newest block backwards. A block that only partially fits
461    // keeps its stage row (and its detail, as far as it fits) plus as many of
462    // its newest sub rows as are left — never the children alone, which would
463    // render as indented rows dangling under whatever stage happened to
464    // precede them.
465    let mut out: Vec<Row<'_>> = Vec::new();
466    let mut remaining = budget;
467    for block in blocks.into_iter().rev() {
468        if remaining == 0 {
469            break;
470        }
471        let total = block.head.len() + block.units.iter().map(Vec::len).sum::<usize>();
472        let mut chunk: Vec<Row<'_>> = if total <= remaining {
473            let mut chunk = block.head;
474            chunk.extend(block.units.into_iter().flatten());
475            chunk
476        } else {
477            let mut chunk = block.head;
478            chunk.truncate(remaining);
479            let mut room = remaining - chunk.len();
480            let mut kept: Vec<Vec<Row<'_>>> = Vec::new();
481            for unit in block.units.into_iter().rev() {
482                if unit.len() > room {
483                    break;
484                }
485                room -= unit.len();
486                kept.push(unit);
487            }
488            chunk.extend(kept.into_iter().rev().flatten());
489            chunk
490        };
491        remaining -= chunk.len();
492        chunk.append(&mut out);
493        out = chunk;
494    }
495    out
496}
497
498// ── Formatting ───────────────────────────────────────────────────────────────
499
500#[cfg(any(target_os = "windows", target_os = "macos"))]
501pub fn format_ms(ms: u64) -> String {
502    if ms >= 10_000 {
503        format!("{:.0}s", ms as f64 / 1000.0)
504    } else if ms >= 1_000 {
505        format!("{:.1}s", ms as f64 / 1000.0)
506    } else {
507        format!("{ms}ms")
508    }
509}
510
511#[cfg(any(target_os = "windows", target_os = "macos"))]
512pub fn format_running(started_at: Instant) -> String {
513    let s = started_at.elapsed().as_secs_f32();
514    if s >= 10.0 {
515        format!("> {:.0}s", s)
516    } else {
517        format!("> {:.1}s", s)
518    }
519}
520
521/// Truncates to `max` chars, appending `..` when it does. Char-based (not
522/// byte-based) so it never splits a multi-byte codepoint.
523pub fn trunc(s: &str, max: usize) -> String {
524    let chars: Vec<char> = s.chars().collect();
525    if chars.len() <= max {
526        s.to_string()
527    } else {
528        chars[..max].iter().collect::<String>() + ".."
529    }
530}
531
532// ── Total / other reconciliation ────────────────────────────────────────────
533
534/// Sum of every *completed* top-level stage's own reported duration.
535/// Only completed stages are summed: a stage's own duration already covers
536/// whatever its subs took (summing subs too would double-count), and an
537/// undone stage would inflate the sum with an ever-changing partial value.
538#[cfg(any(target_os = "windows", target_os = "macos", test))]
539pub fn accounted_ms(stages: &[StageEntry]) -> u64 {
540    stages.iter().filter_map(|s| s.done.as_ref().map(|(dur, ..)| *dur)).sum()
541}
542
543/// `(accounted_ms, other_ms)` given a wall-clock `total_ms`. `other_ms` is
544/// real elapsed time genuinely uncovered by any instrumented stage (process-
545/// spawn scheduling gaps, cef_init-end -> first-paint, etc.) — not a double-
546/// count or a bug; see
547/// `docs/analysis/ANALYSIS_SPLASH_SCREEN_TIMING_2026_07_20.md` §5.
548/// `saturating_sub` guards the should-be-impossible case where accounted
549/// time exceeds the wall-clock total.
550#[cfg(any(target_os = "windows", target_os = "macos", test))]
551pub fn reconcile(stages: &[StageEntry], total_ms: u64) -> (u64, u64) {
552    let accounted = accounted_ms(stages);
553    (accounted, total_ms.saturating_sub(accounted))
554}
555
556// ── Hold duration ────────────────────────────────────────────────────────────
557
558/// How long the splash holds its completed, frozen summary on screen before
559/// fading out. Same env var, same default, on all three platforms — before
560/// this module, Windows and macOS each parsed `AGENTMUX_SPLASH_HOLD_MS`
561/// independently (both happened to converge on the same `2000` default, not
562/// the original spec's documented `3000` — kept here as the actual shipped
563/// behavior rather than "fixing" it to match a spec nothing currently
564/// honors) and Linux used a differently-named, differently-scoped
565/// `min_hold()` answering a different question ("minimum total time
566/// visible" rather than "pause after ready, before dismissing") — see
567/// `docs/reports/REPORT_SPLASH_SCREEN_ARCHITECTURE_RETHINK_2026_09_14.md`
568/// §4.4. Shortened to `min(1000ms)` for a very fast start (<500ms total) so
569/// a near-instant cold start doesn't force an artificially long hold.
570#[cfg(any(target_os = "windows", target_os = "macos", test))]
571pub fn hold_duration(total_ms: u64) -> Duration {
572    let hold_ms = std::env::var("AGENTMUX_SPLASH_HOLD_MS")
573        .ok()
574        .and_then(|v| v.parse::<u64>().ok())
575        .unwrap_or(2000);
576    let hold_ms = if total_ms < 500 { hold_ms.min(1000) } else { hold_ms };
577    Duration::from_millis(hold_ms)
578}
579
580#[cfg(test)]
581mod tests {
582    use super::*;
583    use std::thread::sleep;
584
585    fn begin(stage: &'static str) -> StartupEvent {
586        StartupEvent::StageBegin { stage, label: stage }
587    }
588    fn end(stage: &'static str, ms: u64) -> StartupEvent {
589        StartupEvent::StageEnd { stage, duration_ms: ms, status: StartupStatus::Ok, detail: None }
590    }
591
592    /// Backdate the open gap row so the next begin sees it as `ms` long.
593    fn age_gap(tl: &mut StageTimeline, ms: u64) {
594        let gap = tl.stages.last_mut().unwrap();
595        assert_eq!(gap.stage, GAP_STAGE);
596        gap.started_at = gap.started_at.checked_sub(Duration::from_millis(ms)).unwrap();
597    }
598
599    #[test]
600    fn every_stage_label_fits_the_splash() {
601        let stages = ["prep", "migrations", "prepare", "backend", "host", "dlopen", "cef_init", "paint", "other"];
602        // The labels the launcher and the host report (`stage_begin` calls).
603        let reported = [
604            "Launcher setup", "Updating data", "Backend startup", "Host startup",
605            "Load CEF library", "CEF initialize", "Window paint", "Migrations",
606        ];
607        for label in stages.iter().filter_map(|s| gap_label_after(s)).chain(reported) {
608            assert!(label.chars().count() <= STAGE_LABEL_MAX_CHARS, "{label:?} is cut on the splash");
609        }
610    }
611
612    #[test]
613    fn a_stage_ending_with_none_open_opens_a_gap_named_for_what_runs_next() {
614        let mut tl = StageTimeline::new();
615        tl.apply_tick(vec![begin("host")]);
616        tl.apply_tick(vec![end("host", 30)]);
617        let gap = tl.stages.last().unwrap();
618        assert_eq!((gap.stage, gap.label), (GAP_STAGE, "Connecting"));
619        assert!(gap.done.is_none(), "the gap row is the one running");
620    }
621
622    #[test]
623    fn the_next_stage_closes_a_long_gap_with_its_duration_and_drops_a_short_one() {
624        let mut tl = StageTimeline::new();
625        tl.apply_tick(vec![begin("host")]);
626        tl.apply_tick(vec![end("host", 30)]);
627        age_gap(&mut tl, 1200);
628        tl.apply_tick(vec![begin("cef_init")]);
629        let stages: Vec<&str> = tl.stages.iter().map(|r| r.stage).collect();
630        assert_eq!(stages, vec!["host", GAP_STAGE, "cef_init"]);
631        assert!(tl.stages[1].done.as_ref().unwrap().0 >= 1200);
632
633        tl.apply_tick(vec![end("cef_init", 80)]);
634        tl.apply_tick(vec![begin("paint")]);
635        let stages: Vec<&str> = tl.stages.iter().map(|r| r.stage).collect();
636        assert_eq!(stages, vec!["host", GAP_STAGE, "cef_init", "paint"], "a gap under GAP_MIN_MS leaves no row");
637    }
638
639    #[test]
640    fn no_gap_follows_the_last_stage_or_a_stage_with_another_still_open() {
641        let mut tl = StageTimeline::new();
642        tl.apply_tick(vec![begin("backend"), begin("host")]);
643        tl.apply_tick(vec![end("backend", 10)]);
644        assert_eq!(tl.stages.len(), 2, "host is still open: no gap");
645        tl.apply_tick(vec![end("host", 10)]);
646        age_gap(&mut tl, 500);
647        tl.apply_tick(vec![begin("paint")]);
648        tl.apply_tick(vec![end("paint", 5)]);
649        assert_eq!(tl.stages.last().unwrap().stage, "paint", "nothing follows paint");
650    }
651
652    #[test]
653    fn a_stage_reported_after_the_fact_is_taken_out_of_the_gap_before_it() {
654        let mut tl = StageTimeline::new();
655        tl.apply_tick(vec![begin("host")]);
656        tl.apply_tick(vec![end("host", 30)]);
657        age_gap(&mut tl, 1000);
658        // dlopen's begin and end arrive together, after 700 ms of loading.
659        tl.apply_tick(vec![begin("dlopen"), end("dlopen", 700)]);
660        tl.apply_tick(vec![]);
661        let gap = tl.stages.iter().find(|r| r.stage == GAP_STAGE).expect("300 ms of the gap remain");
662        let ms = gap.done.as_ref().unwrap().0;
663        assert!((300..400).contains(&ms), "gap keeps only the time dlopen didn't report, got {ms}");
664
665        // When the after-the-fact stage covers the whole gap, the gap goes.
666        let mut tl = StageTimeline::new();
667        tl.apply_tick(vec![begin("host")]);
668        tl.apply_tick(vec![end("host", 30)]);
669        age_gap(&mut tl, 500);
670        tl.apply_tick(vec![begin("dlopen"), end("dlopen", 500)]);
671        tl.apply_tick(vec![]);
672        let stages: Vec<&str> = tl.stages.iter().map(|r| r.stage).collect();
673        // No gap is left before dlopen; the one after it is the open wait for
674        // CEF initialize.
675        assert_eq!(stages, vec!["host", "dlopen", GAP_STAGE]);
676        assert!(tl.stages[2].done.is_none());
677    }
678
679    #[test]
680    fn finalize_keeps_an_open_gap_as_real_time_not_interrupted() {
681        let mut tl = StageTimeline::new();
682        tl.apply_tick(vec![begin("cef_init")]);
683        tl.apply_tick(vec![end("cef_init", 10)]);
684        age_gap(&mut tl, 400);
685        tl.finalize_running(Instant::now());
686        let gap = tl.stages.last().unwrap();
687        assert_eq!(gap.stage, GAP_STAGE);
688        let (ms, status, detail) = gap.done.as_ref().unwrap();
689        assert!(*ms >= 400);
690        assert_eq!((*status, detail.as_deref()), (StartupStatus::Ok, None));
691    }
692
693    #[test]
694    fn a_begin_alone_leaves_the_row_running() {
695        let mut tl = StageTimeline::new();
696        assert!(tl.apply_tick(vec![begin("prep")]));
697        assert_eq!(tl.stages.len(), 1);
698        assert!(tl.stages[0].done.is_none());
699    }
700
701    #[test]
702    fn an_end_on_a_later_tick_completes_the_row() {
703        let mut tl = StageTimeline::new();
704        tl.apply_tick(vec![begin("prep")]);
705        assert!(tl.apply_tick(vec![end("prep", 42)]));
706        assert_eq!(tl.stages[0].done.as_ref().unwrap().0, 42);
707    }
708
709    #[test]
710    fn a_same_tick_begin_and_end_is_deferred_not_applied_immediately() {
711        // The count-up bug this module exists to fix on every platform: a
712        // fast step whose Begin+End land in the same drain batch must NOT
713        // be created already-done — the row needs at least one call in the
714        // "running" state.
715        let mut tl = StageTimeline::new();
716        tl.apply_tick(vec![begin("prep"), end("prep", 5)]);
717        assert!(tl.stages[0].done.is_none(), "same-tick End must be deferred, not applied immediately");
718        tl.apply_tick(vec![]);
719        assert_eq!(tl.stages[0].done.as_ref().unwrap().0, 5, "deferred End must apply on the next tick");
720    }
721
722    #[test]
723    fn two_events_in_one_block_do_not_interfere() {
724        let mut tl = StageTimeline::new();
725        tl.apply_tick(vec![begin("prep"), begin("migrations"), end("prep", 5)]);
726        // "prep" is deferred (same-tick begin+end); "migrations" is not
727        // (its Begin has no matching End this tick) and stays running.
728        assert!(tl.stages[0].done.is_none());
729        assert!(tl.stages[1].done.is_none());
730        tl.apply_tick(vec![]);
731        assert_eq!(tl.stages[0].done.as_ref().unwrap().0, 5);
732        assert!(tl.stages[1].done.is_none(), "an unrelated sibling row must not be finalized by an unrelated tick");
733    }
734
735    #[test]
736    fn finalize_running_completes_every_open_row_and_leaves_finished_ones_alone() {
737        let mut tl = StageTimeline::new();
738        tl.apply_tick(vec![begin("prep")]);
739        tl.apply_tick(vec![]);
740        tl.apply_tick(vec![end("prep", 10)]);
741        tl.apply_tick(vec![begin("host")]); // never completes
742        sleep(Duration::from_millis(5));
743
744        tl.finalize_running(Instant::now());
745
746        assert_eq!(tl.stages[0].done.as_ref().unwrap().0, 10, "an already-done row must be left exactly as it was");
747        let host_done = tl.stages[1].done.as_ref().expect("finalize must complete every still-open row");
748        assert_eq!(host_done.1, StartupStatus::Warn);
749    }
750
751    #[test]
752    fn finalize_running_also_closes_open_sub_rows() {
753        // The concrete shipping bug this closes: a sub-row (e.g. Windows'
754        // `first-run-wait`) with no matching SubEnd anywhere.
755        let mut tl = StageTimeline::new();
756        tl.apply_tick(vec![begin("host")]);
757        tl.apply_tick(vec![]);
758        tl.apply_tick(vec![StartupEvent::SubBegin {
759            stage: "host",
760            id: "first-run-wait".into(),
761            label: "First run can take longer".into(),
762        }]);
763        tl.apply_tick(vec![]);
764
765        tl.finalize_running(Instant::now());
766
767        assert!(tl.stages[0].subs[0].done.is_some(), "an orphaned sub-row must be finalized, not left running forever");
768    }
769
770    #[test]
771    fn finalize_running_flushes_a_same_tick_deferral_as_the_real_completion_not_as_interrupted() {
772        // codex P1 / reagent P1 on PR #3222: readiness detected in the exact
773        // same tick a fast stage's Begin+End were deferred (same-tick count-up
774        // fix) must not discard that real, already-known completion and
775        // replace it with a synthetic "interrupted" Warn outcome.
776        let mut tl = StageTimeline::new();
777        tl.apply_tick(vec![begin("prep"), end("prep", 7)]);
778        assert!(tl.stages[0].done.is_none(), "precondition: the End is deferred, not yet applied");
779
780        tl.finalize_running(Instant::now());
781
782        let (ms, status, _) = tl.stages[0].done.as_ref().expect("must be completed one way or another");
783        assert_eq!(*ms, 7, "the row's TRUE duration must survive, not a synthetic elapsed-since-start value");
784        assert_eq!(*status, StartupStatus::Ok, "a real completion must not be downgraded to Warn/interrupted");
785    }
786
787    #[test]
788    fn accounted_and_other_reconcile_exactly_against_total() {
789        let mut tl = StageTimeline::new();
790        tl.apply_tick(vec![begin("prep")]);
791        tl.apply_tick(vec![end("prep", 100)]);
792        tl.apply_tick(vec![begin("backend")]);
793        tl.apply_tick(vec![end("backend", 250)]);
794
795        let (accounted, other) = reconcile(&tl.stages, 500);
796        assert_eq!(accounted, 350);
797        assert_eq!(other, 150);
798        assert_eq!(accounted + other, 500, "accounted + other must equal total exactly, by construction");
799    }
800
801    #[test]
802    fn reconcile_never_panics_when_accounted_exceeds_total() {
803        // Should-be-impossible (a stage can't legitimately take longer than
804        // the whole splash), but a formatting bug must never become a panic.
805        let mut tl = StageTimeline::new();
806        tl.apply_tick(vec![begin("prep")]);
807        tl.apply_tick(vec![end("prep", 1000)]);
808        let (accounted, other) = reconcile(&tl.stages, 10);
809        assert_eq!(accounted, 1000);
810        assert_eq!(other, 0);
811    }
812
813    #[test]
814    fn an_undone_stage_is_excluded_from_accounted_ms() {
815        let mut tl = StageTimeline::new();
816        tl.apply_tick(vec![begin("prep")]);
817        tl.apply_tick(vec![end("prep", 100)]);
818        tl.apply_tick(vec![begin("backend")]); // still running
819        assert_eq!(accounted_ms(&tl.stages), 100);
820    }
821
822    /// Builds a timeline with one stage carrying `n` sub-items, the last of
823    /// which is still running — the shape a migration batch actually has.
824    fn timeline_with_subs(n: usize) -> StageTimeline {
825        let mut tl = StageTimeline::new();
826        tl.apply_tick(vec![begin("backend")]);
827        tl.apply_tick(vec![]);
828        for i in 0..n {
829            let id = format!("m{i:04}");
830            tl.apply_tick(vec![StartupEvent::SubBegin {
831                stage: "backend",
832                id: id.clone(),
833                label: format!("migration {i}"),
834            }]);
835            // Every sub but the last completes.
836            if i + 1 < n {
837                tl.apply_tick(vec![StartupEvent::SubEnd {
838                    stage: "backend",
839                    id,
840                    duration_ms: 10,
841                    status: StartupStatus::Ok,
842                    detail: None,
843                }]);
844            }
845        }
846        tl.apply_tick(vec![]);
847        tl
848    }
849
850    fn labels(rows: &[Row<'_>]) -> Vec<String> {
851        rows.iter()
852            .map(|r| match &r.kind {
853                RowKind::Stage(s) => s.label.to_string(),
854                RowKind::Sub(s) => s.label.clone(),
855                RowKind::SubTally { done, total } => tally_label(*done, *total),
856                RowKind::Detail { text, .. } => format!("detail: {text}"),
857            })
858            .collect()
859    }
860
861    #[test]
862    fn a_short_sub_list_is_shown_in_full_with_no_tally() {
863        let tl = timeline_with_subs(2);
864        let rows = visible_rows(&tl.stages, 12, None);
865        assert_eq!(labels(&rows), vec!["backend", "migration 0", "migration 1"]);
866    }
867
868    #[test]
869    fn a_long_sub_list_collapses_the_older_entries_into_a_tally() {
870        // 9 subs: 8 completed + 1 running. Detail keeps the newest two; the
871        // tally reports the stage's whole ratio, so 8 of 9 are done.
872        let tl = timeline_with_subs(9);
873        let rows = visible_rows(&tl.stages, 12, None);
874        assert_eq!(
875            labels(&rows),
876            vec!["backend", "8/9 done", "migration 7", "migration 8"],
877            "older sub-items must collapse into one tally, not occupy a row each"
878        );
879    }
880
881    #[test]
882    fn the_running_sub_item_survives_summarization() {
883        // The whole point of the display: whatever is happening right now
884        // must be on screen.
885        let tl = timeline_with_subs(20);
886        let rows = visible_rows(&tl.stages, 12, None);
887        let running = rows
888            .iter()
889            .filter_map(|r| match &r.kind {
890                RowKind::Sub(s) if s.done.is_none() => Some(s.label.clone()),
891                _ => None,
892            })
893            .collect::<Vec<_>>();
894        assert_eq!(running, vec!["migration 19"]);
895    }
896
897    #[test]
898    fn overflow_keeps_the_newest_rows_not_the_oldest() {
899        // The defect this function exists to fix: every platform used to
900        // iterate oldest-first and stop at the cap, so the newest rows —
901        // including the running one — were the ones dropped.
902        let mut tl = StageTimeline::new();
903        for stage in ["prep", "backend", "host", "cef_init", "paint"] {
904            tl.apply_tick(vec![begin(stage)]);
905            tl.apply_tick(vec![]);
906        }
907        let rows = visible_rows(&tl.stages, 3, None);
908        assert_eq!(labels(&rows), vec!["host", "cef_init", "paint"]);
909    }
910
911    #[test]
912    fn overflow_never_orphans_a_sub_row_from_its_stage() {
913        // ReAgent P1 / codex P2 on PR #3268: trimming the flat row list by
914        // count alone could cut inside a stage block, dropping the stage row
915        // while keeping its indented children — which then render dangling
916        // under whatever stage happened to precede them. Linux's 4-line
917        // budget hits this with an ordinary prep -> backend(migrations) ->
918        // host sequence.
919        let mut tl = timeline_with_subs(5); // "backend" + 5 subs
920        tl.apply_tick(vec![begin("host")]);
921        tl.apply_tick(vec![]);
922        let rows = visible_rows(&tl.stages, 4, None);
923
924        assert!(
925            matches!(rows[0].kind, RowKind::Stage(_)),
926            "the first visible row must be a stage row, never an orphaned child"
927        );
928        // Every indented row is preceded, somewhere above, by a stage row.
929        let mut seen_stage = false;
930        for row in &rows {
931            match row.kind {
932                RowKind::Stage(_) => seen_stage = true,
933                _ => assert!(seen_stage, "an indented row appeared before any stage row"),
934            }
935        }
936    }
937
938    #[test]
939    fn a_partially_fitting_stage_keeps_its_header_over_its_oldest_child() {
940        // When only part of a block fits, the stage row is mandatory and the
941        // rows given up are its oldest (the tally first, then older detail).
942        let tl = timeline_with_subs(5);
943        let rows = visible_rows(&tl.stages, 2, None);
944        assert_eq!(labels(&rows), vec!["backend", "migration 4"]);
945    }
946
947    #[test]
948    fn a_zero_budget_yields_no_rows_rather_than_panicking() {
949        let tl = timeline_with_subs(5);
950        assert!(visible_rows(&tl.stages, 0, None).is_empty());
951    }
952
953    #[test]
954    fn hold_duration_shortens_for_a_very_fast_start() {
955        std::env::remove_var("AGENTMUX_SPLASH_HOLD_MS");
956        assert_eq!(hold_duration(100), Duration::from_millis(1000));
957        assert_eq!(hold_duration(5000), Duration::from_millis(2000));
958    }
959
960    #[test]
961    fn a_repeated_begin_of_a_running_stage_keeps_one_row() {
962        let mut tl = StageTimeline::new();
963        tl.apply_tick(vec![begin("paint")]);
964        tl.apply_tick(vec![begin("paint"), begin("paint")]);
965        let rows = tl.stages.iter().filter(|r| r.stage == "paint").count();
966        assert_eq!(rows, 1, "load retries of the same window are one wait, not one row each");
967        tl.apply_tick(vec![end("paint", 900)]);
968        assert!(tl.stages.iter().all(|r| r.done.is_some()), "the one end closes the one row");
969    }
970
971    #[test]
972    fn a_begin_after_the_stage_closed_starts_a_new_row() {
973        let mut tl = StageTimeline::new();
974        tl.apply_tick(vec![begin("paint")]);
975        tl.apply_tick(vec![end("paint", 10)]);
976        tl.apply_tick(vec![begin("paint")]);
977        assert_eq!(tl.stages.iter().filter(|r| r.stage == "paint").count(), 2);
978    }
979
980    #[test]
981    fn a_retry_warning_on_the_row_is_replaced_by_the_final_end() {
982        let mut tl = StageTimeline::new();
983        tl.apply_tick(vec![begin("paint")]);
984        tl.apply_tick(vec![StartupEvent::StageEnd {
985            stage: "paint",
986            duration_ms: 800,
987            status: StartupStatus::Warn,
988            detail: Some("Can't reach the app page: ERR_CONNECTION_REFUSED, retrying".to_string()),
989        }]);
990        let row = tl.stages.iter().find(|r| r.stage == "paint").unwrap();
991        assert_eq!(row.done.as_ref().unwrap().2.as_deref(), Some("Can't reach the app page: ERR_CONNECTION_REFUSED, retrying"));
992        tl.apply_tick(vec![end("paint", 9300)]);
993        let rows: Vec<_> = tl.stages.iter().filter(|r| r.stage == "paint").collect();
994        assert_eq!(rows.len(), 1);
995        assert_eq!(rows[0].done.as_ref().unwrap().0, 9300, "the page loaded: the row reports the real total");
996        assert!(rows[0].done.as_ref().unwrap().2.is_none());
997    }
998
999    const RETRY: &str = "Can't reach the app page: ERR_CONNECTION_REFUSED, retrying";
1000
1001    #[test]
1002    fn a_detail_that_fits_stays_on_one_line() {
1003        assert_eq!(wrap_detail("Failed to start", 40, 2), vec!["Failed to start"]);
1004        assert!(wrap_detail("", 40, 2).is_empty());
1005        assert!(wrap_detail("text", 40, 0).is_empty());
1006    }
1007
1008    #[test]
1009    fn a_detail_wraps_at_spaces_and_the_reason_survives() {
1010        assert_eq!(wrap_detail(RETRY, 41, 2), vec!["Can't reach the app page:", "ERR_CONNECTION_REFUSED, retrying"]);
1011        // The narrowest splash (Linux): the second line is cut, still showing the error name.
1012        assert_eq!(wrap_detail(RETRY, 25, 2), vec!["Can't reach the app page:", "ERR_CONNECTION_REFUSED.."]);
1013    }
1014
1015    #[test]
1016    fn a_detail_line_is_never_wider_than_the_splash() {
1017        for width in [8, 14, 25, 41, 60] {
1018            for max_lines in 1..=3 {
1019                for text in [RETRY, "x", "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz", "a b c d e f g h i j k l m n o p"] {
1020                    let lines = wrap_detail(text, width, max_lines);
1021                    assert!(lines.len() <= max_lines, "{text:?} at {width}x{max_lines}: {lines:?}");
1022                    assert!(lines.iter().all(|l| l.chars().count() <= width), "{text:?} at {width}x{max_lines}: {lines:?}");
1023                }
1024            }
1025        }
1026    }
1027
1028    /// A paint row that ended `status` with `detail`, then (optionally) a sub-item with its own.
1029    fn timeline_ending(status: StartupStatus, detail: Option<&str>) -> StageTimeline {
1030        let mut tl = StageTimeline::new();
1031        tl.apply_tick(vec![begin("paint")]);
1032        tl.apply_tick(vec![StartupEvent::StageEnd {
1033            stage: "paint",
1034            duration_ms: 800,
1035            status,
1036            detail: detail.map(str::to_string),
1037        }]);
1038        tl
1039    }
1040
1041    const LAYOUT: Option<DetailLayout> = Some(DetailLayout { width: 41, max_lines: 2 });
1042
1043    #[test]
1044    fn a_warn_or_error_row_shows_its_detail_right_under_it() {
1045        for status in [StartupStatus::Warn, StartupStatus::Error] {
1046            let tl = timeline_ending(status, Some(RETRY));
1047            let rows = visible_rows(&tl.stages, 12, LAYOUT);
1048            assert_eq!(
1049                labels(&rows),
1050                vec!["paint", "detail: Can't reach the app page:", "detail: ERR_CONNECTION_REFUSED, retrying"]
1051            );
1052            assert!(matches!(rows[1].kind, RowKind::Detail { status: s, indented: false, .. } if s == status));
1053        }
1054    }
1055
1056    #[test]
1057    fn an_ok_row_a_row_without_a_detail_and_a_renderer_without_room_show_none() {
1058        let ok = timeline_ending(StartupStatus::Ok, Some("signal"));
1059        assert_eq!(labels(&visible_rows(&ok.stages, 12, LAYOUT)), vec!["paint"]);
1060        let bare = timeline_ending(StartupStatus::Warn, None);
1061        assert_eq!(labels(&visible_rows(&bare.stages, 12, LAYOUT)), vec!["paint"]);
1062        let warn = timeline_ending(StartupStatus::Warn, Some(RETRY));
1063        assert_eq!(labels(&visible_rows(&warn.stages, 12, None)), vec!["paint"]);
1064    }
1065
1066    #[test]
1067    fn a_detail_takes_rows_from_the_budget_and_the_stage_row_stays() {
1068        let tl = timeline_ending(StartupStatus::Warn, Some(RETRY));
1069        assert_eq!(labels(&visible_rows(&tl.stages, 2, LAYOUT)), vec!["paint", "detail: Can't reach the app page:"]);
1070        assert_eq!(labels(&visible_rows(&tl.stages, 1, LAYOUT)), vec!["paint"]);
1071    }
1072
1073    #[test]
1074    fn a_sub_item_keeps_its_detail_or_loses_it_with_it() {
1075        let mut tl = StageTimeline::new();
1076        tl.apply_tick(vec![begin("backend")]);
1077        tl.apply_tick(vec![
1078            StartupEvent::SubBegin { stage: "backend", id: "a".into(), label: "first".into() },
1079            StartupEvent::SubBegin { stage: "backend", id: "b".into(), label: "second".into() },
1080        ]);
1081        tl.apply_tick(vec![
1082            StartupEvent::SubEnd { stage: "backend", id: "a".into(), duration_ms: 5, status: StartupStatus::Error, detail: Some("disk full".into()) },
1083            StartupEvent::SubEnd { stage: "backend", id: "b".into(), duration_ms: 5, status: StartupStatus::Ok, detail: None },
1084        ]);
1085        assert_eq!(
1086            labels(&visible_rows(&tl.stages, 12, LAYOUT)),
1087            vec!["backend", "first", "detail: disk full", "second"]
1088        );
1089        let rows = visible_rows(&tl.stages, 12, LAYOUT);
1090        assert!(matches!(rows[2].kind, RowKind::Detail { indented: true, .. }));
1091        // No room for first + its detail + second: the older sub-item goes whole, never its detail alone.
1092        assert_eq!(labels(&visible_rows(&tl.stages, 3, LAYOUT)), vec!["backend", "second"]);
1093    }
1094}