shep 0.24.1

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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
use super::super::super::app::{App, Body, Control, InputMode, Link, Settings, retrying_sentence};
use super::super::super::pane_bleats::BleatsPane;
use super::super::super::textbox::TextBox;
use super::super::cell;
use super::super::flock::fit;
use super::action_gate::{CONTROL_ENABLED_LABEL, READ_ONLY_LABEL, confirm_prompt, in_flight_text};
use super::key_hint::{
    BLEATS_HINT, CLOSE_DIALOG_HINT, FROZEN_HINT, catalogue_hint, env_armed, hint_for, modal_keys,
    pane_editor, pane_hint, pane_screen, secrets_armed, secrets_hint, secrets_typing,
    sheep_pane_hint,
};
use ratatui::style::Style;
use ratatui::text::{Line, Span};

/// What a text-entry bar names beside its buffer: the one-field editors that
/// apply on enter and cancel on escape. Each bar adds its own gap before it.
pub(in crate::lookout::view) const TEXT_ENTRY_HINT: &str = "enter applies   esc cancels";

/// A text-entry bar: `label`, two columns of gap, the buffer, then `keys`
/// three columns after it. `secret` masks the buffer the way its own row does.
fn entry_line(buffer: &TextBox, secret: bool, label: &str, keys: &str, width: u16) -> String {
    buffer.line(secret, &format!("{label}  "), &format!("   {keys}"), width)
}

/// The banner, when there is one. `None` while the link is live.
///
/// What happened and when the values stopped being current, so an operator
/// reading `online` knows how much to trust it. Once the link is lost,
/// `view::title_band` carries the death sentence above, and this row picks
/// up the `$SHEP_HOME` the title band has no room for.
#[must_use]
pub fn banner_line(app: &App, width: u16) -> Option<Line<'static>> {
    let palette = app.palette();
    match app.link() {
        Link::Live => None,
        Link::Retrying { attempt } => Some(Line::from(Span::styled(
            retrying_sentence(*attempt),
            palette.attention(),
        ))),
        // Through `fit`, unlike the retrying sentence above, which is short
        // enough that no terminal cuts it. `Buffer::set_line` cuts in
        // silence: a mid-word cut beside lines that mark their own
        // truncation reads as a rendering fault.
        Link::Lost { .. } => Some(Line::from(Span::styled(
            fit(
                &format!(
                    " shep lookout   {}  ·  the dashboard stays up so you can read what it had  ·  it will not exit on its own",
                    app.place()
                ),
                width,
            ),
            palette.muted(),
        ))),
    }
}

