tr300-tui 1.4.3

Real-time interactive system diagnostic TUI
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
use crossterm::event::{Event, KeyCode, KeyEventKind, KeyModifiers};
use futures::StreamExt;
use ratatui::DefaultTerminal;
use std::time::Duration;
use tokio::time::interval;

use crate::collectors::disk_health::DiskHealthData;
use crate::collectors::drivers::{DriverData, DriverScanStatus};
use crate::collectors::network_diag::NetworkDiagData;
use crate::collectors::{DiagnosticWarning, SystemSnapshot, WarningSeverity};
use crate::error::Result;
use crate::history::HistoryBuffer;
use crate::types::{DiagnosticMode, HealthStatus, ProcessSortKey, Section, TempUnit};
use crate::ui;

// -- Refresh Intervals --
const REFRESH_FAST: Duration = Duration::from_secs(1);
const REFRESH_SLOW: Duration = Duration::from_secs(5);
const REFRESH_MEDIUM: Duration = Duration::from_secs(3);
const REFRESH_DIAG: Duration = Duration::from_secs(15);
const REFRESH_HEALTH: Duration = Duration::from_secs(60);
const HISTORY_SAMPLES: usize = 60;

/// Main application state
pub struct App {
    /// Current diagnostic mode (None = show mode selection screen)
    pub mode: Option<DiagnosticMode>,
    /// Currently active section
    pub current_section: Section,
    /// Whether the app should quit
    pub should_quit: bool,
    /// Whether to show the help overlay
    pub show_help: bool,
    /// System data snapshot
    pub snapshot: SystemSnapshot,
    /// CPU usage history (60 samples)
    pub cpu_history: HistoryBuffer,
    /// Memory usage history
    pub mem_history: HistoryBuffer,
    /// Network download history
    pub net_down_history: HistoryBuffer,
    /// Network upload history
    pub net_up_history: HistoryBuffer,
    /// Process table scroll offset
    pub process_scroll: usize,
    /// Process sort key
    pub process_sort: ProcessSortKey,
    /// Whether terminal is too small
    pub too_small: bool,
    /// Per-core CPU history
    pub per_core_history: Vec<HistoryBuffer>,
    /// Swap usage history
    pub swap_history: HistoryBuffer,
    /// GPU usage history
    pub gpu_history: HistoryBuffer,
    /// Temperature history
    pub temp_history: HistoryBuffer,
    /// Temperature display unit (Celsius or Fahrenheit)
    pub temp_unit: TempUnit,
    /// Network connection table scroll offset
    pub connection_scroll: usize,
    /// Disk I/O read history
    pub disk_read_history: HistoryBuffer,
    /// Disk I/O write history
    pub disk_write_history: HistoryBuffer,
    /// Drivers section scroll offset (tech mode)
    pub driver_scroll: usize,
    /// Disk section scroll offset (tech mode)
    pub disk_scroll: usize,
    /// Async driver scan handle
    driver_scan_handle: Option<tokio::task::JoinHandle<DriverData>>,
    /// Async connectivity check handle
    connectivity_check_handle:
        Option<tokio::task::JoinHandle<(NetworkDiagData, Vec<DiagnosticWarning>)>>,
    /// Async disk health scan handle
    disk_health_handle: Option<tokio::task::JoinHandle<(DiskHealthData, Vec<DiagnosticWarning>)>>,
}

impl App {
    pub fn new(initial_mode: Option<DiagnosticMode>) -> Self {
        Self {
            mode: initial_mode,
            current_section: Section::Overview,
            should_quit: false,
            show_help: false,
            snapshot: SystemSnapshot::default(),
            cpu_history: HistoryBuffer::new(HISTORY_SAMPLES),
            mem_history: HistoryBuffer::new(HISTORY_SAMPLES),
            net_down_history: HistoryBuffer::new(HISTORY_SAMPLES),
            net_up_history: HistoryBuffer::new(HISTORY_SAMPLES),
            process_scroll: 0,
            process_sort: ProcessSortKey::Cpu,
            too_small: false,
            per_core_history: Vec::new(),
            swap_history: HistoryBuffer::new(HISTORY_SAMPLES),
            gpu_history: HistoryBuffer::new(HISTORY_SAMPLES),
            temp_history: HistoryBuffer::new(HISTORY_SAMPLES),
            temp_unit: TempUnit::Celsius,
            connection_scroll: 0,
            disk_read_history: HistoryBuffer::new(HISTORY_SAMPLES),
            disk_write_history: HistoryBuffer::new(HISTORY_SAMPLES),
            driver_scroll: 0,
            disk_scroll: 0,
            driver_scan_handle: None,
            connectivity_check_handle: None,
            disk_health_handle: None,
        }
    }

