fleetcom 0.9.0

A fleet-view supervisor for arbitrary shell commands.
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
use std::time::Instant;

use super::*;
use crate::{
    emulator::Emulator,
    preview::{MARKER, PreviewState, SummaryAdapter},
    protocol::{Preview, PreviewSource},
};

/// Synthetic screen: adapters read only `live_rows`, so the other facts
/// are inert defaults.
struct RowsScreen {
    rows: Vec<String>,
}

fn rs(rows: &[&str]) -> RowsScreen {
    RowsScreen {
        rows: rows.iter().map(|s| s.to_string()).collect(),
    }
}

impl ScreenFacts for RowsScreen {
    fn revision(&self) -> u64 {
        1
    }

    fn alt_epoch(&self) -> u64 {
        0
    }

    fn alternate_screen(&self) -> bool {
        false
    }

    fn title(&self) -> Option<&str> {
        None
    }

    fn live_floor(&self) -> String {
        self.rows
            .iter()
            .rev()
            .find(|r| !r.is_empty())
            .cloned()
            .unwrap_or_default()
    }

    fn live_rows(&self) -> Vec<String> {
        self.rows.clone()
    }

    fn alt_leave_floor(&self) -> Option<&str> {
        None
    }
}

/// Replay a corpus fixture and resolve one preview against its final
/// screen with `adapter` installed.
fn resolve_corpus(bytes: &[u8], adapter: &dyn SummaryAdapter, rows: u16, cols: u16) -> Preview {
    let mut emu = Emulator::new(rows, cols, 2000);
    emu.process(bytes);
    let mut st = PreviewState::new();
    st.resolve(Instant::now(), &emu, Some(adapter)).clone()
}

fn anchor(text: &str, rule: &'static str) -> (String, PreviewSource, Option<&'static str>) {
    (text.to_string(), PreviewSource::Anchor, Some(rule))
}

fn parts(p: &Preview) -> (String, PreviewSource, Option<&'static str>) {
    (p.text.clone(), p.source, p.rule)
}

/// Selection is a basename match on the first word only: wider than
/// harness detection (arguments are tolerated), but env prefixes and
/// shell syntax glued to the word select nothing.
#[test]
fn select_matches_first_word_basenames_only() {
    for cmd in [
        "claude",
        "claude --model opus",
        "/usr/local/bin/claude --resume abc",
        "codex resume 'not-checked-here'",
        "grok",
    ] {
        assert!(select(cmd).is_some(), "{cmd:?} must select an adapter");
    }
    for cmd in ["vim", "FOO=bar claude", "claude|tee log", "codex; ls", ""] {
        assert!(select(cmd).is_none(), "{cmd:?} must select nothing");
    }
}

/// Each program word routes to its own CLI's matchers: the selected
/// adapter fires that CLI's rule on that CLI's screen shape.
#[test]
fn select_routes_to_the_matching_adapter() {
    let sep = "".repeat(80);
    let claude = rs(&["✻ Hashing… (6s · ↓ 87 tokens)", &sep, "", &sep]);
    assert_eq!(
        select("claude").unwrap().live_preview(&claude).unwrap().1,
        "claude:spinner"
    );
    let codex = rs(&[
        "• Working (2s • esc to interrupt)",
        "",
        "› Write tests",
        "",
        "  gpt-5.6-sol high · 0 in · 0 out",
    ]);
    assert_eq!(
        select("codex").unwrap().live_preview(&codex).unwrap().1,
        "codex:working"
    );
    let grok = rs(&[
        "    ⠼ Sleep 5 seconds then echo ok… 1.5s   2.8s ⇣14.2k [↓][stop]",
        "",
        "  ╭──────────────────────╮",
        "  │ ❯                    │",
        "  ╰── Grok 4.5 (xhigh) · always-approve ─╯",
    ]);
    assert_eq!(
        select("grok").unwrap().live_preview(&grok).unwrap().1,
        "grok:spinner"
    );
}

