bee-tui 1.6.0

Production-grade k9s-style terminal cockpit for Ethereum Swarm Bee node operators.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
//! Tabbed bottom-pane that replaces the previous single-stream
//! `bee::http` tail. Six tabs split the log space along two axes:
//!
//! 1. **Bee severity tabs** — Errors / Warning / Info / Debug. Filled
//!    by parsing the supervised Bee node's stdout (increment 3).
//! 2. **Bee HTTP tab** — the served-request log line filtered out of
//!    the same Bee stream (increment 4).
//! 3. **bee::http tab** — bee-tui's *own* outbound calls (the legacy
//!    `CommandLog` view). Kept as a tab because it's still the trust
//!    anchor for every gauge in the cockpit.
//!
//! Increment 2 (this file) ships the UI scaffolding: tab state
//! machine, ring buffers per tab, height-clamping resize, and
//! state persistence for the operator's last height + active tab.
//! The four Bee-fed tabs render an "(awaiting bee log...)" placeholder
//! until the supervisor wires real entries through.

use std::collections::VecDeque;

use color_eyre::Result;
use ratatui::{
    Frame,
    layout::{Constraint, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph},
};

use super::Component;
use crate::action::Action;
use crate::log_capture::{CockpitCapture, CockpitEntry, LogCapture, LogEntry};
use crate::state::{LOG_PANE_MAX_HEIGHT, LOG_PANE_MIN_HEIGHT};
use crate::theme;

/// Capacity of each Bee-side tab's ring buffer. Generous enough to
/// catch a burst of errors while staying memory-cheap.
const BEE_TAB_RING_CAPACITY: usize = 500;

/// The six tabs, in display order. Order is `Errors → Debug` so the
/// most operator-relevant severity is leftmost (matches reading
/// direction).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogTab {
    Errors,
    Warning,
    Info,
    Debug,
    BeeHttp,
    SelfHttp,
    /// Cockpit-internal events: anything bee-tui emits that isn't a
    /// `bee::http` request — supervisor lifecycle, watch poll loops,
    /// command-bar dispatches, etc.
    Cockpit,
}

impl LogTab {
    pub const ALL: [LogTab; 7] = [
        LogTab::Errors,
        LogTab::Warning,
        LogTab::Info,
        LogTab::Debug,
        LogTab::BeeHttp,
        LogTab::SelfHttp,
        LogTab::Cockpit,
    ];

    /// Parse the kebab-case form persisted in `state.toml`. Unknown
    /// strings → SelfHttp (the only tab guaranteed to have data
    /// regardless of whether [bee] is configured).
    pub fn from_kebab(s: &str) -> Self {
        match s {
            "errors" => Self::Errors,
            "warning" => Self::Warning,
            "info" => Self::Info,
            "debug" => Self::Debug,
            "bee-http" => Self::BeeHttp,
            "self-http" => Self::SelfHttp,
            "cockpit" => Self::Cockpit,
            _ => Self::SelfHttp,
        }
    }

    pub fn to_kebab(self) -> &'static str {
        match self {
            Self::Errors => "errors",
            Self::Warning => "warning",
            Self::Info => "info",
            Self::Debug => "debug",
            Self::BeeHttp => "bee-http",
            Self::SelfHttp => "self-http",
            Self::Cockpit => "cockpit",
        }
    }

    /// Short label rendered in the tab strip.
    pub fn label(self) -> &'static str {
        match self {
            Self::Errors => "Errors",
            Self::Warning => "Warn",
            Self::Info => "Info",
            Self::Debug => "Debug",
            Self::BeeHttp => "Bee HTTP",
            Self::SelfHttp => "bee::http",
            Self::Cockpit => "Cockpit",
        }
    }

    /// Index into [`LogTab::ALL`].
    fn index(self) -> usize {
        Self::ALL.iter().position(|t| *t == self).unwrap_or(5)
    }

    fn from_index(i: usize) -> Self {
        Self::ALL.get(i).copied().unwrap_or(Self::SelfHttp)
    }
}

/// Single line on a Bee-side tab. The supervisor's log tailer
/// (increment 3) builds these from parsed Bee log entries; for now
/// the structure exists so the renderer + key handling can be
/// validated end-to-end against synthetic inputs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BeeLogLine {
    /// `time` field from the source log line, rendered verbatim.
    pub timestamp: String,
    /// `logger` field — usually `node/<subsystem>`.
    pub logger: String,
    /// `msg` field plus any extra key-value pairs the parser kept.
    pub message: String,
}

