shep 0.20.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
//! Putting the whole pane together: the chrome above the body, the panel
//! beside it where the width affords one, and the footer under a dog's.
//!
//! [`pane_lines`] is the entry every caller but the draw loop uses, and
//! [`draw_pane`] is the draw loop's. Which of the four layouts below runs
//! depends on two questions only: whether the field set has groups, and
//! whether the panel fits.

use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};

use super::super::super::app::App;
use super::super::super::pane::{ConfigPane, PaneTarget};
use super::super::super::theme::Palette;
use super::super::flock::fit;
use super::super::overlay;
use super::body::body_lines;
use super::chrome::{
    column_header_line, hairline_line, has_groups, legend_line, tab_row_line, title_band_line,
    title_line,
};
use super::close::draw_close_dialog;
use super::field_row::push_wrapped_blurb;
use super::layout::{body_width, lands_fits_beside_panel, line_columns, panel_width};
use super::list::list_lines;
use super::panel::panel_lines;

/// The pane's lines when its fields carry groups (every sheep): the butter
/// title band naming the target once, the tab row, a hairline, the menu or
/// help line when one is up else the column header row, the body, a
/// hairline, and the legend.
pub(super) fn grouped_pane_lines(
    pane: &ConfigPane,
    palette: Palette,
    width: u16,
    budget: usize,
) -> Vec<Line<'static>> {
    grouped_pane_lines_with_panel(pane, palette, width, budget, None)
}

/// [`grouped_pane_lines`], with the cursor's own field's [`panel_lines`]
/// drawn beside the body only: the title band, tab row, hairline and
/// header row are chrome, not per-field.
///
/// Chrome is laid out at the real `width`, not clamped to the design
/// target. `panel_width` governs how much of that width the panel claims,
/// and nothing here grows it past [`super::layout::PANEL_MAX`].
pub(super) fn grouped_pane_with_panel_lines(
    pane: &ConfigPane,
    palette: Palette,
    width: u16,
    panel_w: u16,
    budget: usize,
) -> Vec<Line<'static>> {
    let panel = panel_lines(pane, palette, panel_w);
    grouped_pane_lines_with_panel(pane, palette, width, budget, Some((panel, panel_w)))
}

/// The body shared by [`grouped_pane_lines`] and
/// [`grouped_pane_with_panel_lines`]: `panel` is `None` for the former,
/// which lays the body out at `width` exactly as it always has, and
/// `Some((lines, panel_width))` for the latter, which lays the body out at
/// `width - panel_width` instead and merges `lines` beside it, since that
/// is the one region tall enough and narrow enough to hold both.
pub(super) fn grouped_pane_lines_with_panel(
    pane: &ConfigPane,
    palette: Palette,
    width: u16,
    budget: usize,
    panel: Option<(Vec<Line<'static>>, u16)>,
) -> Vec<Line<'static>> {
    let has_panel = panel.is_some();
    let show_lands = lands_fits_beside_panel(width, has_panel);
    let left_width = panel
        .as_ref()
        .map_or(width, |(_, panel_width)| width.saturating_sub(*panel_width));
    let mut lines = vec![title_band_line(pane, palette, width)];
    let mut remaining = budget - 1;
    if remaining == 0 {
        return lines;
    }
    // Everything from here down is best-effort, and every push is gated on
    // `remaining > 1` rather than `> 0`: the body's cursor outranks these
    // lines, so a chrome line is added only when one line is still left
    // for the body.
    if remaining > 1 {
        lines.push(tab_row_line(pane, palette, width));
        remaining -= 1;
    }
    if remaining > 1 {
        lines.push(hairline_line(palette, width));
        remaining -= 1;
    }
    if remaining > 1 {
        lines.push(column_header_line(palette, left_width, show_lands));
        remaining -= 1;
    }
    push_wrapped_blurb(&mut lines, &mut remaining, pane, palette, width);
    // Unreachable given `push_wrapped_blurb`'s own floor of `<= 1`. Kept as
    // the explicit statement of that invariant;
    // `the_blurb_never_spends_the_row_the_cursor_needs` is what actually
    // fails if the floor is ever loosened.
    if remaining == 0 {
        return lines;
    }
    // The trailing hairline and legend are reserved ahead of the body: a
    // line nothing counted is a line that can overrun. Never the body's
    // last line, for the same reason as above.
    let footer_lines = if remaining > 1 {
        2.min(remaining - 1)
    } else {
        0
    };
    let body_budget = remaining - footer_lines;
    if body_budget > 0 {
        let body = body_lines(pane, palette, left_width, body_budget, show_lands);
        lines.extend(match panel {
            Some((panel, _)) => merge_beside_panel(body, panel, left_width, body_budget),
            None => body,
        });
    }
    if footer_lines >= 1 {
        lines.push(hairline_line(palette, width));
    }
    if footer_lines >= 2 {
        lines.push(legend_line(palette, width));
    }
    lines
}

