shep 0.21.0

The shep binary: a process manager that keeps a flock of long-running processes alive on macOS, Linux and Windows, with logs, watch and cron restarts, and webhook alerts
Documentation
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
//! The sheep detail pane: four lines about the selected sheep.
//!
//! Three of the four come from the same `ProcessInfo` the flock table's rows
//! are built from. The lamb line is different: it comes from a
//! `Request::Describe` fetched on selection change and on `r`, never on the
//! poll, since `ListFlock` never populates `ProcessInfo::lambs`.
//!
//! Adds over the row above it: the untruncated name, the merged log-path
//! row, the lamb line, and whichever fields the current width tier dropped.

use ratatui::style::Style;
use ratatui::text::{Line, Span};
use shep_core::protocol::DogSource;

use super::super::app::{App, Row, RowKey};
use super::super::theme::Palette;
use super::cell;
use super::flock::fit;
use super::lamb_line::lamb_line;
use crate::output::width::{char_columns, text_columns};
use crate::output::{human_bytes, human_duration};
use crate::vocabulary::Role;

/// The pane's four content lines. Its rule is [`super::draw`]'s.
#[must_use]
pub fn detail_lines(app: &App, width: u16) -> Vec<Line<'static>> {
    let palette = app.palette();
    match app.selected() {
        None => empty_lines(app, width, palette),
        Some(RowKey::Group(name)) => group_lines(app, &name, width, palette),
        Some(RowKey::Sheep(_)) => sheep_lines(app, width, palette),
        Some(RowKey::Fold(name)) => fold_lines(app, &name, width, palette),
        Some(RowKey::Section(_)) => unreachable!("a header is never selectable"),
    }
}

/// A fold's four lines when a [`RowKey::Fold`] is selected: [`App::fold_totals`]'s
/// rollup, in place of one sheep's own fields. The same shape
/// [`group_lines`] draws one level down, since a fold has no more of a
/// single process to walk or tail than a group does: no lamb line, no log
/// paths.
fn fold_lines(app: &App, name: &str, width: u16, palette: Palette) -> Vec<Line<'static>> {
    let totals = app.fold_totals(name);
    let head = format!("fold {name} \u{d7}{}  ", totals.count);
    let status = app.fold_status_text(name);
    let rest = format!(
        "   restarts {}   uptime {}   cpu {}   mem {}",
        totals.restarts,
        totals
            .uptime_ms
            .map_or_else(|| "-".to_string(), human_duration),
        totals
            .cpu
            .map_or_else(|| "-".to_string(), |cpu| format!("{cpu:.1}%")),
        totals.memory.map_or_else(|| "-".to_string(), human_bytes),
    );
    // Both are fit before either is measured: a long name or a mixed status
    // each overflow `MIN_TERM_WIDTH` alone. `min` because `fit` pads as well
    // as truncates, and a padded head leaves the rollup nothing.
    let status = fit(
        &status,
        width.min(u16::try_from(text_columns(&status)).unwrap_or(width)),
    );
    let head_budget = width.saturating_sub(u16::try_from(text_columns(&status)).unwrap_or(0));
    let head = fit(
        &head,
        head_budget.min(u16::try_from(text_columns(&head)).unwrap_or(head_budget)),
    );
    let used = text_columns(&head) + text_columns(&status);
    let status_style = app
        .fold_uniform_status(name)
        .map_or(Style::default(), |status| palette.status(status));

    vec![
        Line::from(vec![
            Span::raw(head),
            Span::styled(status, status_style),
            Span::raw(fit(
                &rest,
                width.saturating_sub(u16::try_from(used).unwrap_or(width)),
            )),
        ]),
        Line::from(Span::styled(
            fit(
                "lambs  a fold has no single process to walk; select one sheep",
                width,
            ),
            palette.muted(),
        )),
        Line::from(Span::raw(String::new())),
        Line::from(Span::raw(String::new())),
    ]
}