/// Renderable row inside the active tab. Pure data so the renderer
/// stays straightforward and snapshot tests can lock layout.
pub enum LogRow<'a> {
    Self_(&'a LogEntry),
    Bee(&'a BeeLogLine),
}

/// Buffers feeding the Bee-side tabs. Each tab has its own ring
/// buffer so a noisy debug stream never evicts a precious error line.
#[derive(Debug, Default)]
pub struct BeeLogBuffers {
    pub errors: VecDeque<BeeLogLine>,
    pub warning: VecDeque<BeeLogLine>,
    pub info: VecDeque<BeeLogLine>,
    pub debug: VecDeque<BeeLogLine>,
    pub bee_http: VecDeque<BeeLogLine>,
}

impl BeeLogBuffers {
    fn buffer_for(&self, tab: LogTab) -> Option<&VecDeque<BeeLogLine>> {
        match tab {
            LogTab::Errors => Some(&self.errors),
            LogTab::Warning => Some(&self.warning),
            LogTab::Info => Some(&self.info),
            LogTab::Debug => Some(&self.debug),
            LogTab::BeeHttp => Some(&self.bee_http),
            LogTab::SelfHttp | LogTab::Cockpit => None,
        }
    }

    /// Number of entries on a given tab. Used by the tab strip's
    /// counter chips ("Errors 3" etc).
    pub fn count(&self, tab: LogTab) -> usize {
        self.buffer_for(tab).map(|b| b.len()).unwrap_or(0)
    }
}

/// The component itself. Owns the tab state + ring buffers; reads
/// the bee::http capture from a borrowed handle, same as the legacy
/// CommandLog did.
pub struct LogPane {
    capture: Option<LogCapture>,
    self_http_entries: Vec<LogEntry>,
    cockpit_capture: Option<CockpitCapture>,
    cockpit_entries: Vec<CockpitEntry>,
    bee_buffers: BeeLogBuffers,
    active_tab: LogTab,
    /// Height in lines including the title strip + borders.
    height: u16,
    /// Set by [`spawn_active`] when bee-tui is the supervisor — toggles
    /// placeholder text on the Bee-side tabs from "configure [bee]"
    /// to "(awaiting first log line)".
    spawn_active: bool,
    /// Scroll offset for the active tab, in lines from the bottom.
    /// 0 = auto-tail (default; latest entries at the bottom). When
    /// non-zero, new entries arriving auto-bump the offset to keep
    /// the visible window stable. Reset to 0 on tab switch.
    scroll_offset: usize,
    /// Horizontal scroll offset in characters. Bee log lines often
    /// run past the pane width; this lets the operator pan right to
    /// see the truncated tail. Reset on tab switch.
    h_scroll_offset: u16,
}

impl LogPane {
    pub fn new(capture: Option<LogCapture>, initial_tab: LogTab, initial_height: u16) -> Self {
        Self {
            capture,
            self_http_entries: Vec::new(),
            cockpit_capture: None,
            cockpit_entries: Vec::new(),
            bee_buffers: BeeLogBuffers::default(),
            active_tab: initial_tab,
            height: initial_height.clamp(LOG_PANE_MIN_HEIGHT, LOG_PANE_MAX_HEIGHT),
            spawn_active: false,
            scroll_offset: 0,
            h_scroll_offset: 0,
        }
    }

    /// Attach the cockpit-capture ring buffer so the Cockpit tab can
    /// render events bee-tui itself emitted (everything that isn't
    /// `bee::http`). Wired by [`App::new`] after
    /// [`crate::logging::init`] has installed the capture.
    pub fn set_cockpit_capture(&mut self, cap: CockpitCapture) {
        self.cockpit_capture = Some(cap);
    }

    pub fn active_tab(&self) -> LogTab {
        self.active_tab
    }

    pub fn height(&self) -> u16 {
        self.height
    }

    /// Tell the pane bee-tui is acting as the supervisor (so the
    /// placeholder changes from "configure [bee]" to "(awaiting first
    /// log line)"). Called once at startup; cheap to call repeatedly.
    pub fn set_spawn_active(&mut self, active: bool) {
        self.spawn_active = active;
    }

    /// Cycle to the next tab (left → right, wrapping). Returns the
    /// new active tab so callers can persist state without re-reading.
    /// Resets the scroll offset — the new tab's content has nothing
    /// to do with where we were on the old one.
    pub fn next_tab(&mut self) -> LogTab {
        let i = (self.active_tab.index() + 1) % LogTab::ALL.len();
        self.active_tab = LogTab::from_index(i);
        self.scroll_offset = 0;
        self.h_scroll_offset = 0;
        self.active_tab
    }

    /// Cycle to the previous tab (right → left, wrapping).
    pub fn prev_tab(&mut self) -> LogTab {
        let len = LogTab::ALL.len();
        let i = (self.active_tab.index() + len - 1) % len;
        self.active_tab = LogTab::from_index(i);
        self.scroll_offset = 0;
        self.h_scroll_offset = 0;
        self.active_tab
    }

    /// Scroll the active tab up by `lines` (toward older entries).
    /// Clamped at draw-time to the buffer length so the user can't
    /// scroll past the top. `lines = 1` is the per-keystroke step;
    /// callers can pass a larger value for page-scrolling.
    pub fn scroll_up(&mut self, lines: usize) {
        self.scroll_offset = self.scroll_offset.saturating_add(lines);
    }

    /// Scroll the active tab down by `lines` (toward newer entries /
    /// the tail). Saturates at 0, which is the auto-tail state.
    pub fn scroll_down(&mut self, lines: usize) {
        self.scroll_offset = self.scroll_offset.saturating_sub(lines);
    }

    /// Snap back to auto-tail mode (scroll_offset = 0). The pane
    /// resumes following new entries as they arrive. Also resets
    /// horizontal pan because operators usually want both axes
    /// reset together when "going back to live."
    pub fn resume_tail(&mut self) {
        self.scroll_offset = 0;
        self.h_scroll_offset = 0;
    }

    /// Pan the active tab right by `cols` characters. Bee log lines
    /// often run past the pane width; ratatui truncates them at the
    /// right edge by default so we add a horizontal scroll to let
    /// operators read the tail.
    pub fn scroll_right(&mut self, cols: u16) {
        self.h_scroll_offset = self.h_scroll_offset.saturating_add(cols);
    }

    /// Pan the active tab left by `cols` characters. Saturates at 0
    /// (the natural left edge).
    pub fn scroll_left(&mut self, cols: u16) {
        self.h_scroll_offset = self.h_scroll_offset.saturating_sub(cols);
    }

    /// Reset horizontal pan to the left edge without touching the
    /// vertical scroll. Used when operators want the line start
    /// back without leaving the historical window.
    pub fn reset_h_scroll(&mut self) {
        self.h_scroll_offset = 0;
    }

    /// Current horizontal scroll offset. Exposed for tests + the
    /// title-strip indicator.
    pub fn h_scroll_offset(&self) -> u16 {
        self.h_scroll_offset
    }

    /// `true` when the pane is auto-tailing (the default state).
    pub fn is_tailing(&self) -> bool {
        self.scroll_offset == 0
    }

    /// Lines the pane is currently scrolled back from the tail.
    /// Useful for rendering "[paused N]" indicators in the title.
    pub fn scroll_offset(&self) -> usize {
        self.scroll_offset
    }

    /// Grow the pane by one line. Returns the new height. No-op once
    /// the cap is hit.
    pub fn grow(&mut self) -> u16 {
        self.height = (self.height + 1).min(LOG_PANE_MAX_HEIGHT);
        self.height
    }

    /// Shrink the pane by one line. Returns the new height. No-op
    /// once the floor is hit.
    pub fn shrink(&mut self) -> u16 {
        self.height = self.height.saturating_sub(1).max(LOG_PANE_MIN_HEIGHT);
        self.height
    }

    /// Push a Bee log line to the appropriate tab. The supervisor's
    /// log tailer calls this for each parsed line. Bounded — when
    /// the ring is full the oldest entry is evicted.
    ///
    /// Scroll-stability: if this push lands on the *active* tab
    /// AND we're currently scrolled back (not auto-tailing), bump
    /// `scroll_offset` so the visible window stays anchored on the
    /// same content rather than drifting upward as new lines push
    /// the old ones up.
    pub fn push_bee(&mut self, tab: LogTab, line: BeeLogLine) {
        let buf = match tab {
            LogTab::Errors => &mut self.bee_buffers.errors,
            LogTab::Warning => &mut self.bee_buffers.warning,
            LogTab::Info => &mut self.bee_buffers.info,
            LogTab::Debug => &mut self.bee_buffers.debug,
            LogTab::BeeHttp => &mut self.bee_buffers.bee_http,
            LogTab::SelfHttp | LogTab::Cockpit => return, // capture-fed tabs
        };
        let was_full = buf.len() == BEE_TAB_RING_CAPACITY;
        if was_full {
            buf.pop_front();
        }
        buf.push_back(line);
        // Stabilise the user's view if they're scrolled back on
        // this same tab. When the ring is already full the eviction
        // already shifted our content by 1, so the offset doesn't
        // need to bump — the visible range stays in place.
        if tab == self.active_tab && self.scroll_offset > 0 && !was_full {
            self.scroll_offset = self.scroll_offset.saturating_add(1);
        }
    }

    fn pull_self_http(&mut self) {
        if let Some(c) = &self.capture {
            let new = c.snapshot();
            // Same stability logic as push_bee: when the operator
            // is scrolled back on the SelfHttp tab and the capture
            // grew by N entries, bump the offset by N so the visible
            // range doesn't drift.
            if self.active_tab == LogTab::SelfHttp && self.scroll_offset > 0 {
                let delta = new.len().saturating_sub(self.self_http_entries.len());
                if delta > 0 {
                    self.scroll_offset = self.scroll_offset.saturating_add(delta);
                }
            }
            self.self_http_entries = new;
        }
    }

    fn pull_cockpit(&mut self) {
        if let Some(c) = &self.cockpit_capture {
            let new = c.snapshot();
            if self.active_tab == LogTab::Cockpit && self.scroll_offset > 0 {
                let delta = new.len().saturating_sub(self.cockpit_entries.len());
                if delta > 0 {
                    self.scroll_offset = self.scroll_offset.saturating_add(delta);
                }
            }
            self.cockpit_entries = new;
        }
    }
}

impl Component for LogPane {
    fn update(&mut self, action: Action) -> Result<Option<Action>> {
        if matches!(action, Action::Tick) {
            self.pull_self_http();
            self.pull_cockpit();
        }
        Ok(None)
    }

    fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> {
        let t = theme::active();
        let active = self.active_tab;

        // Clamp the scroll offset against what the active tab can
        // actually scroll. Pane content area excludes top + bottom
        // borders; we approximate from the outer area here.
        let content_h = (area.height as usize).saturating_sub(2);
        let total_lines = self.active_tab_total_lines();
        let max_offset = total_lines.saturating_sub(content_h);
        if self.scroll_offset > max_offset {
            self.scroll_offset = max_offset;
        }

        let block = Block::default().borders(Borders::ALL).title(tab_title_line(
            active,
            &self.bee_buffers,
            self.scroll_offset,
            self.h_scroll_offset,
            t,
        ));
        let inner = block.inner(area);
        frame.render_widget(block, area);

        let content_area = Layout::vertical([Constraint::Min(0)])
            .split(inner)
            .first()
            .copied()
            .unwrap_or(inner);

        let lines: Vec<Line> = match active {
            LogTab::SelfHttp => render_self_http(&self.self_http_entries, t),
            LogTab::Cockpit => render_cockpit(&self.cockpit_entries, t),
            tab => render_bee_tab(&self.bee_buffers, tab, self.spawn_active, t),
        };

        // Pick the visible window: tail semantics + scroll offset.
        // - tailing (offset = 0): show the last `render_h` lines.
        // - scrolled back: show [end-render_h .. end), where
        //   end = total - offset.
        let render_h = content_area.height as usize;
        let visible: Vec<Line> = if lines.len() > render_h {
            let end = lines.len().saturating_sub(self.scroll_offset);
            let start = end.saturating_sub(render_h);
            lines.into_iter().skip(start).take(end - start).collect()
        } else {
            lines
        };

        // Vertical position is already encoded by the visible
        // window slice; use ratatui's scroll() for the horizontal
        // axis only. (Mixing scroll() with our slice-windowed
        // visible vec works because the slice is what we want to
        // render — scroll() merely shifts each rendered line left
        // by `h_scroll_offset` columns.)
        frame.render_widget(
            Paragraph::new(visible).scroll((0, self.h_scroll_offset)),
            content_area,
        );
        Ok(())
    }
}

impl LogPane {
    /// Number of payload lines the active tab currently has. Used
    /// by `draw()` to clamp the scroll offset and by tests.
    pub fn active_tab_total_lines(&self) -> usize {
        match self.active_tab {
            LogTab::SelfHttp => self.self_http_entries.len(),
            LogTab::Cockpit => self.cockpit_entries.len(),
            tab => self.bee_buffers.count(tab),
        }
    }
}

/// Build the `[Errors 3] [Warn 0] [Info 247] [Debug 1.2k] [Bee HTTP] [bee::http]`
/// title strip with the active tab highlighted and counters from the
/// per-tab buffers. Counters above 999 collapse to `1.2k` style so
/// the strip fits an 80-column terminal.
fn tab_title_line<'a>(
    active: LogTab,
    bufs: &BeeLogBuffers,
    scroll_offset: usize,
    h_scroll_offset: u16,
    t: &theme::Theme,
) -> Line<'a> {
    let mut spans: Vec<Span> = Vec::with_capacity(LogTab::ALL.len() * 2 + 2);
    spans.push(Span::raw(" "));
    for tab in LogTab::ALL {
        let count = bufs.count(tab);
        // SelfHttp + Cockpit don't have BeeLogBuffer counts (their
        // payload comes from the in-process capture buffers, not the
        // supervisor's tail), so render the label without a count.
        let label = if count == 0 || matches!(tab, LogTab::SelfHttp | LogTab::Cockpit) {
            format!(" {} ", tab.label())
        } else {
            format!(" {} {} ", tab.label(), human_count(count))
        };
        let style = if tab == active {
            Style::default()
                .fg(t.tab_active_fg)
                .bg(t.tab_active_bg)
                .add_modifier(Modifier::BOLD)
        } else {
            tab_severity_color(tab, t)
        };
        spans.push(Span::styled(label, style));
        spans.push(Span::raw(" "));
    }
    // "paused N ↑" indicator when the operator has scrolled back.
    // Bright warn-yellow so it's impossible to miss that the pane
    // is no longer auto-tailing.
    if scroll_offset > 0 {
        spans.push(Span::styled(
            format!(" paused {scroll_offset}"),
            Style::default().fg(t.warn).add_modifier(Modifier::BOLD),
        ));
    }
    if h_scroll_offset > 0 {
        // Sibling indicator to "paused N ↑" — surfaces horizontal
        // pan state so an operator who walked away and came back
        // sees why their log lines look chopped on the left.
        spans.push(Span::styled(
            format!("{h_scroll_offset} "),
            Style::default().fg(t.warn).add_modifier(Modifier::BOLD),
        ));
    }
    Line::from(spans)
}