/// The bottom line: eight slots, highest priority first.
///
/// The settings screen's armed or in-flight edit, a dashboard confirm, its
/// free-text editor, the filter box. A notice, an in-flight action, the
/// applied filter line, then the key hint. Control state always renders on
/// the right, and the row is never cut.
#[must_use]
pub fn status_line(app: &App, width: u16) -> Line<'static> {
    let palette = app.palette();
    // Always rendered, in both states. An operator who cannot tell whether
    // the dashboard can act finds out the wrong way. The bleats pane borrows
    // this slot while following the tail: it has no action keys of its own,
    // and pinning is what its reader needs.
    let right = if matches!(app.link(), Link::Lost { .. }) {
        // Ahead of both: whether this dashboard is reading a live shepherd
        // outranks whether a pane is pinned to the newest line, and outranks
        // a control state the lost link already settles.
        "\u{2588} frozen"
    } else if app.bleats_pane().is_some_and(BleatsPane::following) {
        "\u{2588} following"
    } else {
        match app.control() {
            Control::ReadOnly => READ_ONLY_LABEL,
            Control::Allowed => CONTROL_ENABLED_LABEL,
        }
    };
    let right_len = u16::try_from(right.chars().count()).unwrap_or(0);
    // `+ 1` reserves one column of gap so a truncated left side's `…` never
    // butts against the label. The gap rides inside the right span, styled
    // like the label, keeping the line two spans rather than three.
    let left_width = width.saturating_sub(right_len).saturating_sub(1);
    let (left, left_style) = if let Some(modal) = app.modal() {
        // First: a modal takes every key ahead of whatever is under it, so
        // any other hint would name keys that do nothing.
        (
            modal_keys(modal, app.modal_scrolls()).to_string(),
            palette.attention(),
        )
    } else if let Some(prompt) = app.settings().and_then(Settings::pending) {
        // The settings screen's armed scalar or dog edit, or its in-flight
        // sentence once sent. Opening clears `self.action`. `on_key` routes
        // to the settings keymap, so no dashboard confirm can arm while it
        // stays open.
        let text = if prompt.sent {
            format!("{}  sent, waiting for the shepherd", prompt.text)
        } else {
            format!("{}  enter confirms, any other key cancels", prompt.text)
        };
        (text, palette.attention())
    } else if let Some(buffer) = app.bleats_pane().and_then(BleatsPane::match_editing) {
        // Ahead of the filter branch for the reason the comment below gives:
        // the bleats pane's match box shares `InputMode::Text` with the
        // dashboard's name filter, and falling through would label the
        // dashboard's own untouched query as this pane's match.
        (
            entry_line(buffer, false, "match", TEXT_ENTRY_HINT, left_width),
            palette.attention(),
        )
    } else if let Some(buffer) = app
        .sheep_pane()
        .and_then(|pane| pane.feed().match_editing())
    {
        // The same box, embedded: the sheep pane's feed shares
        // `InputMode::Text` with the dashboard's name filter. A fall-through
        // here would label the dashboard's untouched query as this feed's
        // match.
        (
            entry_line(buffer, false, "match", TEXT_ENTRY_HINT, left_width),
            palette.attention(),
        )
    } else if let Some(editor) = app.config_pane().and_then(pane_editor) {
        // The pane's own free-text editor, and the key/value editor the env
        // rows open, ahead of the filter branch: all three share
        // `InputMode::Text`, and a bar that fell through would label this the
        // dashboard's own query. The keys come from the slot, not from here.
        (
            entry_line(
                editor.buffer,
                editor.secret,
                &editor.label,
                editor.keys,
                left_width,
            ),
            palette.attention(),
        )
    } else if let Some(action) = app.action().filter(|a| !a.sent) {
        // A question awaiting an answer outranks everything, including the
        // filter box: `/` cancels a confirm before it opens the box.
        (confirm_prompt(&action), palette.attention())
    } else if let Some((settings, label, buffer)) = app.settings().and_then(|settings| {
        settings
            .typing()
            .map(|(label, buffer)| (settings, label, buffer))
    }) {
        // Checked ahead of the filter-box branch below: both share
        // `InputMode::Text`, but this types into a `shep.toml` key, not
        // `App::filter`.
        (
            entry_line(
                buffer,
                settings.typing_is_secret(),
                &format!("editing {label}"),
                TEXT_ENTRY_HINT,
                left_width,
            ),
            palette.attention(),
        )
    } else if let Some(key) = app.config_pane().and_then(env_armed) {
        // The config pane's one armed thing, ranked with the secrets pane's
        // own below for the same reason: it is a question awaiting an answer,
        // and it must outrank `pane_hint`, which still reads `e edit` while an
        // arm is live.
        (
            format!("delete {key}? enter confirms, any other key cancels"),
            palette.attention(),
        )
    } else if let Some(editor) = secrets_typing(app) {
        // Ahead of the filter-box branch below, for the reason the config
        // pane's own free-text branch above gives: this shares
        // `InputMode::Text` with `App::filter` too.
        (
            entry_line(
                editor.buffer,
                editor.secret,
                &editor.label,
                editor.keys,
                left_width,
            ),
            palette.attention(),
        )
    } else if let Some(key) = secrets_armed(app) {
        // Ranked with the dashboard's own confirm above, for the same
        // reason: an armed delete is a question awaiting an answer, and it
        // must outrank `key_hint::secrets_hint`, which still reads `enter sets a
        // value` while an arm is live.
        (
            format!("delete {key}? enter confirms, any other key cancels"),
            palette.attention(),
        )
    } else if app.mode() == InputMode::Text {
        // Above the notice: bus events arrive with no keypress and
        // `on_text_key` never clears them, so ranking the notice higher
        // would erase a half-typed query. The cursor is a character, not
        // a style: the ANSI gallery renders foregrounds only.
        (
            entry_line(
                app.filter_box(),
                false,
                "filter",
                &format!("{TEXT_ENTRY_HINT}   ctrl-c quits"),
                left_width,
            ),
            palette.attention(),
        )
    } else if let Some(notice) = app.notice() {
        (
            notice.to_string(),
            if notice.is_grave() {
                palette.refusal()
            } else {
                palette.attention()
            },
        )
    } else if let Some(action) = app.action() {
        // Below the notice: `arm`'s "one action is already in flight"
        // refusal is itself a notice, so ranking this above notices would
        // hide it. A keypress cannot wipe this line; the reducer clears
        // the notice, not this ordering.
        let text = in_flight_text(&action);
        // `attention`, the same butter the non-grave notice uses. No modal,
        // no box, no `ratatui::widgets::Clear`. One rule under the header
        // beats a full border for a pane read at 3am. This module draws no
        // overlay.
        (text, palette.attention())
    } else if app.close_dialog().is_some() {
        // Ahead of the config pane's own hint below: the dialog owns the
        // keyboard while it is up. A bar naming `space cycle` under that
        // screen would be the asterisk this file's standing rule forbids.
        // Muted: the dialog's own rows name what each key does.
        (CLOSE_DIALOG_HINT.to_string(), palette.muted())
    } else if let Some(pane) = app.config_pane() {
        // The pane owns the keyboard, so neither dashboard hint is true
        // while it is up. Naming `x stop` where `x` does nothing is the
        // asterisk this rule forbids. Butter: this is a key hint, same as
        // the dashboard's own below.
        (
            pane_hint(app.control(), pane_screen(pane)).to_string(),
            palette.attention(),
        )
    } else if app.bleats_pane().is_some() {
        // Checked below the match box's branch, which owns this slot while
        // open. The design's status-bar line
        // (docs/lookout/design-files/README.md:274) names no key for `m`, so
        // it is appended rather than inserted.
        (BLEATS_HINT.to_string(), palette.attention())
    } else if matches!(app.body(), Body::Secrets(_)) {
        // The pane owns the keyboard here too, same reasoning as the config
        // pane's own branch above: `x stop`/`R restart`/`L reload`/`F folds`
        // belong to the dashboard underneath and do nothing on this screen.
        (secrets_hint(app.control()), palette.attention())
    } else if let Body::Catalogue(pane) = app.body() {
        (
            catalogue_hint(pane.entry.is_some()).to_string(),
            palette.attention(),
        )
    } else if app.sheep_pane().is_some() {
        // Checked below the bleats pane's own branch, the same as the
        // config pane's above it: the full-screen panes cannot be open at
        // once, so their order here is documentation, not correctness.
        (
            sheep_pane_hint(app.control()).to_string(),
            palette.attention(),
        )
    } else if app.settings().is_none() && !app.filter().is_empty() {
        // Gated on the screen being closed: the filter survives the swap
        // into settings (`App::on_settings_key` never touches it), but `/`
        // and `esc` mean something else entirely while the screen owns the
        // keyboard, so this line would be false the moment it stayed up.
        (
            format!("filter \"{}\"   / edit   esc clear", app.filter()),
            palette.muted(),
        )
    } else if matches!(app.link(), Link::Lost { .. }) {
        // Only this branch, not the pane hints above. A pane opened before
        // the freeze keeps naming its own keys. This line is the flock
        // table's. Every action key `key_hint::hint_for` would name is
        // refused once the link is gone.
        (FROZEN_HINT.to_string(), palette.attention())
    } else {
        // Butter: the keys, same rule as the pane's own hint above.
        (
            hint_for(app.control(), app.settings().is_some(), app.grouping()),
            palette.attention(),
        )
    };
    // `patch`, not a fresh `Style`. `ground` sets only the background, so
    // patching it keeps each span's own foreground. `fit` pads `left` to
    // `left_width`, so the ground reaches every column the label does not.
    let ground = palette.ground();
    Line::from(vec![
        Span::styled(fit(&left, left_width), left_style.patch(ground)),
        Span::styled(format!(" {right}"), palette.muted().patch(ground)),
    ])
}