/// The pane's four lines when nothing is selected. Names the cause, not the
/// fact: whether the flock is empty or the filter matched nothing.
fn empty_lines(app: &App, width: u16, palette: Palette) -> Vec<Line<'static>> {
    let why = if app.flock_len() == 0 {
        "no sheep selected: the flock is empty".to_string()
    } else {
        format!("no sheep selected: no name contains \"{}\"", app.filter())
    };
    vec![
        Line::from(Span::styled(fit(&why, width), palette.muted())),
        Line::from(Span::raw(String::new())),
        Line::from(Span::raw(String::new())),
        Line::from(Span::raw(String::new())),
    ]
}

/// An app's four lines when a [`RowKey::Group`] is selected: the rollup
/// [`App::group_totals`] computes, in place of one sheep's own fields. No
/// lamb line and no log paths, since a group has no single process to walk
/// or tail.
fn group_lines(app: &App, name: &str, width: u16, palette: Palette) -> Vec<Line<'static>> {
    let totals = app.group_totals(name);
    let head = format!("app {name} \u{d7}{}  ", totals.count);
    let status = app.group_status_text(name);
    let rest = format!(
        "   restarts {}   uptime {}   cpu {}   mem {}",
        totals.restarts,
        totals
            .uptime_ms
            .map_or_else(|| "-".to_string(), human_duration),
        totals
            .cpu
            .map_or_else(|| "-".to_string(), |cpu| format!("{cpu:.1}%")),
        totals.memory.map_or_else(|| "-".to_string(), human_bytes),
    );
    // Both fit before either is measured, the rule the fold branch states.
    let status = fit(
        &status,
        width.min(u16::try_from(text_columns(&status)).unwrap_or(width)),
    );
    let head_budget = width.saturating_sub(u16::try_from(text_columns(&status)).unwrap_or(0));
    let head = fit(
        &head,
        head_budget.min(u16::try_from(text_columns(&head)).unwrap_or(head_budget)),
    );
    let used = text_columns(&head) + text_columns(&status);
    // `palette.status`, not `palette.reported`: a selected group is always
    // an app's own instances, never a dog.
    let status_style = app
        .group_uniform_status(name)
        .map_or(Style::default(), |status| palette.status(status));

    vec![
        Line::from(vec![
            Span::raw(head),
            Span::styled(status, status_style),
            Span::raw(fit(
                &rest,
                width.saturating_sub(u16::try_from(used).unwrap_or(width)),
            )),
        ]),
        Line::from(Span::styled(
            fit("lambs  not shown for a group; select one instance", width),
            palette.muted(),
        )),
        Line::from(Span::raw(String::new())),
        Line::from(Span::raw(String::new())),
    ]
}

/// A real sheep's four lines. `app.selected_row()` is `None` here only when
/// the selection has just gone stale between messages; that frame reuses the
/// empty pane's own sentence rather than inventing a fifth state.
fn sheep_lines(app: &App, width: u16, palette: Palette) -> Vec<Line<'static>> {
    let Some(row) = app.selected_row() else {
        return empty_lines(app, width, palette);
    };
    vec![
        identity_line(app, row, width, palette),
        lamb_line(app, row.info.id, width, palette),
        log_row(app, width),
        // The two path lines merged into `log_row`, one slot narrower than
        // before; this keeps the pane's line count agreeing with
        // `DETAIL_ROWS` without inventing a fifth field to fill it.
        Line::from(Span::raw(String::new())),
    ]
}