/// Subtle per-tab tint on the inactive label so Errors stand out
/// even when the operator is on a different tab.
fn tab_severity_color(tab: LogTab, t: &theme::Theme) -> Style {
    match tab {
        LogTab::Errors => Style::default().fg(t.fail),
        LogTab::Warning => Style::default().fg(t.warn),
        LogTab::Info => Style::default().fg(t.info),
        LogTab::Debug => Style::default().fg(t.dim),
        LogTab::BeeHttp => Style::default().fg(t.accent),
        LogTab::SelfHttp => Style::default().fg(t.dim),
        LogTab::Cockpit => Style::default().fg(t.accent),
    }
}

fn human_count(n: usize) -> String {
    if n < 1_000 {
        n.to_string()
    } else if n < 1_000_000 {
        format!("{:.1}k", n as f64 / 1000.0)
    } else {
        format!("{:.1}m", n as f64 / 1_000_000.0)
    }
}

fn render_cockpit<'a>(entries: &'a [CockpitEntry], t: &theme::Theme) -> Vec<Line<'a>> {
    if entries.is_empty() {
        return vec![Line::from(Span::styled(
            "  (no cockpit-internal events captured yet)",
            Style::default().fg(t.dim).add_modifier(Modifier::ITALIC),
        ))];
    }
    entries.iter().map(|e| cockpit_line(e, t)).collect()
}

