shep 0.25.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
//! The lookout's state and its reducer: `Msg` in, `Effect` out.
//!
//! No I/O, no terminal types, no clock. [`App::update`] is synchronous, work
//! for the outside comes back as an [`Effect`] the caller runs, and every
//! `Instant` arrives on a message.
//!
//! The bus is lossy, so [`Msg::Event`] upserts and [`Msg::Snapshot`] replaces
//! the whole flock map. The cursor is a [`RowKey`], and [`App::reseat`] puts
//! it back on a real row. Sibling modules hold what reads or changes them.

use core::fmt;
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::path::PathBuf;
use std::time::{Duration, Instant};

use shep_client::RequestError;
use shep_core::config::DogTable;
use shep_core::dogs::pane::{PANE_ACTION, Pane};
use shep_core::protocol::{
    ActionOutcome, BusEvent, DogSectionToml, DogSource, EnvValue, Lamb, ProcessEventKind,
    ProcessInfo, Request, Response, SelectorSpec, SheepConfigView, SheepRefusal,
};
use shep_core::secrets::ALL_ENVIRONMENTS;
use shep_core::status::ProcStatus;

use super::field::FieldKind;
use super::level::{Classifier, Level};
use super::pane::{
    ConfigPane, DogRow, DogToggle, FieldValue, ListedDog, Lock, PaneEdit, PaneRow, PaneTarget,
    ReloadKind, SectionWrite, SheepDogEntry,
};
use super::pane::{DeclaredPane, DogStatus};
use super::pane_bleats::BleatsPane;
use super::pane_sheep::SheepPane;
use super::secrets::{SecretRow, SecretsModel, Source};
use super::tail::Stream;
use super::textbox::{TextBox, TextEdit};
use super::theme::Palette;
use super::viewport::Viewport;
use crate::commands::dogs::DogEntry;
use crate::commands::settings::{DogView, SettingEdit, SettingsSnapshot};
use crate::style::{StyleLevel, StyleSource};
use crate::vocabulary::Reported;
pub(in crate::lookout) use settings_confirm::apply_needs;
use settings_confirm::confirm_text;

mod action;
mod bleats;
mod catalogue;
mod close_dialog;
mod config_pane;
mod config_pane_edits;
mod config_pane_keys;
#[cfg(test)]
mod disabled_tests;
mod dog_job;
mod dog_pane;
mod dog_pane_actions;
#[cfg(test)]
mod dog_pane_entries;
#[cfg(test)]
mod dog_pane_entry_add;
#[cfg(test)]
mod dog_pane_entry_removal;
mod dog_pane_pull;
mod dog_pane_refresh;
mod feed_keys;
mod focus;
mod keys;
mod lambs;
mod long_actions;
// The layer is whole and drawn, but nothing opens a modal until the install flow does.
#[allow(dead_code)]
mod modal;
mod msg;
mod over_host;
mod pane_dogs;
mod pane_list;
mod read;
mod rows;
mod samples;
mod secrets_keys;
mod secrets_pane;
mod secrets_write;
mod selection;
mod settings;
mod settings_confirm;
#[cfg(test)]
mod settings_dog_tree_tests;
mod settings_dogs;
mod settings_env;
#[cfg(test)]
mod settings_env_tests;
mod settings_keys;
mod sheep_pane;
#[cfg(test)]
mod testing;
mod update;

pub use action::*;
pub(crate) use catalogue::{
    CataloguePane, CatalogueRead, CatalogueRow, DogState, fetch as catalogue_fetch,
    read_cache as catalogue_read_cache,
};
pub use close_dialog::*;
pub(crate) use config_pane::*;
pub(crate) use dog_job::{DogJob, DogRun, DogRunner, GrantReply};
// Re-exported rather than imported (IR-32): every module under `app` opens
// `use super::super::*` or `use super::*`, and the shared key/value editor is
// what they all drive.
pub(crate) use super::keyvalue::{Grammar, KeyValues, Outcome};
pub(crate) use super::pane::EnvSubmit;
pub(crate) use focus::{Focus, FocusAsk};
pub(crate) use modal::Modal;
pub use msg::*;
pub(crate) use over_host::NOT_OVER_HOST;
pub use rows::*;
pub(crate) use samples::*;
pub(crate) use secrets_pane::*;
pub use settings::*;