/// `left`'s lines and `panel`'s lines, side by side: `left` padded out to
/// exactly `left_width` columns with a blank span, then whichever `panel`
/// row shares that index appended after it.
///
/// Either side short of the other draws blank rather than dropping the
/// longer side's rows, up to `budget`, the ceiling
/// [`body_lines`] was already laid out against.
pub(super) fn merge_beside_panel(
    left: Vec<Line<'static>>,
    panel: Vec<Line<'static>>,
    left_width: u16,
    budget: usize,
) -> Vec<Line<'static>> {
    let left_width = usize::from(left_width);
    // `left` never exceeds `budget` on its own, since `body_lines`
    // already laid it out against the same ceiling; the `min` only ever
    // trims `panel`'s own overrun.
    let rows = left.len().max(panel.len()).min(budget);
    let mut left = left.into_iter();
    let mut panel = panel.into_iter();
    (0..rows)
        .map(|_| {
            let line = left.next().unwrap_or_default();
            let used = line_columns(&line);
            let mut spans = line.spans;
            if used < left_width {
                spans.push(Span::raw(" ".repeat(left_width - used)));
            }
            if let Some(panel_line) = panel.next() {
                spans.extend(panel_line.spans);
            }
            Line::from(spans)
        })
        .collect()
}

/// The trailing "shep publishes..." line a dog-target render reserves out
/// of its own budget before the body claims what is left: `None` for a
/// sheep, which owns its own reload, and for a dog with no budget left.
///
/// Text only; the caller decides whether reserving it costs one line of
/// `body_budget`, since [`pane_lines`]'s plain branch and
/// `ungrouped_pane_lines_with_panel` both need that decision made first.
pub(super) fn dog_footer_text(pane: &ConfigPane, body_budget: usize) -> Option<String> {
    let (PaneTarget::Dog { name, .. } | PaneTarget::SheepDog { dog: name, .. }) = pane.target()
    else {
        return None;
    };
    (body_budget > 0).then(|| format!("shep publishes the change; {name} decides what to reload"))
}

/// Pushes `footer`'s line onto `lines`, muted and fit to `width`: the tail
/// half of [`dog_footer_text`], shared the same way the reservation half is.
pub(super) fn push_footer_line(
    lines: &mut Vec<Line<'static>>,
    footer: Option<String>,
    width: u16,
    palette: Palette,
) {
    if let Some(text) = footer {
        lines.push(Line::from(Span::styled(
            format!("  {}", fit(&text, body_width(width))),
            palette.muted(),
        )));
    }
}

/// Every line of the pane, top to bottom, laid out for a terminal `height`
/// rows tall. `height` counts lines, and no more than that ever come back.
/// Zero means unlimited, which is what a test with no terminal gets.
///
/// The close dialog is not drawn here: it overlays the whole field list
/// (`draw_pane`). See [`super::super::scroll`] for the viewport's offset.
#[must_use]
pub fn pane_lines(
    pane: &ConfigPane,
    palette: Palette,
    width: u16,
    height: u16,
) -> Vec<Line<'static>> {
    let budget = if height == 0 {
        usize::MAX
    } else {
        usize::from(height)
    };
    if budget == 0 {
        return Vec::new();
    }
    let focus = pane.focus();
    if let Some(list) = focus.list() {
        return list_lines(focus, list, palette, width, budget);
    }
    if has_groups(pane) {
        if let Some(panel_w) = panel_width(width) {
            return grouped_pane_with_panel_lines(pane, palette, width, panel_w, budget);
        }
        return grouped_pane_lines(pane, palette, width, budget);
    }
    let panel = panel_width(width).map(|panel_w| (panel_lines(pane, palette, panel_w), panel_w));
    ungrouped_pane_lines_with_panel(pane, palette, width, budget, panel)
}

