fleetcom 0.12.0

A fleet-view supervisor for concurrent 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
//! Display-only summary adapters for the Anchor tier of the dashboard preview.
//! Each adapter extracts status text from an agent CLI's bottom chrome.
//!
//! # Display-only contract
//!
//! Adapter output is rendered in the dashboard and never enters a shell
//! command. It is therefore outside the session-ID validation boundary in
//! [`is_uuid`](super::is_uuid).
//!
//! # Title tiers
//!
//! Adapters also normalize terminal titles for the preview cascade's Title
//! tiers. An alternate-screen title falls back to the sanitized captured title
//! when normalization rejects it. A retained primary-screen title renders only
//! when the adapter recognizes its shape because any inline program can replace
//! the terminal title.
//!
//! # Anchor discipline
//!
//! Status-shaped text can also appear in scrollback or conversation content.
//! To avoid treating it as live status, every matcher:
//!
//! 1. locates the chrome region structurally (claude's separator-pair input
//!    box, codex's composer, grok's bordered input box, omp's two-row input
//!    box) and limits status candidates relative to it;
//! 2. returns `None` when the expected structure is absent or inconsistent;
//! 3. preserves CLI-generated ellipsis truncation. omp also requires its
//!    trailing interrupt hint; wrapped rows fail that structural check.
//!
//! Normalization removes spinner glyphs, elapsed counters, throughput data,
//! and key hints while preserving the CLI's status text. The only synthesized
//! status is `awaiting approval`, for approval menus: claude's dialog,
//! codex's modal, and omp's selector. Corpus fixtures in `tests/corpus` pin
//! the supported screen structures.

use std::path::Path;

use crate::preview::SummaryAdapter;

/// Select an adapter by the basename of the command's first
/// whitespace-separated word. Arguments are accepted; environment prefixes
/// and compound shell commands do not select an adapter. Selection is
/// independent of session-capture instrumentation.
pub fn select(command: &str) -> Option<&'static dyn SummaryAdapter> {
    let first = command.split_whitespace().next()?;
    let name = Path::new(first).file_name()?.to_str()?;
    super::AGENTS
        .iter()
        .find(|a| a.harness.shape().0 == name)
        .map(|a| a.summary)
}

/// Preview text shared by approval-menu matchers and Claude's registry
/// permission prompt.
pub(crate) const AWAITING_APPROVAL: &str = "awaiting approval";

/// Whether `row` is a full-width horizontal rule: nothing but `─`, long
/// enough that box borders and inline list rules never qualify. claude's
/// input box is fenced by two such rows.
fn is_rule_row(row: &str) -> bool {
    let mut n = 0usize;
    for c in row.trim().chars() {
        if c != '' {
            return false;
        }
        n += 1;
    }
    n >= 40
}

/// Whether `c` is a Unicode Braille Patterns code point used as a spinner
/// frame by the supported CLIs.
fn braille_frame(c: char) -> bool {
    ('\u{2800}'..='\u{28FF}').contains(&c)
}

/// The status phrase of a spinner row: a frame char accepted by `is_frame`,
/// a space, then text through the first `…` inclusive. The phrase must open
/// alphanumeric; past that it is task-derived and unconstrained. Trailing
/// text is left for the caller to interpret.
fn spinner_text(row: &str, is_frame: impl Fn(char) -> bool) -> Option<String> {
    let mut chars = row.chars();
    if !is_frame(chars.next()?) || chars.next()? != ' ' {
        return None;
    }
    let rest = chars.as_str();
    let text = &rest[..rest.find('')? + ''.len_utf8()];
    text.chars()
        .next()?
        .is_alphanumeric()
        .then(|| text.to_string())
}

/// Keep nonempty ` · `-separated segments not matched by `drop`, preserving
/// their order and separator prefixes.
fn slow_segments(tail: &str, drop: impl Fn(&str) -> bool) -> String {
    let mut out = String::new();
    for seg in tail.split(" · ") {
        let seg = seg.trim();
        if seg.is_empty() || drop(seg) {
            continue;
        }
        out.push_str(" · ");
        out.push_str(seg);
    }
    out
}

// ---------------------------------------------------------------- claude --

/// Accepted claude spinner frames. A frame matches only when followed by a
/// space and an `…`-terminated status phrase.
const CLAUDE_SPINNER: &[char] = &['·', '', '', '', '', ''];

