runnerd-web 0.0.6

The web dashboard runnerd serves on loopback: a client of the daemon's API
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
//! `/`: the memory budget as blocks, every slot and the job it runs, the slice's CPU and memory over the last half
//! hour, the repositories with pause and resume, and the latest jobs.

use std::collections::BTreeMap;

use maud::{Markup, html};
use runnerd_core::api::{
    HostSample, HostSamples, Job, JobPage, JobQuery, JobState, JobSummary, ProfileStatus,
    RepositoryStatus, Sample, SampleSeries, SlotStatus, Status,
};
use runnerd_core::client::{Client, ClientError};

use super::{
    Live, Page, Parts, badge, digest, js, page, profile_class, repository_id, slot_id, time_ago,
};
use crate::chart::{Base, Series, Sparkline, TimeChart, nice_top};
use crate::format;

/// How far back the host charts reach.
pub(crate) const HOST_WINDOW: u64 = 30 * 60;
/// How much longer the samples of the slice are kept, so the oldest stretch of a live chart stays whole.
const HOST_MARGIN: u64 = 5 * 60;
/// How far back a slot's sparkline reaches.
const SPARK_WINDOW: u64 = 5 * 60;
/// Latest jobs listed.
const RECENT: u32 = 8;
/// Queued jobs listed, the oldest; the history lists the rest.
const QUEUED_SHOWN: usize = 8;

/// Everything the overview shows.
#[derive(Debug, Clone)]
pub(crate) struct Overview {
    pub(crate) now: u64,
    pub(crate) status: Status,
    /// Running jobs with their steps.
    pub(crate) running: Vec<Job>,
    /// Samples of each running job, by job ID.
    pub(crate) samples: BTreeMap<u64, Vec<Sample>>,
    pub(crate) host: HostSamples,
    pub(crate) recent: Vec<JobSummary>,
}

impl Overview {
    pub(crate) async fn load(daemon: &Client, now: u64) -> Result<Overview, ClientError> {
        let status: Status = daemon.get("/v1/status").await?;
        let host = daemon
            .get(&format!(
                "/v1/host/samples?since={}",
                now.saturating_sub(HOST_WINDOW + HOST_MARGIN)
            ))
            .await?;
        let recent: JobPage = daemon
            .get_query(
                "/v1/jobs",
                &JobQuery {
                    limit: Some(RECENT),
                    ..JobQuery::default()
                },
            )
            .await?;
        let mut overview = Overview {
            now,
            status,
            running: Vec::new(),
            samples: BTreeMap::new(),
            host,
            recent: recent.jobs,
        };
        overview.reload_running(daemon).await?;
        Ok(overview)
    }

    /// Reads the running jobs again, and the samples of those not seen before.
    pub(crate) async fn reload_running(&mut self, daemon: &Client) -> Result<(), ClientError> {
        let page: JobPage = daemon
            .get_query(
                "/v1/jobs",
                &JobQuery {
                    state: Some(JobState::Running),
                    limit: Some(100),
                    ..JobQuery::default()
                },
            )
            .await?;
        let mut running = Vec::with_capacity(page.jobs.len());
        for summary in page.jobs {
            running.push(
                daemon
                    .get::<Job>(&format!("/v1/jobs/{}", summary.id))
                    .await?,
            );
        }
        self.samples
            .retain(|id, _| running.iter().any(|job| job.summary.id == *id));
        for job in &running {
            if let std::collections::btree_map::Entry::Vacant(entry) =
                self.samples.entry(job.summary.id)
            {
                let series: SampleSeries = daemon
                    .get(&format!("/v1/jobs/{}/samples", job.summary.id))
                    .await?;
                entry.insert(series.samples);
            }
        }
        self.running = running;
        Ok(())
    }

    /// Adds a live sample of a running job.
    pub(crate) fn add_job_sample(&mut self, job: u64, sample: Sample) {
        if let Some(samples) = self.samples.get_mut(&job) {
            samples.push(sample);
        }
    }

    /// Adds a live sample of the slice, dropping those older than the window and its margin.
    pub(crate) fn add_host_sample(&mut self, sample: HostSample) {
        let since = sample.at.saturating_sub(HOST_WINDOW + HOST_MARGIN);
        self.host.samples.push(sample);
        self.host.samples.retain(|sample| sample.at >= since);
    }