/// The body [`pane_lines`] draws for a pane with no groups, which is a
/// dog's own shape: `panel` is [`None`] below [`panel_width`]'s floor, and
/// `Some((lines, panel_width))` above it.
///
/// No tab row and no legend: a dog's schema carries no group to name. The
/// trailing "shep publishes..." footer is chrome, reserved before the body
/// claims what is left.
pub(super) fn ungrouped_pane_lines_with_panel(
    pane: &ConfigPane,
    palette: Palette,
    width: u16,
    budget: usize,
    panel: Option<(Vec<Line<'static>>, u16)>,
) -> Vec<Line<'static>> {
    let show_lands = lands_fits_beside_panel(width, panel.is_some());
    let left_width = panel
        .as_ref()
        .map_or(width, |(_, panel_width)| width.saturating_sub(*panel_width));
    let mut lines = vec![title_line(pane, palette, width)];
    // The title is unconditional, so the body is laid out against what is
    // left after it. An empty form (unreachable for a sheep, whose schema
    // is a committed file with 40 properties, but a dog answers `--schema`
    // for itself) leaves the title as the whole pane.
    let mut body_budget = budget - 1;
    // The one line a dog pane has that a sheep pane does not: shep does not
    // know what a dog's field costs, so every row's COST cell is empty.
    // Reserved before the blurb, which is the line to lose: the blurb
    // describes the row rather than being it.
    let footer = dog_footer_text(pane, body_budget);
    if footer.is_some() {
        body_budget -= 1;
    }
    // The selected field's own help text, on the lines under the title.
    // Subtracted from the budget rather than appended, per `body_from`'s
    // own doc on markers. See `top_lines`.
    push_wrapped_blurb(&mut lines, &mut body_budget, pane, palette, width);
    if !pane.rows().is_empty() && body_budget > 0 {
        let body = body_lines(pane, palette, left_width, body_budget, show_lands);
        lines.extend(match panel {
            Some((panel, _)) => merge_beside_panel(body, panel, left_width, body_budget),
            None => body,
        });
    }
    push_footer_line(&mut lines, footer, width, palette);
    lines
}

/// Draws the pane into `area`, straight into `buffer`.
pub fn draw_pane(app: &App, pane: &ConfigPane, area: Rect, buffer: &mut Buffer) {
    if area.width == 0 || area.height == 0 {
        return;
    }
    let lines = pane_lines(pane, app.palette(), area.width, area.height);
    for (offset, line) in lines.iter().enumerate().take(usize::from(area.height)) {
        let offset = u16::try_from(offset).unwrap_or(0);
        buffer.set_line(area.x, area.y + offset, line, area.width);
    }
    if let Some(dialog) = app.close_dialog() {
        // The pane draws first and is then muted whole, so 1e's own render
        // is untouched and its four pinned snapshots do not move.
        overlay::mute(buffer, area, app.palette());
        draw_close_dialog(dialog, app.palette(), app.now(), area, buffer);
    }
}

#[cfg(test)]
mod tests {
    use super::super::fixtures::{
        bark_pane, config_pane_lines_for_tests, marked, nested_sheep_dog_pane,
        nested_table_dog_pane, pane_to, screen_of, text_of, web_pane,
    };
    use super::super::layout::{FULL_WIDTH, LANDS_WITH_PANEL_MIN};
    use super::*;
    use crate::lookout::app::{Effect, KeyPress, Msg};
    use crate::lookout::pane::PaneRow;
    use crate::lookout::textbox::TextEdit;
    use crate::lookout::view::MIN_TERM_WIDTH;
    use crate::lookout::view::fixtures;
    use crate::output::width::visible_width;