/// A run of `─` across the pane, under the header.
///
/// One rule, not a box. `output::table`'s own doc argues that a table a
/// user can `awk` over beats one that looks nice; the same instinct applies
/// to a pane an operator reads at 3am, and a full border costs two columns
/// and two rows of the thing they are trying to read.
#[must_use]
pub fn rule_line(style: Style, width: u16) -> Line<'static> {
    Line::from(Span::styled(cell::rule(usize::from(width)), style))
}

#[cfg(test)]
mod tests {

    use super::super::super::super::app::{App, Control};

    use super::super::super::fixtures::{
        acting_app, allowed_app, app_armed_to_delete_a_secret, app_in_settings, app_in_settings_on,
        app_in_settings_with_control, armed_app, armed_app_with_a_filter_and_a_notice, editing_app,
        filtered_app, rendered, with_selection,
    };
    use super::super::testing::*;
    use super::*;
    use crate::lookout::app::{ActionVerb, KeyPress, Msg};
    use crate::lookout::theme::Palette;
    use shep_core::protocol::BusEvent;
    use std::ffi::OsStr;
    use std::time::Instant;

    /// Pinned at 49 columns: the default hint is 59 characters and the
    /// label 9, the width where the hint truncates but the label still
    /// fits.
    #[test]
    fn a_truncated_hint_still_leaves_a_gap_before_the_control_label() {
        let palette = Palette::detect(None, Some(OsStr::new("xterm-256color")), None);
        let app = App::new(
            palette,
            Control::ReadOnly,
            "/home/ada/.shep".to_string(),
            Instant::now(),
        );
        let line = status_line(&app, 49);
        let rendered: String = line
            .spans
            .iter()
            .map(|span| span.content.as_ref())
            .collect();

        assert_eq!(rendered.chars().count(), 49, "must fill the full width");
        assert!(
            rendered.ends_with(" read-only"),
            "expected a space before the label, got: {rendered:?}"
        );
        assert!(
            !rendered.contains("…read-only"),
            "the ellipsis must not butt straight against the label: {rendered:?}"
        );
    }