/// The spinner phrase survives, the elapsed/token parenthetical drops,
/// and the concrete-action row wins over the spinner when present.
#[test]
fn claude_spinner_and_action_row() {
    let sep = "".repeat(120);
    let spin = rs(&["✻ Hashing… (6s · ↓ 87 tokens)", &sep, "", &sep, "  status"]);
    assert_eq!(
        ClaudeSummary.live_preview(&spin),
        Some(("Hashing…".to_string(), "claude:spinner"))
    );

    let action = rs(&[
        "⏺ Running 1 shell command…",
        "",
        "· Hashing… (3s · ↓ 52 tokens)",
        &sep,
        "",
        &sep,
    ]);
    assert_eq!(
        ClaudeSummary.live_preview(&action),
        Some(("Running 1 shell command…".to_string(), "claude:action-row"))
    );

    // An indented attachment above the spinner is not the action row.
    let attach = rs(&[
        "  Running 1 shell command…",
        "  ⎿  $ sleep 5 && echo ok",
        "✻ Hashing… (6s)",
        &sep,
        "",
        &sep,
    ]);
    assert_eq!(
        ClaudeSummary.live_preview(&attach),
        Some(("Hashing…".to_string(), "claude:spinner"))
    );

    // A `⏺` reply row without a trailing ellipsis is not the action row.
    let reply = rs(&["⏺ ok", "", "✻ Hashing… (2s)", &sep, "", &sep]);
    assert_eq!(
        ClaudeSummary.live_preview(&reply),
        Some(("Hashing…".to_string(), "claude:spinner"))
    );
}

/// Task-derived spinner phrases may contain spaces, parentheses, and
/// digits; extraction keeps everything through the first ellipsis.
#[test]
fn claude_spinner_extracts_task_derived_phrases() {
    let sep = "".repeat(120);
    let s = rs(&[
        "✳ Overseeing phase 4 (adapters)… (54s · almost done thinking with high effort)",
        &sep,
        "",
        &sep,
    ]);
    assert_eq!(
        ClaudeSummary.live_preview(&s),
        Some((
            "Overseeing phase 4 (adapters)… · almost done thinking with high effort".to_string(),
            "claude:spinner"
        ))
    );
}

/// Parenthetical segments: recognized ticker shapes are dropped and
/// unknown segments are preserved. A bare row is unchanged.
#[test]
fn claude_parenthetical_keeps_slow_segments_and_drops_tickers() {
    let sep = "".repeat(120);
    let spin = |row: &str| {
        let rows = [row, &sep, "", &sep];
        ClaudeSummary.live_preview(&rs(&rows))
    };
    assert_eq!(
        spin("✻ Envisioning… (1m 8s · ↓ 2.1k tokens · thinking with high effort)"),
        Some((
            "Envisioning… · thinking with high effort".to_string(),
            "claude:spinner"
        ))
    );
    for ticker in [
        "6s",
        "1m 8s",
        "2h 3m",
        "8.7s",
        "↓ 87 tokens",
        "↑ 1.2k tokens",
        "↓ 2.1k",
        "2.1k tokens",
        "esc to interrupt",
    ] {
        assert_eq!(
            spin(&format!("✻ Hashing… ({ticker})")),
            Some(("Hashing…".to_string(), "claude:spinner")),
            "{ticker:?} must drop"
        );
        assert_eq!(
            spin(&format!("✻ Hashing… ({ticker} · thinking)")),
            Some(("Hashing… · thinking".to_string(), "claude:spinner")),
            "{ticker:?} must drop beside a kept segment"
        );
    }
    assert_eq!(
        spin("✽ Concocting…"),
        Some(("Concocting…".to_string(), "claude:spinner")),
        "a row with no parenthetical is unchanged"
    );
}

/// The action row wins the head while the spinner row's parenthetical
/// still contributes the semantic tail.
#[test]
fn claude_action_row_carries_the_spinner_rows_semantic_tail() {
    let sep = "".repeat(120);
    let rows = [
        "⏺ Running 1 shell command…",
        "",
        "✻ Envisioning… (1m 8s · ↓ 2.1k tokens · thinking with high effort)",
        &sep,
        "",
        &sep,
    ];
    assert_eq!(
        ClaudeSummary.live_preview(&rs(&rows)),
        Some((
            "Running 1 shell command… · thinking with high effort".to_string(),
            "claude:action-row"
        ))
    );
}