    /// The whole pane at a comfortable width, unbounded. The snapshot is the
    /// assertion: it pins the title, the four section headers in order, all
    /// 40 rows, the two flags and the cost cell beside each one.
    #[test]
    fn a_sheep_pane_at_a_comfortable_width() {
        let lines = pane_lines(&web_pane(), fixtures::plain(), 120, 0);
        insta::assert_snapshot!("sheep_pane_wide", text_of(&lines).join("\n"));
    }

    /// The editor draws the cursor where it is. The snapshot is the
    /// assertion: the open row reads the value with the cursor inside it,
    /// and every other row is untouched.
    #[test]
    fn an_open_editor_draws_its_cursor_in_the_middle_of_the_value() {
        let mut pane = web_pane();
        pane.move_to_key("max_restarts");
        pane.begin_typing();
        pane.edit_text(TextEdit::Left);
        let lines = pane_lines(&pane, fixtures::plain(), 120, 0);
        let text = text_of(&lines);
        assert!(
            text.iter().any(|line| line.contains("3\u{258f}2")),
            "the cursor sits between the 3 and the 2: {text:?}"
        );
        insta::assert_snapshot!("sheep_pane_editor_cursor_mid_value", text.join("\n"));
    }

    /// `Buffer::set_line` clips in silence, so an overrun renders as a
    /// truncated cost cell with nothing saying it was cut.
    #[test]
    fn every_pane_line_fits_the_width_it_was_drawn_for() {
        let pane = web_pane();
        for width in MIN_TERM_WIDTH..=200 {
            for line in text_of(&pane_lines(&pane, fixtures::plain(), width, 0)) {
                assert!(
                    visible_width(&line) <= usize::from(width),
                    "width {width} drew {}: {line:?}",
                    visible_width(&line)
                );
            }
        }
    }

    /// Both directions: `watch` is `Live`, draws `now`, and can still
    /// park. `autostart` is `NextSpawn`, draws `next start`, and takes
    /// effect at muster, not at the next spawn. The column is never
    /// corrected after a reply, since a reply covers one row of
    /// forty; it stays a prediction everywhere, the bar reports the
    /// outcome, and the row's `!` flag carries it afterwards.
    #[test]
    fn the_cost_column_predicts_and_the_status_bar_reports() {
        for (key, column, pending, sentence) in [
            ("watch", "now", true, "waits for `shep reload web`"),
            ("autostart", "next start", false, "set to false"),
        ] {
            let mut app = fixtures::app_in_sheep_pane_with_control();
            pane_to(&mut app, key);

            // Below the panel's own floor: the panel suppresses the row's own
            // COST cell, which is exactly what this test reads.
            let text = text_of(&pane_lines(
                app.config_pane().unwrap(),
                fixtures::plain(),
                89,
                0,
            ));
            // A group header line is bare, just its name; a field row always
            // carries a value and a cost cell after the key, so the header
            // never matches once a second token is required. `key` can equal
            // its own group's name (the `watch` field, the `watch` group).
            let row = text
                .iter()
                .find(|line| {
                    let mut words = line.split_whitespace();
                    let mut rest = line.get(3..).map(str::split_whitespace);
                    (words.next() == Some(key) && words.next().is_some())
                        || rest
                            .as_mut()
                            .is_some_and(|w| w.next() == Some(key) && w.next().is_some())
                })
                .unwrap_or_else(|| panic!("{key} is drawn at 89 columns: {text:?}"));
            assert!(row.contains(column), "{key}: {row:?}");

            app.update(Msg::Key(KeyPress::Cycle));
            // `app_in_sheep_pane_with_control` parks `kill_signal`
            // unconditionally, so `esc` only asks; `c` is what actually
            // gets the write onto the wire.
            let _ = app.update(Msg::Key(KeyPress::Escape));
            let effect = if app.close_dialog().is_some() {
                app.update(Msg::Key(KeyPress::Continue))
            } else {
                Effect::None
            };
            let Effect::SendAll(mut batch) = effect else {
                panic!("{key}: closing the pane sends");
            };
            app.update(Msg::Replied {
                sent: batch.remove(0),
                result: Ok(shep_core::protocol::Response::SheepFieldSet {
                    name: "web".to_string(),
                    key: key.to_string(),
                    pending,
                    warning: None,
                }),
            });
            let bar = crate::lookout::view::status::status_line(&app, 200).to_string();
            assert!(bar.contains(sentence), "{key}: {bar:?}");
        }
    }