/// Maximum nonblank rows inspected above the input box. Blank rows do not
/// consume the limit; indented hint and task-list rows do.
const CLAUDE_STATUS_WINDOW: usize = 16;

/// claude (alt screen). Working state: a column-0 spinner row above the
/// input box's top separator, within [`CLAUDE_STATUS_WINDOW`] nonblank rows
/// of it.
/// Approval state: the dialog replaces the input box entirely; the menu
/// match fires only when that box is gone.
pub struct ClaudeSummary;

impl SummaryAdapter for ClaudeSummary {
    fn live_preview(&self, rows: &[String]) -> Option<(String, &'static str)> {
        match claude_box_top(rows) {
            Some(top) => claude_spinner_status(rows, top),
            // Consider approval menus only when the normal input box is absent.
            None => claude_approval(rows),
        }
    }

    fn model_label(&self, rows: &[String]) -> Option<String> {
        claude_welcome_label(rows)
    }

    /// Strip a recognized claude spinner, braille, or quadrant-circle frame
    /// from a nonempty title. Other title shapes return `None`.
    fn normalize_title(&self, title: &str) -> Option<String> {
        let mut chars = title.chars();
        let frame = chars.next()?;
        let framed = CLAUDE_SPINNER.contains(&frame)
            || braille_frame(frame)
            || ('\u{25D0}'..='\u{25D3}').contains(&frame);
        // An empty payload cannot produce a usable preview.
        (framed && chars.next()? == ' ' && !chars.as_str().is_empty())
            .then(|| chars.as_str().to_string())
    }
}

/// Index of the input box's top separator. The bottom-most full-width rule
/// is the box's bottom edge (only statusline rows render below it); a
/// second rule within six rows is its top edge, and a `❯`-headed row between
/// them is the input line. Body text above and statusline rows below never
/// enter the scan.
fn claude_box_top(rows: &[String]) -> Option<usize> {
    let bottom = rows.iter().rposition(|r| is_rule_row(r))?;
    let top = (bottom.saturating_sub(6)..bottom)
        .rev()
        .find(|&i| is_rule_row(&rows[i]))?;
    rows[top + 1..bottom]
        .iter()
        .any(|r| r.starts_with(''))
        .then_some(top)
}

/// Scan upward from the input box for a spinner or waiting row. Blank rows do
/// not consume the window; indented rows do. The first other column-0 row,
/// including body prose or a wrapped status tail, invalidates the structure.
fn claude_spinner_status(rows: &[String], top: usize) -> Option<(String, &'static str)> {
    let mut content = 0usize;
    for i in (0..top).rev() {
        let row = &rows[i];
        if row.is_empty() {
            continue;
        }
        content += 1;
        if content > CLAUDE_STATUS_WINDOW {
            return None;
        }
        if row.starts_with(' ') {
            continue;
        }
        if let Some(verb) = spinner_text(row, |c| CLAUDE_SPINNER.contains(&c)) {
            // The spinner row's parenthetical contributes its slow
            // semantic tail to whichever text wins the head.
            let tail = claude_semantic_tail(row);
            // The spinner confirms the working state; only then prefer the
            // concrete-action row over the rotating verb.
            if let Some(action) = claude_action_row(rows, i) {
                return Some((format!("{action}{tail}"), "claude:action-row"));
            }
            return Some((format!("{verb}{tail}"), "claude:spinner"));
        }
        // Action-row lookup applies only to ellipsis-terminated spinner rows.
        if let Some(waiting) = claude_waiting_text(row) {
            return Some((waiting, "claude:waiting"));
        }
        // Foreign column-0 row: abort (see above).
        return None;
    }
    None
}

/// Match a spinner-framed `Waiting for {digits} {subject} to finish` row and
/// return its text verbatim. The subject must contain one to three words.
fn claude_waiting_text(row: &str) -> Option<String> {
    let mut chars = row.chars();
    if !CLAUDE_SPINNER.contains(&chars.next()?) || chars.next()? != ' ' {
        return None;
    }
    let text = chars.as_str();
    let rest = text.strip_prefix("Waiting for ")?;
    let digits = rest.chars().take_while(char::is_ascii_digit).count();
    if digits == 0 {
        return None;
    }
    let middle = rest[digits..]
        .strip_prefix(' ')?
        .strip_suffix(" to finish")?;
    (1..=3)
        .contains(&middle.split_whitespace().count())
        .then(|| text.to_string())
}