    /// The first 40 characters of the replacement are unchanged, so
    /// `a_truncated_hint_still_leaves_a_gap_before_the_control_label` still
    /// measures the same thing.
    #[test]
    fn the_key_hint_says_what_the_keys_now_do() {
        let app = App::new(
            Palette::detect(None, None, None),
            Control::ReadOnly,
            "/home/ada/.shep".to_string(),
            Instant::now(),
        );
        let hint: String = status_line(&app, 200)
            .spans
            .iter()
            .map(|span| span.content.as_ref())
            .collect();
        assert!(hint.contains("j/k select"), "got {hint:?}");
        assert!(hint.contains("g/G first/last"), "got {hint:?}");
        assert!(
            !hint.contains("scroll"),
            "the pane no longer scrolls: {hint:?}"
        );
    }

    #[test]
    fn a_wide_status_line_still_pads_out_to_the_full_width() {
        let palette = Palette::detect(None, Some(OsStr::new("xterm-256color")), None);
        let app = App::new(
            palette,
            Control::Allowed,
            "/home/ada/.shep".to_string(),
            Instant::now(),
        );
        let line = status_line(&app, 120);
        let rendered: String = line
            .spans
            .iter()
            .map(|span| span.content.as_ref())
            .collect();

        assert_eq!(rendered.chars().count(), 120);
        assert!(rendered.ends_with(" control enabled"));
    }

    #[test]
    fn the_bar_names_the_filter_keys_while_a_filter_is_applied() {
        let app = filtered_app("web");
        let bar = rendered(&status_line(&app, 120));
        assert!(bar.contains("filter \"web\""), "the query, quoted: {bar:?}");
        assert!(bar.contains("/ edit"), "got {bar:?}");
        assert!(bar.contains("esc clear"), "got {bar:?}");
    }

    #[test]
    fn the_bar_carries_the_query_and_a_cursor_while_editing() {
        let app = editing_app("we");
        let bar = rendered(&status_line(&app, 120));
        assert!(
            bar.contains("filter  we\u{258f}"),
            "query then cursor: {bar:?}"
        );
        assert!(bar.contains("enter applies"), "got {bar:?}");
        assert!(bar.contains("esc cancels"), "got {bar:?}");
        assert!(bar.contains("ctrl-c quits"), "got {bar:?}");
    }

    /// Both share `InputMode::Text`, so this pins that the bar reads the
    /// settings editor's own state, not the dashboard's untouched filter.
    #[test]
    fn the_bar_shows_the_settings_editor_rather_than_the_filter_box() {
        let mut app = app_in_settings_on("daemon.socket");
        let _ = app.update(Msg::Key(KeyPress::Confirm));
        let bar = rendered(&status_line(&app, 120));
        assert!(
            bar.contains("editing daemon.socket  "),
            "names the field being typed: {bar:?}"
        );
        assert!(
            bar.contains("/home/ada/.shep/run/shep.sock\u{258f}"),
            "shows the buffer and the cursor, not the dashboard's own filter: {bar:?}"
        );
        assert!(
            !bar.contains("filter "),
            "must not read as the filter box: {bar:?}"
        );
    }

    /// A `Dropped` event arrives mid-edit and must not cover the box.
    #[test]
    fn a_notice_raised_while_typing_does_not_cover_the_box() {
        let mut app = editing_app("we");
        app.update(Msg::Event(BusEvent::Dropped { count: 3 }));
        let bar = rendered(&status_line(&app, 120));
        assert!(
            bar.contains("filter  we\u{258f}"),
            "the box is still there: {bar:?}"
        );
        assert!(!bar.contains("dropped 3 events"), "got {bar:?}");
    }

    #[test]
    fn closing_the_box_shows_the_notice_that_was_waiting() {
        let mut app = editing_app("we");
        app.update(Msg::Event(BusEvent::Dropped { count: 3 }));
        app.update(Msg::Key(KeyPress::TextApply));
        let bar = rendered(&status_line(&app, 120));
        assert!(bar.contains("dropped 3 events"), "got {bar:?}");
    }

    #[test]
    fn the_read_only_hint_advertises_the_filter_key() {
        let app = filtered_app("");
        let hint = rendered(&status_line(&app, 200));
        assert!(hint.contains("/ filter"), "got {hint:?}");
    }

    #[test]
    fn an_armed_confirm_names_the_verb_the_sheep_and_the_answer() {
        let app = armed_app(ActionVerb::Restart);
        let bar = rendered(&status_line(&app, 120));
        assert!(bar.contains("restart api (id 2)?"), "got {bar:?}");
        assert!(
            bar.contains("enter confirms, any other key cancels"),
            "got {bar:?}"
        );
    }

    /// The secrets pane's own destructive arm gets the same sentence the
    /// dashboard's does: which key, and how to answer.
    #[test]
    fn an_armed_secret_delete_names_the_key_and_the_answer() {
        let app = app_armed_to_delete_a_secret();
        let bar = rendered(&status_line(&app, 120));
        assert!(bar.contains("delete DB_PASSWORD"), "got {bar:?}");
        assert!(
            bar.contains("enter confirms, any other key cancels"),
            "got {bar:?}"
        );
    }