    fn job_in(&self, profile: &str, slot: usize) -> Option<&Job> {
        self.running.iter().find(|job| {
            job.summary
                .runner
                .as_ref()
                .is_some_and(|runner| runner.profile == profile && runner.slot == slot)
        })
    }
}

/// The live regions, by id, in the order the page has them, with their parts.
pub(crate) fn regions(overview: &Overview) -> [(&'static str, Markup, Parts); 5] {
    let region = |id, render: &dyn Fn(&Parts) -> Markup| {
        let parts = Parts::default();
        let markup = render(&parts);
        (id, markup, parts)
    };
    [
        region("budget", &|parts| budget(overview, parts)),
        region("slots", &|parts| slots(overview, parts)),
        region("host", &|parts| host(overview, parts)),
        region("repositories", &|_| repositories(&overview.status)),
        region("recent", &|_| recent(overview)),
    ]
}

/// The whole page.
pub(crate) fn render(overview: &Overview) -> Markup {
    let [budget, slots, host, repositories, recent] = regions(overview);
    let live = Live {
        url: "/live/overview",
        at: overview.now,
        log: None,
        regions: [&budget, &slots, &host, &repositories, &recent]
            .iter()
            .map(|(id, markup, _)| (*id, digest(&markup.0)))
            .collect(),
    };
    let main = html! {
        h1.visually-hidden { "Overview" }
        (budget.1)
        (slots.1)
        (host.1)
        div.split {
            (repositories.1)
            (recent.1)
        }
    };
    page("Overview", Some(Page::Overview), Some(&live), &main)
}

#[allow(
    clippy::cast_precision_loss,
    reason = "sizes as flex weights in GiB; precision far beyond what a pixel shows"
)]
fn gib(bytes: u64) -> f64 {
    bytes as f64 / f64::from(1u32 << 30)
}

/// What an element standing for a slot does on hover, focus and touch: it selects the slot, which outlines its
/// block, card and job rows and shows its line of the budget's readout. Only the key is kept, so each live update
/// renders that line from the new data.
struct Link {
    enter: String,
    /// Clears the selection, unless another element has made its own since, as a tap does before the last one's
    /// blur.
    leave: String,
    /// `leave` for a mouse only: a finger leaves as soon as it lifts, so what a tap selected stays until the next tap
    /// or until focus moves on.
    pointer_leave: String,
    linked: String,
}

fn link(key: &str, repository: Option<&str>) -> Link {
    let key = js(key);
    Link {
        enter: format!("$_slot = {key}"),
        leave: format!("$_slot == {key} && ($_slot = '')"),
        pointer_leave: format!("evt.pointerType == 'mouse' && $_slot == {key} && ($_slot = '')"),
        linked: match repository {
            Some(repository) => format!("$_slot == {key} || $_repo == {}", js(repository)),
            None => format!("$_slot == {key}"),
        },
    }
}

/// What the budget's readout shows for a block: a figure in bold, and the words after it.
#[derive(Clone)]
struct Lens {
    figure: String,
    text: String,
}

/// A slot's lens, its card's id, and the job it runs, if any.
struct SlotView<'overview> {
    key: String,
    job: Option<&'overview Job>,
    memory: Option<u64>,
    lens: Lens,
}

fn slot_view<'overview>(
    overview: &'overview Overview,
    profile: &ProfileStatus,
    slot: &SlotStatus,
) -> SlotView<'overview> {
    let job = overview.job_in(&profile.name, slot.slot);
    let memory = job
        .and_then(|job| overview.samples.get(&job.summary.id))
        .and_then(|samples| samples.last())
        .map(|sample| sample.memory);
    let name = format!("{} {}", profile.name, slot.slot);
    let cap = format::bytes(profile.memory);
    let lens = match (&slot.runner, job, memory) {
        (Some(_), Some(job), Some(memory)) => Lens {
            figure: format::bytes(memory),
            text: format!(
                "of {cap} in {name}, {} on {}",
                job.summary.name, job.summary.repository
            ),
        },
        (Some(_), Some(job), None) => Lens {
            figure: cap,
            text: format!("{name}, {} on {}", job.summary.name, job.summary.repository),
        },
        (Some(runner), None, _) => Lens {
            figure: cap,
            text: format!(
                "{name}, a runner for {} waiting for its job",
                runner.repository
            ),
        },
        (None, _, _) if profile.reseeding && slot.slot == 1 => Lens {
            figure: cap,
            text: format!("{name}, reseeding the snapshot"),
        },
        (None, _, _) => Lens {
            figure: cap,
            text: format!("{name}, idle"),
        },
    };
    SlotView {
        key: slot_id(&profile.name, slot.slot),
        job,
        memory,
        lens,
    }
}