/// The spinner parenthetical's slow semantic tail:
/// `(1m 8s · ↓ 2.1k tokens · thinking with high effort)` keeps
/// ` · thinking with high effort`. Recognized ticker segments drop;
/// everything else is kept in order as ` · {seg}`. No parenthetical yields
/// an empty tail; an unclosed one is parsed to the cut.
fn claude_semantic_tail(row: &str) -> String {
    let Some(open) = row.find("… (") else {
        return String::new();
    };
    let inner = &row[open + "… (".len()..];
    let inner = inner.strip_suffix(')').unwrap_or(inner);
    slow_segments(inner, claude_ticker_segment)
}

/// Whether one parenthetical segment is recognized ticker churn: elapsed
/// time (each whitespace token is digits, optional dot, then `s`/`m`/`h`:
/// `6s`, `1m 8s`, `2h 3m`), token/throughput counters (`↓`/`↑`-headed or
/// `tokens`-suffixed), or the `esc to interrupt` affordance.
fn claude_ticker_segment(seg: &str) -> bool {
    if seg == "esc to interrupt"
        || seg == "tokens"
        || seg.starts_with('')
        || seg.starts_with('')
        || seg.ends_with(" tokens")
    {
        return true;
    }
    !seg.is_empty()
        && seg.split_whitespace().all(|tok| {
            let Some((num, unit)) = tok.split_at_checked(tok.len() - 1) else {
                return false;
            };
            matches!(unit, "s" | "m" | "h")
                && num.starts_with(|c: char| c.is_ascii_digit())
                && num.chars().all(|c| c.is_ascii_digit() || c == '.')
        })
}

/// The concrete-action row above a confirmed spinner: skip the blank gap,
/// probe exactly one row. `⏺ Running 1 shell command…` names real work while
/// the spinner phrase rotates per request, so it wins when both are
/// present. The probe requires the `⏺` head and a single trailing `…`
/// (`⏺ ok`-style reply rows fail it); anything else keeps the spinner
/// phrase; scanning further up could match conversation content.
fn claude_action_row(rows: &[String], spinner: usize) -> Option<String> {
    let row = rows[..spinner].iter().rev().find(|r| !r.is_empty())?;
    let text = row.strip_prefix("")?.trim();
    let tail = text.len().checked_sub(''.len_utf8())?;
    (text.find('') == Some(tail)).then(|| text.to_string())
}

/// Match an approval selector only when the input box is absent: `❯ 1. …`
/// with a `2. …` option below, within the last nine painted rows. Returns the
/// synthesized label `awaiting approval`.
fn claude_approval(rows: &[String]) -> Option<(String, &'static str)> {
    let last = rows.iter().rposition(|r| !r.is_empty())?;
    let i = (last.saturating_sub(8)..=last).find(|&i| rows[i].trim_start().starts_with("❯ 1. "))?;
    let next = rows[i + 1..].iter().find(|r| !r.is_empty())?;
    next.trim_start()
        .starts_with("2. ")
        .then(|| (AWAITING_APPROVAL.to_string(), "claude:approval-menu"))
}

/// Complete effort values accepted before a welcome-box ellipsis.
const CLAUDE_EFFORT: &[&str] = &["low", "medium", "high", "xhigh", "max"];

/// `Fable 5 with high effort` from the welcome box → `Fable 5 (high)`. The
/// welcome box is the stable source; user-configurable statusline rows are not
/// parsed. When the box scrolls away, the label is unavailable.
fn claude_welcome_label(rows: &[String]) -> Option<String> {
    let start = rows
        .iter()
        .take(4)
        .position(|r| r.trim_start().starts_with("╭─── Claude Code"))?;
    for row in &rows[start + 1..] {
        if row.trim_start().starts_with('') {
            break;
        }
        // First cell of the box row: the welcome pane, left of the divider.
        let Some(cell) = row.split('').nth(1) else {
            continue;
        };
        let head = cell.trim().split(" · ").next().unwrap_or("");
        if let Some(label) = claude_model_effort(head) {
            return Some(label);
        }
    }
    None
}