    /// Armed, `Enter` deletes rather than opening the value input, so the
    /// bar must stop claiming the older job.
    #[test]
    fn an_armed_secret_delete_stops_advertising_set_a_value() {
        let app = app_armed_to_delete_a_secret();
        let bar = rendered(&status_line(&app, 120));
        assert!(
            !bar.contains("set a value"),
            "the arm changes what enter does: {bar:?}"
        );
    }

    #[test]
    fn an_in_flight_action_says_it_is_waiting() {
        let app = acting_app(ActionVerb::Stop);
        let bar = rendered(&status_line(&app, 120));
        assert!(
            bar.contains("stop api (id 2): sent, waiting for the shepherd"),
            "got {bar:?}"
        );
    }

    #[test]
    fn the_confirm_outranks_a_notice_and_the_filter_line() {
        let app = armed_app_with_a_filter_and_a_notice();
        let bar = rendered(&status_line(&app, 120));
        assert!(bar.contains("stop api (id 2)?"), "got {bar:?}");
        assert!(
            !bar.contains("filter \""),
            "the filter line is below it: {bar:?}"
        );
    }

    /// Also covers the bus-raised case: `DaemonShutdown` must reach the bar
    /// the same way a keypress refusal does.
    #[test]
    fn a_refusal_while_an_action_is_in_flight_reaches_the_bar() {
        let mut app = acting_app(ActionVerb::Stop);
        app.update(Msg::Key(KeyPress::Action(ActionVerb::Restart)));
        let bar = rendered(&status_line(&app, 120));
        assert!(
            bar.contains("one action is already in flight"),
            "the refusal is on the bar, not only in the reducer: {bar:?}"
        );

        let mut app = acting_app(ActionVerb::Stop);
        app.update(Msg::Event(BusEvent::DaemonShutdown));
        let bar = rendered(&status_line(&app, 120));
        assert!(bar.contains("the shepherd is shutting down"), "got {bar:?}");
    }

    #[test]
    fn the_in_flight_line_comes_back_when_the_notice_clears() {
        let mut app = acting_app(ActionVerb::Stop);
        app.update(Msg::Key(KeyPress::Action(ActionVerb::Restart)));
        app.update(Msg::Key(KeyPress::SelectDown));
        let bar = rendered(&status_line(&app, 120));
        assert!(
            bar.contains("stop api (id 2): sent, waiting for the shepherd"),
            "got {bar:?}"
        );
    }

    #[test]
    fn the_action_keys_are_advertised_only_when_the_gate_is_open() {
        let closed = rendered(&status_line(&filtered_app(""), 200));
        for key in ["x stop", "R restart", "L reload"] {
            assert!(
                !closed.contains(key),
                "{key} advertised read-only: {closed:?}"
            );
        }
        let open = rendered(&status_line(&allowed_app(), 200));
        for key in ["x stop", "R restart", "L reload"] {
            assert!(
                open.contains(key),
                "{key} missing when the gate is open: {open:?}"
            );
        }
        assert!(
            open.contains("/ filter"),
            "and the filter key survives both forms"
        );
    }

    /// `s` is named as `esc/s close`: on this screen `s` closes rather than
    /// opens.
    #[test]
    fn the_settings_edit_keys_are_advertised_only_when_the_gate_is_open() {
        let closed = rendered(&status_line(&app_in_settings(), 200));
        for key in ["space cycle", "enter apply"] {
            assert!(
                !closed.contains(key),
                "{key} advertised read-only: {closed:?}"
            );
        }
        let open = rendered(&status_line(&app_in_settings_with_control(), 200));
        for key in ["space cycle", "enter apply"] {
            assert!(
                open.contains(key),
                "{key} missing when the gate is open: {open:?}"
            );
        }
        for both in [&closed, &open] {
            assert!(both.contains("esc/s close"), "got {both:?}");
            assert!(both.contains("r refresh"), "got {both:?}");
        }
    }

    /// `App` handles `q` in its settings key dispatch, same as the
    /// dashboard.
    #[test]
    fn q_quit_is_named_on_the_settings_screen_in_both_control_states() {
        let closed = rendered(&status_line(&app_in_settings(), 200));
        let open = rendered(&status_line(&app_in_settings_with_control(), 200));
        for hint in [&closed, &open] {
            assert!(hint.contains("q quit"), "got {hint:?}");
        }
    }