/// The budget: the slice as the ground, a block per slot sized by its memory cap, filled as high as the job's last
/// sampled memory; the mirror and each seed container; and what is free. A block opens its job, or its slot's card;
/// hovering or focusing one says what it holds in the readout above the bar.
pub(crate) fn budget(overview: &Overview, parts: &Parts) -> Markup {
    let status = &overview.status;
    let budget = &status.budget;
    let reserved: u64 = status
        .profiles
        .iter()
        .map(|profile| profile.memory * profile.slots.len() as u64)
        .sum();
    let held = held(status);
    let held_total: u64 = held.iter().map(|part| part.memory).sum();
    let free = budget
        .memory_max
        .map(|max| max.saturating_sub(reserved + held_total));
    let used_now = overview.host.samples.last().map(|sample| sample.memory);
    let max = budget
        .memory_max
        .map_or("no limit".to_owned(), format::bytes);
    // What is in use now is the readout's, which changes with every sample.
    let label = format!(
        "Memory budget of {}: {} of {max} reserved by running containers",
        budget.slice,
        format::bytes(budget.memory_in_use),
    );
    let free = free.filter(|free| *free > 0);
    let free_lens = free.map(|free| Lens {
        figure: format::bytes(free),
        text: format!("of {max} free"),
    });
    let mut lenses: Vec<(String, Lens)> = status
        .profiles
        .iter()
        .flat_map(|profile| {
            profile.slots.iter().map(|slot| {
                let view = slot_view(overview, profile, slot);
                (view.key, view.lens)
            })
        })
        .collect();
    lenses.extend(
        held.iter()
            .map(|part| (part.key.clone(), part.lens.clone())),
    );
    if let Some(lens) = &free_lens {
        lenses.push(("free".to_owned(), lens.clone()));
    }
    html! {
        section #budget .budget aria-labelledby="budget-title"
            "data-signals:_slot__ifmissing"="''" "data-signals:_repo__ifmissing"="''" {
            h2 #budget-title .visually-hidden { "Budget" }
            (readout(overview, used_now, &lenses, parts))
            div.bar role="group" aria-label=(label) {
                @for profile in &status.profiles {
                    @for slot in &profile.slots {
                        (block(overview, profile, slot, parts))
                    }
                }
                @for part in &held {
                    @let link = link(&part.key, None);
                    div class=(format!("block {}", part.class)) tabindex="0" role="img"
                        style=(format!("--size: {:.3}", gib(part.memory)))
                        aria-label=(format!("{} {}", part.lens.figure, part.lens.text))
                        data-on:pointerenter=(link.enter) data-on:focus=(link.enter)
                        data-on:pointerleave=(link.pointer_leave) data-on:blur=(link.leave) data-class:linked=(link.linked) {
                        span.size { (part.lens.figure) }
                        span.name { (part.name) }
                    }
                }
                @if let Some((free, lens)) = free.zip(free_lens.as_ref()) {
                    @let link = link("free", None);
                    div.free tabindex="0" role="img" style=(format!("--size: {:.3}", gib(free)))
                        aria-label=(format!("{} {}", lens.figure, lens.text))
                        data-on:pointerenter=(link.enter) data-on:focus=(link.enter)
                        data-on:pointerleave=(link.pointer_leave) data-on:blur=(link.leave) data-class:linked=(link.linked) {
                        span.size { (lens.figure) }
                    }
                }
            }
            (bar_keys(&held, free_lens.as_ref()))
            @if status.shutting_down {
                p.warning { "runnerd is shutting down: it starts no new runners and stops once running jobs finish." }
            }
        }
    }
}