/// Normalize `<model> with <effort> effort` and its ellipsis form to
/// `<model> (<effort>)`. The ellipsis form requires a complete
/// [`CLAUDE_EFFORT`] value; a partial token returns `None`.
fn claude_model_effort(head: &str) -> Option<String> {
    let (model, effort) = match head.strip_suffix(" effort") {
        Some(full) => full.rsplit_once(" with ")?,
        None => {
            let (model, effort) = head.strip_suffix('')?.rsplit_once(" with ")?;
            CLAUDE_EFFORT.contains(&effort).then_some((model, effort))?
        }
    };
    (!model.is_empty() && !effort.is_empty()).then(|| format!("{model} ({effort})"))
}

// ----------------------------------------------------------------- codex --

/// Column-0 glyphs accepted as the Codex composer prompt.
const CODEX_PROMPT: &[char] = &['', '»', '!'];

/// Column-0 queued-message heads allowed between the status row and composer.
/// Prefix matching admits runtime affordances appended to a head.
const CODEX_QUEUED_HEADS: &[&str] = &[
    "• Messages to be submitted after next tool call",
    "• Messages to be submitted at end of turn",
    "• Queued follow-up inputs",
];

/// Reasoning-effort words accepted in a `model-with-reasoning` item.
const CODEX_EFFORT: &[&str] = &[
    "minimal", "low", "medium", "high", "xhigh", "max", "ultra", "default",
];

/// Maximum indented rows crossed between the composer and the status row.
/// Queued-message blocks are exempt: their height is the user's queue
/// depth, so counting them would push the status row out of reach.
const CODEX_STATUS_WINDOW: usize = 10;

/// codex (inline UI, primary screen). The pin is its composer: the
/// bottom-most column-0 prompt-glyph row that is not a modal selector;
/// status rows sit above it, and scrollback beyond the first foreign row is
/// out of bounds. The approval modal removes the composer and is checked
/// first. The status line or indented hint rows may appear below the composer.
pub struct CodexSummary;

impl SummaryAdapter for CodexSummary {
    fn live_preview(&self, rows: &[String]) -> Option<(String, &'static str)> {
        if let Some(hit) = codex_approval(rows) {
            return Some(hit);
        }
        let composer = codex_composer(rows)?;
        codex_status(rows, composer)
    }

    fn model_label(&self, rows: &[String]) -> Option<String> {
        codex_model_label(rows)
    }

    /// Fold braille frames to `⠋` and `[ . ] ` to `[ ! ] `. Other title
    /// shapes return `None`.
    fn normalize_title(&self, title: &str) -> Option<String> {
        if let Some(rest) = title.strip_prefix("[ . ] ") {
            return Some(format!("[ ! ] {rest}"));
        }
        let mut chars = title.chars();
        let frame = chars.next()?;
        (braille_frame(frame) && chars.next()? == ' ').then(|| format!("{}", chars.as_str()))
    }
}

/// `› 1. Yes, proceed (y)`: the modal's selected option row (column-0 `›`,
/// one digit, `. `).
fn codex_menu_head(row: &str) -> bool {
    row.strip_prefix("")
        .and_then(|r| r.strip_prefix(|c: char| c.is_ascii_digit()))
        .is_some_and(|r| r.starts_with(". "))
}

/// An unselected modal option: indented, `{digit}. `-headed.
fn codex_numbered_option(row: &str) -> bool {
    let t = row.trim_start();
    let digits = t.chars().take_while(char::is_ascii_digit).count();
    t.len() > digits && digits >= 1 && t[digits..].starts_with(". ")
}

/// Codex's approval modal: a selector row with an indented numbered sibling
/// below it, pinned to the last nine painted rows. A quoted menu retains the
/// live composer below it, so any non-selector [`CODEX_PROMPT`] row after the
/// selector suppresses the match. Suppression tests the glyph alone because
/// modal detection must not reinterpret a live composer as quoted content.
fn codex_approval(rows: &[String]) -> Option<(String, &'static str)> {
    let last = rows.iter().rposition(|r| !r.is_empty())?;
    let i = (last.saturating_sub(8)..=last).find(|&i| codex_menu_head(&rows[i]))?;
    let sibling = rows[i + 1..].iter().find(|r| !r.is_empty())?;
    if !(sibling.starts_with(' ') && codex_numbered_option(sibling)) {
        return None;
    }
    rows[i + 1..]
        .iter()
        .all(|r| !r.starts_with(CODEX_PROMPT) || codex_menu_head(r))
        .then(|| (AWAITING_APPROVAL.to_string(), "codex:approval-menu"))
}