/// Waiting rows return verbatim; malformed skeletons fail and do not
/// trigger an action-row lookup.
#[test]
fn claude_waiting_family_matches_the_skeleton_and_never_probes() {
    let sep = "".repeat(120);
    let spin = |row: &str| {
        let rows = [row, &sep, "", &sep];
        ClaudeSummary.live_preview(&rs(&rows))
    };
    for row in [
        "✻ Waiting for 1 background agent to finish",
        "· Waiting for 1 background agent to finish",
        "✻ Waiting for 3 background agents to finish",
        "✻ Waiting for 1 dynamic workflow to finish",
        "✽ Waiting for 3 dynamic workflows to finish",
        "✻ Waiting for 2 tasks to finish",
    ] {
        let want = row.chars().skip(2).collect::<String>();
        assert_eq!(spin(row), Some((want, "claude:waiting")), "{row:?}");
    }

    // Reject missing digits, more than three subject words, a foreign
    // suffix, or a missing subject.
    for row in [
        "✻ Waiting patiently",
        "· Waiting for review comments to land",
        "✻ Waiting for some agents to finish",
        "✻ Waiting for 2 very long noun phrases here to finish",
        "✻ Waiting for 2 agents to start",
        "✻ Waiting for 3 to finish",
    ] {
        assert_eq!(spin(row), None, "{row:?}");
    }

    // Waiting rows return without probing the action row above them.
    let rows = [
        "⏺ Running 1 shell command…",
        "",
        "✻ Waiting for 1 background agent to finish",
        &sep,
        "",
        &sep,
    ];
    assert_eq!(
        ClaudeSummary.live_preview(&rs(&rows)),
        Some((
            "Waiting for 1 background agent to finish".to_string(),
            "claude:waiting"
        ))
    );
}

/// Every spinner frame canonicalizes to `✻`; non-frame titles pass through.
#[test]
fn claude_title_frames_canonicalize_to_constant_text() {
    for frame in CLAUDE_SPINNER {
        assert_eq!(
            ClaudeSummary.normalize_title(&format!("{frame} Claude Code")),
            Some("✻ Claude Code".to_string()),
            "{frame:?}"
        );
    }
    let a = ClaudeSummary.normalize_title("✢ Claude Code");
    let b = ClaudeSummary.normalize_title("✽ Claude Code");
    assert_eq!(a, b, "two frames must normalize identically");

    // A braille frame plus the session summary.
    assert_eq!(
        ClaudeSummary.normalize_title("⠐ Review fleetcom preview design document"),
        Some("✻ Review fleetcom preview design document".to_string())
    );
    assert_eq!(
        ClaudeSummary.normalize_title("⠴ Review fleetcom preview design document"),
        Some("✻ Review fleetcom preview design document".to_string()),
        "mid-block braille frame"
    );

    assert_eq!(ClaudeSummary.normalize_title("zellij: main"), None);
    assert_eq!(ClaudeSummary.normalize_title(""), None, "frame alone");
}

/// Cascade-level: with the claude adapter installed and no anchor on
/// the screen, a frame-led title renders canonicalized under the Title
/// tier; without an adapter it renders verbatim.
#[test]
fn title_tier_renders_the_normalized_title() {
    let mut emu = Emulator::new(24, 80, 100);
    emu.process(b"\x1b[?1049h\x1b]0;\xe2\x9c\xa2 Claude Code\x07conversation body");
    let mut st = PreviewState::new();
    let p = st
        .resolve(Instant::now(), &emu, Some(&ClaudeSummary))
        .clone();
    assert_eq!(
        (p.text.as_str(), p.source, p.rule),
        ("✻ Claude Code", PreviewSource::Title, None)
    );

    let mut st = PreviewState::new();
    let p = st.resolve(Instant::now(), &emu, None).clone();
    assert_eq!(
        (p.text.as_str(), p.source),
        ("✢ Claude Code", PreviewSource::Title),
        "no adapter: verbatim"
    );
}

/// A column-0 row in the chrome window that is not spinner-shaped aborts:
/// a wrapped status tail and body text touching the chrome both refuse.
#[test]
fn claude_aborts_on_foreign_column_zero_rows() {
    let sep = "".repeat(120);
    let wrapped = rs(&["✻ Hashing… (6s · ↓ 87 to", "kens)", &sep, "", &sep]);
    assert_eq!(ClaudeSummary.live_preview(&wrapped), None);

    // A menu quoted in the body, reaching the window with the input box
    // intact, refuses rather than synthesizing approval.
    let menu = rs(&["❯ 1. Yes", "  2. No", &sep, "", &sep]);
    assert_eq!(ClaudeSummary.live_preview(&menu), None);
}