/// The slice's total, and beside it the selected block's line. Each block has its own name, so the lines are for the
/// eye only.
fn readout(
    overview: &Overview,
    used_now: Option<u64>,
    lenses: &[(String, Lens)],
    parts: &Parts,
) -> Markup {
    let budget = &overview.status.budget;
    html! {
        div.figures {
            (parts.html("budget-readout", html! {
                p #budget-readout .readout {
                    span.big { (format::bytes(budget.memory_in_use)) }
                    span { " of " (budget.memory_max.map_or("unlimited".to_owned(), format::bytes)) " in " code { (budget.slice) } }
                    @if let Some(used) = used_now {
                        span.muted { " · " (format::bytes(used)) " in use" }
                    }
                }
            }))
            // The blocks' descriptions, so a block's name stays what it shows.
            p.lens aria-hidden="true" {
                @for (key, lens) in lenses {
                    // Every line takes its place, hidden but for the selected one, so the readout is as tall as its
                    // longest line and selecting a block never moves the bar.
                    @let id = lens_id(key);
                    (parts.html(&id, html! {
                        span #(id) data-class:on=(format!("$_slot == {}", js(key))) {
                            strong { (lens.figure) } " " (lens.text)
                        }
                    }))
                }
            }
        }
    }
}

/// The id of a block's line in the readout, which also describes the block.
fn lens_id(key: &str) -> String {
    format!("lens-{key}")
}

/// On a touch screen the mirror, a seed container and the free remainder may be too thin to tap: keys under the bar
/// select them instead, and say their sizes.
fn bar_keys(held: &[Held], free_lens: Option<&Lens>) -> Markup {
    html! {
        @if !held.is_empty() || free_lens.is_some() {
            div.bar-keys {
                @for part in held {
                    @let key = js(&part.key);
                    button class=(format!("bar-key {}", part.class)) type="button"
                        data-on:click=(format!("$_slot = $_slot == {key} ? '' : {key}"))
                        data-class:linked=(format!("$_slot == {key}")) {
                        span.swatch aria-hidden="true" {} (part.lens.figure) " " (part.name)
                    }
                }
                @if let Some(lens) = free_lens {
                    button.bar-key.key-free type="button" data-on:click="$_slot = $_slot == 'free' ? '' : 'free'"
                        data-class:linked="$_slot == 'free'" {
                        span.swatch aria-hidden="true" {} (lens.figure) " free"
                    }
                }
            }
        }
    }
}

/// Memory the budget holds for something other than a slot: the mirror, or a profile's seed container.
struct Held {
    key: String,
    /// The block's classes.
    class: String,
    /// What its block says under its size.
    name: String,
    memory: u64,
    lens: Lens,
}

/// The mirror, then each seed container, in the colour of the profile it reseeds.
fn held(status: &Status) -> Vec<Held> {
    let budget = &status.budget;
    let mirror = (budget.mirror_memory > 0).then(|| Held {
        key: "mirror".to_owned(),
        class: "mirror".to_owned(),
        name: "mirror".to_owned(),
        memory: budget.mirror_memory,
        lens: Lens {
            figure: format::bytes(budget.mirror_memory),
            text: "held by the mirror".to_owned(),
        },
    });
    let seeds = budget.seed_memory.iter().map(|seed| Held {
        key: format!("seed-{}", slot_id(&seed.profile, 0)),
        class: format!("seed {}", profile_class(status, &seed.profile)),
        name: format!("{} seed", seed.profile),
        memory: seed.memory,
        lens: Lens {
            figure: format::bytes(seed.memory),
            text: format!("held by {}'s seed container", seed.profile),
        },
    });
    mirror.into_iter().chain(seeds).collect()
}