/// Return the first ` · `-separated item from the bottom-most qualifying row
/// among the last six painted rows. The status line is independent of the
/// composer and may be absent or omit the model.
///
/// Two shapes qualify:
///
/// - a `{…} in · {…} out` tail, which pins the model to the first item;
/// - a `model-with-reasoning` head, `{model} {effort}` with an optional third
///   word, matched by [`codex_model_with_reasoning`].
///
/// Neither shape means no label. The row must also be indented: the composer
/// and reply bullets begin at column 0 and can otherwise satisfy the same text
/// shapes.
fn codex_model_label(rows: &[String]) -> Option<String> {
    let last = rows.iter().rposition(|r| !r.is_empty())?;
    (last.saturating_sub(5)..=last).rev().find_map(|i| {
        if !rows[i].starts_with(' ') {
            return None;
        }
        let segs: Vec<&str> = rows[i].trim().split(" · ").collect();
        if segs[0].is_empty() {
            return None;
        }
        let in_out = segs.len() >= 3
            && segs[segs.len() - 2].ends_with(" in")
            && segs[segs.len() - 1].ends_with(" out");
        (in_out || codex_model_with_reasoning(segs[0])).then(|| segs[0].to_string())
    })
}

/// Whether an item has the accepted `model-with-reasoning` shape: two or three
/// words, with a recognized effort word second. The optional third word
/// occupies the service-tier position. The fixed effort vocabulary limits
/// prose-shaped false matches.
fn codex_model_with_reasoning(item: &str) -> bool {
    let words: Vec<&str> = item.split_whitespace().collect();
    matches!(words.len(), 2 | 3) && CODEX_EFFORT.contains(&words[1])
}

/// The composer: the bottom-most column-0 [`CODEX_PROMPT`] row that is not a
/// modal selector. The row is the glyph alone or the glyph and a space. Rows
/// below it are tolerated, never required: blank rows, indented affordance
/// hints (`tab to queue message`), or the status line. The working layout can
/// paint hints below the composer with no status line at all. Prompt echoes in
/// scrollback share the glyph but sit above the composer, so the
/// bottom-most wins.
fn codex_composer(rows: &[String]) -> Option<usize> {
    rows.iter().rposition(|r| {
        let mut chars = r.chars();
        chars.next().is_some_and(|c| CODEX_PROMPT.contains(&c))
            && matches!(chars.next(), None | Some(' '))
            && !codex_menu_head(r)
    })
}

/// Walk up from the composer through the status region: blanks and indented
/// rows (tool-output attachments like `└ ok`, wrapped continuations) are
/// skipped, [`CODEX_QUEUED_HEADS`] are walked past, and the first other
/// column-0 row decides. Only two shapes extract ([`codex_status_head`] and
/// `• Ran `); any other column-0 row (a reply bullet, a `⚠` notice, a turn
/// separator) stops the scan: scrollback holds `• Ran` rows from every
/// prior turn, and skipping an unknown row to reach one would resurface
/// stale work as live status. `• Ran ` is tested first because the status
/// head matches on structure, not on a literal verb.
fn codex_status(rows: &[String], composer: usize) -> Option<(String, &'static str)> {
    // Indented rows crossed since the last column-0 row. A queued head
    // claims the ones below it, so a deep queue never exhausts the window.
    let mut indented = 0usize;
    for row in rows[..composer].iter().rev() {
        if row.is_empty() {
            continue;
        }
        if row.starts_with(' ') {
            indented += 1;
            continue;
        }
        if CODEX_QUEUED_HEADS.iter().any(|h| row.starts_with(h)) {
            indented = 0;
            continue;
        }
        if indented > CODEX_STATUS_WINDOW {
            return None;
        }
        if let Some(cmd) = row.strip_prefix("• Ran ")
            && !cmd.is_empty()
        {
            return Some((format!("Ran {cmd}"), "codex:ran"));
        }
        if let Some((header, after_paren)) = codex_status_head(row) {
            return Some((codex_working(header, after_paren), "codex:working"));
        }
        return None;
    }
    None
}