    /// The whole dog pane at a comfortable width. The snapshot is the
    /// assertion: the title says `dog config`, the rows are flat, every
    /// COST cell is empty, and the foot says the dog decides once.
    ///
    /// The three assertions ahead of it fail loudly rather than as a
    /// snapshot diff: a webhook URL on screen is the leak the secret
    /// contract exists to prevent.
    #[test]
    fn a_dog_pane_at_a_comfortable_width() {
        let text = text_of(&pane_lines(&bark_pane(), fixtures::plain(), 120, 0));
        assert!(
            !text.iter().any(|line| line.contains("hooks.example")),
            "a secret is never rendered: {text:?}"
        );
        assert!(text.iter().any(|line| line.contains("<set>")), "{text:?}");
        assert!(
            text.iter()
                .any(|line| line.contains("decides what to reload")),
            "{text:?}"
        );
        insta::assert_snapshot!("dog_pane_wide", text.join("\n"));
    }

    /// An adopted dog's pane draws the `env` section a sheep's `process` tab
    /// draws: the keys its `shep.toml` entry sets, then the row that adds
    /// one. The pane's rows have carried those rows since an adopted dog
    /// gained an `env`, but the dog-pane layout walked `field_rows` alone,
    /// which drops every env row, so the cursor could stand on `+ add a key`
    /// while the screen still drew the field above it.
    #[test]
    fn an_adopted_dogs_pane_draws_its_env_rows_and_the_row_that_adds_one() {
        let app = fixtures::app_in_adopted_channel_dog_pane_from_row();
        let text = text_of(&config_pane_lines_for_tests(&app, 120, 0));
        assert!(
            text.iter().any(|line| line.contains("+ add a key")),
            "the row that adds the dog's first env key: {text:?}"
        );
        insta::assert_snapshot!("adopted_dog_pane_env_rows", text.join("\n"));
    }

    /// The row is not merely in the walk: `End` lands on it and the screen
    /// shows it selected, which is what an operator needs to file a key.
    #[test]
    fn an_adopted_dogs_env_rows_are_the_last_rows_of_its_walk() {
        let mut app = fixtures::app_in_adopted_channel_dog_pane_from_row();
        app.update(Msg::Key(KeyPress::SelectLast));
        let pane = app.config_pane().expect("the pane is open");
        assert_eq!(pane.cursor(), Some(PaneRow::AddEnv), "{:?}", pane.rows());
        let text = text_of(&config_pane_lines_for_tests(&app, 120, 0));
        assert!(
            text.iter()
                .any(|line| line.starts_with('>') && line.contains("+ add a key")),
            "the selected row is the one drawn: {text:?}"
        );
    }

    /// The same pane over a dog whose schema nests a table: a tree with the
    /// first level open, the table two levels down closed, and the cost cell
    /// empty on every row. Opening that table reveals the credential in it,
    /// which reads `<set>`.
    #[test]
    fn a_dog_pane_over_a_nested_table() {
        let mut pane = nested_table_dog_pane();
        let text = text_of(&pane_lines(&pane, fixtures::plain(), 120, 0));
        assert!(
            text.iter().any(|line| line.contains("\u{25b8} worker")),
            "the table two levels down starts closed: {text:?}"
        );
        assert!(!text.iter().any(|line| line.contains("token")), "{text:?}");
        insta::assert_snapshot!("dog_pane_nested_table_closed", text.join("\n"));
        pane.move_to_key("models.worker.token");
        let text = text_of(&pane_lines(&pane, fixtures::plain(), 120, 0));
        assert!(
            !text.iter().any(|line| line.contains("sk-live")),
            "a secret is never rendered: {text:?}"
        );
        assert!(
            text.iter().any(|line| line.contains("\u{25be} worker")),
            "{text:?}"
        );
        insta::assert_snapshot!("dog_pane_nested_table", text.join("\n"));
    }