fn block(overview: &Overview, profile: &ProfileStatus, slot: &SlotStatus, parts: &Parts) -> Markup {
    let class = profile_class(&overview.status, &profile.name);
    let view = slot_view(overview, profile, slot);
    #[allow(
        clippy::cast_precision_loss,
        reason = "a ratio of two sizes for a CSS fill"
    )]
    let fill = view
        .memory
        .map(|memory| (memory as f64 / profile.memory.max(1) as f64).min(1.0));
    let state = match (&slot.runner, view.job) {
        (None, _) => "idle",
        (Some(_), Some(_)) => "busy",
        (Some(_), None) => "starting",
    };
    let href = view.job.map_or(format!("#{}", view.key), |job| {
        format!("/jobs/{}", job.summary.id)
    });
    let repository = slot
        .runner
        .as_ref()
        .map(|runner| runner.repository.as_str());
    let link = link(&view.key, repository);
    let fill_id = format!("fill-{}", view.key);
    html! {
        a class=(format!("block {class} {state}")) href=(href)
            style=(format!("--size: {:.3}", gib(profile.memory)))
            aria-describedby=(lens_id(&view.key))
            data-on:pointerenter=(link.enter) data-on:focus=(link.enter)
            data-on:pointerleave=(link.pointer_leave) data-on:blur=(link.leave) data-class:linked=(link.linked) {
            @if let Some(fill) = fill {
                (parts.html(&fill_id, html! {
                    span.fill #(fill_id) aria-hidden="true" style=(format!("--fill: {fill:.3}")) {}
                }))
            }
            // Its name is what it shows, for voice control: the space joins the two as words.
            span.size { (format::bytes(profile.memory)) }
            " "
            span.name { (profile.name) " " (slot.slot) }
        }
    }
}

/// A card per slot: what runs in it, its current step, and its memory and CPU over the last minutes.
pub(crate) fn slots(overview: &Overview, parts: &Parts) -> Markup {
    let status = &overview.status;
    html! {
        section #slots .slots aria-labelledby="slots-title" {
            h2 #slots-title .visually-hidden { "Slots" }
            @if status.profiles.is_empty() {
                p.muted { "No profiles in runnerd.toml, so no slots." }
            }
            ul.slot-grid {
                @for profile in &status.profiles {
                    @for slot in &profile.slots {
                        (slot_card(overview, profile, slot, parts))
                    }
                }
            }
        }
    }
}