fn cockpit_line<'a>(e: &'a CockpitEntry, t: &theme::Theme) -> Line<'a> {
    let level_style = match e.level.as_str() {
        "ERROR" => Style::default().fg(t.fail).add_modifier(Modifier::BOLD),
        "WARN" => Style::default().fg(t.warn).add_modifier(Modifier::BOLD),
        "INFO" => Style::default().fg(t.info),
        _ => Style::default().fg(t.dim),
    };
    Line::from(vec![
        Span::styled(format!("{} ", e.ts), Style::default().fg(t.dim)),
        Span::styled(format!("{:<5}", e.level), level_style),
        Span::raw(" "),
        Span::styled(
            format!("{:<22}", trim_target(&e.target)),
            Style::default().fg(t.accent),
        ),
        Span::raw("  "),
        Span::raw(e.message.clone()),
    ])
}

/// Drop the leading `bee_tui::` prefix on cockpit-event targets so
/// the rendered line stays under 80 columns. `bee_tui::watch::peers`
/// → `watch::peers`.
fn trim_target(target: &str) -> &str {
    target.strip_prefix("bee_tui::").unwrap_or(target)
}

fn render_self_http<'a>(entries: &'a [LogEntry], t: &theme::Theme) -> Vec<Line<'a>> {
    if entries.is_empty() {
        return vec![Line::from(Span::styled(
            "  (waiting for first request…)",
            Style::default().fg(t.dim).add_modifier(Modifier::ITALIC),
        ))];
    }
    entries.iter().map(|e| self_http_line(e, t)).collect()
}

