syswatch 0.6.0

Single-host, read-only system diagnostics TUI. Twelve tabs covering CPU, memory, disks, processes, GPU, power, services, network, plus a Timeline scrubber and an Insights anomaly engine. Sibling to netwatch.
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
use std::io;
use std::time::{Duration, Instant};

use anyhow::Result;
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use crossterm::execute;
use crossterm::terminal::{
    disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use ratatui::backend::CrosstermBackend;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::Terminal;

use std::collections::HashMap;

pub use crate::collect::Snapshot;
use crate::collect::{Collector, Ring};
use crate::config::SyswatchConfig;
use crate::insights::{self, Insight};
use crate::tabs;
use crate::ui::chrome;
use crate::ui::graph::GraphStyle;

pub struct Options {
    pub start_tab: Option<String>,
    /// Source of truth for tick_ms / theme / graph_style / default_tab.
    /// CLI overrides are applied to this struct in main() before handoff.
    pub config: SyswatchConfig,
    /// Pre-loaded snapshots from a `--replay` invocation. When Some,
    /// the run loop skips live collection entirely and the user
    /// scrubs through the recorded ticks instead.
    pub replay: Option<Vec<Snapshot>>,
}

pub struct History {
    /// Aggregate CPU usage % (0..100), one sample per tick.
    pub cpu: Ring<f32>,
    /// Memory used / total ratio (0..1).
    pub mem: Ring<f32>,
    /// Swap used in bytes — used by the swap-thrash heuristic.
    pub swap: Ring<u64>,
    /// Net rx+tx bytes/sec aggregated.
    pub net_rate: Ring<f64>,
    /// Disk rd+wr bytes/sec aggregated.
    pub io_rate: Ring<f64>,
    /// Aggregate GPU usage % (0..100), max across all detected devices per
    /// tick — captures the "any GPU is busy" signal regardless of which one.
    /// 0 when no GPU exposes live util (Linux NVIDIA without nvml, etc.).
    pub gpu_util: Ring<f32>,
    /// Per-pid CPU EWMA, decayed each tick. Pids absent in the latest tick
    /// are pruned. Values are 0..100. The runaway-proc heuristic reads this
    /// to find processes whose load is sustained, not transient.
    pub proc_cpu_ewma: HashMap<u32, f32>,
    /// Full session: every snapshot pushed in order. Bounded — sized to
    /// match the metric rings so scrubbing stays in sync. The Timeline tab
    /// drives scrubbing; other tabs read App::displayed_snap().
    pub session: Ring<Snapshot>,
}

impl History {
    pub(crate) fn new(cap: usize) -> Self {
        Self {
            cpu: Ring::new(cap),
            mem: Ring::new(cap),
            swap: Ring::new(cap),
            net_rate: Ring::new(cap),
            io_rate: Ring::new(cap),
            gpu_util: Ring::new(cap),
            proc_cpu_ewma: HashMap::new(),
            session: Ring::new(cap),
        }
    }

    pub(crate) fn push(&mut self, snap: &Snapshot) {
        // Mirror the snapshot into the session ring so scrubbing has full data.
        self.session.push(snap.clone());
        self.cpu.push(snap.cpu.usage_pct);
        let m = if snap.mem.total_bytes > 0 {
            (snap.mem.used_bytes as f32) / (snap.mem.total_bytes as f32)
        } else {
            0.0
        };
        self.mem.push(m);
        self.swap.push(snap.mem.swap_used_bytes);
        let net = snap.net.iter().map(|i| i.rx_rate + i.tx_rate).sum::<f64>();
        self.net_rate.push(net);
        self.io_rate
            .push(snap.disk_io.read_rate + snap.disk_io.write_rate);
        // Max util across all GPUs — handles laptops with iGPU+dGPU and the
        // common case of a single device alike. Defaults to 0 when no device
        // exposes util_pct.
        let gpu = snap
            .gpus
            .iter()
            .filter_map(|g| g.util_pct)
            .fold(0.0_f32, f32::max);
        self.gpu_util.push(gpu);

        // Update per-pid EWMA. Alpha=0.3 → ~5 ticks to stabilize.
        // Prune pids that aren't in the current snapshot.
        let mut next: HashMap<u32, f32> = HashMap::with_capacity(snap.procs.len());
        for proc_ in &snap.procs {
            let prev = self
                .proc_cpu_ewma
                .get(&proc_.pid)
                .copied()
                .unwrap_or(proc_.cpu_pct);
            let ewma = 0.7 * prev + 0.3 * proc_.cpu_pct;
            next.insert(proc_.pid, ewma);
        }
        self.proc_cpu_ewma = next;
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TabId {
    Overview,
    Cpu,
    Memory,
    Disks,
    Fs,
    Procs,
    Gpu,
    Power,
    Services,
    Net,
    Timeline,
    Insights,
}

pub const ALL_TABS: &[TabId] = &[
    TabId::Overview,
    TabId::Cpu,
    TabId::Memory,
    TabId::Disks,
    TabId::Fs,
    TabId::Procs,
    TabId::Gpu,
    TabId::Power,
    TabId::Services,
    TabId::Net,
    TabId::Timeline,
    TabId::Insights,
];

impl TabId {
    pub fn glyph(&self) -> &'static str {
        match self {
            TabId::Overview => "1",
            TabId::Cpu => "2",
            TabId::Memory => "3",
            TabId::Disks => "4",
            TabId::Fs => "5",
            TabId::Procs => "6",
            TabId::Gpu => "7",
            TabId::Power => "8",
            TabId::Services => "9",
            TabId::Net => "0",
            TabId::Timeline => "-",
            TabId::Insights => "+",
        }
    }
    pub fn title(&self) -> &'static str {
        match self {
            TabId::Overview => "Overview",
            TabId::Cpu => "CPU",
            TabId::Memory => "Memory",
            TabId::Disks => "Disks",
            TabId::Fs => "FS",
            TabId::Procs => "Procs",
            TabId::Gpu => "GPU",
            TabId::Power => "Power",
            TabId::Services => "Services",
            TabId::Net => "Net",
            TabId::Timeline => "Timeline",
            TabId::Insights => "Insights",
        }
    }
    fn from_str_loose(s: &str) -> Option<TabId> {
        match s.to_ascii_lowercase().as_str() {
            "overview" | "1" => Some(TabId::Overview),
            "cpu" | "2" => Some(TabId::Cpu),
            "memory" | "mem" | "3" => Some(TabId::Memory),
            "disks" | "disk" | "4" => Some(TabId::Disks),
            "fs" | "filesystems" | "5" => Some(TabId::Fs),
            "procs" | "processes" | "6" => Some(TabId::Procs),
            "gpu" | "7" => Some(TabId::Gpu),
            "power" | "8" => Some(TabId::Power),
            "services" | "9" => Some(TabId::Services),
            "net" | "network" | "0" => Some(TabId::Net),
            "timeline" | "-" => Some(TabId::Timeline),
            "insights" | "+" => Some(TabId::Insights),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcSort {
    Cpu,
    Rss,
    Io,
    Start,
    Name,
    /// %GPU desc — None values sort to the bottom so platforms
    /// without per-PID GPU data don't put empty rows at the top.
    Gpu,
    /// Combined net rx+tx desc — same None-to-bottom rule.
    Net,
}

impl ProcSort {
    pub fn label(&self) -> &'static str {
        match self {
            ProcSort::Cpu => "cpu",
            ProcSort::Rss => "rss",
            ProcSort::Io => "io",
            ProcSort::Start => "start",
            ProcSort::Name => "name",
            ProcSort::Gpu => "gpu",
            ProcSort::Net => "net",
        }
    }
    pub const ALL: [ProcSort; 7] = [
        ProcSort::Cpu,
        ProcSort::Rss,
        ProcSort::Io,
        ProcSort::Start,
        ProcSort::Name,
        ProcSort::Gpu,
        ProcSort::Net,
    ];
    fn next(self) -> ProcSort {
        let i = ProcSort::ALL.iter().position(|s| *s == self).unwrap_or(0);
        ProcSort::ALL[(i + 1) % ProcSort::ALL.len()]
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ServiceSort {
    Name,
    Status,
    Pid,
}

impl ServiceSort {
    pub const ALL: [ServiceSort; 3] = [ServiceSort::Name, ServiceSort::Status, ServiceSort::Pid];
    pub fn label(&self) -> &'static str {
        match self {
            ServiceSort::Name => "name",
            ServiceSort::Status => "status",
            ServiceSort::Pid => "pid",
        }
    }
    fn next(self) -> ServiceSort {
        let i = ServiceSort::ALL
            .iter()
            .position(|s| *s == self)
            .unwrap_or(0);
        ServiceSort::ALL[(i + 1) % ServiceSort::ALL.len()]
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LiveState {
    Live,
    Paused,
    Scrub,
    /// Replay mode — `--replay path.swr` was passed. No live data,
    /// the scrubber walks recorded snapshots.
    Replay,
}

pub struct App {
    pub active: TabId,
    pub paused: bool,
    pub history: History,
    pub snap: Option<Snapshot>,
    pub proc_sort: ProcSort,
    pub proc_sel: usize,
    pub service_sort: ServiceSort,
    pub service_sel: usize,
    pub insights: Vec<Insight>,
    /// Scrub offset in ticks back from "now" (0 = live). Driven by Timeline's
    /// arrow keys; clamped to session length. Affects every tab via
    /// App::displayed_snap.
    pub scrub_offset: usize,
    /// Chart rendering style. Toggled with `g`. Affects every multi-row
    /// sparkline tile (CPU/Net/Disks aggregates, Overview KPIs).
    pub graph_style: GraphStyle,

    // ── Settings popup state ─────────────────────────────────────────────
    /// In-memory user config. Mutated by the settings popup; written to
    /// disk only when the user presses S. `t`/`g` mutate runtime state
    /// AND mirror into this struct so that opening settings reflects
    /// current values.
    pub user_config: SyswatchConfig,
    /// Whether the settings popup is open. Routes key input through
    /// `crate::ui::settings` while true.
    pub settings_active: bool,
    /// Cursor row inside the settings popup.
    pub settings_cursor: usize,
    /// Whether the popup is in text-edit mode for the cursor row
    /// (numerics — currently just `tick_ms`).
    pub settings_editing: bool,
    /// Buffer for in-progress text edits.
    pub settings_edit_buf: String,
    /// Status line shown under the popup body — "saved", validation
    /// errors, etc.
    pub settings_status: Option<String>,

    /// Transient status flash shown in the footer — used by the `S`
    /// snapshot command to confirm the dump path. `(message, expires_at)`.
    pub footer_flash: Option<(String, Instant)>,

    /// Whether the `?` help popup is open. Absorbs all input while true
    /// (Esc / `?` to close).
    pub help_active: bool,

    // ── Procs filter (`/` key) ──────────────────────────────────────────
    /// True while the user is typing into the filter input box. Esc
    /// cancels (drops both the buffer and any active filter); Enter
    /// commits the buffer to `proc_filter_active`.
    pub proc_filter_input: bool,
    /// In-progress filter text. Applied live to the procs list while
    /// typing so the user sees match results immediately.
    pub proc_filter_buf: String,
    /// Currently-applied filter (case-insensitive substring match
    /// against name/cmd/user). None means no filter.
    pub proc_filter_active: Option<String>,

    /// Active session recorder, when the user has pressed `R`. None
    /// means not recording. Drop on quit flushes the buffered tail.
    pub recorder: Option<crate::recording::Recorder>,

    /// True when the app was launched with --replay; suppresses live
    /// collection and changes the LiveState badge.
    pub replay_mode: bool,
}

impl App {
    /// Render-time graph options bundle. Built once per render path from
    /// `user_config.graph_fade`; passed to every `graph::render` call site
    /// so a single config toggle drives the entire UI.
    pub fn graph_opts(&self) -> crate::ui::graph::GraphOpts {
        crate::ui::graph::GraphOpts {
            fade: self.user_config.graph_fade,
        }
    }

    pub fn displayed_snap(&self) -> Option<&Snapshot> {
        if self.scrub_offset > 0 {
            self.history.session.nth_back(self.scrub_offset)
        } else {
            self.snap.as_ref()
        }
    }
    pub fn live_state(&self) -> LiveState {
        if self.replay_mode {
            return LiveState::Replay;
        }
        if self.scrub_offset > 0 {
            LiveState::Scrub
        } else if self.paused {
            LiveState::Paused
        } else {
            LiveState::Live
        }
    }
}

impl App {
    fn new(start: TabId, config: SyswatchConfig) -> Self {
        // Theme is already applied globally in main(). Resolve graph_style
        // from the same config.
        let graph_style = match config.graph_style.to_lowercase().as_str() {
            "dots" => GraphStyle::Dots,
            _ => GraphStyle::Bars,
        };
        Self {
            active: start,
            paused: false,
            history: History::new(120),
            snap: None,
            proc_sort: ProcSort::Cpu,
            proc_sel: 0,
            service_sort: ServiceSort::Name,
            service_sel: 0,
            insights: Vec::new(),
            scrub_offset: 0,
            graph_style,
            user_config: config,
            settings_active: false,
            settings_cursor: 0,
            settings_editing: false,
            settings_edit_buf: String::new(),
            settings_status: None,
            footer_flash: None,
            help_active: false,
            proc_filter_input: false,
            proc_filter_buf: String::new(),
            proc_filter_active: None,
            recorder: None,
            replay_mode: false,
        }
    }

    fn handle_key(&mut self, k: KeyEvent) -> bool {
        if k.kind != KeyEventKind::Press {
            return false;
        }
        // Procs filter input mode — narrow keyboard scope so chars
        // typed into the search box don't also fire dashboard hotkeys.
        if self.proc_filter_input {
            match (k.code, k.modifiers) {
                (KeyCode::Char('c'), KeyModifiers::CONTROL) => return true,
                (KeyCode::Esc, _) => {
                    // Cancel: drop both the in-progress text and any
                    // currently-applied filter.
                    self.proc_filter_input = false;
                    self.proc_filter_buf.clear();
                    self.proc_filter_active = None;
                    self.proc_sel = 0;
                }
                (KeyCode::Enter, _) => {
                    self.proc_filter_input = false;
                    self.proc_filter_active = if self.proc_filter_buf.is_empty() {
                        None
                    } else {
                        Some(self.proc_filter_buf.clone())
                    };
                    self.proc_sel = 0;
                }
                (KeyCode::Backspace, _) => {
                    self.proc_filter_buf.pop();
                    // Live-apply so the table updates as the user types.
                    self.proc_filter_active = if self.proc_filter_buf.is_empty() {
                        None
                    } else {
                        Some(self.proc_filter_buf.clone())
                    };
                    self.proc_sel = 0;
                }
                (KeyCode::Char(c), _) => {
                    self.proc_filter_buf.push(c);
                    self.proc_filter_active = Some(self.proc_filter_buf.clone());
                    self.proc_sel = 0;
                }
                _ => {}
            }
            return false;
        }
        // Help popup is the simplest modal — Esc, `?`, or Ctrl-C close
        // it; every other key is swallowed so the user can't accidentally
        // act on the dashboard behind the popup.
        if self.help_active {
            match (k.code, k.modifiers) {
                (KeyCode::Char('c'), KeyModifiers::CONTROL) => return true,
                (KeyCode::Esc, _) | (KeyCode::Char('?'), _) => self.help_active = false,
                _ => {}
            }
            return false;
        }
        // Settings popup absorbs all input while active. Returns true if
        // the popup wants the parent app to ignore the key entirely.
        if self.settings_active {
            return self.handle_settings_key(k);
        }
        match (k.code, k.modifiers) {
            (KeyCode::Char('q'), _) => return true,
            (KeyCode::Char('c'), KeyModifiers::CONTROL) => return true,
            (KeyCode::Char('p'), _) => self.paused = !self.paused,
            (KeyCode::Char(','), _) => {
                self.settings_active = true;
                self.settings_cursor = 0;
                self.settings_status = None;
                self.settings_editing = false;
                return false;
            }
            (KeyCode::Char('?'), _) => {
                self.help_active = true;
                return false;
            }
            (KeyCode::Char('S'), _) => {
                // Dump the currently-displayed snapshot (live or scrubbed).
                // Status flash shows the resulting path for ~3s.
                let msg = match self.displayed_snap() {
                    Some(snap) => match crate::snapshot::write(snap) {
                        Ok(path) => format!("snapshot → {}", path.display()),
                        Err(e) => format!("snapshot failed: {}", e),
                    },
                    None => "no snapshot yet — wait for first sample".into(),
                };
                self.footer_flash = Some((msg, Instant::now() + Duration::from_secs(3)));
            }
            (KeyCode::Char('R'), _) => {
                // Toggle session recording. Each tick after start gets
                // appended; pressing R again (or quitting) flushes and
                // closes the file.
                let msg = if let Some(rec) = self.recorder.take() {
                    let path = rec.path().display().to_string();
                    let count = rec.count;
                    drop(rec); // explicit flush via Drop
                    format!("recording stopped → {} ({} ticks)", path, count)
                } else {
                    match crate::recording::fresh_path() {
                        Some(p) => match crate::recording::Recorder::create(p) {
                            Ok(rec) => {
                                let path = rec.path().display().to_string();
                                self.recorder = Some(rec);
                                format!("recording → {}", path)
                            }
                            Err(e) => format!("recording failed: {}", e),
                        },
                        None => "cannot determine local data dir".into(),
                    }
                };
                self.footer_flash = Some((msg, Instant::now() + Duration::from_secs(3)));
            }
            (KeyCode::Char('g'), _) => {
                self.graph_style = self.graph_style.next();
                // Mirror into user_config so the settings popup sees the
                // current value. Disk write happens only on S in settings.
                self.user_config.graph_style = self.graph_style.label().into();
            }
            (KeyCode::Char('t'), _) => {
                let next = crate::ui::theme::cycle();
                self.user_config.theme = next.into();
            }
            (KeyCode::Char('1'), _) => self.active = TabId::Overview,
            (KeyCode::Char('2'), _) => self.active = TabId::Cpu,
            (KeyCode::Char('3'), _) => self.active = TabId::Memory,
            (KeyCode::Char('4'), _) => self.active = TabId::Disks,
            (KeyCode::Char('5'), _) => self.active = TabId::Fs,
            (KeyCode::Char('6'), _) => self.active = TabId::Procs,
            (KeyCode::Char('7'), _) => self.active = TabId::Gpu,
            (KeyCode::Char('8'), _) => self.active = TabId::Power,
            (KeyCode::Char('9'), _) => self.active = TabId::Services,
            (KeyCode::Char('0'), _) => self.active = TabId::Net,
            (KeyCode::Char('-'), _) => self.active = TabId::Timeline,
            (KeyCode::Char('+') | KeyCode::Char('='), _) => self.active = TabId::Insights,
            (KeyCode::Tab, _) => self.active = next_tab(self.active),
            (KeyCode::BackTab, _) => self.active = prev_tab(self.active),
            (KeyCode::Up, _) if self.active == TabId::Procs => {
                self.proc_sel = self.proc_sel.saturating_sub(1);
            }
            (KeyCode::Down, _) if self.active == TabId::Procs => {
                // Clamp against the *filtered* list — netwatch issue #26
                // taught us not to let selection land on rows the user
                // can't see.
                let max = self
                    .snap
                    .as_ref()
                    .map(|s| {
                        crate::tabs::procs::filtered_sorted(
                            &s.procs,
                            self.proc_sort,
                            self.proc_filter_active.as_deref(),
                        )
                        .len()
                        .saturating_sub(1)
                    })
                    .unwrap_or(0);
                self.proc_sel = (self.proc_sel + 1).min(max);
            }
            (KeyCode::Char('s'), _) if self.active == TabId::Procs => {
                self.proc_sort = self.proc_sort.next();
                self.proc_sel = 0;
            }
            (KeyCode::Char('/'), _) if self.active == TabId::Procs => {
                // Enter filter input mode. Pre-fill with the current
                // applied filter (if any) so the user can refine it.
                self.proc_filter_input = true;
                self.proc_filter_buf = self.proc_filter_active.clone().unwrap_or_default();
            }
            (KeyCode::Up, _) if self.active == TabId::Services => {
                self.service_sel = self.service_sel.saturating_sub(1);
            }
            (KeyCode::Down, _) if self.active == TabId::Services => {
                let max = self
                    .snap
                    .as_ref()
                    .map(|s| s.services.len().saturating_sub(1))
                    .unwrap_or(0);
                self.service_sel = (self.service_sel + 1).min(max);
            }
            (KeyCode::Char('s'), _) if self.active == TabId::Services => {
                self.service_sort = self.service_sort.next();
                self.service_sel = 0;
            }
            // Scrub controls: active on every tab, but most useful on Timeline.
            (KeyCode::Left, _) => {
                let max = self.history.session.len().saturating_sub(1);
                self.scrub_offset = (self.scrub_offset + 1).min(max);
            }
            (KeyCode::Right, _) => {
                self.scrub_offset = self.scrub_offset.saturating_sub(1);
            }
            (KeyCode::Home, _) => {
                self.scrub_offset = self.history.session.len().saturating_sub(1);
            }
            (KeyCode::End, _) => {
                self.scrub_offset = 0;
            }
            _ => {}
        }
        false
    }
}

impl App {
    /// Settings-popup key router. Returns true to quit the app (only on
    /// Ctrl-C); false otherwise.
    fn handle_settings_key(&mut self, k: KeyEvent) -> bool {
        use crate::ui::settings;
        if self.settings_editing {
            match k.code {
                KeyCode::Esc => {
                    self.settings_editing = false;
                    self.settings_edit_buf.clear();
                    self.settings_status = None;
                }
                KeyCode::Enter => {
                    let buf = std::mem::take(&mut self.settings_edit_buf);
                    match settings::apply_edit(&mut self.user_config, self.settings_cursor, &buf) {
                        Ok(()) => {
                            self.settings_editing = false;
                            self.settings_status = Some("applied (press S to save to disk)".into());
                        }
                        Err(msg) => {
                            self.settings_status = Some(msg);
                            // Keep editing so user can retry.
                            self.settings_edit_buf = buf;
                        }
                    }
                }
                KeyCode::Backspace => {
                    self.settings_edit_buf.pop();
                }
                KeyCode::Char(c) => {
                    self.settings_edit_buf.push(c);
                }
                _ => {}
            }
            return false;
        }
        match (k.code, k.modifiers) {
            (KeyCode::Char('c'), KeyModifiers::CONTROL) => return true,
            (KeyCode::Esc, _) => {
                self.settings_active = false;
                self.settings_status = None;
            }
            (KeyCode::Up, _) => {
                self.settings_cursor = self.settings_cursor.saturating_sub(1);
                self.settings_status = None;
            }
            (KeyCode::Down, _) => {
                self.settings_cursor = (self.settings_cursor + 1).min(settings::ROWS - 1);
                self.settings_status = None;
            }
            (KeyCode::Left, _) => {
                settings::cycle_prev(&mut self.user_config, self.settings_cursor);
                self.apply_runtime_from_config();
            }
            (KeyCode::Right, _) => {
                settings::cycle_next(&mut self.user_config, self.settings_cursor);
                self.apply_runtime_from_config();
            }
            (KeyCode::Enter, _) => {
                // Enter is only meaningful for non-enum (text) rows.
                self.settings_edit_buf =
                    settings::edit_value(&self.user_config, self.settings_cursor);
                self.settings_editing = true;
                self.settings_status = None;
            }
            (KeyCode::Char('s' | 'S'), _) => match self.user_config.save() {
                Ok(()) => {
                    self.settings_status = Some(format!(
                        "saved to {}",
                        crate::config::SyswatchConfig::path()
                            .map(|p| p.display().to_string())
                            .unwrap_or_else(|| "config dir".into())
                    ));
                }
                Err(e) => self.settings_status = Some(format!("save failed: {}", e)),
            },
            _ => {}
        }
        false
    }

    /// Sync runtime state (theme + graph_style) from `user_config`. Called
    /// after each ←/→ cycle in the settings popup so the user sees the
    /// effect immediately on the dashboard behind the popup.
    fn apply_runtime_from_config(&mut self) {
        crate::ui::theme::set_by_name(&self.user_config.theme);
        self.graph_style = match self.user_config.graph_style.to_lowercase().as_str() {
            "dots" => GraphStyle::Dots,
            _ => GraphStyle::Bars,
        };
        // `graph_fade` deliberately has no cached runtime copy on `App` —
        // `App::graph_opts()` reads it from `user_config` live each render
        // tick, so the toggle takes effect on the very next frame without
        // a sync step here. Don't add a redundant mirror; it'll drift.
    }
}

fn next_tab(t: TabId) -> TabId {
    let i = ALL_TABS.iter().position(|x| *x == t).unwrap_or(0);
    ALL_TABS[(i + 1) % ALL_TABS.len()]
}

fn prev_tab(t: TabId) -> TabId {
    let i = ALL_TABS.iter().position(|x| *x == t).unwrap_or(0);
    ALL_TABS[(i + ALL_TABS.len() - 1) % ALL_TABS.len()]
}

pub fn run(opts: Options) -> Result<()> {
    // Replay mode forces Timeline as the starting tab — that's where
    // the scrubber lives — unless the user explicitly passed --tab.
    let user_picked_tab = opts.start_tab.is_some();
    let start = opts
        .start_tab
        .as_deref()
        .and_then(TabId::from_str_loose)
        .unwrap_or(TabId::Overview);
    let start = if opts.replay.is_some() && !user_picked_tab {
        TabId::Timeline
    } else {
        start
    };

    let mut app = App::new(start, opts.config);

    // Populate History from the recording up front, then plant the
    // scrubber at oldest tick so the user sees the start. Live
    // collection is skipped entirely in replay mode.
    if let Some(snaps) = opts.replay {
        app.replay_mode = true;
        // Resize the History rings if needed so the entire recording
        // fits — default cap is 120 ticks; sessions longer than that
        // would otherwise lose the head on push.
        let needed = snaps.len().max(120);
        app.history = History::new(needed);
        for s in &snaps {
            app.history.push(s);
        }
        // Park scrubber at the oldest tick so the user explores
        // forward through the recording.
        app.scrub_offset = app.history.session.len().saturating_sub(1);
        app.snap = snaps.last().cloned();
        app.insights = if let Some(last) = snaps.last() {
            insights::compute(&app.history, last)
        } else {
            Vec::new()
        };
    }

    // Skip collector setup in replay mode — IOReport / system_profiler
    // / ioreg probes do real work we don't need when there's no live
    // sampling to do.
    let mut collector: Option<Collector> = if app.replay_mode {
        None
    } else {
        Some(Collector::new())
    };

    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen)?;
    let backend = CrosstermBackend::new(stdout);
    let mut term = Terminal::new(backend)?;

    // Force the first sample to fire immediately. After that we re-read
    // the tick interval from `user_config` on every iteration so changes
    // made through the settings popup take effect on the next cycle
    // without a restart.
    let mut last_tick = Instant::now() - Duration::from_secs(60);
    let res = loop {
        // 100..=5000 ms — matches the validation in `config::validate`
        // and `settings::apply_edit`. The clamp is defensive in case a
        // hand-edited config slipped through.
        let tick = Duration::from_millis(app.user_config.tick_ms.clamp(100, 5000));
        if last_tick.elapsed() >= tick {
            if !app.paused {
                if let Some(c) = collector.as_mut() {
                    let s = c.sample();
                    app.history.push(&s);
                    app.insights = insights::compute(&app.history, &s);
                    // Append to active recording (best-effort — we
                    // don't want one bad write to brick the live UI).
                    if let Some(rec) = app.recorder.as_mut() {
                        if let Err(e) = rec.push(&s) {
                            app.footer_flash = Some((
                                format!("recording: {}", e),
                                Instant::now() + Duration::from_secs(3),
                            ));
                            app.recorder = None;
                        }
                    }
                    app.snap = Some(s);
                }
                // Replay mode: nothing to sample, the History ring is
                // pre-populated and the scrubber drives displayed_snap.
            }
            last_tick = Instant::now();
        }

        if let Some(snap) = app.displayed_snap() {
            term.draw(|f| draw(f, &app, snap))?;
        }

        let timeout = tick.saturating_sub(last_tick.elapsed());
        if event::poll(timeout.max(Duration::from_millis(33)))? {
            match event::read()? {
                Event::Key(k) => {
                    if app.handle_key(k) {
                        break Ok::<(), anyhow::Error>(());
                    }
                }
                Event::Resize(_, _) => {}
                _ => {}
            }
        }
    };

    disable_raw_mode()?;
    execute!(term.backend_mut(), LeaveAlternateScreen)?;
    res?;
    Ok(())
}

fn draw(f: &mut ratatui::Frame, app: &App, snap: &Snapshot) {
    let area = f.area();
    if area.width < 20 || area.height < 6 {
        return;
    }
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // header
            Constraint::Length(2), // tab bar (label + underline)
            Constraint::Min(0),    // body
            Constraint::Length(2), // footer (separator + hotkeys)
        ])
        .split(area);

    chrome::draw_header(f, chunks[0], snap, app.live_state(), app.recorder.is_some());
    let active_insights = app
        .insights
        .iter()
        .filter(|i| i.severity != insights::Severity::Info)
        .count();
    chrome::draw_tab_bar(f, chunks[1], app.active, active_insights);
    let body = Rect {
        x: chunks[2].x,
        y: chunks[2].y,
        width: chunks[2].width,
        height: chunks[2].height,
    };
    tabs::draw(f, body, app, snap);
    // Drain expired footer flashes before drawing.
    let flash = app
        .footer_flash
        .as_ref()
        .filter(|(_, expires)| Instant::now() < *expires)
        .map(|(msg, _)| msg.as_str());
    chrome::draw_footer(f, chunks[3], app.graph_style, flash);

    // Modal popups paint over the dashboard. Help wins ties since it's
    // a hard requirement to read the docs even with settings open
    // (in practice both modals can't be open at once, but this is the
    // safe ordering).
    if app.settings_active {
        crate::ui::settings::render(f, app, area);
    }
    if app.help_active {
        crate::ui::help::render(f, area);
    }
}

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

    fn proc(pid: u32, cpu: f32) -> ProcTick {
        ProcTick {
            pid,
            cpu_pct: cpu,
            ..Default::default()
        }
    }

    fn snap_with(procs: Vec<ProcTick>) -> Snapshot {
        Snapshot {
            procs,
            ..Default::default()
        }
    }

    #[test]
    fn ewma_first_observation_is_value_itself() {
        let mut h = History::new(10);
        h.push(&snap_with(vec![proc(42, 80.0)]));
        // No prior reading → ewma = 0.7 * value + 0.3 * value = value.
        assert_eq!(h.proc_cpu_ewma.get(&42).copied(), Some(80.0));
    }

    #[test]
    fn ewma_converges_to_steady_state() {
        let mut h = History::new(20);
        // Stable signal at 100% over many ticks should pull EWMA toward 100.
        for _ in 0..15 {
            h.push(&snap_with(vec![proc(1, 100.0)]));
        }
        let v = h.proc_cpu_ewma.get(&1).copied().unwrap();
        assert!((v - 100.0).abs() < 0.01, "expected ≈100, got {}", v);
    }

    #[test]
    fn ewma_smooths_a_spike() {
        let mut h = History::new(20);
        for _ in 0..5 {
            h.push(&snap_with(vec![proc(1, 0.0)]));
        }
        // One transient spike to 100%.
        h.push(&snap_with(vec![proc(1, 100.0)]));
        let v = h.proc_cpu_ewma.get(&1).copied().unwrap();
        // Should be much less than 100 — the spike doesn't dominate.
        assert!(v > 20.0 && v < 50.0, "expected ~30, got {}", v);
    }

    #[test]
    fn ewma_prunes_pids_absent_from_latest_snapshot() {
        let mut h = History::new(10);
        h.push(&snap_with(vec![proc(1, 50.0), proc(2, 50.0)]));
        assert!(h.proc_cpu_ewma.contains_key(&1));
        assert!(h.proc_cpu_ewma.contains_key(&2));

        // pid 2 disappears.
        h.push(&snap_with(vec![proc(1, 50.0)]));
        assert!(h.proc_cpu_ewma.contains_key(&1));
        assert!(!h.proc_cpu_ewma.contains_key(&2));
    }

    #[test]
    fn session_mirrors_snapshots_into_ring() {
        let mut h = History::new(3);
        for cpu in [10.0, 20.0, 30.0, 40.0_f32] {
            h.push(&snap_with(vec![proc(1, cpu)]));
        }
        // Cap=3 → drops the oldest (10.0).
        let session = h.session.to_vec();
        assert_eq!(session.len(), 3);
        assert_eq!(session[0].procs[0].cpu_pct, 20.0);
        assert_eq!(session[2].procs[0].cpu_pct, 40.0);
    }
}