    #[test]
    fn the_panes_edit_keys_are_advertised_only_when_the_gate_is_open() {
        let closed = rendered(&status_line(
            &super::super::super::fixtures::app_in_sheep_pane(),
            200,
        ));
        let open = rendered(&status_line(
            &super::super::super::fixtures::app_in_sheep_pane_with_control(),
            200,
        ));
        for key in ["space cycle", "e edit"] {
            assert!(
                !closed.contains(key),
                "{key} advertised read-only: {closed:?}"
            );
            assert!(
                open.contains(key),
                "{key} missing with the gate open: {open:?}"
            );
        }
        assert!(closed.contains("esc close"), "got {closed:?}");
        assert!(
            open.contains("esc close"),
            "the gate is open, but esc only asks or closes now: {open:?}"
        );
        for both in [&closed, &open] {
            assert!(both.contains("h help"), "got {both:?}");
            assert!(both.contains("* yours"), "got {both:?}");
            assert!(both.contains("! parked"), "got {both:?}");
            assert!(both.contains("q quit"), "got {both:?}");
            assert!(!both.contains("x stop"), "got {both:?}");
        }
    }

    /// An env row is on the same screen as every field, so it carries the
    /// field list's own hint: `esc close`, not a sub-screen's `esc back`,
    /// and `e edit` since `begin_env_typing` is the same door
    /// `confirm_field` already opens for a typed field.
    #[test]
    fn an_env_rows_status_bar_hint_is_the_field_lists_own() {
        let mut app = super::super::super::fixtures::app_in_sheep_pane_with_control();
        app.update(Msg::Key(KeyPress::SelectLast));
        assert!(matches!(
            app.config_pane().unwrap().cursor(),
            Some(crate::lookout::pane::PaneRow::Env(_) | crate::lookout::pane::PaneRow::AddEnv)
        ));
        let bar = rendered(&status_line(&app, 200));
        assert!(bar.contains("esc close"), "got {bar:?}");
        assert!(bar.contains("e edit"), "got {bar:?}");
    }

    /// Nothing the config pane files is armed or in flight, so the bar
    /// keeps its key hint rather than asking a question the operator's
    /// next keystroke does not answer.
    #[test]
    fn a_filed_pane_edit_leaves_the_status_bar_on_its_key_hint() {
        let mut app = super::super::super::fixtures::app_in_sheep_pane_with_control();
        pane_to(&mut app, "autorestart");
        app.update(Msg::Key(KeyPress::Cycle));
        let bar = rendered(&status_line(&app, 200));
        assert!(!bar.contains("enter confirms"), "got {bar:?}");
        assert!(!bar.contains("sent, waiting"), "got {bar:?}");
        assert!(bar.contains("esc close"), "got {bar:?}");
    }

    #[test]
    fn the_panes_editors_get_their_own_status_line_rather_than_the_filters() {
        let mut app = super::super::super::fixtures::app_in_sheep_pane_with_control();
        pane_to(&mut app, "cwd");
        app.update(Msg::Key(KeyPress::Confirm));
        app.update(Msg::Key(KeyPress::TextChar('x')));
        let field = rendered(&status_line(&app, 200));
        assert!(field.contains("editing cwd"), "got {field:?}");
        assert!(!field.contains("filter"), "got {field:?}");
        app.update(Msg::Key(KeyPress::TextAbandon));

        // `SelectLast` lands on `+ add a key`; two steps up is `DB_HOST`,
        // the fixture's first env key.
        app.update(Msg::Key(KeyPress::SelectLast));
        app.update(Msg::Key(KeyPress::SelectUp));
        app.update(Msg::Key(KeyPress::SelectUp));
        assert_eq!(
            app.config_pane().unwrap().cursor(),
            Some(crate::lookout::pane::PaneRow::Env(0))
        );
        app.update(Msg::Key(KeyPress::Confirm));
        app.update(Msg::Key(KeyPress::TextChar('y')));
        let env = rendered(&status_line(&app, 200));
        assert!(env.contains("env DB_HOST VALUE"), "got {env:?}");
        assert!(env.contains("\u{2588}\u{258f}"), "got {env:?}");
        assert!(!env.contains("  y"), "the typed value is drawn: {env:?}");
        assert!(!env.contains("filter"), "got {env:?}");
    }

    /// The bar echoes the open editor, so it masks what its row masks and
    /// `ctrl-r` shows both.
    #[test]
    fn a_secrets_value_is_masked_on_the_bar_while_it_is_typed() {
        use crate::lookout::textbox::TextEdit;

        let mut app = super::super::super::fixtures::app_with_secrets_and_control();
        app.update(Msg::Key(KeyPress::SelectLast));
        app.update(Msg::Key(KeyPress::Confirm));
        for c in "DB_NEW".chars() {
            app.update(Msg::Key(KeyPress::TextChar(c)));
        }
        let key = rendered(&status_line(&app, 200));
        assert!(
            key.contains("DB_NEW\u{258f}"),
            "KEY is not a secret: {key:?}"
        );

        app.update(Msg::Key(KeyPress::NextField));
        for c in "hunter2".chars() {
            app.update(Msg::Key(KeyPress::TextChar(c)));
        }
        let masked = rendered(&status_line(&app, 200));
        assert!(!masked.contains("hunter2"), "got {masked:?}");
        assert!(
            masked.contains("\u{2588}\u{2588}\u{2588}\u{2588}\u{2588}\u{2588}\u{2588}\u{258f}"),
            "got {masked:?}"
        );

        app.update(Msg::Key(KeyPress::TextEdit(TextEdit::Reveal)));
        let shown = rendered(&status_line(&app, 200));
        assert!(shown.contains("hunter2\u{258f}"), "got {shown:?}");
    }