fn render_bee_tab<'a>(
    bufs: &'a BeeLogBuffers,
    tab: LogTab,
    spawn_active: bool,
    t: &theme::Theme,
) -> Vec<Line<'a>> {
    let buf = match bufs.buffer_for(tab) {
        Some(b) => b,
        None => return Vec::new(),
    };
    if buf.is_empty() {
        let msg = if spawn_active {
            "  (awaiting bee log entries on this severity…)"
        } else {
            "  (no bee child — set [bee] in config or pass --bee-bin / --bee-config)"
        };
        return vec![Line::from(Span::styled(
            msg,
            Style::default().fg(t.dim).add_modifier(Modifier::ITALIC),
        ))];
    }
    buf.iter()
        .map(|line| {
            Line::from(vec![
                Span::styled(format!("{} ", line.timestamp), Style::default().fg(t.dim)),
                Span::styled(
                    format!("{:<22}", line.logger),
                    Style::default().fg(t.accent).add_modifier(Modifier::BOLD),
                ),
                Span::raw("  "),
                Span::raw(line.message.clone()),
            ])
        })
        .collect()
}

fn self_http_line<'a>(e: &'a LogEntry, t: &theme::Theme) -> Line<'a> {
    let status_style = match e.status {
        Some(s) if (200..300).contains(&s) => Style::default().fg(t.pass),
        Some(s) if (300..400).contains(&s) => Style::default().fg(t.info),
        Some(s) if (400..500).contains(&s) => Style::default().fg(t.warn),
        Some(_) => Style::default().fg(t.fail),
        None => Style::default().fg(t.dim),
    };
    let method_style = Style::default()
        .fg(method_color(&e.method))
        .add_modifier(Modifier::BOLD);
    let elapsed = e
        .elapsed_ms
        .map(|ms| format!("{ms:>4}ms"))
        .unwrap_or_else(|| "".into());
    let path = path_only(&e.url);
    Line::from(vec![
        Span::styled(format!("{} ", e.ts), Style::default().fg(t.dim)),
        Span::styled(format!("{:<5}", e.method), method_style),
        Span::raw(" "),
        Span::raw(path),
        Span::raw("  "),
        Span::styled(
            e.status
                .map(|s| s.to_string())
                .unwrap_or_else(|| "".into()),
            status_style,
        ),
        Span::raw("  "),
        Span::styled(elapsed, Style::default().fg(t.dim)),
    ])
}