    /// Run the main event loop
    pub async fn run(&mut self, terminal: &mut DefaultTerminal) -> Result<()> {
        // Initial data collection
        self.snapshot.refresh_static();
        self.snapshot.refresh_fast();
        self.snapshot.refresh_slow();
        self.snapshot.refresh_connections();

        // Initial driver scan — async to avoid blocking UI
        self.start_driver_scan();

        // Initial connectivity check in background
        self.start_connectivity_check();
        self.start_disk_health_scan();

        let mut fast_tick = interval(REFRESH_FAST);
        let mut slow_tick = interval(REFRESH_SLOW);
        let mut medium_tick = interval(REFRESH_MEDIUM);
        let mut diag_tick = interval(REFRESH_DIAG);
        let mut health_tick = interval(REFRESH_HEALTH);
        let mut event_stream = crossterm::event::EventStream::new();

        loop {
            self.poll_background_scans().await;

            // Draw
            let size = terminal.size()?;
            self.too_small = size.width < 80 || size.height < 24;
            terminal.draw(|frame| ui::render(frame, self))?;

            if self.should_quit {
                return Ok(());
            }

            // Event handling with tokio select
            tokio::select! {
                _ = fast_tick.tick() => {
                    self.snapshot.refresh_fast();
                    self.update_fast_history();
                }
                _ = slow_tick.tick() => {
                    self.snapshot.refresh_slow();
                }
                _ = medium_tick.tick() => {
                    self.snapshot.refresh_connections();
                }
                _ = diag_tick.tick() => {
                    if self.connectivity_check_handle.is_none() {
                        self.start_connectivity_check();
                    }
                }
                _ = health_tick.tick() => {
                    if self.disk_health_handle.is_none() {
                        self.start_disk_health_scan();
                    }
                }
                event = event_stream.next() => {
                    if let Some(Ok(evt)) = event {
                        self.handle_event(evt);
                    }
                }
            }
        }
    }

    fn start_driver_scan(&mut self) {
        self.snapshot.drivers.scan_status = DriverScanStatus::Scanning;
        self.driver_scan_handle = Some(tokio::task::spawn_blocking(
            crate::collectors::drivers::collect,
        ));
    }

    fn start_connectivity_check(&mut self) {
        self.connectivity_check_handle = Some(tokio::task::spawn_blocking(
            crate::collectors::network_diag::collect_connectivity,
        ));
    }

    fn start_disk_health_scan(&mut self) {
        self.disk_health_handle = Some(tokio::task::spawn_blocking(
            crate::collectors::disk_health::collect,
        ));
    }

    async fn poll_background_scans(&mut self) {
        if self
            .driver_scan_handle
            .as_ref()
            .is_some_and(tokio::task::JoinHandle::is_finished)
        {
            if let Some(handle) = self.driver_scan_handle.take() {
                if let Ok(data) = handle.await {
                    self.snapshot.warnings.retain(|w| w.source != "Drivers");
                    if let DriverScanStatus::ScanFailed(ref msg) = data.scan_status {
                        self.snapshot.warnings.push(DiagnosticWarning {
                            source: "Drivers".into(),
                            message: msg.clone(),
                            severity: WarningSeverity::Warning,
                        });
                    }
                    self.snapshot.drivers = data;
                }
            }
        }

        if self
            .connectivity_check_handle
            .as_ref()
            .is_some_and(tokio::task::JoinHandle::is_finished)
        {
            if let Some(handle) = self.connectivity_check_handle.take() {
                if let Ok((diag_data, diag_warnings)) = handle.await {
                    self.snapshot.network_diag.gateway = diag_data.gateway;
                    self.snapshot.network_diag.dns = diag_data.dns;
                    self.snapshot.network_diag.internet = diag_data.internet;
                    self.snapshot.warnings.retain(|w| w.source != "Network");
                    self.snapshot.warnings.extend(diag_warnings);
                }
            }
        }

        if self
            .disk_health_handle
            .as_ref()
            .is_some_and(tokio::task::JoinHandle::is_finished)
        {
            if let Some(handle) = self.disk_health_handle.take() {
                if let Ok((health_data, health_warnings)) = handle.await {
                    self.snapshot.disk_health = health_data;
                    self.snapshot.warnings.retain(|w| w.source != "Disk Health");
                    self.snapshot.warnings.extend(health_warnings);
                }
            }
        }
    }

    fn update_fast_history(&mut self) {
        // CPU total
        self.cpu_history.push(self.snapshot.cpu.total_usage as f64);

        // Per-core
        while self.per_core_history.len() < self.snapshot.cpu.per_core_usage.len() {
            self.per_core_history
                .push(HistoryBuffer::new(HISTORY_SAMPLES));
        }
        for (i, usage) in self.snapshot.cpu.per_core_usage.iter().enumerate() {
            if let Some(buf) = self.per_core_history.get_mut(i) {
                buf.push(*usage as f64);
            }
        }

        // Memory
        let mem_pct = if self.snapshot.memory.total_bytes > 0 {
            (self.snapshot.memory.used_bytes as f64 / self.snapshot.memory.total_bytes as f64)
                * 100.0
        } else {
            0.0
        };
        self.mem_history.push(mem_pct);

        // Swap
        let swap_pct = if self.snapshot.memory.swap_total_bytes > 0 {
            (self.snapshot.memory.swap_used_bytes as f64
                / self.snapshot.memory.swap_total_bytes as f64)
                * 100.0
        } else {
            0.0
        };
        self.swap_history.push(swap_pct);

        // Network
        self.net_down_history
            .push(self.snapshot.network.total_download_rate as f64);
        self.net_up_history
            .push(self.snapshot.network.total_upload_rate as f64);

        // GPU
        self.gpu_history
            .push(self.snapshot.gpu.utilization_percent as f64);

        // Temperature
        if let Some(cpu_temp) = self.snapshot.thermals.cpu_temp {
            self.temp_history.push(cpu_temp);
        }

        // Disk I/O
        if let Some(drive) = self.snapshot.disk_health.drives.first() {
            if let Some(ref io) = drive.io_stats {
                self.disk_read_history.push(io.read_bytes_per_sec as f64);
                self.disk_write_history.push(io.write_bytes_per_sec as f64);
            }
        }
    }