/// Split a live status row into its header and the text after the opening
/// parenthesis. The optional activity prefix is `• ` or `◦ `; the header must
/// begin alphanumeric. [`codex_interrupt_paren`] supplies the fixed structure
/// and admits rows truncated at the terminal width.
fn codex_status_head(row: &str) -> Option<(&str, &str)> {
    let rest = row
        .strip_prefix("")
        .or_else(|| row.strip_prefix(""))
        .unwrap_or(row);
    if !rest.starts_with(char::is_alphanumeric) {
        return None;
    }
    // The header can carry its own parentheses (`Starting MCP servers
    // (1/3): a, b, c`), so the first ` (` opening a counter wins.
    rest.match_indices(" (").find_map(|(i, _)| {
        let after = &rest[i + " (".len()..];
        codex_interrupt_paren(after).then(|| (&rest[..i], after))
    })
}

/// Whether `s` begins with an elapsed counter and interrupt affordance. An
/// elapsed counter alone is ambiguous with conversation prose and does not
/// qualify. An unclosed affordance qualifies only when the row ends in `…`,
/// the terminal-truncation marker.
fn codex_interrupt_paren(s: &str) -> bool {
    let Some(hint) = codex_elapsed(s).and_then(|rest| rest.strip_prefix("")) else {
        return false;
    };
    match hint.find(')') {
        Some(end) => hint[..end].ends_with(" to interrupt"),
        None => hint.ends_with(''),
    }
}

/// The text after codex's compact elapsed counter, or `None` when `s` does
/// not open with one: space-separated `{digits}{unit}` fields in strictly
/// descending `h`, `m`, `s` order, ending at the seconds field (`0s`,
/// `1m 00s`, `25h 02m 03s`). A field that is not digits plus a unit (`1/3`,
/// `9.9s`) fails.
fn codex_elapsed(s: &str) -> Option<&str> {
    let mut rest = s;
    let mut units = "hms";
    loop {
        let digits = rest.chars().take_while(char::is_ascii_digit).count();
        if digits == 0 {
            return None;
        }
        let tail = &rest[digits..];
        let unit = tail.chars().next()?;
        let at = units.find(unit)?;
        units = &units[at + 1..];
        let after = &tail[unit.len_utf8()..];
        if unit == 's' {
            return Some(after);
        }
        rest = after.strip_prefix(' ')?;
    }
}

/// `Working`, `7s • esc to interrupt) · 1 background terminal running · /ps
/// to view · /stop to close` → `Working · 1 background terminal running`.
/// The parenthetical is the elapsed counter plus interrupt affordance,
/// dropped whole. Without a closing parenthesis, no suffix is parsed. Of the
/// ` · ` suffixes, `/`-headed segments are key hints; every other nonempty
/// segment is preserved.
fn codex_working(header: &str, after_paren: &str) -> String {
    let tail = after_paren.find(')').map_or("", |i| &after_paren[i + 1..]);
    format!(
        "{header}{}",
        slow_segments(tail, |seg| seg.starts_with('/'))
    )
}

// ------------------------------------------------------------------ grok --

/// grok (alt screen). The pin is its bordered input box; the status row
/// (braille spinner while working, `Worked for {n}s` after a turn, or
/// `◎ … still running` / `◎ waiting` while background work is live) is
/// the first painted row above the box's top border.
pub struct GrokSummary;

impl SummaryAdapter for GrokSummary {
    fn live_preview(&self, rows: &[String]) -> Option<(String, &'static str)> {
        let (top, _) = grok_input_box(rows)?;
        // One probe row: the first painted row above the box. The splash
        // panel's hints and the session header land here in non-working
        // states and match neither shape.
        let probe = rows[..top].iter().rev().find(|r| !r.is_empty())?;
        let t = probe.trim_start();
        // Keep the label through its first ellipsis. Wrapped tail rows have no
        // spinner prefix, so they fail the frame check and fall through.
        if let Some(text) = spinner_text(t, braille_frame) {
            return Some((text, "grok:spinner"));
        }
        // Still-running is the same probe, never a scan: a closer spinner
        // or Worked-for row already returned above.
        grok_worked(t)
            .then(|| (t.to_string(), "grok:worked"))
            .or_else(|| grok_still_running(t).map(|text| (text, "grok:still-running")))
    }

    fn model_label(&self, rows: &[String]) -> Option<String> {
        let (_, bottom) = grok_input_box(rows)?;
        grok_border_label(&rows[bottom])
    }
}