    /// A dog whose only setting is a table with no keys has no field, but
    /// the table is still a row the cursor can stand on, so it is drawn.
    #[test]
    fn a_dog_pane_holding_only_an_empty_table_draws_its_row() {
        let schema = serde_json::json!({
            "properties": { "limits": { "type": "object", "properties": {} } }
        });
        let pane = ConfigPane::dog("jobs".into(), None, schema, String::new(), Vec::new());
        let text = text_of(&pane_lines(&pane, fixtures::plain(), 120, 0));
        assert!(text.iter().any(|line| line.contains("limits")), "{text:?}");
    }

    /// Every table opened down to the credential, so the tree shows all
    /// three depths.
    fn opened(mut pane: ConfigPane) -> ConfigPane {
        pane.move_to_key("models.worker.token");
        pane
    }

    /// The dog pane as a tree at the design target, and at a width with no
    /// side panel. The snapshots are the assertions.
    #[test]
    fn a_dog_pane_as_a_tree_at_160x48_and_narrow() {
        for (name, width) in [("dog_pane_tree_160x48", 160), ("dog_pane_tree_narrow", 89)] {
            let lines = pane_lines(
                &opened(nested_table_dog_pane()),
                fixtures::plain(),
                width,
                48,
            );
            let text = text_of(&lines);
            assert!(
                !text.iter().any(|line| line.contains("sk-live")),
                "a secret is never rendered: {text:?}"
            );
            insta::assert_snapshot!(name, text.join("\n"));
        }
    }

    /// The per-sheep table pane as a tree, at the same two widths.
    #[test]
    fn a_sheep_dog_table_pane_as_a_tree_at_160x48_and_narrow() {
        for (name, width) in [
            ("sheep_dog_pane_tree_160x48", 160),
            ("sheep_dog_pane_tree_narrow", 89),
        ] {
            let lines = pane_lines(
                &opened(nested_sheep_dog_pane()),
                fixtures::plain(),
                width,
                48,
            );
            let text = text_of(&lines);
            assert!(
                !text.iter().any(|line| line.contains("sk-live")),
                "a secret is never rendered: {text:?}"
            );
            insta::assert_snapshot!(name, text.join("\n"));
        }
    }

    /// At `view::MIN_HEIGHT` the body has no room for the chrome, so the
    /// cursor's row is drawn alone, whether it is a table or a leaf.
    #[test]
    fn the_cursor_row_of_a_tree_survives_at_the_minimum_height() {
        let mut app = fixtures::app_in_dog_pane_with_a_nested_table();
        let total = app.config_pane().expect("open").rows().len();
        let mut frames = Vec::new();
        for _ in 0..total {
            let text = screen_of(&mut app, 160, crate::lookout::view::flock::MIN_HEIGHT);
            assert_eq!(marked(&text), 1, "{text}");
            frames.push(text);
            app.update(Msg::Key(KeyPress::SelectDown));
        }
        insta::assert_snapshot!("dog_pane_tree_min_height_on_a_table", frames[0]);
        insta::assert_snapshot!("dog_pane_tree_min_height_on_a_leaf", frames[total - 1]);

        // The per-sheep table pane, with the three body lines
        // `view::MIN_HEIGHT` leaves under the title.
        let mut pane = nested_sheep_dog_pane();
        let lines = pane_lines(&pane, fixtures::plain(), 160, 3);
        let on_a_table = text_of(&lines);
        assert!(
            on_a_table
                .iter()
                .any(|line| line.starts_with(">  \u{25be} models")),
            "{on_a_table:?}"
        );
        insta::assert_snapshot!("sheep_dog_pane_tree_min_height", on_a_table.join("\n"));
        pane.move_to_last();
        let on_a_leaf = text_of(&pane_lines(&pane, fixtures::plain(), 160, 3));
        assert!(
            on_a_leaf.iter().any(|line| line.starts_with(">  name")),
            "{on_a_leaf:?}"
        );
    }