    fn handle_event(&mut self, event: Event) {
        if let Event::Key(key) = event {
            if key.kind != KeyEventKind::Press {
                return;
            }

            // Ctrl+C always quits immediately
            if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {
                self.should_quit = true;
                return;
            }

            // Help overlay takes priority
            if self.show_help {
                match key.code {
                    KeyCode::Char('?') | KeyCode::Esc => self.show_help = false,
                    _ => {}
                }
                return;
            }

            // Mode selection screen
            if self.mode.is_none() {
                match key.code {
                    KeyCode::Char('1') => self.mode = Some(DiagnosticMode::User),
                    KeyCode::Char('2') => self.mode = Some(DiagnosticMode::Technician),
                    KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true,
                    _ => {}
                }
                return;
            }

            // Main navigation
            match key.code {
                KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true,
                KeyCode::Char('m') => self.mode = None,
                KeyCode::Char('?') => self.show_help = true,
                KeyCode::Char(c @ '1'..='9') => {
                    if let Some(section) = Section::from_number(c as u8 - b'0') {
                        self.current_section = section;
                        self.process_scroll = 0;
                        self.connection_scroll = 0;
                        self.driver_scroll = 0;
                        self.disk_scroll = 0;
                    }
                }
                // Scrollable table controls
                KeyCode::Char('j') | KeyCode::Down => {
                    match self.current_section {
                        Section::Processes => {
                            let max = self.snapshot.processes.list.len().saturating_sub(1);
                            self.process_scroll = (self.process_scroll + 1).min(max);
                        }
                        Section::Network => {
                            let max = self
                                .snapshot
                                .network_diag
                                .active_connections
                                .len()
                                .saturating_sub(1);
                            self.connection_scroll = (self.connection_scroll + 1).min(max);
                        }
                        Section::Drivers => {
                            // Upper bound clamped in render; just increment here
                            self.driver_scroll = self.driver_scroll.saturating_add(1);
                        }
                        Section::Disk => {
                            self.disk_scroll = self.disk_scroll.saturating_add(1);
                        }
                        _ => {}
                    }
                }
                KeyCode::Char('k') | KeyCode::Up => match self.current_section {
                    Section::Processes => {
                        self.process_scroll = self.process_scroll.saturating_sub(1);
                    }
                    Section::Network => {
                        self.connection_scroll = self.connection_scroll.saturating_sub(1);
                    }
                    Section::Drivers => {
                        self.driver_scroll = self.driver_scroll.saturating_sub(1);
                    }
                    Section::Disk => {
                        self.disk_scroll = self.disk_scroll.saturating_sub(1);
                    }
                    _ => {}
                },
                KeyCode::Char('c') if self.current_section == Section::Processes => {
                    self.process_sort = ProcessSortKey::Cpu;
                }
                KeyCode::Char('M') if self.current_section == Section::Processes => {
                    self.process_sort = ProcessSortKey::Memory;
                }
                KeyCode::Char('n') if self.current_section == Section::Processes => {
                    self.process_sort = ProcessSortKey::Name;
                }
                KeyCode::Char('p') if self.current_section == Section::Processes => {
                    self.process_sort = ProcessSortKey::Pid;
                }
                // Temperature unit toggle
                KeyCode::Char('f') => {
                    self.temp_unit = self.temp_unit.toggle();
                }
                // Manual refresh for drivers section (non-blocking)
                KeyCode::Char('r')
                    if self.current_section == Section::Drivers
                        && self.driver_scan_handle.is_none() =>
                {
                    self.start_driver_scan();
                }
                _ => {}
            }
        }
    }

    /// Get overall system health status
    pub fn overall_health(&self) -> HealthStatus {
        let cpu_status = HealthStatus::from_percent(self.snapshot.cpu.total_usage as f64);
        let mem_pct = if self.snapshot.memory.total_bytes > 0 {
            (self.snapshot.memory.used_bytes as f64 / self.snapshot.memory.total_bytes as f64)
                * 100.0
        } else {
            0.0
        };
        let mem_status = HealthStatus::from_percent(mem_pct);

        // Worst of all statuses
        if cpu_status == HealthStatus::Critical || mem_status == HealthStatus::Critical {
            HealthStatus::Critical
        } else if cpu_status == HealthStatus::Warning || mem_status == HealthStatus::Warning {
            HealthStatus::Warning
        } else {
            HealthStatus::Good
        }
    }
}