/// What occupies the body between the title band and the status bar.
///
/// A variant per pane, rather than a shared "which pane is open" enum plus
/// state beside it. The flock table needs no state of its own. The others
/// carry their screen's state directly, so nothing stale survives a switch.
/// One field, one variant at a time: nothing is left to resurface.
#[derive(Debug)]
pub(crate) enum Body {
    /// The dashboard: flock table, host strip, sheep detail, bleats feed.
    FlockTable,
    /// The settings screen, opened by [`KeyPress::Settings`].
    Settings(Settings),
    /// An open config pane, for a sheep or a dog, opened by
    /// [`KeyPress::Edit`].
    ConfigPane(Box<ConfigPane>),
    /// The bleats feed given the whole screen, opened by
    /// [`KeyPress::Bleats`].
    Bleats(BleatsPane),
    /// The secrets pane, opened by [`KeyPress::Secrets`].
    Secrets(SecretsPane),
    /// One sheep given the whole screen, opened by [`KeyPress::Confirm`].
    Sheep(Box<SheepPane>),
    /// The dog index as a list and an entry, opened by
    /// [`App::open_catalogue`].
    Catalogue(CataloguePane),
}

/// The body's own pane accessors, so a call site need not match on it.
///
/// A method on the body borrows only the body field, which is what lets a
/// caller still read `App::now` or `App::mode` while it holds a pane. Every
/// match below lists every variant, so a new variant fails to compile.
impl Body {
    /// The open config pane, or `None` on any other variant.
    #[must_use]
    pub(super) fn config_pane(&self) -> Option<&ConfigPane> {
        match self {
            Body::ConfigPane(pane) => Some(pane),
            Body::FlockTable
            | Body::Settings(_)
            | Body::Bleats(_)
            | Body::Secrets(_)
            | Body::Sheep(_)
            | Body::Catalogue(_) => None,
        }
    }

    /// [`Self::config_pane`]'s mutable twin.
    pub(super) fn config_pane_mut(&mut self) -> Option<&mut ConfigPane> {
        match self {
            Body::ConfigPane(pane) => Some(pane),
            Body::FlockTable
            | Body::Settings(_)
            | Body::Bleats(_)
            | Body::Secrets(_)
            | Body::Sheep(_)
            | Body::Catalogue(_) => None,
        }
    }

    /// The settings screen, or `None` on any other variant.
    #[must_use]
    pub(super) fn settings(&self) -> Option<&Settings> {
        match self {
            Body::Settings(settings) => Some(settings),
            Body::FlockTable
            | Body::ConfigPane(_)
            | Body::Bleats(_)
            | Body::Secrets(_)
            | Body::Sheep(_)
            | Body::Catalogue(_) => None,
        }
    }

    /// [`Self::settings`]'s mutable twin.
    pub(super) fn settings_mut(&mut self) -> Option<&mut Settings> {
        match self {
            Body::Settings(settings) => Some(settings),
            Body::FlockTable
            | Body::ConfigPane(_)
            | Body::Bleats(_)
            | Body::Secrets(_)
            | Body::Sheep(_)
            | Body::Catalogue(_) => None,
        }
    }

    /// The open sheep pane, or `None` on any other variant.
    #[must_use]
    pub(super) fn sheep_pane(&self) -> Option<&SheepPane> {
        match self {
            Body::Sheep(pane) => Some(pane.as_ref()),
            Body::FlockTable
            | Body::Settings(_)
            | Body::ConfigPane(_)
            | Body::Bleats(_)
            | Body::Secrets(_)
            | Body::Catalogue(_) => None,
        }
    }