/// One sheep's identity line: the `SHEEP N` chip, its name, status and the
/// rest of its row. Split out of [`sheep_lines`] so [`super::sheep`]'s own
/// identity band can draw it for the sheep pane's pinned sheep.
///
/// Every figure this line reads (`App::uptime_ms`, `App::cpu_now`) takes
/// `row`'s own id, so a pinned sheep that has left the flock is not drawn
/// with the selection's figures.
#[must_use]
pub(crate) fn identity_line(app: &App, row: &Row, width: u16, palette: Palette) -> Line<'static> {
    let info = &row.info;

    // The `SHEEP N` chip, meadow like the flock band, then the name and the
    // rest of the row. Everything after the chip is raw except the status
    // word, which is the one coloured cell, same as the table.
    let chip = chip_text(&format!("SHEEP {}", info.id));
    let facts = format!("  {}   ", info.name);
    // `Row::reported`, not `info.status.to_string()`: this pane must agree
    // with the flock table's own STATUS cell for the same row, and a dog
    // that has never handshook reads `silent` there.
    let status = row.reported().word();
    // Reuses `cfg_cell`, the same function `Column::Cfg` calls, rather than a
    // second renderer for the same rule. Only the pending half: an override
    // with nothing parked is already the flock table's `*N`, and nothing
    // pending shows nothing at all.
    let cfg = crate::output::cfg_cell(info.pending.as_deref(), None);
    let cfg_text = if cfg.starts_with('!') {
        format!("   cfg {cfg} pending")
    } else {
        String::new()
    };
    let rest = format!(
        "   pid {}   restarts {}   uptime {}   cpu {}   mem {}   fold {}{}{}",
        info.pid
            .map_or_else(|| "-".to_string(), |pid| pid.to_string()),
        info.restarts,
        app.uptime_ms(info.id)
            .map_or_else(|| "-".to_string(), human_duration),
        // `App::cpu_now`, not `info.cpu_percent`: this band must agree with
        // the flock table's own CPU cell for the same row.
        app.cpu_now(info.id)
            .map_or_else(|| "-".to_string(), |cpu| format!("{cpu:.1}%")),
        info.memory_bytes
            .map_or_else(|| "-".to_string(), human_bytes),
        info.fold.as_deref().unwrap_or("-"),
        // Second to last, so it is the first thing a narrow terminal
        // truncates: a dog is a rare row, and every field before it is true
        // of every row.
        match &info.dog {
            None => String::new(),
            Some(DogSource::BuiltIn { .. }) => "   dog built-in".to_string(),
            Some(DogSource::Adopted { path, .. }) => format!("   dog adopted {path}"),
            // `DogSource` is `#[non_exhaustive]`: a source a newer shepherd
            // added must not take the pane down, and must not be reported as
            // anything it is not.
            _ => "   dog (unrecognised source)".to_string(),
        },
        // Last of all: rarer still than a dog, since it fires only for a
        // sheep with edits parked awaiting a respawn. Folded into the same
        // truncatable string as everything before it, so it is the first
        // thing a narrow terminal drops.
        cfg_text,
    );
    let used = text_columns(&chip) + text_columns(&facts) + text_columns(&status);

    Line::from(vec![
        Span::styled(chip, palette.band(Role::Meadow)),
        Span::raw(facts),
        Span::styled(status, palette.reported(row.reported())),
        Span::raw(fit(
            &rest,
            width.saturating_sub(u16::try_from(used).unwrap_or(width)),
        )),
    ])
}

/// `cell::band`'s own two-block marker and label, sized to its own text
/// rather than padded to a pane's full width: a compact chip an inline
/// header can prefix, not a full-width band.
///
/// `pub(crate)`, not private: `view::bleats`'s own header chip shares this
/// rather than re-deriving the same natural-width computation.
pub(crate) fn chip_text(label: &str) -> String {
    let natural = format!(" \u{2588}\u{2588} {label}");
    let cells: usize = text_columns(&natural);
    cell::band(label, cells)
}

