telelogs 0.3.1

Telelogs desktop app: a native log viewer for Docker and Kubernetes
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
//! The window's root view: owns all app state and lays out the title bar, sidebar and
//! the active screen. Each screen renders from its own module.

mod add_source;
mod pages;
mod palette;
mod range;
mod selections;
mod sidebar;
mod stream;

use std::collections::{HashMap, HashSet};
use std::time::{Duration, SystemTime};

use futures::StreamExt;
use futures::channel::mpsc::UnboundedReceiver;
use gpui_kit::component::input::{InputEvent, InputState};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use telelog_core::{Filter, Level, LogRecord, SourceKind, Target};

use crate::client::{Client, ClientEvent};
use crate::theme::{self, MONO, tokens};
use crate::time_range::TimeRange;
use crate::ui::Icon;

actions!(telelogs, [ToggleCommandPalette, ToggleJsonView]);

/// Records kept in memory. Older ones are dropped; long retention lives in buckets.
pub const BUFFER: usize = 200_000;

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Screen {
    Stream,
    Sources,
    Storage,
    Team,
    Agents,
}

pub enum Status {
    Connecting,
    Connected,
    Disconnected { reason: String },
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum View {
    Rows,
    Json,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum LevelFilter {
    All,
    Error,
    Warn,
    Info,
    Debug,
}

impl LevelFilter {
    /// Each button picks one level, not "this level and worse": Warn shows warnings only.
    /// Debug also covers trace, the level below it.
    fn includes(self, level: Level) -> bool {
        match self {
            LevelFilter::All => true,
            LevelFilter::Error => level == Level::Error,
            LevelFilter::Warn => level == Level::Warn,
            LevelFilter::Info => level == Level::Info,
            LevelFilter::Debug => matches!(level, Level::Debug | Level::Trace),
        }
    }
}

pub struct Entry {
    pub id: u64,
    pub record: LogRecord,
}

/// Lines fetched from the server's archive bucket for the current time range.
pub enum ArchiveState {
    /// No bucket, or the range doesn't reach past the live buffer.
    Off,
    Loading,
    Loaded {
        lines: usize,
        truncated: bool,
    },
    Failed(String),
}

/// Archived entries get ids from their own range so they never collide with live ones.
const ARCHIVED_IDS: u64 = 1 << 62;

pub struct Workspace {
    server: String,
    client: Client,
    screen: Screen,
    status: Status,
    targets: Vec<Target>,
    /// Origins (target names) included in the stream. Missing means included.
    enabled: HashMap<String, bool>,
    /// Choices saved for this server, which decide for sources the first time they're seen.
    selections: selections::Selections,
    open_groups: HashSet<SourceKind>,
    /// Kubernetes namespaces expanded in the sidebar; all start collapsed.
    open_namespaces: HashSet<String>,

    entries: Vec<Entry>,
    next_id: u64,
    /// Oldest timestamp in `entries` per origin; that origin's archived lines from then on are
    /// already live.
    live_starts: HashMap<String, SystemTime>,
    /// Lines from the archive bucket that aren't in the live buffer, merged in by time.
    archived: Vec<Entry>,
    next_archived_id: u64,
    archive: ArchiveState,
    /// Number of the newest archive request; older answers are ignored.
    archive_request: u64,
    storage: Option<Result<telelog_proto::v1::StorageInfo, String>>,
    /// Indices into `archived` followed by `entries` (see [`Workspace::entry`]) that pass the filters.
    visible: Vec<usize>,
    filter: Filter,
    level: LevelFilter,
    range: TimeRange,
    range_open: bool,
    range_error: Option<String>,
    range_inputs: range::RangeInputs,
    view: View,
    follow: bool,
    selected: Option<u64>,
    copied: bool,

    filter_input: Entity<InputState>,
    /// The rows view: one item per `visible` line, sized to its wrapped text.
    rows: ListState,
    json_scroll: ScrollHandle,

    palette_open: bool,
    palette_input: Entity<InputState>,
    palette_index: usize,

    add_open: bool,
    add_kind: SourceKind,
    add_inputs: add_source::Inputs,

    focus: FocusHandle,
    _subscriptions: Vec<Subscription>,
    _pump: Task<()>,
    _range_tick: Task<()>,
}

impl Workspace {
    pub fn new(
        server: String,
        client: Client,
        mut events: UnboundedReceiver<ClientEvent>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Self {
        let filter_input = cx.new(|cx| InputState::new(window, cx).placeholder("Filter by text or container…"));
        let palette_input = cx.new(|cx| InputState::new(window, cx).placeholder("Type a command or search sources…"));
        let subscriptions = vec![
            cx.subscribe(&filter_input, |this, _, event, cx| {
                if let InputEvent::Change = event {
                    this.refilter(cx);
                }
            }),
            cx.subscribe(&palette_input, |this, _, event, cx| {
                if let InputEvent::Change = event {
                    this.palette_index = 0;
                    cx.notify();
                }
            }),
        ];

        // Drain events in batches so a burst of lines costs one re-render.
        let pump = cx.spawn(async move |this, cx| {
            while let Some(first) = events.next().await {
                let mut batch = vec![first];
                while let Ok(event) = events.try_recv() {
                    batch.push(event);
                }
                if this.update(cx, |this, cx| this.apply(batch, cx)).is_err() {
                    break;
                }
            }
        });

        // Relative ranges ("last 15 minutes") move with the clock, so old lines age out.
        let range_tick = cx.spawn(async move |this, cx| {
            loop {
                cx.background_executor().timer(Duration::from_secs(5)).await;
                let alive = this.update(cx, |this, cx| {
                    if this.range.is_relative() {
                        this.refilter(cx);
                    }
                });
                if alive.is_err() {
                    break;
                }
            }
        });

        let focus = cx.focus_handle();
        focus.focus(window, cx);

        let selections = selections::Selections::load(&server);
        Workspace {
            server,
            client,
            screen: Screen::Stream,
            status: Status::Connecting,
            targets: Vec::new(),
            enabled: HashMap::new(),
            selections,
            open_groups: HashSet::from([SourceKind::Docker, SourceKind::Kubernetes]),
            open_namespaces: HashSet::new(),
            entries: Vec::new(),
            next_id: 1,
            live_starts: HashMap::new(),
            archived: Vec::new(),
            next_archived_id: ARCHIVED_IDS,
            archive: ArchiveState::Off,
            archive_request: 0,
            storage: None,
            visible: Vec::new(),
            filter: Filter::default(),
            level: LevelFilter::All,
            range: TimeRange::All,
            range_open: false,
            range_error: None,
            range_inputs: range::RangeInputs::new(window, cx),
            view: View::Rows,
            follow: true,
            selected: None,
            copied: false,
            filter_input,
            rows: ListState::new(0, ListAlignment::Top, px(240.)),
            json_scroll: ScrollHandle::new(),
            palette_open: false,
            palette_input,
            palette_index: 0,
            add_open: false,
            add_kind: SourceKind::Docker,
            add_inputs: add_source::Inputs::new(window, cx),
            focus,
            _subscriptions: subscriptions,
            _pump: pump,
            _range_tick: range_tick,
        }
    }

    fn server_addr(&self) -> &str {
        self.server.trim_start_matches("http://").trim_start_matches("https://")
    }

    /// Whether a source is on when it first appears: as saved, or else `fallback`.
    fn first_choice(&self, source: SourceKind, name: &str, fallback: bool) -> bool {
        self.selections
            .choice(source == SourceKind::Kubernetes, name)
            .unwrap_or(fallback)
    }

    fn is_enabled(&self, origin: &str) -> bool {
        self.enabled.get(origin).copied().unwrap_or(true)
    }

    fn passes(&self, entry: &Entry) -> bool {
        self.is_enabled(&entry.record.origin)
            && self.level.includes(entry.record.level)
            && self.filter.matches(&entry.record)
    }

    fn apply(&mut self, batch: Vec<ClientEvent>, cx: &mut Context<Self>) {
        // Taken before the batch moves or drops lines, so a rebuild can find the same line.
        let anchor = self.scroll_anchor();
        let shown = self.visible.len();
        let mut rebuild = false;
        for event in batch {
            match event {
                ClientEvent::Connecting => {
                    if !matches!(self.status, Status::Disconnected { .. }) {
                        self.status = Status::Connecting;
                    }
                }
                ClientEvent::Connected { targets } => {
                    // The server resends backlog on reconnect, so start fresh.
                    self.entries.clear();
                    self.live_starts.clear();
                    self.selected = None;
                    rebuild = true;
                    self.client.fetch_storage();
                    for target in &targets {
                        let on = self.first_choice(target.source, &target.name, target.state == "running");
                        self.enabled.entry(target.name.clone()).or_insert(on);
                    }
                    self.targets = targets;
                    self.status = Status::Connected;
                }
                ClientEvent::Disconnected { reason } => self.status = Status::Disconnected { reason },
                ClientEvent::TargetChanged(target) => self.update_target(target),
                ClientEvent::Record(record) => {
                    self.note_target(&record);
                    let entry = Entry {
                        id: self.next_id,
                        record,
                    };
                    self.next_id += 1;
                    let timestamp = entry.record.timestamp;
                    let start = self.live_starts.entry(entry.record.origin.clone()).or_insert(timestamp);
                    if timestamp <= *start {
                        *start = timestamp;
                        // The boundary hiding this origin's archived duplicates moved.
                        rebuild |= !self.archived.is_empty();
                    }
                    if self.passes(&entry) {
                        self.visible.push(self.archived.len() + self.entries.len());
                    }
                    self.entries.push(entry);
                }
                ClientEvent::Archive { request, result } if request == self.archive_request => {
                    match result {
                        Ok(records) => {
                            let lines = records.len();
                            self.archived = records
                                .into_iter()
                                .map(|record| {
                                    self.next_archived_id += 1;
                                    Entry {
                                        id: self.next_archived_id,
                                        record,
                                    }
                                })
                                .collect();
                            self.archive = ArchiveState::Loaded {
                                lines,
                                truncated: lines >= crate::client::ARCHIVE_LIMIT as usize,
                            };
                        }
                        Err(e) => self.archive = ArchiveState::Failed(e),
                    }
                    rebuild = true;
                }
                ClientEvent::Archive { .. } => {}
                ClientEvent::Storage(result) => {
                    let enabled = matches!(&result, Ok(info) if info.enabled);
                    self.storage = Some(result);
                    if enabled && matches!(self.archive, ArchiveState::Off) {
                        self.load_archive();
                    }
                }
            }
        }

        if self.entries.len() > BUFFER {
            let excess = self.entries.len() - BUFFER;
            self.entries.drain(..excess);
            self.live_starts.clear();
            for e in &self.entries {
                let start = self
                    .live_starts
                    .entry(e.record.origin.clone())
                    .or_insert(e.record.timestamp);
                *start = (*start).min(e.record.timestamp);
            }
            rebuild = true;
        }
        if rebuild {
            self.rebuild_visible_from(anchor);
        } else {
            self.rows.splice(shown..shown, self.visible.len() - shown);
        }
        self.scroll_to_end_if_following();
        cx.notify();
    }

    /// The server follows containers as they start; the first line from one adds it to the sidebar.
    fn note_target(&mut self, record: &LogRecord) {
        if self.targets.iter().any(|t| t.name == record.origin) {
            return;
        }
        let id = record
            .labels
            .get("container_id")
            .cloned()
            .unwrap_or_else(|| record.origin.clone());
        self.targets.push(Target {
            id,
            name: record.origin.clone(),
            source: record.source,
            state: "running".into(),
            labels: record.labels.clone(),
        });
        let on = self.first_choice(record.source, &record.origin, true);
        self.enabled.entry(record.origin.clone()).or_insert(on);
    }

    /// Applies a lifecycle change from the server. Targets are matched by name, which is also how
    /// lines and toggles refer to them; a recreated container with the same name is the same target.
    fn update_target(&mut self, target: Target) {
        let position = self.targets.iter().position(|t| t.name == target.name);
        if target.state == "removed" {
            // Keep a removed container while its lines are still in the buffer, so they stay
            // filterable; otherwise drop it from the sidebar.
            let has_lines = self.entries.iter().any(|e| e.record.origin == target.name);
            match position {
                Some(ix) if has_lines => self.targets[ix].state = target.state,
                Some(ix) => {
                    self.targets.remove(ix);
                }
                None => {}
            }
            return;
        }
        let on = self.first_choice(target.source, &target.name, true);
        self.enabled.entry(target.name.clone()).or_insert(on);
        match position {
            Some(ix) => self.targets[ix] = target,
            None => self.targets.push(target),
        }
    }

    fn refilter(&mut self, cx: &mut Context<Self>) {
        let text = self.filter_input.read(cx).value();
        self.filter = Filter::new(&text);
        (self.filter.from, self.filter.to) = self.range.bounds(SystemTime::now());
        self.rebuild_visible();
        self.scroll_to_end_if_following();
        cx.notify();
    }

    /// The `i`th line of the combined list: archived lines first, then the live buffer.
    pub(super) fn entry(&self, i: usize) -> &Entry {
        match i.checked_sub(self.archived.len()) {
            Some(live) => &self.entries[live],
            None => &self.archived[i],
        }
    }

    /// The line at the top of the rows view and how far into it the view is scrolled, so the
    /// view can stay on it while the lines around it change. None while following.
    fn scroll_anchor(&self) -> Option<(u64, SystemTime, Pixels)> {
        if self.follow {
            return None;
        }
        let top = self.rows.logical_scroll_top();
        let entry = self.entry(*self.visible.get(top.item_ix)?);
        Some((entry.id, entry.record.timestamp, top.offset_in_item))
    }

    fn rebuild_visible(&mut self) {
        let anchor = self.scroll_anchor();
        self.rebuild_visible_from(anchor);
    }

    fn rebuild_visible_from(&mut self, anchor: Option<(u64, SystemTime, Pixels)>) {
        let archived: Vec<usize> = (0..self.archived.len())
            .filter(|&i| {
                let e = &self.archived[i];
                let duplicate = self
                    .live_starts
                    .get(&e.record.origin)
                    .is_some_and(|&start| e.record.timestamp >= start);
                !duplicate && self.passes(e)
            })
            .collect();
        let live: Vec<usize> = (0..self.entries.len())
            .filter(|&i| self.passes(&self.entries[i]))
            .map(|i| self.archived.len() + i)
            .collect();
        // Both are in time order; merge them so a removed container's archived lines sit
        // among the live lines of the same moment.
        let mut visible = Vec::with_capacity(archived.len() + live.len());
        let (mut a, mut l) = (archived.into_iter().peekable(), live.into_iter().peekable());
        while let (Some(&ai), Some(&li)) = (a.peek(), l.peek()) {
            if self.entry(ai).record.timestamp <= self.entry(li).record.timestamp {
                visible.push(ai);
                a.next();
            } else {
                visible.push(li);
                l.next();
            }
        }
        visible.extend(a);
        visible.extend(l);
        self.visible = visible;

        self.rows
            .reset_with_uniform_height(self.visible.len(), px(stream::ROW_HEIGHT));
        if let Some((id, timestamp, offset)) = anchor {
            // The same line if it's still shown, otherwise the first one after it.
            let (item_ix, offset_in_item) = match self.visible.iter().position(|&i| self.entry(i).id == id) {
                Some(ix) => (ix, offset),
                None => (
                    self.visible
                        .partition_point(|&i| self.entry(i).record.timestamp < timestamp),
                    px(0.),
                ),
            };
            self.rows.scroll_to(ListOffset {
                item_ix,
                offset_in_item,
            });
        }
    }

    /// Fetches the time range from the archive bucket, minus what the live buffer already holds
    /// for each origin.
    pub(super) fn load_archive(&mut self) {
        self.archive_request += 1;
        self.archived.clear();
        self.archive = ArchiveState::Off;
        let bucket = matches!(&self.storage, Some(Ok(info)) if info.enabled);
        if !bucket || self.range == TimeRange::All {
            return;
        }
        let now = SystemTime::now();
        let (from, to) = self.range.bounds(now);
        let to = to.unwrap_or(now);
        if from.is_some_and(|from| from > to) {
            return;
        }
        self.archive = ArchiveState::Loading;
        self.client
            .query_archive(self.archive_request, from, to, self.live_starts.clone());
    }

    fn scroll_to_end_if_following(&self) {
        if !self.follow || self.visible.is_empty() {
            return;
        }
        match self.view {
            View::Rows => self.rows.scroll_to_end(),
            View::Json => self.json_scroll.scroll_to_bottom(),
        }
    }

    fn set_follow(&mut self, follow: bool, cx: &mut Context<Self>) {
        if self.follow != follow {
            self.follow = follow;
            self.scroll_to_end_if_following();
            cx.notify();
        }
    }

    fn set_view(&mut self, view: View, cx: &mut Context<Self>) {
        self.view = view;
        self.screen = Screen::Stream;
        self.scroll_to_end_if_following();
        cx.notify();
    }

    fn toggle_target(&mut self, origin: &str, cx: &mut Context<Self>) {
        let on = !self.is_enabled(origin);
        self.enabled.insert(origin.to_string(), on);
        self.selections.set_target(origin, on);
        self.selections.save(&self.server);
        self.rebuild_visible();
        cx.notify();
    }

    /// Turns every target in a Kubernetes namespace on, or off when they're all on already.
    fn toggle_namespace(&mut self, namespace: &str, cx: &mut Context<Self>) {
        let names: Vec<String> = self
            .targets
            .iter()
            .filter(|target| target.source == SourceKind::Kubernetes && namespace_of(&target.name) == namespace)
            .map(|target| target.name.clone())
            .collect();
        let on = !names.iter().all(|name| self.is_enabled(name));
        for name in names {
            self.enabled.insert(name, on);
        }
        self.selections.set_namespace(namespace, on);
        self.selections.save(&self.server);
        self.rebuild_visible();
        cx.notify();
    }

    /// "Tail only this": include one origin, exclude the rest.
    fn solo(&mut self, origin: &str, cx: &mut Context<Self>) {
        for target in &self.targets {
            self.enabled.insert(target.name.clone(), target.name == origin);
        }
        self.enabled.insert(origin.to_string(), true);
        self.screen = Screen::Stream;
        self.rebuild_visible();
        self.scroll_to_end_if_following();
        cx.notify();
    }

    fn set_filter_text(&mut self, text: String, window: &mut Window, cx: &mut Context<Self>) {
        self.filter_input
            .update(cx, |input, cx| input.set_value(text, window, cx));
        self.refilter(cx);
    }

    fn reset_filters(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.level = LevelFilter::All;
        self.range = TimeRange::All;
        for target in &self.targets {
            self.enabled.insert(target.name.clone(), target.state == "running");
        }
        self.set_filter_text(String::new(), window, cx);
    }

    fn go(&mut self, screen: Screen, cx: &mut Context<Self>) {
        if screen == Screen::Storage {
            self.client.fetch_storage();
        }
        self.screen = screen;
        self.selected = None;
        cx.notify();
    }

    fn toggle_theme(&mut self, cx: &mut Context<Self>) {
        let dark = tokens(cx).dark;
        theme::apply(!dark, cx);
        cx.notify();
    }

    fn clear_stream(&mut self, cx: &mut Context<Self>) {
        self.entries.clear();
        self.live_starts.clear();
        self.archived.clear();
        self.archive = ArchiveState::Off;
        self.archive_request += 1;
        self.visible.clear();
        self.rows.reset(0);
        self.selected = None;
        cx.notify();
    }

    fn selected_entry(&self) -> Option<&Entry> {
        let id = self.selected?;
        // Ids are increasing within each list, so the entry can be found by binary search.
        let list = if id > ARCHIVED_IDS {
            &self.archived
        } else {
            &self.entries
        };
        let ix = list.binary_search_by_key(&id, |e| e.id).ok()?;
        list.get(ix)
    }

    /// Lines `origin` wrote during the last minute (by log timestamp, so backlog doesn't count).
    fn lines_per_minute(&self, origin: &str) -> usize {
        let cutoff = SystemTime::now() - std::time::Duration::from_secs(60);
        self.entries
            .iter()
            .rev()
            .take_while(|e| e.record.timestamp >= cutoff)
            .filter(|e| e.record.origin == origin)
            .count()
    }

    fn oldest_record(&self) -> Option<SystemTime> {
        self.entries.first().map(|e| e.record.timestamp)
    }

    fn open_palette(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.palette_open = true;
        self.add_open = false;
        self.palette_index = 0;
        self.palette_input.update(cx, |input, cx| {
            input.set_value("", window, cx);
            input.focus(window, cx);
        });
        cx.notify();
    }

    fn close_overlays(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.palette_open = false;
        self.add_open = false;
        self.focus.focus(window, cx);
        cx.notify();
    }

    fn open_add_source(&mut self, cx: &mut Context<Self>) {
        self.add_open = true;
        self.palette_open = false;
        cx.notify();
    }

    /// Escape, arrows and Enter are handled here, before inputs see them, so they work
    /// while typing in the command palette.
    fn capture_key(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
        let key = event.keystroke.key.as_str();
        if self.palette_open {
            let count = self.palette_commands(cx).len();
            match key {
                "escape" => self.close_overlays(window, cx),
                "down" if count > 0 => self.palette_index = (self.palette_index + 1) % count,
                "up" if count > 0 => self.palette_index = (self.palette_index + count - 1) % count,
                "enter" => {
                    if let Some(command) = self.palette_commands(cx).into_iter().nth(self.palette_index) {
                        self.close_overlays(window, cx);
                        self.run(command.action, window, cx);
                    }
                }
                _ => return,
            }
            cx.stop_propagation();
            cx.notify();
        } else if key == "escape" {
            // Close the innermost thing that is open: range picker, dialog, then selection.
            if self.range_open {
                self.close_range(cx);
            } else if self.add_open {
                self.close_overlays(window, cx);
            } else if self.selected.is_some() {
                self.selected = None;
                cx.notify();
            } else {
                return;
            }
            cx.stop_propagation();
        }
    }

    fn render_titlebar(&self, cx: &mut Context<Self>) -> impl IntoElement + use<> {
        let t = tokens(cx);
        div()
            .h(px(40.))
            .flex_none()
            .relative()
            .flex()
            .items_center()
            .px(px(14.))
            .bg(t.bg2)
            .border_b_1()
            .border_color(t.line)
            .on_mouse_down(MouseButton::Left, |event, window, _| {
                if event.click_count == 2 {
                    window.titlebar_double_click();
                } else {
                    window.start_window_move();
                }
            })
            .child(
                div()
                    .absolute()
                    .inset_0()
                    .flex()
                    .items_center()
                    .justify_center()
                    .gap(px(8.))
                    .text_size(px(12.5))
                    .font_weight(FontWeight::MEDIUM)
                    .text_color(t.fg2)
                    .child("telelogs")
                    .child(div().text_color(t.fg3).child("—"))
                    .child(
                        div()
                            .font_family(MONO)
                            .text_size(px(12.))
                            .child(self.server_addr().to_string()),
                    ),
            )
            .child(div().flex_1())
            .child(
                div()
                    .id("theme-toggle")
                    .w(px(28.))
                    .h(px(26.))
                    .flex()
                    .items_center()
                    .justify_center()
                    .rounded(px(6.))
                    .border_1()
                    .border_color(t.line2)
                    .bg(t.bg)
                    .cursor_pointer()
                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
                    .on_click(cx.listener(|this, _, _, cx| this.toggle_theme(cx)))
                    .child(crate::ui::icon(if t.dark { Icon::Sun } else { Icon::Moon }, 14., t.fg2)),
            )
    }

    fn render_screen(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
        match self.screen {
            Screen::Stream => self.render_stream(window, cx).into_any_element(),
            Screen::Sources => self.render_sources(cx).into_any_element(),
            Screen::Storage => self.render_storage(cx).into_any_element(),
            Screen::Team => self.render_team(cx).into_any_element(),
            Screen::Agents => self.render_agents(cx).into_any_element(),
        }
    }
}

impl Render for Workspace {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let t = tokens(cx);
        let screen = self.render_screen(window, cx);
        let palette = self.palette_open.then(|| self.render_palette(cx));
        let add = self.add_open.then(|| self.render_add_source(cx));

        div()
            .key_context("Workspace")
            .track_focus(&self.focus)
            .on_action(cx.listener(|this, _: &ToggleCommandPalette, window, cx| {
                if this.palette_open {
                    this.close_overlays(window, cx);
                } else {
                    this.open_palette(window, cx);
                }
            }))
            .on_action(cx.listener(|this, _: &ToggleJsonView, _, cx| {
                let view = if this.view == View::Rows {
                    View::Json
                } else {
                    View::Rows
                };
                this.set_view(view, cx);
            }))
            .capture_key_down(cx.listener(Self::capture_key))
            .relative()
            .size_full()
            .flex()
            .flex_col()
            .bg(t.bg)
            .font_family(theme::SANS)
            .text_color(t.fg)
            .child(self.render_titlebar(cx))
            .child(
                div().flex_1().min_h_0().flex().child(self.render_sidebar(cx)).child(
                    div()
                        .flex_1()
                        .min_w_0()
                        .h_full()
                        .flex()
                        .flex_col()
                        .bg(t.bg)
                        .child(screen),
                ),
            )
            .children(palette)
            .children(add)
    }
}

/// A full-window scrim that closes overlays when clicked outside `panel`.
fn modal(t: crate::theme::Tokens, panel: impl IntoElement, top: Option<f32>, cx: &mut Context<Workspace>) -> Div {
    div()
        .absolute()
        .inset_0()
        .occlude()
        .bg(t.scrim)
        .flex()
        .justify_center()
        .map(|el| match top {
            Some(top) => el.items_start().pt(px(top)),
            None => el.items_center(),
        })
        .on_mouse_down(
            MouseButton::Left,
            cx.listener(|this, _, window, cx| this.close_overlays(window, cx)),
        )
        .child(panel)
}

/// The namespace of a Kubernetes target, the first part of `namespace/pod/container`.
pub(super) fn namespace_of(name: &str) -> &str {
    name.split_once('/').map_or(name, |(namespace, _)| namespace)
}

/// A short name for lists and log rows. Kubernetes targets are `namespace/pod/container`, too
/// long to tell apart when cut off. They show as the app plus the pod's own suffix, so replicas
/// stay distinct (`auth-svc-t2xv7`), with `/container` when the name doesn't already say it
/// (`kong-gateway-7d79c/proxy`). The full name stays in the detail panel and on Sources.
pub(super) fn display_name(
    source: SourceKind,
    name: &str,
    labels: &std::collections::BTreeMap<String, String>,
) -> String {
    if source != SourceKind::Kubernetes {
        return name.to_string();
    }
    let mut parts = name.splitn(3, '/').skip(1);
    let (Some(pod), Some(container)) = (parts.next(), parts.next()) else {
        return name.to_string();
    };
    let owner = match (labels.get("app"), pod.rsplit_once('-')) {
        (Some(app), Some((_, suffix))) if pod != app => format!("{app}-{suffix}"),
        _ => pod.to_string(),
    };
    if owner.contains(container) {
        owner
    } else {
        format!("{owner}/{container}")
    }
}

#[cfg(test)]
mod tests {
    use telelog_core::Level;

    use super::LevelFilter;

    #[test]
    fn level_buttons_pick_one_level() {
        let all = [
            Level::Unknown,
            Level::Trace,
            Level::Debug,
            Level::Info,
            Level::Warn,
            Level::Error,
        ];
        let shown = |filter: LevelFilter| all.into_iter().filter(|&l| filter.includes(l)).collect::<Vec<_>>();
        assert_eq!(shown(LevelFilter::All), all);
        assert_eq!(shown(LevelFilter::Error), [Level::Error]);
        assert_eq!(shown(LevelFilter::Warn), [Level::Warn]);
        assert_eq!(shown(LevelFilter::Info), [Level::Info]);
        assert_eq!(shown(LevelFilter::Debug), [Level::Trace, Level::Debug]);
    }

    #[test]
    fn finds_kubernetes_namespace() {
        use super::namespace_of;
        assert_eq!(
            namespace_of("cert-manager/cert-manager-6d8b/controller"),
            "cert-manager"
        );
        assert_eq!(namespace_of("default/auth-svc-54bf699c7d-t2xv7/auth"), "default");
        assert_eq!(namespace_of("odd"), "odd");
    }

    #[test]
    fn shortens_kubernetes_names() {
        use std::collections::BTreeMap;
        use telelog_core::SourceKind;

        use super::display_name;
        let app = |name: &str| BTreeMap::from([("app".to_string(), name.to_string())]);
        let k8s = |name: &str, labels: &BTreeMap<String, String>| display_name(SourceKind::Kubernetes, name, labels);
        // Replicas of one deployment stay distinct, and a container named like its app is implied.
        assert_eq!(
            k8s("default/auth-svc-54bf699c7d-t2xv7/auth", &app("auth-svc")),
            "auth-svc-t2xv7"
        );
        assert_eq!(
            k8s("default/auth-svc-54bf699c7d-tp7ct/auth", &app("auth-svc")),
            "auth-svc-tp7ct"
        );
        assert_eq!(
            k8s("kong/kong-gateway-57d64f6696-7d79c/proxy", &app("kong-gateway")),
            "kong-gateway-7d79c/proxy"
        );
        assert_eq!(k8s("kafka/djplatform-kafka-combined-0/kafka", &app("kafka")), "kafka-0");
        assert_eq!(k8s("demo/flaky/worker", &app("flaky")), "flaky/worker");
        assert_eq!(k8s("demo/flaky/worker", &BTreeMap::new()), "flaky/worker");
        assert_eq!(k8s("odd", &BTreeMap::new()), "odd");
        assert_eq!(
            display_name(SourceKind::Docker, "shop-api-1", &app("api")),
            "shop-api-1"
        );
    }
}