    /// [`Self::sheep_pane`]'s mutable twin.
    pub(super) fn sheep_pane_mut(&mut self) -> Option<&mut SheepPane> {
        match self {
            Body::Sheep(pane) => Some(pane.as_mut()),
            Body::FlockTable
            | Body::Settings(_)
            | Body::ConfigPane(_)
            | Body::Bleats(_)
            | Body::Secrets(_)
            | Body::Catalogue(_) => None,
        }
    }

    /// The full-screen bleats pane, or `None` on any other variant.
    #[must_use]
    pub(super) fn bleats_pane(&self) -> Option<&BleatsPane> {
        match self {
            Body::Bleats(pane) => Some(pane),
            Body::FlockTable
            | Body::Settings(_)
            | Body::ConfigPane(_)
            | Body::Secrets(_)
            | Body::Sheep(_)
            | Body::Catalogue(_) => None,
        }
    }

    /// [`Self::bleats_pane`]'s mutable twin.
    pub(super) fn bleats_pane_mut(&mut self) -> Option<&mut BleatsPane> {
        match self {
            Body::Bleats(pane) => Some(pane),
            Body::FlockTable
            | Body::Settings(_)
            | Body::ConfigPane(_)
            | Body::Secrets(_)
            | Body::Sheep(_)
            | Body::Catalogue(_) => None,
        }
    }

    /// The open secrets pane, or `None` on any other variant.
    ///
    /// The mutable shape alone, as [`App::secrets_pane_mut`] has had it: no
    /// reader needs the secrets pane by shared reference, the view reaching
    /// it through [`App::body`].
    pub(super) fn secrets_pane_mut(&mut self) -> Option<&mut SecretsPane> {
        match self {
            Body::Secrets(pane) => Some(pane),
            Body::FlockTable
            | Body::Settings(_)
            | Body::ConfigPane(_)
            | Body::Bleats(_)
            | Body::Sheep(_)
            | Body::Catalogue(_) => None,
        }
    }

    /// The open catalogue pane, or `None` on any other variant.
    #[must_use]
    #[cfg_attr(
        not(test),
        expect(
            dead_code,
            reason = "nothing opens the catalogue until its key and verb land"
        )
    )]
    pub(crate) fn catalogue_pane(&self) -> Option<&CataloguePane> {
        match self {
            Body::Catalogue(pane) => Some(pane),
            Body::FlockTable
            | Body::Settings(_)
            | Body::ConfigPane(_)
            | Body::Bleats(_)
            | Body::Secrets(_)
            | Body::Sheep(_) => None,
        }
    }

    /// [`Self::catalogue_pane`]'s mutable twin.
    #[cfg_attr(
        not(test),
        expect(
            dead_code,
            reason = "nothing opens the catalogue until its key and verb land"
        )
    )]
    pub(super) fn catalogue_pane_mut(&mut self) -> Option<&mut CataloguePane> {
        match self {
            Body::Catalogue(pane) => Some(pane),
            Body::FlockTable
            | Body::Settings(_)
            | Body::ConfigPane(_)
            | Body::Bleats(_)
            | Body::Secrets(_)
            | Body::Sheep(_) => None,
        }
    }
}