    /// A sheep's env VALUE, through the same slot.
    #[test]
    fn an_env_value_is_masked_on_the_bar_while_it_is_typed() {
        let mut app = super::super::super::fixtures::app_in_sheep_pane_with_control();
        app.update(Msg::Key(KeyPress::SelectLast));
        app.update(Msg::Key(KeyPress::Confirm));
        app.update(Msg::Key(KeyPress::TextChar('K')));
        app.update(Msg::Key(KeyPress::NextField));
        for c in "hunter2".chars() {
            app.update(Msg::Key(KeyPress::TextChar(c)));
        }
        let bar = rendered(&status_line(&app, 200));
        assert!(!bar.contains("hunter2"), "got {bar:?}");
        assert!(bar.contains("\u{2588}\u{258f}"), "got {bar:?}");
    }

    /// The whole point of one editor: the keys the bar names for a focused
    /// field are the same words on both panes, so an operator who learned one
    /// has learned the other.
    #[test]
    fn the_key_hint_for_each_field_reads_the_same_in_both_panes() {
        let mut env_app = super::super::super::fixtures::app_in_sheep_pane_with_control();
        // `SelectLast` lands on `+ add a key`, the env row whose editor opens
        // on KEY.
        env_app.update(Msg::Key(KeyPress::SelectLast));
        env_app.update(Msg::Key(KeyPress::Confirm));
        let env_key = rendered(&status_line(&env_app, 200));

        let mut secret_app = super::super::super::fixtures::app_with_secrets_and_control();
        secret_app.update(Msg::Key(KeyPress::SelectLast));
        secret_app.update(Msg::Key(KeyPress::Confirm));
        let secret_key = rendered(&status_line(&secret_app, 200));

        let on_key = "tab value   enter next   esc cancels";
        assert!(env_key.contains(on_key), "env KEY focus: {env_key:?}");
        assert!(
            secret_key.contains(on_key),
            "secrets KEY focus: {secret_key:?}"
        );

        env_app.update(Msg::Key(KeyPress::TextChar('A')));
        secret_app.update(Msg::Key(KeyPress::TextChar('A')));
        env_app.update(Msg::Key(KeyPress::NextField));
        secret_app.update(Msg::Key(KeyPress::NextField));
        let env_value = rendered(&status_line(&env_app, 200));
        let secret_value = rendered(&status_line(&secret_app, 200));

        let on_value = "tab key   enter writes   esc cancels";
        assert!(
            env_value.contains(on_value),
            "env VALUE focus: {env_value:?}"
        );
        assert!(
            secret_value.contains(on_value),
            "secrets VALUE focus: {secret_value:?}"
        );
    }

    /// An armed env delete takes the bar the way an armed secret delete
    /// already does, with the same promise.
    #[test]
    fn an_armed_env_delete_owns_the_status_line() {
        let mut app = super::super::super::fixtures::app_in_sheep_pane_with_control();
        // `SelectLast` lands on `+ add a key`; two steps up is `DB_HOST`, the
        // fixture's first env key. `D` arms its removal.
        app.update(Msg::Key(KeyPress::SelectLast));
        app.update(Msg::Key(KeyPress::SelectUp));
        app.update(Msg::Key(KeyPress::SelectUp));
        app.update(Msg::Key(KeyPress::ArmDelete));
        let bar = rendered(&status_line(&app, 200));
        assert!(
            bar.contains("delete DB_HOST? enter confirms, any other key cancels"),
            "{bar:?}"
        );
        assert!(
            !bar.contains("e edit"),
            "the arm outranks the pane's own hint: {bar:?}"
        );
    }

    #[test]
    fn the_config_pane_gets_its_own_key_hint() {
        let app = super::super::super::fixtures::app_in_sheep_pane();
        let bar = status_line(&app, 120).to_string();
        assert!(bar.contains("esc close"), "got {bar:?}");
        assert!(bar.contains("r refresh"), "got {bar:?}");
        assert!(!bar.contains("x stop"), "got {bar:?}");
        assert!(!bar.contains("s settings"), "got {bar:?}");
    }