    #[test]
    fn a_dog_panes_footer_is_paid_for_out_of_the_height_it_was_given() {
        let mut pane = bark_pane();
        for height in 1..=20u16 {
            pane.set_rows(usize::from(height.saturating_sub(1)));
            for cursor in [0usize, 2, 4] {
                pane.move_to_first();
                pane.move_by(isize::try_from(cursor).unwrap());
                let text = text_of(&pane_lines(&pane, fixtures::plain(), 120, height));
                assert!(
                    text.len() <= usize::from(height),
                    "height {height}, cursor {cursor}: {text:?}"
                );
            }
        }
    }

    /// The footer is the newest line and the longest, and
    /// `Buffer::set_line` clips in silence.
    #[test]
    fn every_dog_pane_line_fits_the_width_it_was_drawn_for() {
        let pane = bark_pane();
        for width in MIN_TERM_WIDTH..=200 {
            for line in text_of(&pane_lines(&pane, fixtures::plain(), width, 0)) {
                assert!(
                    visible_width(&line) <= usize::from(width),
                    "width {width} drew {}: {line:?}",
                    visible_width(&line)
                );
            }
        }
    }

    /// No row may cross the panel boundary or run past the terminal it was
    /// drawn for, at the design target and at a terminal wider than it: the
    /// chrome now stretches to fill a wide terminal instead of capping at
    /// 160 with blank space to the right, so the ceiling this checks
    /// against is `width` itself, not a fixed 160.
    #[test]
    fn no_row_spills_across_the_panel_boundary_or_past_its_own_width() {
        let app = fixtures::app_in_sheep_pane();
        let pane = app.config_pane().expect("the pane is open");
        for width in [160, 200] {
            for line in pane_lines(pane, fixtures::plain(), width, 48) {
                let cols = line_columns(&line);
                assert!(
                    cols <= usize::from(width),
                    "a row is {cols} columns wide at terminal width {width}: {line:?}"
                );
            }
        }
    }

    #[test]
    fn lands_gives_way_to_the_panel_below_the_design_target_and_joins_it_above() {
        let app = fixtures::app_in_sheep_pane();
        for width in MIN_TERM_WIDTH..=200 {
            let rows = fixtures::render_all(&config_pane_lines_for_tests(&app, width, 48));
            let panel = rows.contains("FOCUSED");
            let lands = rows.contains("LANDS");
            let has_panel = panel_width(width).is_some();
            match (has_panel, width >= LANDS_WITH_PANEL_MIN) {
                // 160 and up: the panel and the column share the row.
                (true, true) => assert!(
                    panel && lands,
                    "the panel and LANDS must both draw at {width} columns"
                ),
                // 90 to 159: the panel draws, LANDS gives way to it.
                (true, false) => assert!(
                    panel && !lands,
                    "LANDS must give way to the panel at {width} columns"
                ),
                // below 90: no panel, so LANDS carries cost alone, subject
                // to `widths`'s own pre-existing narrow-terminal cascade,
                // which this fix leaves untouched.
                (false, _) => {
                    assert!(!panel, "the panel must not draw at {width} columns");
                    let expected_lands = body_width(width) >= FULL_WIDTH;
                    assert_eq!(
                        lands, expected_lands,
                        "LANDS mismatch at {width} columns, no panel"
                    );
                }
            }
        }
    }

    /// Every width the pane can be drawn at draws inside itself. This is
    /// the same sweep the existing pane tests run and it stays.
    #[test]
    fn every_row_fits_the_width_it_was_drawn_for() {
        for width in MIN_TERM_WIDTH..=200 {
            let app = fixtures::app_in_sheep_pane();
            for row in config_pane_lines_for_tests(&app, width, 48) {
                assert!(
                    fixtures::render_all(std::slice::from_ref(&row))
                        .chars()
                        .count()
                        <= usize::from(width),
                    "a row overflows at {width}"
                );
            }
        }
    }
}