/// grok's input box: the bottom-most `╰…╯` border (the splash panel's box
/// sits higher), a `╭…╮` top border within six rows above it, and at least
/// one `│`-headed row between. Returns `(top, bottom)` border indexes.
fn grok_input_box(rows: &[String]) -> Option<(usize, usize)> {
    let bottom = rows.iter().rposition(|r| {
        let t = r.trim();
        t.starts_with('') && t.ends_with('')
    })?;
    let top = (bottom.saturating_sub(6)..bottom).rev().find(|&i| {
        let t = rows[i].trim();
        t.starts_with('') && t.ends_with('')
    })?;
    rows[top + 1..bottom]
        .iter()
        .any(|r| r.trim_start().starts_with(''))
        .then_some((top, bottom))
}

/// The completion row grok leaves above its box, kept verbatim: `Worked for
/// 8.7s`, with digits, `.`, and the `m`/`h`/space of longer durations
/// tolerated after a leading digit.
fn grok_worked(t: &str) -> bool {
    t.strip_prefix("Worked for ")
        .and_then(|r| r.strip_suffix('s'))
        .is_some_and(|n| {
            n.starts_with(|c: char| c.is_ascii_digit())
                && n.chars()
                    .all(|c| c.is_ascii_digit() || matches!(c, '.' | ' ' | 'm' | 'h'))
        })
}

/// Background-task chrome grok paints above the box while the main turn
/// looks idle. The `◎` head and the ` · send a message to interrupt` hint
/// drop; `waiting` and `{count} still running` stay. Scrollback such as
/// `Subagent running:` has no `◎` and never matches.
fn grok_still_running(t: &str) -> Option<String> {
    let rest = t.strip_prefix("")?;
    let rest = rest
        .strip_suffix(" · send a message to interrupt")
        .unwrap_or(rest);
    if rest == "waiting" {
        return Some(rest.to_string());
    }
    let body = rest.strip_suffix(" still running")?;
    body.split(" · ")
        .all(grok_still_running_count)
        .then(|| rest.to_string())
}

/// One count segment: ascii digits, a space, then one to three words.
fn grok_still_running_count(seg: &str) -> bool {
    let digits = seg.chars().take_while(char::is_ascii_digit).count();
    if digits == 0 {
        return false;
    }
    let Some(words) = seg[digits..].strip_prefix(' ') else {
        return false;
    };
    (1..=3).contains(&words.split_whitespace().count())
}

/// `╰──── Grok 4.5 (xhigh) · always-approve ─╯` → `Grok 4.5 (xhigh)`: the
/// text grok embeds in its bottom border, first ` · ` segment (the second is
/// the approval mode). A plain border has nothing after its last `─` and
/// yields no label.
fn grok_border_label(row: &str) -> Option<String> {
    let t = row.trim().strip_suffix('')?;
    let t = t.trim_end_matches(['', ' ']);
    let text = &t[t.rfind('')? + ''.len_utf8()..];
    let label = text.trim().split(" · ").next()?.trim();
    (!label.is_empty()).then(|| label.to_string())
}

// ------------------------------------------------------------------- omp --

/// Interrupt-hint suffixes accepted on an anchored status row.
const OMP_HINTS: &[&str] = &["⟦esc⟧", "⟨esc⟩"];

/// Selector cursors accepted by [`omp_approve_row`]. The exact remainder check
/// prevents the ASCII `>` cursor from matching quoted prose.
const OMP_CURSORS: &[&str] = &["", "\u{f054}", ">"];

/// omp inline-UI adapter. A two-row `╭…╮`/`╰…╯` input box anchors the nearest
/// painted status row above it. The approval selector replaces the box, so its
/// absence selects approval matching.
///
/// Unicode box corners anchor status. ASCII `+` and `-` do not: transcript
/// tables and rules use the same glyphs. The plain-text approval selector still
/// matches under ASCII.
pub struct OmpSummary;

impl SummaryAdapter for OmpSummary {
    fn live_preview(&self, rows: &[String]) -> Option<(String, &'static str)> {
        match omp_input_box(rows) {
            Some(top) => omp_spinner_status(rows, top),
            // Consider the approval selector only with the input box gone.
            None => omp_approval(rows),
        }
    }

    /// Model text is user-configurable status-line content, not a stable label.
    fn model_label(&self, _rows: &[String]) -> Option<String> {
        None
    }

