1#[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
38pub 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
57pub const GAP_STAGE: &str = "gap";
62
63pub const GAP_MIN_MS: u64 = 150;
66
67#[cfg_attr(target_os = "linux", allow(dead_code))]
72pub const STAGE_LABEL_MAX_CHARS: usize = 16;
73
74pub 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#[derive(PartialEq)]
92enum BeginKey {
93 Stage(&'static str),
94 Sub(&'static str, String),
95}
96
97#[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 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 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 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 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 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 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 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
305pub const SUB_DETAIL_MAX: usize = 2;
317
318pub enum RowKind<'a> {
323 Stage(&'a StageEntry),
324 Sub(&'a SubEntry),
325 SubTally { done: usize, total: usize },
328 Detail { text: String, status: StartupStatus, indented: bool },
333}
334
335pub struct Row<'a> {
336 pub kind: RowKind<'a>,
337}
338
339#[derive(Clone, Copy)]
342pub struct DetailLayout {
343 pub width: usize,
344 pub max_lines: usize,
345}
346
347pub 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 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
395fn 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 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
410pub fn tally_label(done: usize, total: usize) -> String {
413 format!("{done}/{total} done")
414}
415
416pub fn visible_rows(stages: &[StageEntry], budget: usize, detail: Option<DetailLayout>) -> Vec<Row<'_>> {
427 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 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 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#[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
521pub 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#[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#[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#[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 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 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 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 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 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 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 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")]); 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 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 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 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")]); assert_eq!(accounted_ms(&tl.stages), 100);
820 }
821
822 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 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 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 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 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 let mut tl = timeline_with_subs(5); 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 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 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 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 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 assert_eq!(labels(&visible_rows(&tl.stages, 3, LAYOUT)), vec!["backend", "second"]);
1093 }
1094}