/// The whole dashboard's state.
#[derive(Debug)]
pub struct App {
    flock: BTreeMap<u32, Row>,
    /// Which row the detail pane and the bleats feed describe. `None` only for
    /// an empty flock.
    ///
    /// A [`RowKey`], not an index: the flock map is replaced wholesale every
    /// two seconds, and an index would silently start pointing at a different
    /// sheep. The viewport offset is derived from this
    /// ([`super::view::flock::scroll_offset`]).
    selected: Option<RowKey>,
    /// The live substring filter over sheep names, empty when there is none.
    ///
    /// Case-insensitive `contains`, taken literally with no trimming. Not the
    /// CLI's selector grammar, which is exact-match and so cannot narrow as you
    /// type.
    filter: TextBox,
    /// Which keymap [`super::input::map_key`] is called with. Normal until `/`
    /// opens the box; the reducer, not the keymap, owns this state.
    mode: InputMode,
    /// The next write ticket, shared by the config pane's batches and the
    /// settings screen's one edit. Monotonic and never reused, so a reply
    /// can only name the write it belongs to.
    next_write_ticket: u64,
    /// The newest [`Effect::ListSheepDogs`] asked. Only its own answer may
    /// list the dogs tab: closing the pane moves it on, so no answer
    /// outlives the pane that asked.
    sheep_dogs_ask: u64,
    link: Link,
    notice: Option<Notice>,
    palette: Palette,
    control: Control,
    /// The `$SHEP_HOME` this lookout watches, for the title line.
    home: String,
    /// The ssh destination this lookout watches in place of this machine's
    /// shepherd, or `None` for the local one. Set through
    /// [`Self::set_remote_host`].
    remote_host: Option<String>,
    /// The clock the view reads. Advanced by [`Msg::Tick`], and never once the
    /// link is [`Link::Lost`], so a frozen dashboard's uptime column stops.
    now: Instant,
    /// When the link was declared lost, on [`Self::now`]'s clock. `None`
    /// while it is still up.
    froze_at: Option<Instant>,
    /// How long ago that was, as of the last [`Msg::Tick`].
    ///
    /// The one number on a frozen dashboard that still moves. [`Self::now`]
    /// stops, so every uptime stops with it; this rides the tick separately,
    /// because how long the shepherd has been gone is a fact about now
    /// rather than a value the shepherd reported.
    frozen_for: Duration,
    /// The last host reading, or `None` before the first heartbeat and on a
    /// platform `sysinfo` does not support. [`Self::host_unsupported`] tells
    /// the strip which of the two it is looking at.
    host: Option<super::source::HostSample>,
    /// True once a sample has come back `None`, which the strip says a
    /// different sentence for than a heartbeat that has not fired yet.
    host_unsupported: bool,
    /// The selected sheep's most recent output, as of the last refresh. An
    /// empty, unlabelled tail before the first one, which the feed reads the
    /// same way as a sheep that has written nothing.
    feed: super::tail::Tail,
    /// The last lamb reading, or `None` before there has been one. Keyed by the
    /// id it was taken for, so a stale reading and a dropped request both read
    /// as "not read yet".
    lambs: Option<LambReading>,
    /// The last reading of the selected sheep's log files on disk, keyed the
    /// same way and taken on the same cadence as [`Self::lambs`].
    log_size: Option<LogSize>,
    /// The one action this dashboard is in the middle of, or `None`.
    action: Option<Action>,
    /// What the body between the title band and the status bar is showing.
    ///
    /// One field rather than the two `Option`s this replaced: see [`Body`]'s
    /// doc for why.
    body: Body,
    /// Which sheep a config pane is open for, or wanted for.
    ///
    /// Set when the read goes out, cleared when the pane closes, checked
    /// when a reply lands. Without it, two `e` presses and an `Esc` could
    /// reopen a closed pane on the late reply. [`Self::config_pane`] alone
    /// cannot tell those two `None` states apart.
    config_target: Option<String>,
    /// Which screen [`Self::config_target`] is standing in for, while it is
    /// `Some`. `None` whenever `config_target` is: the two are set and
    /// cleared together, always in the same step that sends
    /// [`Sent::SheepConfig`]. See [`ConfigFor`].
    config_for: Option<ConfigFor>,
    /// The dog a config pane is open for, or wanted for, and the schema its
    /// binary answered with.
    ///
    /// [`Self::config_target`]'s twin. Carries a schema because it is
    /// probed once at open and reused on every re-read, so `r` never
    /// respawns the dog's binary. Cleared alongside `config_target`.
    dog_target: Option<DogProbe>,
    /// Which opening of a dog's config pane is the latest.
    ///
    /// Raised each time a pane opens over a dashboard or the settings
    /// screen, never on a re-read. A manifest read and a `shep.pane` pull
    /// carry the number they were raised under, and one that lands under
    /// another is for a pane the operator has since left.
    dog_opening: u64,
    /// Whether `Escape` on a whole-table pane is waiting on its re-read.
    ///
    /// Set by [`Self::reread_before_closing`]. Cleared by its answer, by an
    /// unsent read, or by the pane closing. While set, the pane's next
    /// config answer decides the close instead of refreshing it.
    closing: bool,
    /// Whether a [`Sent::SheepConfig`] or [`Sent::DogSection`] read for the
    /// open pane is out and has not answered yet.
    ///
    /// Set by [`Self::reread_pane`], cleared by [`Self::on_sheep_config`],
    /// [`Self::on_dog_section`], or an unsent read. A reply carries nothing
    /// back to say which of two outstanding reads it answers, so this stops a
    /// second one going out while the first is still in flight.
    config_read_in_flight: bool,
    /// The close dialog over the open pane, or `None`.
    ///
    /// Raised by `Escape` on a pane carrying changes the running child has
    /// not taken, and it owns the keyboard while it is up. Cleared with the
    /// pane, so no dialog can outlive the edits it counted.
    close_dialog: Option<CloseDialog>,
    /// The verb the close dialog chose, waiting on its own writes to answer.
    ///
    /// Set by [`Self::answer_close`] alongside the batch that must land
    /// first, and cleared on the reply that finishes it or on
    /// [`CONFIRM_EXPIRY`], the same as the dialog it followed from.
    held: Option<HeldAction>,
    /// The resolved style level and which layer chose it. Defaulted here and
    /// overridden through [`Self::set_style`], so the STYLE LEVEL row reads the
    /// same answer the rest of the CLI does.
    style: (StyleLevel, StyleSource),
    /// Each sheep's last [`HISTORY`] CPU-percent samples, oldest first,
    /// keyed by [`ProcessInfo::id`].
    ///
    /// Populated by [`Msg::Snapshot`] only: the bus's per-event
    /// [`Msg::Event`] carries no CPU reading, so a sample is one point per
    /// poll. A row missing from the latest snapshot loses its entry entirely.
    cpu_history: HashMap<u32, VecDeque<f32>>,
    /// The whole flock's summed CPU percent, one sample per poll, same
    /// depth and ordering as [`Self::cpu_history`].
    flock_cpu: VecDeque<f32>,
    /// Each sheep's last [`HISTORY`] RSS samples, oldest first, keyed by
    /// [`ProcessInfo::id`], on the same terms as [`Self::cpu_history`].
    ///
    /// Buffered as read rather than differenced: RSS is a reading at an
    /// instant, and only CPU arrives as a counter.
    rss_history: HashMap<u32, VecDeque<u64>>,
    /// The previous CPU counter and the instant it was read, per sheep.
    ///
    /// What makes a sample a mean over one poll rather than over the
    /// shepherd's own baseline window. Dropped when a sheep reports no
    /// reading, so a stop is never differenced across.
    cpu_last: HashMap<u32, (Option<u32>, u64, Instant)>,
    /// How [`Self::visible_rows`] gathers the flock table, toggled by `F`.
    grouping: Grouping,
    /// Fold names `z` has collapsed: [`Self::visible_rows`] skips a
    /// collapsed fold's members, leaving its own [`RowKey::Fold`] header
    /// behind.
    ///
    /// Names, not [`RowKey`]s: a fold has no id to key on, and a name
    /// surviving one poll to the next is exactly what keeps a collapse in
    /// place while the flock underneath it changes shape.
    collapsed_folds: HashSet<String>,
    /// Whether the keymap overlay is up.
    ///
    /// Not an [`InputMode`]: `map_key` has exactly two modes and an overlay
    /// that swallows keys is a reducer concern rather than a keyboard-edge
    /// one. A third mode would also have to answer what a letter means in
    /// it, and the answer is nothing.
    keymap_open: bool,
    /// The modal layer, which takes every key while a modal is open.
    modals: modal::Modals,
    /// What `shep lookout <sheep> [tab] [dog]` asked for, held until the
    /// first flock answer can say whether the sheep is there.
    ///
    /// Taken whole by [`App::resolve_focus`] on that answer, whether or not
    /// it can be honoured: a shepherd still restoring the flock is a reason
    /// to report a missing sheep, not a reason to reopen a pane on every
    /// poll.
    focus: Option<Focus>,
    /// The tab and the dog [`Self::focus`] asked for, held for the config pane
    /// of the one sheep the command line named, and spent by that pane's read
    /// and by the `dogs` tab's listing.
    ///
    /// Retired with the pane, and by [`Self::ask_for_sheep_config`] the moment
    /// an ask for another sheep replaces the read this one was waiting on.
    focus_ask: Option<FocusAsk>,
    /// The rows of the latest [`Effect::LoadCatalogue`], kept whether or not
    /// the catalogue is open so another screen can read them.
    catalogue: Vec<CatalogueRow>,
    /// The one dog job this lookout runs at a time, and what its modals are
    /// waiting on.
    ///
    /// A job is `commands::dogs::session` on its own thread; this is the
    /// dashboard's half of it. Dropping the `App` drops the job's grant
    /// replies, which is what releases a callback still waiting for an
    /// operator who has already quit.
    dog_job: DogJob,
    /// The pane actions a dog answered with an id and has not yet reported
    /// done, and the last result.
    long_actions: long_actions::LongActions,
    /// The tag of the quit question lookout is asking, or `None`.
    ///
    /// Held here rather than inside [`DogJob::Running`] because the answer can
    /// arrive after the job it was asked about has landed, and a yes to a
    /// question still on screen must still quit.
    dog_quit: Option<u64>,
    /// The line `shep flock` would print under this flock, from
    /// [`Msg::Hint`]. Cleared when the link is lost.
    hint: Option<String>,
    /// The tag and dog of the delete question lookout is asking, or `None`.
    dog_delete: Option<(u64, String)>,
    /// The tag and trigger of the pane action question lookout is asking, or
    /// `None`. A yes sends the trigger.
    pane_action: Option<(u64, Sent)>,
    /// The next modal tag.
    ///
    /// Shared by every modal owner so no two open modals carry the same tag,
    /// and never reused, the same way [`Self::next_write_ticket`] is.
    next_modal_tag: u64,
}