/// The status scan crosses bounded indented gaps but stops at body prose.
#[test]
fn claude_scan_crosses_task_list_gaps_within_the_window() {
    let sep = "".repeat(120);
    let behind_gap = |status: &str, gap: usize| {
        let mut rows = vec![status.to_string()];
        rows.push("  ⎿  ✔ Phase 0: verify facts".to_string());
        rows.extend((1..gap).map(|i| format!("     ◼ Phase {i}: generic step")));
        rows.extend([sep.clone(), "".to_string(), sep.clone()]);
        let refs: Vec<&str> = rows.iter().map(String::as_str).collect();
        ClaudeSummary.live_preview(&rs(&refs))
    };
    for gap in [4, 15] {
        assert_eq!(
            behind_gap(
                "✢ Running phase 1 (dashboard UI)… (4m 20s · ↓ 17.1k tokens)",
                gap
            ),
            Some((
                "Running phase 1 (dashboard UI)…".to_string(),
                "claude:spinner"
            )),
            "gap of {gap} indented rows"
        );
    }
    for gap in [16, 17, 24] {
        assert_eq!(
            behind_gap(
                "✢ Running phase 1 (dashboard UI)… (4m 20s · ↓ 17.1k tokens)",
                gap
            ),
            None,
            "gap of {gap} indented rows must exhaust the window"
        );
    }

    // Waiting rows use the same bounded scan.
    assert_eq!(
        behind_gap("✻ Waiting for 2 background agents to finish", 5),
        Some((
            "Waiting for 2 background agents to finish".to_string(),
            "claude:waiting"
        ))
    );

    // Column-0 body prose invalidates the status structure.
    let prose = rs(&[
        "✢ Running phase 1 (dashboard UI)… (4m 20s · ↓ 17.1k tokens)",
        "⏺ The phase list below is queued, not running.",
        "  ⎿  ✔ Phase 0: verify facts",
        "     ◼ Phase 1: dashboard polish",
        &sep,
        "",
        &sep,
    ]);
    assert_eq!(ClaudeSummary.live_preview(&prose), None);
}

/// Blank rows do not consume the nonblank-row window.
#[test]
fn claude_blank_rows_do_not_consume_the_window() {
    let sep = "".repeat(120);
    let resolve = |rows: Vec<String>| {
        let refs: Vec<&str> = rows.iter().map(String::as_str).collect();
        ClaudeSummary.live_preview(&rs(&refs))
    };
    let boxed = |sep: &str| [sep.to_string(), "❯ /workflows".to_string(), sep.to_string()];

    // Nineteen blank rows separate the waiting row from the input box.
    let mut rows = vec!["✻ Waiting for 1 dynamic workflow to finish".to_string()];
    rows.extend(std::iter::repeat_n(String::new(), 19));
    rows.extend(boxed(&sep));
    assert_eq!(
        resolve(rows),
        Some((
            "Waiting for 1 dynamic workflow to finish".to_string(),
            "claude:waiting"
        ))
    );

    // Fifteen indented rows plus the spinner fill the 16-row window;
    // interleaved blank rows do not affect the count.
    let mut rows = vec!["✢ Running phase 1 (dashboard UI)… (4m 20s)".to_string()];
    for i in 0..15 {
        rows.push(String::new());
        rows.push(format!("     ◼ Phase {i}: generic step"));
    }
    rows.extend(boxed(&sep));
    assert_eq!(
        resolve(rows),
        Some((
            "Running phase 1 (dashboard UI)…".to_string(),
            "claude:spinner"
        ))
    );

    // Sixteen indented rows plus the spinner exceed the window.
    let mut rows = vec!["✢ Running phase 1 (dashboard UI)… (4m 20s)".to_string()];
    for i in 0..16 {
        rows.push(String::new());
        rows.push(format!("     ◼ Phase {i}: generic step"));
    }
    rows.extend(boxed(&sep));
    assert_eq!(resolve(rows), None);

    // An intervening column-0 prose row still aborts the scan.
    let prose = rs(&[
        "✻ Hashing… (6s · ↓ 87 tokens)",
        "",
        "",
        "⏺ The workflow report lands below.",
        "",
        "",
        &sep,
        "❯ /workflows",
        &sep,
    ]);
    assert_eq!(ClaudeSummary.live_preview(&prose), None);
}

/// The approval menu synthesizes its label only with the input box gone,
/// and requires the `2.` sibling below the selector.
#[test]
fn claude_approval_requires_the_dialog_shape() {
    let dialog = rs(&[
        " Do you want to create word.txt?",
        " ❯ 1. Yes",
        "   2. Yes, allow all edits during this session (shift+tab)",
        "   3. No",
        "",
        " Esc to cancel · Tab to amend",
    ]);
    assert_eq!(
        ClaudeSummary.live_preview(&dialog),
        Some(("awaiting approval".to_string(), "claude:approval-menu"))
    );

    let lone = rs(&[" ❯ 1. Yes", "", " Esc to cancel"]);
    assert_eq!(ClaudeSummary.live_preview(&lone), None);
}