/// The merged log-path row: `out` and `err`, a `\u{2502}` divider, and the
/// size on disk as of the last poll ([`App::log_size_for`]).
///
/// When the row does not fit, the size drops first, then each path truncates
/// from its head: a log path's tail is the half that identifies it. No
/// reading yet, a reading for another sheep, and a rotated-away log all drop
/// the size rather than the row.
fn log_row(app: &App, width: u16) -> Line<'static> {
    const OUT_LABEL: &str = "out  ";
    const ERR_LABEL: &str = "err  ";
    const DIVIDER: &str = "   \u{2502}   ";

    let palette = app.palette();
    let info = &app
        .selected_row()
        .expect("a selected sheep is in the flock")
        .info;
    let out_path = info.out_file.as_deref();
    let err_path = info.err_file.as_deref();
    let out_full = out_path.unwrap_or("not reported");
    let err_full = err_path.unwrap_or("not reported");

    // Read on the poll rather than here: `App::log_size_for` is the last
    // reading for this sheep, and a `stat` inside a 30 fps draw stops being
    // free the moment the log directory is a network mount.
    let size_text = app
        .log_size_for(info.id)
        .map(|bytes| format!("   {} on disk", human_bytes(bytes)));

    let overhead = text_columns(OUT_LABEL) + text_columns(DIVIDER) + text_columns(ERR_LABEL);
    let width_usize = usize::from(width);
    let paths_len = overhead + text_columns(out_full) + text_columns(err_full);

    let (out_val, err_val, size_val) =
        if paths_len + size_text.as_deref().map_or(0, text_columns) <= width_usize {
            (out_full.to_string(), err_full.to_string(), size_text)
        } else if paths_len <= width_usize {
            (out_full.to_string(), err_full.to_string(), None)
        } else {
            // The size already dropped and the untruncated paths still do not
            // fit: split what is left evenly and take each path's tail, since
            // that is the half that identifies it.
            let budget = width_usize.saturating_sub(overhead);
            let out_budget = budget / 2;
            let err_budget = budget - out_budget;
            (
                truncate_from_left(out_full, out_budget),
                truncate_from_left(err_full, err_budget),
                None,
            )
        };

    let mut spans = vec![
        Span::styled(format!("{OUT_LABEL}{out_val}"), palette.muted()),
        // `line`, not `muted`: the divider is chrome between two facts, the
        // same role the flock table's own rules draw in.
        Span::styled(DIVIDER, palette.line()),
        Span::styled(
            format!("{ERR_LABEL}{err_val}{}", size_val.unwrap_or_default()),
            palette.muted(),
        ),
    ];
    let used: usize = spans
        .iter()
        .map(|span| text_columns(span.content.as_ref()))
        .sum();
    if used < width_usize {
        spans.push(Span::styled(
            " ".repeat(width_usize - used),
            palette.muted(),
        ));
    }
    Line::from(spans)
}

/// Keeps `path`'s tail, the half that identifies the file, marking the drop
/// with a leading `\u{2026}` when it does not fit `budget` columns.
fn truncate_from_left(path: &str, budget: usize) -> String {
    if text_columns(path) <= budget {
        return path.to_string();
    }
    if budget == 0 {
        return String::new();
    }
    let keep = budget - 1;
    let mut kept: Vec<char> = Vec::new();
    let mut used = 0;
    for c in path.chars().rev() {
        let width = char_columns(c);
        if used + width > keep {
            break;
        }
        used += width;
        kept.push(c);
    }
    kept.reverse();
    format!("\u{2026}{}", kept.into_iter().collect::<String>())
}

#[cfg(test)]
mod tests {
    use shep_core::protocol::ProcessInfo;
    use shep_core::status::ProcStatus;

    use super::super::fixtures::{
        app_fixture, app_with, coloured, plain, render_all, rendered, sheep_in_fold,
        sheep_in_fold_with_status, with_selection, with_selection_and_palette,
    };
    use super::super::flock::FrameFacts;
    use super::*;
    use crate::lookout::app::{App, Control, KeyPress, Msg, RowKey};
    use crate::lookout::theme::Palette;

    /// The untruncated name matters: an operator types it into `shep stop`,
    /// and the name column truncates.
    #[test]
    fn the_pane_adds_the_full_name_and_both_log_paths() {
        let app = with_selection(
            ProcessInfo::builder(7, "payments-reconciliation-worker", ProcStatus::Errored)
                .out_file(Some("/home/ada/.shep/logs/payments-out.log".to_string()))
                .err_file(Some("/home/ada/.shep/logs/payments-err.log".to_string()))
                .build(),
        );
        let rendered = render_all(&detail_lines(&app, 200));
        assert!(
            rendered.contains("payments-reconciliation-worker"),
            "the whole name"
        );
        assert!(rendered.contains("out  /home/ada/.shep/logs/payments-out.log"));
        assert!(rendered.contains("err  /home/ada/.shep/logs/payments-err.log"));
    }