/// Per-method colour, lazygit-style. Same palette as the legacy
/// CommandLog so the bee::http tab keeps its identity after the
/// move into the tabbed pane.
fn method_color(method: &str) -> Color {
    match method {
        "GET" => Color::Blue,
        "POST" => Color::Green,
        "PUT" => Color::Yellow,
        "DELETE" => Color::Red,
        "PATCH" => Color::Magenta,
        "HEAD" => Color::Cyan,
        _ => Color::White,
    }
}

/// Drop scheme + host from the URL so the tail stays readable on
/// 80-col terminals. `http://localhost:1633/health` → `/health`.
/// Matches the legacy CommandLog implementation; tests live here too.
fn path_only(url: &str) -> String {
    if let Some(rest) = url.split_once("//").and_then(|(_, r)| r.split_once('/')) {
        format!("/{}", rest.1)
    } else {
        url.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn next_tab_wraps() {
        let mut pane = LogPane::new(None, LogTab::Errors, 10);
        for expected in [
            LogTab::Warning,
            LogTab::Info,
            LogTab::Debug,
            LogTab::BeeHttp,
            LogTab::SelfHttp,
            LogTab::Cockpit,
            LogTab::Errors,
        ] {
            assert_eq!(pane.next_tab(), expected);
        }
    }

    #[test]
    fn prev_tab_wraps() {
        let mut pane = LogPane::new(None, LogTab::Errors, 10);
        for expected in [
            LogTab::Cockpit,
            LogTab::SelfHttp,
            LogTab::BeeHttp,
            LogTab::Debug,
            LogTab::Info,
            LogTab::Warning,
            LogTab::Errors,
        ] {
            assert_eq!(pane.prev_tab(), expected);
        }
    }

    #[test]
    fn grow_clamps_at_max() {
        let mut pane = LogPane::new(None, LogTab::SelfHttp, LOG_PANE_MAX_HEIGHT - 1);
        pane.grow();
        assert_eq!(pane.height(), LOG_PANE_MAX_HEIGHT);
        // Further grows are no-ops.
        pane.grow();
        pane.grow();
        assert_eq!(pane.height(), LOG_PANE_MAX_HEIGHT);
    }

    #[test]
    fn shrink_clamps_at_min() {
        let mut pane = LogPane::new(None, LogTab::SelfHttp, LOG_PANE_MIN_HEIGHT + 1);
        pane.shrink();
        assert_eq!(pane.height(), LOG_PANE_MIN_HEIGHT);
        pane.shrink();
        pane.shrink();
        assert_eq!(pane.height(), LOG_PANE_MIN_HEIGHT);
    }

    #[test]
    fn fresh_pane_is_tailing() {
        let pane = LogPane::new(None, LogTab::Errors, 10);
        assert!(pane.is_tailing());
        assert_eq!(pane.scroll_offset(), 0);
    }

    #[test]
    fn scroll_up_disables_tail_and_remembers_offset() {
        let mut pane = LogPane::new(None, LogTab::Errors, 10);
        pane.scroll_up(3);
        assert!(!pane.is_tailing());
        assert_eq!(pane.scroll_offset(), 3);
        pane.scroll_up(2);
        assert_eq!(pane.scroll_offset(), 5);
    }

    #[test]
    fn scroll_down_eventually_resumes_tail() {
        let mut pane = LogPane::new(None, LogTab::Errors, 10);
        pane.scroll_up(5);
        pane.scroll_down(2);
        assert_eq!(pane.scroll_offset(), 3);
        // Saturating-sub: scrolling down past 0 snaps to tail.
        pane.scroll_down(100);
        assert_eq!(pane.scroll_offset(), 0);
        assert!(pane.is_tailing());
    }

    #[test]
    fn resume_tail_resets_offset() {
        let mut pane = LogPane::new(None, LogTab::Errors, 10);
        pane.scroll_up(7);
        pane.resume_tail();
        assert!(pane.is_tailing());
    }

    #[test]
    fn tab_switch_resets_scroll_offset() {
        // A scroll offset on tab A makes no sense on tab B — different
        // ring buffer, different content. Reset on switch.
        let mut pane = LogPane::new(None, LogTab::Errors, 10);
        pane.scroll_up(4);
        pane.next_tab();
        assert_eq!(pane.scroll_offset(), 0);
        assert!(pane.is_tailing());
        // Same on prev_tab.
        pane.scroll_up(4);
        pane.prev_tab();
        assert_eq!(pane.scroll_offset(), 0);
    }

    #[test]
    fn push_bee_bumps_offset_for_active_tab_when_scrolled() {
        // Scroll-back stability: when the operator is scrolled up
        // and a new entry lands on the same tab, the offset bumps
        // so the visible window stays anchored on the same content.
        let mut pane = LogPane::new(None, LogTab::Errors, 10);
        pane.push_bee(LogTab::Errors, line("err1"));
        pane.push_bee(LogTab::Errors, line("err2"));
        pane.scroll_up(2);
        pane.push_bee(LogTab::Errors, line("err3"));
        // Offset went from 2 → 3 to compensate for the new entry
        // shifting the window's relative position.
        assert_eq!(pane.scroll_offset(), 3);
    }

    #[test]
    fn push_bee_doesnt_bump_offset_when_tailing() {
        // While tailing (offset = 0) the pane should keep tailing
        // without spuriously paging into "paused" mode.
        let mut pane = LogPane::new(None, LogTab::Errors, 10);
        for i in 0..5 {
            pane.push_bee(LogTab::Errors, line(&format!("e{i}")));
        }
        assert_eq!(pane.scroll_offset(), 0);
        assert!(pane.is_tailing());
    }

    #[test]
    fn push_bee_doesnt_bump_offset_for_inactive_tab() {
        // Activity on a different tab shouldn't move the operator's
        // anchor on the one they're reading.
        let mut pane = LogPane::new(None, LogTab::Errors, 10);
        pane.push_bee(LogTab::Errors, line("err1"));
        pane.scroll_up(1);
        let before = pane.scroll_offset();
        pane.push_bee(LogTab::Debug, line("dbg1"));
        assert_eq!(pane.scroll_offset(), before);
    }

    fn line(msg: &str) -> BeeLogLine {
        BeeLogLine {
            timestamp: "t".into(),
            logger: "node/test".into(),
            message: msg.into(),
        }
    }

    #[test]
    fn ring_capacity_is_enforced() {
        let mut pane = LogPane::new(None, LogTab::Debug, 10);
        // Push 600 entries — the ring should keep the most recent 500.
        for i in 0..(BEE_TAB_RING_CAPACITY + 100) {
            pane.push_bee(
                LogTab::Debug,
                BeeLogLine {
                    timestamp: format!("t{i}"),
                    logger: "node/test".into(),
                    message: format!("msg {i}"),
                },
            );
        }
        assert_eq!(pane.bee_buffers.debug.len(), BEE_TAB_RING_CAPACITY);
        assert_eq!(pane.bee_buffers.debug.front().unwrap().timestamp, "t100");
        assert_eq!(
            pane.bee_buffers.debug.back().unwrap().timestamp,
            format!("t{}", BEE_TAB_RING_CAPACITY + 99)
        );
    }

    #[test]
    fn push_bee_to_self_http_is_noop() {
        // Defensive: only the bee-side severities have buffers; the
        // SelfHttp tab is fed by the LogCapture. push_bee on SelfHttp
        // must silently drop, not panic.
        let mut pane = LogPane::new(None, LogTab::SelfHttp, 10);
        pane.push_bee(
            LogTab::SelfHttp,
            BeeLogLine {
                timestamp: "t".into(),
                logger: "x".into(),
                message: "m".into(),
            },
        );
        for tab in LogTab::ALL {
            assert_eq!(pane.bee_buffers.count(tab), 0, "tab {tab:?} got an entry");
        }
    }

    #[test]
    fn human_count_formats_thousands() {
        assert_eq!(human_count(0), "0");
        assert_eq!(human_count(42), "42");
        assert_eq!(human_count(999), "999");
        assert_eq!(human_count(1000), "1.0k");
        assert_eq!(human_count(1234), "1.2k");
        assert_eq!(human_count(999_999), "1000.0k");
        assert_eq!(human_count(1_000_000), "1.0m");
    }

    #[test]
    fn from_kebab_unknown_falls_back_to_self_http() {
        // Defensive: a hand-edited state.toml with a future tab name
        // shouldn't crash startup, just silently snap to a known good.
        assert_eq!(LogTab::from_kebab("future-tab"), LogTab::SelfHttp);
        assert_eq!(LogTab::from_kebab(""), LogTab::SelfHttp);
    }

    #[test]
    fn kebab_round_trips() {
        for tab in LogTab::ALL {
            assert_eq!(LogTab::from_kebab(tab.to_kebab()), tab);
        }
    }

    #[test]
    fn path_only_strips_scheme_and_host() {
        assert_eq!(path_only("http://localhost:1633/status"), "/status");
        assert_eq!(
            path_only("https://bee.example.com:1633/stamps/abc"),
            "/stamps/abc"
        );
    }

    #[test]
    fn path_only_handles_root_only() {
        assert_eq!(path_only("http://localhost:1633"), "http://localhost:1633");
    }

    #[test]
    fn h_scroll_starts_at_zero() {
        let pane = LogPane::new(None, LogTab::SelfHttp, LOG_PANE_MIN_HEIGHT);
        assert_eq!(pane.h_scroll_offset(), 0);
    }

    #[test]
    fn scroll_right_then_left_returns_to_zero() {
        let mut pane = LogPane::new(None, LogTab::SelfHttp, LOG_PANE_MIN_HEIGHT);
        pane.scroll_right(8);
        pane.scroll_right(8);
        assert_eq!(pane.h_scroll_offset(), 16);
        pane.scroll_left(16);
        assert_eq!(pane.h_scroll_offset(), 0);
    }

    #[test]
    fn scroll_left_saturates_at_zero() {
        let mut pane = LogPane::new(None, LogTab::SelfHttp, LOG_PANE_MIN_HEIGHT);
        pane.scroll_left(100);
        assert_eq!(pane.h_scroll_offset(), 0);
    }

    #[test]
    fn switching_tabs_resets_h_scroll() {
        let mut pane = LogPane::new(None, LogTab::Errors, LOG_PANE_MIN_HEIGHT);
        pane.scroll_right(40);
        assert_eq!(pane.h_scroll_offset(), 40);
        pane.next_tab();
        assert_eq!(pane.h_scroll_offset(), 0);
        pane.scroll_right(20);
        pane.prev_tab();
        assert_eq!(pane.h_scroll_offset(), 0);
    }

    #[test]
    fn resume_tail_resets_both_axes() {
        let mut pane = LogPane::new(None, LogTab::SelfHttp, LOG_PANE_MIN_HEIGHT);
        pane.scroll_up(5);
        pane.scroll_right(24);
        pane.resume_tail();
        assert_eq!(pane.scroll_offset(), 0);
        assert_eq!(pane.h_scroll_offset(), 0);
    }

    #[test]
    fn reset_h_scroll_only_touches_horizontal() {
        let mut pane = LogPane::new(None, LogTab::SelfHttp, LOG_PANE_MIN_HEIGHT);
        pane.scroll_up(7);
        pane.scroll_right(16);
        pane.reset_h_scroll();
        assert_eq!(pane.scroll_offset(), 7);
        assert_eq!(pane.h_scroll_offset(), 0);
    }
}