/// The model label comes from the welcome box and reads as
/// `{model} ({effort})`; no box, no label.
#[test]
fn claude_label_reads_the_welcome_box() {
    let boxed = rs(&[
        "╭─── Claude Code v2.1.215 ────────────╮",
        "│ Fable 5 with high effort · Claude Max ·  │ notes │",
        "╰──────────────────────────────────────╯",
    ]);
    assert_eq!(
        ClaudeSummary.model_label(&boxed),
        Some("Fable 5 (high)".to_string())
    );
    assert_eq!(ClaudeSummary.model_label(&rs(&["no box here"])), None);
}

/// Working-row normalization: parenthetical dropped (unclosed included),
/// `/`-hint suffixes dropped, slow suffixes kept, with the CLI's own
/// ellipsis when truncated.
#[test]
fn codex_working_normalization() {
    let tail = [
        "",
        "› Write tests for @filename",
        "",
        "  gpt-5.6-sol high · 0 in · 0 out",
    ];
    let full = "• Working (7s • esc to interrupt) · 1 background terminal running · /ps to view · /stop to close";
    for (row, want) in [
        (full, "Working · 1 background terminal running"),
        ("• Working (2s • esc to interrupt)", "Working"),
        ("• Working (7s • esc to…", "Working"),
        (
            "• Working (7s • esc to interrupt) · 1 background termi…",
            "Working · 1 background termi…",
        ),
    ] {
        let mut rows = vec![row];
        rows.extend(tail);
        assert_eq!(
            CodexSummary.live_preview(&rs(&rows)),
            Some((want.to_string(), "codex:working")),
            "{row:?}"
        );
    }
    assert_eq!(
        CodexSummary.model_label(&rs(&tail[1..])),
        Some("gpt-5.6-sol high".to_string())
    );
}

/// `• Ran` extracts through its indented attachment, but never through a
/// foreign column-0 row: scrollback `• Ran` rows from prior turns sit
/// behind reply bullets and separators, and skipping those would
/// resurface stale work.
#[test]
fn codex_ran_stops_at_foreign_rows() {
    let transient = rs(&[
        "• Ran sleep 5 && echo ok",
        "  └ ok",
        "",
        "",
        "",
        "  gpt-5.6-sol high · 1 in · 2 out",
    ]);
    assert_eq!(
        CodexSummary.live_preview(&transient),
        Some(("Ran sleep 5 && echo ok".to_string(), "codex:ran"))
    );

    let sep = "".repeat(120);
    let behind_reply = rs(&[
        "• Ran sleep 5 && echo ok",
        "  └ ok",
        "",
        &sep,
        "",
        "• ok",
        "",
        "",
        "",
        "  gpt-5.6-sol high · 1 in · 2 out",
    ]);
    assert_eq!(CodexSummary.live_preview(&behind_reply), None);
}

/// A hint row may follow the composer without a token bar. The anchor
/// still fires, without a model prefix.
#[test]
fn codex_hint_row_layout_anchors_without_a_token_bar() {
    let hinted = rs(&[
        "• Running cargo test --test daemon_env",
        "",
        "",
        "• Working (10m 26s • esc to interrupt)",
        "",
        "",
        "",
        "  tab to queue message",
    ]);
    assert_eq!(
        CodexSummary.live_preview(&hinted),
        Some(("Working".to_string(), "codex:working"))
    );
    assert_eq!(CodexSummary.model_label(&hinted), None);
}

/// The approval modal replaces composer and token bar with a numbered
/// menu; the selector row plus a numbered sibling synthesizes the
/// label, wherever the selection sits.
#[test]
fn codex_approval_modal_synthesizes_on_any_selection() {
    let on_first = rs(&[
        "  Would you like to run the following command?",
        "",
        "  $ cargo test --test daemon_env",
        "",
        "› 1. Yes, proceed (y)",
        "  2. Yes, and don't ask again for commands that start with `cargo test` (p)",
        "  3. No, and tell Codex what to do differently (esc)",
        "",
        "  Press enter to confirm or esc to cancel",
    ]);
    assert_eq!(
        CodexSummary.live_preview(&on_first),
        Some(("awaiting approval".to_string(), "codex:approval-menu"))
    );

    let on_second = rs(&[
        "  1. Yes, proceed (y)",
        "› 2. Yes, and don't ask again (p)",
        "  3. No (esc)",
        "",
        "  Press enter to confirm or esc to cancel",
    ]);
    assert_eq!(
        CodexSummary.live_preview(&on_second),
        Some(("awaiting approval".to_string(), "codex:approval-menu"))
    );
}