    /// The design spec names this cell alongside the `SHEEP N` chip; reuses
    /// `cfg_cell`, the same function the flock table's own CFG column calls.
    /// Rendered last, inside the same truncatable `rest` span as `pid`,
    /// `restarts`, `uptime`, `cpu`, `mem`, `fold` and `dog` (see
    /// `a_narrow_width_truncates_the_cfg_cell_before_the_universal_fields`
    /// below for the position that matters).
    #[test]
    fn the_header_names_the_pending_count() {
        let app = with_selection(
            ProcessInfo::builder(2, "api", ProcStatus::Online)
                .pending(Some(vec!["cwd".to_string(), "env".to_string()]))
                .build(),
        );
        let rendered = render_all(&detail_lines(&app, 200));
        assert!(rendered.contains("cfg !2 pending"), "got {rendered:?}");
    }

    /// Round 1 put the `cfg` cell outside `rest`, immune to truncation, so a
    /// narrow terminal cut fields true of every row to make room for one true
    /// of almost none. `cfg` fires only for a sheep with edits parked, at
    /// least as rare as `dog`, so it goes after it and through `fit`.
    #[test]
    fn a_narrow_width_truncates_the_cfg_cell_before_the_universal_fields() {
        let app = with_selection(
            ProcessInfo::builder(2, "api", ProcStatus::Online)
                .pid(Some(4_242))
                .restarts(3)
                .pending(Some(vec!["cwd".to_string()]))
                .build(),
        );
        let wide = render_all(&detail_lines(&app, 200));
        assert!(wide.contains("cfg !1 pending"), "got {wide:?}");

        let narrow = render_all(&detail_lines(&app, 40));
        assert!(
            !narrow.contains("cfg"),
            "the rarest field truncates first: {narrow:?}"
        );
        assert!(
            narrow.contains("pid"),
            "a universal field must survive over the cfg cell: {narrow:?}"
        );
    }

    /// "Nothing at all rather than a zero": a sheep with no pending fields
    /// gets no `cfg` cell at all, not `cfg !0 pending`.
    #[test]
    fn a_sheep_with_nothing_pending_shows_no_cfg_cell() {
        let app = with_selection(ProcessInfo::builder(2, "api", ProcStatus::Online).build());
        let rendered = render_all(&detail_lines(&app, 200));
        assert!(!rendered.contains("cfg"), "got {rendered:?}");
    }

    /// Same rule as the table's: the coloured cell is the cell whose text
    /// already says the same thing.
    #[test]
    fn only_the_status_word_is_coloured() {
        let palette = coloured();
        let app = with_selection_and_palette(
            ProcessInfo::builder(2, "api", ProcStatus::Errored).build(),
            palette,
        );
        let lines = detail_lines(&app, 200);
        let coloured: Vec<&str> = lines
            .iter()
            .flat_map(|line| &line.spans)
            .filter(|span| span.style.fg == palette.alarm().fg)
            .map(|span| span.content.as_ref())
            .collect();
        assert_eq!(coloured, vec!["errored"], "got {coloured:?}");
    }

    #[test]
    fn an_empty_flock_says_why_the_pane_has_nothing_to_describe() {
        let app = App::new(
            Palette::detect(None, None, None),
            Control::ReadOnly,
            "/home/ada/.shep".to_string(),
            std::time::Instant::now(),
        );
        let rendered = render_all(&detail_lines(&app, 200));
        assert!(
            rendered.contains("no sheep selected: the flock is empty"),
            "got {rendered:?}"
        );
    }