/// What a partly refused walk should say, or `None` when nothing was
/// refused.
///
/// Names the apps rather than counting them, because "2 refused" sends an
/// operator to the shepherd's log to find out which. One app's reason is
/// worth carrying; several would outrun the status bar, so past the first
/// the sentence names the apps alone.
fn refusal_sentence(refused: &[SheepRefusal]) -> Option<String> {
    match refused {
        [] => None,
        [only] => Some(format!("{} refused it: {}", only.name, only.reason)),
        many => {
            let names: Vec<&str> = many.iter().map(|one| one.name.as_str()).collect();
            Some(format!("{} refused it", names.join(", ")))
        }
    }
}

/// Saturating `Duration` to milliseconds. Saturates for clippy's
/// `cast_possible_truncation`, not for a lookout left open 580 million years.
fn millis(d: Duration) -> u64 {
    u64::try_from(d.as_millis()).unwrap_or(u64::MAX)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lookout::view::fixtures;

    /// The names of the [`Body`] accessors that answer for `body`, in the
    /// order the type declares them.
    fn answered(body: &mut Body) -> Vec<&'static str> {
        let mut answered = Vec::new();
        if body.config_pane().is_some() {
            answered.push("config_pane");
        }
        if body.config_pane_mut().is_some() {
            answered.push("config_pane_mut");
        }
        if body.settings().is_some() {
            answered.push("settings");
        }
        if body.settings_mut().is_some() {
            answered.push("settings_mut");
        }
        if body.sheep_pane().is_some() {
            answered.push("sheep_pane");
        }
        if body.sheep_pane_mut().is_some() {
            answered.push("sheep_pane_mut");
        }
        if body.bleats_pane().is_some() {
            answered.push("bleats_pane");
        }
        if body.bleats_pane_mut().is_some() {
            answered.push("bleats_pane_mut");
        }
        if body.secrets_pane_mut().is_some() {
            answered.push("secrets_pane_mut");
        }
        if body.catalogue_pane().is_some() {
            answered.push("catalogue_pane");
        }
        if body.catalogue_pane_mut().is_some() {
            answered.push("catalogue_pane_mut");
        }
        answered
    }

    /// A dashboard with one sheep given the whole screen: `enter` on the
    /// selected row, which is the only way this variant is ever reached.
    fn app_in_sheep_pane() -> App {
        let mut app =
            fixtures::with_selection(ProcessInfo::builder(9, "web", ProcStatus::Online).build());
        app.update(Msg::Key(KeyPress::Confirm));
        app
    }

    /// Every pane variant is reached by its own accessors and by no
    /// other's, and the dashboard by none. An accessor that answered for a
    /// variant it does not name would hand a caller a pane the operator
    /// never opened.
    #[test]
    fn each_body_accessor_answers_only_for_its_own_variant() {
        let none: Vec<&'static str> = Vec::new();
        assert_eq!(answered(&mut fixtures::full_app().body), none);
        assert_eq!(
            answered(&mut fixtures::app_in_settings().body),
            ["settings", "settings_mut"]
        );
        assert_eq!(
            answered(&mut fixtures::app_in_dog_pane().body),
            ["config_pane", "config_pane_mut"]
        );
        assert_eq!(
            answered(&mut fixtures::bleats_pane_with_filters().body),
            ["bleats_pane", "bleats_pane_mut"]
        );
        assert_eq!(
            answered(&mut fixtures::app_with_secrets().body),
            ["secrets_pane_mut"]
        );
        assert_eq!(
            answered(&mut app_in_sheep_pane().body),
            ["sheep_pane", "sheep_pane_mut"]
        );
        let mut app = fixtures::full_app();
        app.open_catalogue();
        assert_eq!(
            answered(&mut app.body),
            ["catalogue_pane", "catalogue_pane_mut"]
        );
    }

    /// Each key that would read or write this machine's `shep.toml`,
    /// `dogs.toml`, secret store or dog binaries, pressed on an app watching
    /// a host: the same notice, no effect, and the screen it would have
    /// opened stays shut.
    #[test]
    fn over_a_host_the_settings_secrets_and_dog_keys_raise_a_notice_and_no_effect() {
        use crate::lookout::app::testing::app_in_web;

        let cases: [(&str, App, KeyPress); 5] = [
            (
                "settings",
                fixtures::app_with_a_dog_selected_and_control(),
                KeyPress::Settings,
            ),
            (
                "secrets",
                fixtures::app_with_a_dog_selected_and_control(),
                KeyPress::Secrets,
            ),
            (
                "a dog's config pane",
                fixtures::app_with_a_dog_selected_and_control(),
                KeyPress::Edit,
            ),
            (
                "a sheep's dogs tab",
                app_in_web(Control::Allowed),
                KeyPress::Group(9),
            ),
            (
                "a dog toggle",
                fixtures::app_in_settings_on_dog("metrics"),
                KeyPress::Cycle,
            ),
        ];
        for (what, mut app, key) in cases {
            let before = core::mem::discriminant(app.body());
            app.set_remote_host("build-01");

            let effect = app.update(Msg::Key(key));

            assert_eq!(effect, Effect::None, "{what}");
            let notice = app.notice().unwrap_or_else(|| panic!("{what}: no notice"));
            assert_eq!(notice.to_string(), NOT_OVER_HOST, "{what}");
            assert_eq!(
                core::mem::discriminant(app.body()),
                before,
                "{what}: the body changed"
            );
        }
    }
}