/// A menu quoted in the conversation always has the live composer
/// somewhere below it; the composer's presence suppresses the modal
/// match, and the quote is a foreign row to the status scan: no
/// anchor, floor tier.
#[test]
fn codex_quoted_menu_with_a_live_composer_is_not_a_modal() {
    let quoted = rs(&[
        "• I found these options in the doc:",
        "",
        "› 1. Yes, proceed (y)",
        "  2. No, cancel (esc)",
        "",
        "",
        "",
        "  gpt-5.6-sol high · 0 in · 0 out",
    ]);
    assert_eq!(CodexSummary.live_preview(&quoted), None);
}

/// Without any composer row (codex exited; its resume hint owns the
/// floor) the whole pin fails.
#[test]
fn codex_requires_the_composer_pin() {
    let exited = rs(&[
        "• Ran sleep 5 && echo ok",
        "",
        "Token usage: total=14,353 input=14,063",
        "To continue this session, run codex resume 0199-fake",
    ]);
    assert_eq!(CodexSummary.live_preview(&exited), None);
    assert_eq!(CodexSummary.model_label(&exited), None);
}

/// Spinner label cut at its `…`; the completion row kept verbatim,
/// longer durations included; free text above the box refuses.
#[test]
fn grok_status_shapes() {
    let boxed = [
        "  ╭──────────────────────╮",
        "  │ ❯                    │",
        "  ╰── Grok 4.5 (xhigh) · always-approve ─╯",
    ];
    let probe = |status: &str| {
        let mut rows = vec![status, ""];
        rows.extend(boxed);
        GrokSummary.live_preview(&rs(&rows))
    };
    assert_eq!(
        probe("    ⠼ Sleep 5 seconds then echo ok… 1.5s   2.8s ⇣14.2k [↓][stop]"),
        Some(("Sleep 5 seconds then echo ok…".to_string(), "grok:spinner"))
    );
    assert_eq!(
        probe("    ⠋ Thinking… 0.2s"),
        Some(("Thinking…".to_string(), "grok:spinner"))
    );
    assert_eq!(
        probe("     Worked for 8.7s"),
        Some(("Worked for 8.7s".to_string(), "grok:worked"))
    );
    assert_eq!(
        probe("     Worked for 1m 24s"),
        Some(("Worked for 1m 24s".to_string(), "grok:worked"))
    );
    assert_eq!(probe("     Worked for a while"), None);
    assert_eq!(
        probe("  Coming from Codex? Resume your session from 7m ago using ctrl+u"),
        None
    );

    let mut rows = vec!["    ⠋ Thinking… 0.2s", ""];
    rows.extend(boxed);
    assert_eq!(
        GrokSummary.model_label(&rs(&rows)),
        Some("Grok 4.5 (xhigh)".to_string())
    );
    // A plain border carries no label.
    let plain = rs(&["    ⠋ Thinking… 0.2s", "", "╭────╮", "│ ❯  │", "╰────╯"]);
    assert_eq!(GrokSummary.model_label(&plain), None);
}

// ------------------------------------------------------- corpus replay --