    /// Drives `detail_lines` through a real `App` built from a real
    /// `Msg::Snapshot`, the same door the production render loop walks
    /// through, rather than calling `group_lines` directly.
    #[test]
    fn a_selected_group_row_shows_the_apps_rollup_and_no_lambs_or_paths() {
        let app = app_with(
            vec![
                ProcessInfo::builder(1, "web", ProcStatus::Online)
                    .instance(Some(0))
                    .memory_bytes(Some(100 << 20))
                    .uptime_ms(120_000)
                    .out_file(Some("/home/ada/.shep/logs/web-0-out.log".to_string()))
                    .build(),
                ProcessInfo::builder(2, "web", ProcStatus::Online)
                    .instance(Some(1))
                    .memory_bytes(Some(150 << 20))
                    .uptime_ms(30_000)
                    .build(),
            ],
            plain(),
        );
        // Sanity: the group is the whole flock here, so the default
        // selection lands on it with no keypress.
        assert!(
            matches!(app.selected(), Some(RowKey::Group(ref name)) if name == "web"),
            "sanity: the group is selected by default, got {:?}",
            app.selected()
        );

        let rendered = render_all(&detail_lines(&app, 200));
        assert!(rendered.contains("app web \u{d7}2"), "got {rendered:?}");
        assert!(
            rendered.contains("uptime 30s"),
            "the MINIMUM uptime (30s), not the first instance's 120s: {rendered:?}"
        );
        assert!(
            rendered.contains("mem 250.0M"),
            "memory summed (100 + 150 MiB): {rendered:?}"
        );
        assert!(
            rendered.contains("lambs  not shown for a group; select one instance"),
            "got {rendered:?}"
        );
        assert!(
            !rendered.contains("web-0-out.log"),
            "no arbitrarily-chosen instance's log path: {rendered:?}"
        );
    }

    /// The detail pane already refuses to invent a single process for a
    /// group. A fold is the same situation one level up.
    #[test]
    fn a_selected_fold_shows_the_rollup_and_no_log_paths() {
        let mut app = app_with(
            vec![
                sheep_in_fold(1, "api", Some("edge")),
                sheep_in_fold(2, "cdn", Some("edge")),
            ],
            plain(),
        );
        let _ = app.update(Msg::Key(KeyPress::FoldView));
        app.select_fold_for_tests("edge");
        let text = render_all(&detail_lines(&app, 200));
        assert!(text.contains("fold edge \u{d7}2"), "got {text}");
        assert!(
            text.contains("restarts") && text.contains("uptime") && text.contains("cpu"),
            "the rollup a fold shows in place of one sheep's fields: {text}"
        );
        // Not `!contains("out  ")`, which cannot fail: `log_row` reaches the
        // log paths through `selected_row`, and that is `None` for a fold, so
        // the label can only be absent. Asserting the rollup IS present is
        // what catches `fold_lines` drifting toward a sheep's own shape.
    }

    /// Drives both panes off the same [`App`] built from the same row, the
    /// way an operator with both open sees them.
    #[test]
    fn a_silent_dogs_status_word_and_colour_agree_with_the_flock_pane() {
        use shep_core::protocol::DogSource;
        use shep_core::status::ProcStatus;

        use super::super::flock::{columns_for, row_line};

        let dog = ProcessInfo::builder(9, "log-rotate", ProcStatus::Online)
            .pid(Some(4_242))
            .dog(Some(DogSource::Adopted {
                grants: None,
                path: "/usr/local/bin/shep-log-rotate".to_string(),
                channel: false,
            }))
            .handshook(Some(false))
            .build();
        let app = with_selection_and_palette(dog, coloured());
        let palette = app.palette();

        let detail_rendered = render_all(&detail_lines(&app, 200));
        assert!(
            detail_rendered.contains("silent"),
            "detail pane must say silent: {detail_rendered:?}"
        );
        assert!(!detail_rendered.contains("online"), "{detail_rendered:?}");

        let row = app.row(9).unwrap();
        let flock_line = row_line(
            &app,
            &FrameFacts::new(&app),
            row,
            columns_for(200),
            200,
            false,
        );
        let flock_rendered: String = flock_line
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect();
        assert!(flock_rendered.contains("silent"), "{flock_rendered:?}");

        // Both panes colour the word `--butter`: a gap the operator can
        // close, not `--bark`.
        let detail_colour = detail_lines(&app, 200)[0]
            .spans
            .iter()
            .find(|span| span.content.as_ref() == "silent")
            .map(|span| span.style.fg);
        assert_eq!(detail_colour, Some(palette.attention().fg));
    }