    /// The three keys the list sub-screen binds that no other screen
    /// does, each pressed rather than called.
    #[test]
    fn the_list_sub_screens_own_keys_do_what_its_hint_says() {
        let mut app = super::super::super::fixtures::app_in_sheep_pane_with_control();
        pane_to(&mut app, "args");
        app.update(Msg::Key(KeyPress::Confirm));
        let bar = rendered(&status_line(&app, 200));
        assert!(bar.contains("esc back"), "got {bar:?}");
        assert!(bar.contains("d remove"), "got {bar:?}");
        assert!(bar.contains("K/J move"), "got {bar:?}");
        app.update(Msg::Key(KeyPress::StepDown));
        assert_eq!(
            filed_args(&app),
            Some(serde_json::json!(["8080", "--port"])),
            "J files the array with the element moved down"
        );
        // Ordered J before d on purpose: the two compose, so a removal
        // first would leave one element and nothing for J to move.
        app.update(Msg::Key(KeyPress::Remove));
        assert_eq!(
            filed_args(&app),
            Some(serde_json::json!(["--port"])),
            "d files the array without the element under the cursor"
        );
    }

    /// The bleats pane's match box gets the status bar, not the dashboard's
    /// name filter.
    ///
    /// Both own `InputMode::Text`, and the filter branch is a catch-all, so
    /// without a branch of its own the bar labels the dashboard's untouched
    /// query as this pane's match. The same trap the config pane's editor
    /// sits ahead of the filter branch to avoid.
    #[test]
    fn the_bleats_match_box_owns_the_status_bar_while_it_is_open() {
        use shep_core::protocol::ProcessInfo;
        use shep_core::status::ProcStatus;

        let mut app = with_selection(ProcessInfo::builder(9, "web", ProcStatus::Online).build());
        let _ = app.update(Msg::Key(KeyPress::Bleats));
        let _ = app.update(Msg::Key(KeyPress::FilterStart));
        for typed in "pool".chars() {
            let _ = app.update(Msg::Key(KeyPress::TextChar(typed)));
        }
        let bar = rendered(&status_line(&app, 160));
        assert!(bar.contains("match  pool"), "got {bar}");
        assert!(!bar.contains("filter"), "not the dashboard's box: {bar}");
    }

    /// The bleats pane's own hint carries the design's full line, plus `m`
    /// for the minimum-level axis the design names no key for at all. Every
    /// other key hint test in this module checks for its own screen's
    /// keys the same way; a bare "the bar is non-empty" would pass for the
    /// dashboard's hint too, since the title alone already renders.
    #[test]
    fn the_bleats_pane_gets_its_own_status_line() {
        use shep_core::protocol::ProcessInfo;
        use shep_core::status::ProcStatus;

        let mut app = with_selection(ProcessInfo::builder(9, "web", ProcStatus::Online).build());
        let _ = app.update(Msg::Key(KeyPress::Bleats));
        let bar = rendered(&status_line(&app, 200));
        for key in [
            "esc back",
            "j/k line",
            "ctrl-d/u page",
            "G end",
            "/ search",
            "n/N match",
            "f follow",
            "w wrap",
            "o out/err/both",
            "m level",
        ] {
            assert!(bar.contains(key), "missing {key:?}: got {bar}");
        }
    }

    /// The right-aligned `█ following` indicator replaces the control-state
    /// label while the bleats pane is pinned to the tail, and only then:
    /// the design names it for this screen alone.
    #[test]
    fn the_following_indicator_replaces_control_state_while_pinned_to_the_tail() {
        use shep_core::protocol::ProcessInfo;
        use shep_core::status::ProcStatus;

        let mut app = with_selection(ProcessInfo::builder(9, "web", ProcStatus::Online).build());
        let _ = app.update(Msg::Key(KeyPress::Bleats));
        let bar = rendered(&status_line(&app, 160));
        assert!(bar.contains("\u{2588} following"), "got {bar}");
        assert!(!bar.contains("read-only"), "got {bar}");

        let _ = app.update(Msg::Key(KeyPress::SelectUp));
        let scrolled = rendered(&status_line(&app, 160));
        assert!(
            !scrolled.contains("\u{2588} following"),
            "scrolled back, no longer following: {scrolled}"
        );
        assert!(scrolled.contains("read-only"), "got {scrolled}");
    }

    /// `x`/`R`/`L` are wired, so the hint keeps naming them; `b`/`/` are
    /// wired too now, so the hint names them alongside the write keys
    /// rather than dropping them, the same rule that gates the write keys
    /// behind `Control::Allowed` just below.
    #[test]
    fn the_sheep_panes_hint_names_the_write_keys_and_the_feeds_own() {
        use shep_core::protocol::ProcessInfo;
        use shep_core::status::ProcStatus;

        let mut app = with_selection(ProcessInfo::builder(9, "web", ProcStatus::Online).build());
        app.set_control_for_tests(Control::Allowed);
        let _ = app.update(Msg::Key(KeyPress::Confirm));
        let bar = rendered(&status_line(&app, 200));
        for key in [
            "esc flock",
            "e edit",
            "J/K next sheep",
            "x stop",
            "R restart",
            "L reload",
            "b full log",
            "/ filter",
        ] {
            assert!(bar.contains(key), "missing {key:?}: got {bar}");
        }
    }
}