/// Positive per-state fixtures at capture geometry (40×120): exact
/// normalized text, Anchor provenance, and the matcher id.
#[test]
fn corpus_positive_states_anchor_exactly() {
    struct Case(
        &'static str,
        &'static [u8],
        &'static dyn SummaryAdapter,
        &'static str,
        &'static str,
    );
    let cases = [
        Case(
            "preview_claude_working",
            include_bytes!("../../tests/corpus/preview_claude_working.bin"),
            &ClaudeSummary,
            "Fable 5 (high) · Concocting…",
            "claude:spinner",
        ),
        Case(
            "preview_claude_working_tool",
            include_bytes!("../../tests/corpus/preview_claude_working_tool.bin"),
            &ClaudeSummary,
            "Fable 5 (high) · Hashing…",
            "claude:spinner",
        ),
        Case(
            "preview_claude_action",
            include_bytes!("../../tests/corpus/preview_claude_action.bin"),
            &ClaudeSummary,
            "Fable 5 (high) · Running 1 shell command…",
            "claude:action-row",
        ),
        Case(
            "preview_claude_approval",
            include_bytes!("../../tests/corpus/preview_claude_approval.bin"),
            &ClaudeSummary,
            "Fable 5 (high) · awaiting approval",
            "claude:approval-menu",
        ),
        Case(
            "preview_claude_tasklist",
            include_bytes!("../../tests/corpus/preview_claude_tasklist.bin"),
            &ClaudeSummary,
            // Without the welcome box, the preview has no model prefix.
            "Running phase 1 (dashboard UI)…",
            "claude:spinner",
        ),
        Case(
            "preview_codex_working",
            include_bytes!("../../tests/corpus/preview_codex_working.bin"),
            &CodexSummary,
            "gpt-5.6-sol high · Working · 1 background terminal running",
            "codex:working",
        ),
        Case(
            "preview_codex_ran",
            include_bytes!("../../tests/corpus/preview_codex_ran.bin"),
            &CodexSummary,
            "gpt-5.6-sol high · Ran sleep 5 && echo ok",
            "codex:ran",
        ),
        Case(
            "preview_claude_waiting",
            include_bytes!("../../tests/corpus/preview_claude_waiting.bin"),
            &ClaudeSummary,
            // The welcome box is absent, so there is no model prefix.
            "Waiting for 1 background agent to finish",
            "claude:waiting",
        ),
        Case(
            "preview_claude_workflow_wait",
            include_bytes!("../../tests/corpus/preview_claude_workflow_wait.bin"),
            &ClaudeSummary,
            // The roster below the input box is excluded from the status.
            "Waiting for 1 dynamic workflow to finish",
            "claude:waiting",
        ),
        Case(
            "preview_codex_hint_row",
            include_bytes!("../../tests/corpus/preview_codex_hint_row.bin"),
            &CodexSummary,
            // No token bar in this layout: no model prefix, correctly.
            "Working",
            "codex:working",
        ),
        Case(
            "preview_codex_approval",
            include_bytes!("../../tests/corpus/preview_codex_approval.bin"),
            &CodexSummary,
            "awaiting approval",
            "codex:approval-menu",
        ),
        Case(
            "preview_grok_working",
            include_bytes!("../../tests/corpus/preview_grok_working.bin"),
            &GrokSummary,
            "Grok 4.5 (xhigh) · Sleep 5 seconds then echo ok…",
            "grok:spinner",
        ),
        Case(
            "preview_grok_worked",
            include_bytes!("../../tests/corpus/preview_grok_worked.bin"),
            &GrokSummary,
            "Grok 4.5 (xhigh) · Worked for 8.7s",
            "grok:worked",
        ),
    ];
    for Case(name, bytes, adapter, text, rule) in cases {
        let p = resolve_corpus(bytes, adapter, 40, 120);
        assert_eq!(parts(&p), anchor(text, rule), "{name}");
    }
}

/// Idle and post-turn screens have no anchor and resolve to the
/// alternate-screen marker.
#[test]
fn corpus_idle_states_fall_through() {
    let cases: [(&str, &[u8], &dyn SummaryAdapter); 4] = [
        (
            "preview_claude_idle",
            include_bytes!("../../tests/corpus/preview_claude_idle.bin"),
            &ClaudeSummary,
        ),
        (
            "preview_claude_done",
            include_bytes!("../../tests/corpus/preview_claude_done.bin"),
            &ClaudeSummary,
        ),
        (
            "preview_grok_idle",
            include_bytes!("../../tests/corpus/preview_grok_idle.bin"),
            &GrokSummary,
        ),
        (
            "preview_grok_splash",
            include_bytes!("../../tests/corpus/preview_grok_splash.bin"),
            &GrokSummary,
        ),
    ];
    for (name, bytes, adapter) in cases {
        let p = resolve_corpus(bytes, adapter, 40, 120);
        assert_eq!(
            parts(&p),
            (MARKER.to_string(), PreviewSource::Marker, None),
            "{name}"
        );
    }
}