    /// The three widths `log_row`'s own tiers need, derived from the
    /// fixture's actual paths rather than a hardcoded literal.
    ///
    /// `app_fixture`'s tempdir is whatever the host resolves, so a fixed
    /// literal is a bet on the environment. `wide` fits both paths plus the
    /// size, `medium` fits both paths but not the size, `narrow` is a small
    /// constant well under the full row's width.
    fn log_row_thresholds(app: &App) -> (u16, u16, u16) {
        let info = &app.selected_row().expect("a selected sheep").info;
        let out = info.out_file.as_deref().unwrap_or("not reported");
        let err = info.err_file.as_deref().unwrap_or("not reported");
        let full = "out  ".len() + out.len() + "   \u{2502}   ".len() + "err  ".len() + err.len();
        let wide = u16::try_from(full + 40).expect("a test fixture's width fits u16");
        let medium = u16::try_from(full + 5).expect("a test fixture's width fits u16");
        // Independent of the fixture's path length: `full` above always
        // exceeds this, since a real tempdir path is never this short.
        let narrow = 39;
        (wide, medium, narrow)
    }

    #[test]
    fn the_log_row_carries_both_paths_and_the_size() {
        let (wide, ..) = log_row_thresholds(&app_fixture());
        let line = log_row(&app_fixture(), wide);
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("out"));
        assert!(text.contains("err"));
        assert!(text.contains('\u{2502}'), "a divider between the two");
    }

    #[test]
    fn a_narrow_log_row_drops_the_size_before_it_truncates_a_path() {
        let app = app_fixture();
        let (wide, medium, _) = log_row_thresholds(&app);
        let wide_text: String = log_row(&app, wide)
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect();
        let medium_text: String = log_row(&app, medium)
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect();
        assert!(wide_text.contains("on disk"));
        assert!(!medium_text.contains("on disk"));
    }

    #[test]
    fn a_path_truncates_from_the_left_so_its_filename_survives() {
        let app = app_fixture();
        let (_, _, narrow) = log_row_thresholds(&app);
        let narrow_text: String = log_row(&app, narrow)
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect();
        assert!(
            narrow_text.contains("-out.log"),
            "the tail identifies the file"
        );
    }

    /// The reading is keyed by id, so one taken for another sheep draws
    /// nothing rather than label that sheep's bytes as this one's. The pane no
    /// longer reads the filesystem, which is what makes this possible to get
    /// wrong: the rule that both files must be sized moved to
    /// `source::LocalReader::log_sizes` and is tested there.
    #[test]
    fn a_reading_taken_for_another_sheep_draws_no_size() {
        let mut app = app_fixture();
        let (wide, ..) = log_row_thresholds(&app);
        let before = rendered(&log_row(&app, wide));
        assert!(before.contains("on disk"), "the fixture polled: {before:?}");

        app.update(Msg::LogSize {
            id: 999,
            total_bytes: Some(4_096),
        });
        let after = rendered(&log_row(&app, wide));
        assert!(
            !after.contains("on disk"),
            "the reading names sheep 999, not the selected 7: {after:?}"
        );
    }

    /// `used` must be measured in display columns, not `char`s: a sheep name
    /// with double-width characters undercounts by `chars().count()`, which
    /// hands `fit` a larger budget than actually remains and pushes the
    /// composed line past `width`.
    #[test]
    fn a_wide_character_name_does_not_push_the_first_line_past_width() {
        let info = ProcessInfo::builder(3, "羊羊羊羊羊", ProcStatus::Online)
            .pid(Some(48_103))
            .build();
        let app = with_selection(info);
        let width = 60;

        let lines = detail_lines(&app, width);
        let first = rendered(&lines[0]);
        assert!(
            text_columns(&first) <= usize::from(width),
            "first line is {} columns wide, wanted at most {width}: {first:?}",
            text_columns(&first)
        );
    }

    /// The group path composes its own first line and so needs the same
    /// column measurement the sheep path does. `chars().count()` over an
    /// app name of double-width characters undercounts by half, and the
    /// rollup line runs off the right edge.
    #[test]
    fn a_wide_character_group_name_does_not_push_the_first_line_past_width() {
        let app = app_with(
            vec![
                ProcessInfo::builder(
                    1,
                    "\u{7f8a}\u{7f8a}\u{7f8a}\u{7f8a}\u{7f8a}",
                    ProcStatus::Online,
                )
                .instance(Some(0))
                .build(),
                ProcessInfo::builder(
                    2,
                    "\u{7f8a}\u{7f8a}\u{7f8a}\u{7f8a}\u{7f8a}",
                    ProcStatus::Online,
                )
                .instance(Some(1))
                .build(),
            ],
            plain(),
        );
        let width = 60;

        let lines = detail_lines(&app, width);
        let first = rendered(&lines[0]);
        assert!(
            text_columns(&first) <= usize::from(width),
            "first line is {} columns wide, wanted at most {width}: {first:?}",
            text_columns(&first)
        );
    }

    /// A long fold name cannot push the status word off a narrow pane.
    ///
    /// `MIN_TERM_WIDTH` is 33 and the head is built before anything is fit,
    /// so a fold named at length would spend the whole row. A mixed status is
    /// fit too: four differing statuses read wider than 33 on their own.
    #[test]
    fn a_mixed_status_does_not_overflow_a_narrow_pane() {
        for selected in ["fold", "group"] {
            let mut app = app_with(
                vec![
                    sheep_in_fold_with_status(1, "api", Some("edge"), ProcStatus::Errored),
                    sheep_in_fold_with_status(2, "cdn", Some("edge"), ProcStatus::Online),
                    sheep_in_fold_with_status(3, "img", Some("edge"), ProcStatus::Starting),
                    sheep_in_fold_with_status(4, "web", Some("edge"), ProcStatus::Stopped),
                ],
                plain(),
            );
            if selected == "fold" {
                let _ = app.update(Msg::Key(KeyPress::FoldView));
                app.select_fold_for_tests("edge");
            } else {
                // The group header is the first selectable row when every
                // instance shares a name.
                app.select_fold_for_tests("edge");
                let _ = app.update(Msg::Key(KeyPress::FoldView));
            }
            for line in &detail_lines(&app, 33) {
                let drawn: String = line
                    .spans
                    .iter()
                    .map(|span| span.content.as_ref())
                    .collect();
                assert!(
                    text_columns(&drawn) <= 33,
                    "{selected} row overflowed 33 columns: {drawn:?}"
                );
            }
        }
    }

    #[test]
    fn a_long_fold_name_does_not_push_the_status_off_a_narrow_pane() {
        let mut app = app_with(
            vec![
                sheep_in_fold(1, "api", Some("edge-services-and-more")),
                sheep_in_fold(2, "cdn", Some("edge-services-and-more")),
            ],
            plain(),
        );
        let _ = app.update(Msg::Key(KeyPress::FoldView));
        app.select_fold_for_tests("edge-services-and-more");
        let lines = detail_lines(&app, 33);
        for line in &lines {
            let drawn: String = line
                .spans
                .iter()
                .map(|span| span.content.as_ref())
                .collect();
            assert!(
                text_columns(&drawn) <= 33,
                "a detail row overflowed 33 columns: {drawn:?}"
            );
        }
        let head = render_all(&lines);
        assert!(head.contains("online"), "the status survives: {head}");
    }
}