    /// Normalize omp's `π {separator} {label}` and `π: {label}` titles. `>`
    /// and `π:` yield a nonempty label, braille frames fold to `⠋`, and `!`
    /// remains the waiting marker. Unsupported shapes and empty idle or
    /// disabled labels return `None`.
    fn normalize_title(&self, title: &str) -> Option<String> {
        if let Some(label) = title.strip_prefix("π: ") {
            return (!label.is_empty()).then(|| label.to_string());
        }
        let mut chars = title.strip_prefix("π ")?.chars();
        let sep = chars.next()?;
        let label = match chars.next() {
            None => "",
            Some(' ') => chars.as_str(),
            Some(_) => return None,
        };
        match sep {
            '>' => (!label.is_empty()).then(|| label.to_string()),
            // `!` and the frame stay: without a label they are the state.
            '!' if label.is_empty() => Some("!".to_string()),
            '!' => Some(format!("! {label}")),
            f if braille_frame(f) && label.is_empty() => Some("".to_string()),
            f if braille_frame(f) => Some(format!("{label}")),
            _ => None,
        }
    }
}

/// Inspect the bottom-most `╰…╯` row and return its predecessor only when that
/// row is a `╭…╮` border. Adjacency rejects preview boxes containing a command.
fn omp_input_box(rows: &[String]) -> Option<usize> {
    let bottom = rows.iter().rposition(|r| {
        let t = r.trim();
        t.starts_with('') && t.ends_with('')
    })?;
    let t = rows[..bottom].last()?.trim();
    (t.starts_with('') && t.ends_with('')).then(|| bottom - 1)
}

/// The status row: the first painted row above the input box, shaped
/// `{frame} {phrase} {hint}` one column in. Everything between the frame and
/// the hint is the model's own streamed intent phrase (`Listing directory
/// contents`; `Working…` when the model streams nothing) and is returned
/// verbatim, the CLI's own truncating `…` included. A wrapped row left its
/// hint on the next line and fails the suffix check rather than yielding half
/// a phrase.
fn omp_spinner_status(rows: &[String], top: usize) -> Option<(String, &'static str)> {
    let probe = rows[..top].iter().rev().find(|r| !r.is_empty())?;
    let mut chars = probe.trim_start().chars();
    if !braille_frame(chars.next()?) || chars.next()? != ' ' {
        return None;
    }
    let rest = chars.as_str();
    let text = OMP_HINTS
        .iter()
        .find_map(|h| rest.strip_suffix(h))?
        .strip_suffix(' ')?;
    text.chars()
        .next()?
        .is_alphanumeric()
        .then(|| (text.to_string(), "omp:spinner"))
}

/// omp's approval selector, reached only with the input box gone: an
/// `Allow tool: {name}` head within six rows above the selected `Approve` row,
/// and `Deny` as the next painted row below it. The selection must occupy one
/// of the final nine rows. Prose quoted above a live input box never reaches
/// this matcher.
fn omp_approval(rows: &[String]) -> Option<(String, &'static str)> {
    let last = rows.iter().rposition(|r| !r.is_empty())?;
    let i = (last.saturating_sub(8)..=last).find(|&i| omp_approve_row(&rows[i]))?;
    if rows[i + 1..].iter().find(|r| !r.is_empty())?.trim() != "Deny" {
        return None;
    }
    rows[i.saturating_sub(6)..i]
        .iter()
        .any(|r| omp_allow_head(r))
        .then(|| (AWAITING_APPROVAL.to_string(), "omp:approval-menu"))
}

/// The selector's chosen row: a cursor spelling, a space, then `Approve` and
/// nothing more. Equality after the cursor is the whole check: the ascii
/// cursor `>` also opens a quoted line, so the row's remainder has to be
/// exact.
fn omp_approve_row(row: &str) -> bool {
    let t = row.trim();
    OMP_CURSORS
        .iter()
        .any(|c| t.strip_prefix(c) == Some(" Approve"))
}

/// The selector's head row: `Allow tool: {name}`. The prefix's trailing
/// space carries the name requirement: a trimmed row cannot end in one, so
/// a bare `Allow tool:` fails.
fn omp_allow_head(row: &str) -> bool {
    row.trim().starts_with("Allow tool: ")
}

#[cfg(test)]
#[path = "summary_tests.rs"]
mod tests;