/// Status-shaped conversation text does not extract.
/// The claude fixtures quote an approval menu in the conversation; the
/// codex fixtures hold `• Ran` in scrollback behind a finished turn.
#[test]
fn corpus_body_shaped_text_never_extracts() {
    // Menu in the body, spinner live: the pinned spinner wins.
    let p = resolve_corpus(
        include_bytes!("../../tests/corpus/preview_claude_body_menu.bin"),
        &ClaudeSummary,
        40,
        120,
    );
    assert_eq!(
        parts(&p),
        anchor("Fable 5 (high) · Hashing…", "claude:spinner")
    );

    // Menu touching the chrome window on an idle screen: abort, marker.
    let p = resolve_corpus(
        include_bytes!("../../tests/corpus/preview_claude_body_menu_idle.bin"),
        &ClaudeSummary,
        40,
        120,
    );
    assert_eq!(parts(&p), (MARKER.to_string(), PreviewSource::Marker, None));

    // Body prose between spinner-shaped text and the task list yields the marker.
    let p = resolve_corpus(
        include_bytes!("../../tests/corpus/preview_claude_body_above_tasklist.bin"),
        &ClaudeSummary,
        40,
        120,
    );
    assert_eq!(parts(&p), (MARKER.to_string(), PreviewSource::Marker, None));

    // Prior-turn `• Ran` in scrollback with the turn finished: the scan
    // stops at the reply bullet and the floor tier reports the screen.
    let p = resolve_corpus(
        include_bytes!("../../tests/corpus/preview_codex_scrollback.bin"),
        &CodexSummary,
        40,
        120,
    );
    assert_eq!(
        parts(&p),
        (
            // Floor previews omit the status bar's indentation.
            "gpt-5.6-sol high · 5.26K used · 28.2K in · 78 out".to_string(),
            PreviewSource::Floor,
            None
        )
    );

    // A modal-shaped menu quoted in the body with the live composer
    // below it: the composer suppresses the approval match, the quote
    // is foreign to the status scan, and the floor tier reports.
    let p = resolve_corpus(
        include_bytes!("../../tests/corpus/preview_codex_body_menu.bin"),
        &CodexSummary,
        40,
        120,
    );
    assert_eq!(
        parts(&p),
        (
            "gpt-5.6-sol high · 0 in · 0 out".to_string(),
            PreviewSource::Floor,
            None
        )
    );

    // `• Ran` visible mid-turn with `• Working` at the pin: live wins.
    let p = resolve_corpus(
        include_bytes!("../../tests/corpus/preview_codex_working_over_ran.bin"),
        &CodexSummary,
        40,
        120,
    );
    assert_eq!(
        parts(&p),
        anchor("gpt-5.6-sol high · Working", "codex:working")
    );
}

/// 80-column truncation: the CLIs cut their status rows at a word
/// boundary with their own ellipsis; head matching still extracts and
/// the kept suffix keeps that ellipsis verbatim.
#[test]
fn corpus_truncated_rows_still_anchor() {
    let p = resolve_corpus(
        include_bytes!("../../tests/corpus/preview_trunc_claude.bin"),
        &ClaudeSummary,
        40,
        80,
    );
    // No welcome box on the narrow screen: the label drops with it.
    assert_eq!(parts(&p), anchor("Hashing…", "claude:spinner"));

    let p = resolve_corpus(
        include_bytes!("../../tests/corpus/preview_trunc_codex.bin"),
        &CodexSummary,
        40,
        80,
    );
    assert_eq!(
        parts(&p),
        anchor(
            "gpt-5.6-sol high · Working · 1 background terminal running",
            "codex:working"
        )
    );

    let p = resolve_corpus(
        include_bytes!("../../tests/corpus/preview_trunc_grok.bin"),
        &GrokSummary,
        40,
        80,
    );
    assert_eq!(
        parts(&p),
        anchor(
            "Grok 4.5 (xhigh) · Sleep 5 seconds then echo…",
            "grok:spinner"
        )
    );
}

/// At 30 columns, a wrapped status ellipsis fails the structure check and
/// resolves to the alternate-screen marker.
#[test]
fn corpus_wrapped_ellipsis_falls_through() {
    let p = resolve_corpus(
        include_bytes!("../../tests/corpus/preview_wrap_grok.bin"),
        &GrokSummary,
        40,
        30,
    );
    assert_eq!(parts(&p), (MARKER.to_string(), PreviewSource::Marker, None));
}

/// Non-agent TUIs on the alternate screen resolve through the
/// title/marker tiers with an adapter installed exactly as without one:
/// the anchor tier never fires on foreign screens.
#[test]
fn corpus_non_agent_tuis_keep_their_tiers() {
    for (name, bytes) in [
        (
            "vim_session",
            &include_bytes!("../../tests/corpus/vim_session.bin")[..],
        ),
        (
            "less_altscreen",
            &include_bytes!("../../tests/corpus/less_altscreen.bin")[..],
        ),
    ] {
        // Cut before the final alt-screen exit so the TUI still owns the
        // screen, as it does for the task's whole interactive life.
        let cut = bytes
            .windows(8)
            .rposition(|w| w == b"\x1b[?1049l")
            .expect("fixture exits the alt screen");
        let mut emu = Emulator::new(40, 120, 2000);
        emu.process(&bytes[..cut]);
        assert!(emu.alternate_screen(), "{name}: alt screen active at cut");
        let mut st = PreviewState::new();
        let with = st
            .resolve(Instant::now(), &emu, Some(&ClaudeSummary))
            .clone();
        let mut st = PreviewState::new();
        let without = st.resolve(Instant::now(), &emu, None).clone();
        assert_eq!(with, without, "{name}: the adapter must change nothing");
        assert_eq!(with.source, PreviewSource::Marker, "{name}");
    }
}