fn slot_card(
    overview: &Overview,
    profile: &ProfileStatus,
    slot: &SlotStatus,
    parts: &Parts,
) -> Markup {
    let class = profile_class(&overview.status, &profile.name);
    let view = slot_view(overview, profile, slot);
    let state = match (&slot.runner, view.job) {
        (None, _) => " idle",
        (Some(_), None) => " starting",
        (Some(_), Some(_)) => "",
    };
    let repository = slot
        .runner
        .as_ref()
        .map(|runner| runner.repository.as_str());
    let link = link(&view.key, repository);
    html! {
        li #(view.key) class=(format!("slot {class}{state}"))
            data-on:pointerenter=(link.enter) data-on:focusin=(link.enter)
            data-on:pointerleave=(link.pointer_leave) data-on:focusout=(link.leave) data-class:linked=(link.linked) {
            div.slot-head {
                h3.slot-name { (profile.name) " " (slot.slot) }
                span.slot-caps { (format::bytes(profile.memory)) " · " (profile.cpus) " CPUs" }
            }
            @match (&slot.runner, view.job) {
                (None, _) => {
                    @if profile.reseeding && slot.slot == 1 {
                        p.slot-idle { "Reseeding the profile's snapshot" }
                    } @else {
                        p.visually-hidden { "Idle" }
                    }
                }
                (Some(runner), None) => {
                    span.repo { (runner.repository) }
                    @let id = format!("{}-waiting", view.key);
                    p.slot-idle { "Waiting for its job " (parts.html(&id, html! { span.muted #(id) { (time_ago(runner.started_at, overview.now)) } })) }
                }
                (Some(_), Some(job)) => { (running_job(overview, profile, job, &view.key, parts)) }
            }
        }
    }
}

fn running_job(
    overview: &Overview,
    profile: &ProfileStatus,
    job: &Job,
    key: &str,
    parts: &Parts,
) -> Markup {
    let summary = &job.summary;
    let now = overview.now;
    let started = summary
        .timeline
        .started_at
        .unwrap_or(summary.timeline.queued_at);
    // The running step, or the last one done, and its place among the job's steps, as `runnerctl watch` counts it.
    let current = job
        .steps
        .iter()
        .position(|step| step.status == "in_progress")
        .or_else(|| {
            job.steps
                .iter()
                .rposition(|step| step.status == "completed")
        })
        .map(|place| (place + 1, &job.steps[place]));
    let samples = overview
        .samples
        .get(&summary.id)
        .map_or(&[][..], Vec::as_slice);
    let memory: Vec<(u64, u64)> = samples
        .iter()
        .map(|sample| (sample.at, sample.memory))
        .collect();
    let cpu: Vec<(u64, u64)> = samples
        .iter()
        .map(|sample| (sample.at, sample.cpu))
        .collect();
    let sparkline = |points, top, class: &'static str| {
        Sparkline {
            points,
            start: started.min(now),
            end: now,
            window: SPARK_WINDOW,
            top,
            class,
            live: Some(format!("{key}-{class}")),
        }
        .render(parts)
    };
    let last = samples.last();
    let figure = |class: &str, text: String| {
        let id = format!("{key}-{class}-now");
        parts.html(&id, html! { dd #(id) { (text) } })
    };
    let elapsed = format!("{key}-elapsed");
    html! {
        div.slot-title {
            a.slot-job href=(format!("/jobs/{}", summary.id)) {
                span.repo { (summary.repository) }
                span.job-name { (summary.name) }
            }
            (parts.html(&elapsed, html! {
                p.elapsed #(elapsed) { span.visually-hidden { "Running for " } (format::duration(now.saturating_sub(started))) }
            }))
        }
        p.step {
            @if let Some((place, step)) = current {
                span.step-count { (place) "/" (job.steps.len()) }
                " " (step.name)
            } @else {
                "Setting up"
            }
        }
        dl.slot-figures {
            div.memory {
                dt.visually-hidden { "Memory" }
                (figure("memory", last.map_or("–".to_owned(), |sample| format::bytes(sample.memory))))
                (sparkline(&memory, profile.memory, "memory"))
            }
            div.cpu {
                dt.visually-hidden { "CPU" }
                (figure("cpu", last.map_or("–".to_owned(), |sample| format!("{} cores", format::cores(sample.cpu)))))
                (sparkline(&cpu, u64::from(profile.cpus) * 1000, "cpu"))
            }
        }
    }
}

/// The slice's memory and CPU over the last half hour, against `MemoryMax` and the CPUs the slots may use.
pub(crate) fn host(overview: &Overview, parts: &Parts) -> Markup {
    let status = &overview.status;
    let now = overview.now;
    let samples = &overview.host.samples;
    let memory: Vec<(u64, u64)> = samples.iter().map(|s| (s.at, s.memory)).collect();
    let cpu: Vec<(u64, u64)> = samples.iter().map(|s| (s.at, s.cpu)).collect();
    let shown = |points: &[(u64, u64)]| {
        let since = now.saturating_sub(HOST_WINDOW);
        points
            .iter()
            .filter(|point| point.0 >= since)
            .map(|point| point.1)
            .max()
            .unwrap_or(0)
    };
    let cpus: u64 = status
        .profiles
        .iter()
        .map(|profile| u64::from(profile.cpus) * profile.slots.len() as u64)
        .sum();
    let gap = overview.host.interval.max(1) * 3;
    let memory_peak = shown(&memory);
    let cpu_peak = shown(&cpu);
    let memory_chart = TimeChart {
        title: format!(
            "Memory of {} over the last 30 minutes, sampled every {} s",
            status.budget.slice, overview.host.interval
        ),
        start: 0,
        end: now,
        window: Some(HOST_WINDOW),
        live: Some("host-memory".to_owned()),
        series: vec![Series {
            label: "memory".to_owned(),
            class: "memory",
            points: memory,
            area: true,
        }],
        limit: status
            .budget
            .memory_max
            .map(|max| (max, format!("MemoryMax {}", format::bytes(max)))),
        value: format::bytes,
        time: relative_clock,
        gap,
    };
    let memory_top = nice_top(
        memory_peak.max(status.budget.memory_max.unwrap_or(0)),
        Base::Binary,
    );
    let cpu_chart = TimeChart {
        title: format!(
            "CPU of {} over the last 30 minutes, sampled every {} s",
            status.budget.slice, overview.host.interval
        ),
        start: 0,
        end: now,
        window: Some(HOST_WINDOW),
        live: Some("host-cpu".to_owned()),
        series: vec![Series {
            label: "CPU".to_owned(),
            class: "cpu",
            points: cpu,
            area: true,
        }],
        limit: (cpus > 0).then(|| (cpus * 1000, format!("{cpus} CPUs of all slots"))),
        value: |millicores| format!("{} cores", format::cores(millicores)),
        time: relative_clock,
        gap,
    };
    let cpu_top = nice_top(cpu_peak.max(cpus * 1000), Base::Decimal);
    html! {
        section #host .host aria-labelledby="host-title" {
            h2 #host-title .visually-hidden { "Slice" }
            div.charts {
                div.chart-card {
                    h3 {
                        "Memory"
                        (reading(parts, "host-memory-now", &overview.host.samples.last().map_or("–".to_owned(), |s| format::bytes(s.memory)), &format::bytes(memory_peak)))
                    }
                    (memory_chart.render(memory_top, parts))
                }
                div.chart-card {
                    h3 {
                        "CPU"
                        (reading(parts, "host-cpu-now", &overview.host.samples.last().map_or("–".to_owned(), |s| format!("{} cores", format::cores(s.cpu))), &format::cores(cpu_peak)))
                    }
                    (cpu_chart.render(cpu_top, parts))
                }
            }
        }
    }
}

/// A chart's latest value and its peak, which change with every sample.
fn reading(parts: &Parts, id: &str, now: &str, peak: &str) -> Markup {
    parts.html(
        id,
        html! { span #(id) .reading { (now) span.muted { " · peak " (peak) } } },
    )
}

fn relative_clock(at: u64) -> String {
    format!("{} UTC", format::clock(at))
}

/// The configured repositories, with their queue and a pause or resume button, and below them a pause and a resume
/// of every one, each while some repository is not yet in that state. A single repository has only its own button.
pub(crate) fn repositories(status: &Status) -> Markup {
    let paused = status
        .repositories
        .iter()
        .filter(|repository| repository.paused)
        .count();
    let mut every = Vec::new();
    if status.repositories.len() > 1 {
        if paused < status.repositories.len() {
            every.push(("pause", "Pause all", "Pause all repositories"));
        }
        if paused > 0 {
            every.push(("resume", "Resume all", "Resume all repositories"));
        }
    }
    html! {
        section #repositories .repositories aria-labelledby="repositories-title" {
            h2 #repositories-title .visually-hidden { "Repositories" }
            @if status.repositories.is_empty() {
                p.muted { "No repositories yet. Add a " code { "[[repositories]]" } " table to runnerd.toml." }
            }
            ul.repo-list {
                @for repository in &status.repositories {
                    (repository_row(status, repository))
                }
                @if !every.is_empty() {
                    li.all {
                        @for (action, label, name) in every {
                            button.button-quiet type="button"
                                data-indicator:_busy_all=""
                                data-attr:aria-busy="$_busy_all && 'true'"
                                data-attr:disabled="$_busy_all"
                                data-on:click=(format!("@post('/v1/repositories/{action}')"))
                                // The name starts with the label, so voice control finds it by what it shows.
                                aria-label=(name) { (label) }
                        }
                    }
                }
            }
        }
    }
}

/// One repository's row; a pause or resume replaces it. Hovering it lights up the slots its runners hold and its
/// latest jobs.
pub(crate) fn repository_row(status: &Status, repository: &RepositoryStatus) -> Markup {
    let class = profile_class(status, &repository.profile);
    let (action, label) = if repository.paused {
        ("resume", "Resume")
    } else {
        ("pause", "Pause")
    };
    let held: Vec<String> = status
        .profiles
        .iter()
        .flat_map(|profile| {
            profile.slots.iter().filter_map(|slot| {
                slot.runner
                    .as_ref()
                    .filter(|runner| runner.repository == repository.name)
                    .map(|_| js(&slot_id(&profile.name, slot.slot)))
            })
        })
        .collect();
    let enter = format!("$_repo = {}", js(&repository.name));
    let linked = format!(
        "$_repo == {} || [{}].includes($_slot)",
        js(&repository.name),
        held.join(", ")
    );
    html! {
        li #(repository_id(&repository.name)) class=(format!("repository {class}"))
            data-on:pointerenter=(enter) data-on:focusin=(enter)
            data-on:pointerleave="evt.pointerType == 'mouse' && ($_repo = '')" data-on:focusout="$_repo = ''" data-class:linked=(linked) {
            div.repo-name {
                span.swatch aria-hidden="true" {}
                a href=(format!("/history?repository={}", repository.name)) { (repository.name) }
            }
            div.repo-meta {
                span { (repository.profile) }
                @if repository.queued_jobs > 0 { span { (repository.queued_jobs) " queued" } }
                @if repository.paused { span.badge.neutral { "paused" } }
            }
            // One busy signal per row, so a pending pause greys out only its own button.
            @let busy = format!("_busy_{}", repository_id(&repository.name).replace('-', "_"));
            button.button-quiet type="button"
                data-indicator=(busy)
                data-attr:aria-busy=(format!("${busy} && 'true'"))
                data-attr:disabled=(format!("${busy}"))
                data-on:click=(format!("@post('/v1/repositories/{}/{action}')", repository.name))
                aria-label=(format!("{label} {}", repository.name)) { (label) }
        }
    }
}

/// The jobs: those queued, oldest first, then the latest ones, any state. A queued job's row opens it on GitHub and
/// lights up its repository; a running job's row lights up its slot.
pub(crate) fn recent(overview: &Overview) -> Markup {
    let queued = &overview.status.queued;
    let more_queued = queued.len().saturating_sub(QUEUED_SHOWN);
    // The history has queued jobs too; the status's queue shows them.
    let latest = overview
        .recent
        .iter()
        .filter(|job| !queued.iter().any(|known| known.id == job.id));
    html! {
        section #recent .recent aria-labelledby="recent-title" {
            h2 #recent-title .visually-hidden { "Latest jobs" }
            @if overview.recent.is_empty() && queued.is_empty() {
                p.muted { "No jobs yet. Jobs show here once a runner of this machine takes one." }
            } @else {
                ul.job-list {
                    @for job in queued.iter().take(QUEUED_SHOWN) {
                        @let repository = js(&job.repository);
                        @let enter = format!("$_repo = {repository}");
                        li.queued data-class:linked=(format!("$_repo == {repository}"))
                            data-on:pointerenter=(enter) data-on:focusin=(enter)
                            data-on:pointerleave="evt.pointerType == 'mouse' && ($_repo = '')"
                            data-on:focusout="$_repo = ''" {
                            a href=(job.url.clone().unwrap_or_else(|| format!("/jobs/{}", job.id))) {
                                span.badge.queued { "queued" }
                                (job_name(job.workflow.as_deref(), &job.name))
                                span.repo { (job.repository) }
                                @if job.queued_at > 0 {
                                    span.when { (time_ago(job.queued_at, overview.now)) }
                                }
                            }
                        }
                    }
                    @if more_queued > 0 {
                        li.all { a href="/history?outcome=queued" { (more_queued) " more queued" } }
                    }
                    @for job in latest {
                        @let running = job.runner.as_ref().filter(|_| job.state == JobState::Running);
                        @let key = running.map(|runner| js(&slot_id(&runner.profile, runner.slot)));
                        @let linked = match &key {
                            Some(key) => format!("$_slot == {key} || $_repo == {}", js(&job.repository)),
                            None => format!("$_repo == {}", js(&job.repository)),
                        };
                        @let enter = key.as_ref().map(|key| format!("$_slot = {key}"));
                        li data-class:linked=(linked)
                            data-on:pointerenter=[enter.as_ref()] data-on:focusin=[enter.as_ref()]
                            data-on:pointerleave=[enter.as_ref().map(|_| "evt.pointerType == 'mouse' && ($_slot = '')")]
                            data-on:focusout=[enter.as_ref().map(|_| "$_slot = ''")] {
                            a href=(format!("/jobs/{}", job.id)) {
                                (badge(job))
                                (job_name(job.workflow.as_deref(), &job.name))
                                span.repo { (job.repository) }
                                span.when { (time_ago(job.timeline.queued_at, overview.now)) }
                            }
                        }
                    }
                    li.all { a href="/history" { "All history" } }
                }
            }
        }
    }
}

/// A job's name after its workflow's, which reads quieter: `CI / build`, as every client names a job.
fn job_name(workflow: Option<&str>, name: &str) -> Markup {
    html! {
        span.job-name {
            @if let Some(workflow) = workflow { span.workflow { (workflow) " / " } }
            (name)
        }
    }
}