syce 0.1.1

Monitoring TUI for horsies task library
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
use crate::{
    action::Action,
    components::Component,
    errors::Result,
    state::AppState,
    theme::Theme,
};
use ratatui::{
    prelude::*,
    widgets::{Axis, Block, Borders, Cell, Chart, Dataset, GraphType, Paragraph, Row, Table},
};

pub struct Workers<'a> {
    state: &'a AppState,
}

impl<'a> Workers<'a> {
    pub fn new(state: &'a AppState) -> Self {
        Self { state }
    }

    /// Render the worker list table (left pane)
    fn render_worker_list(&self, frame: &mut Frame, area: Rect, theme: &Theme) {
        let block = Block::default()
            .title("Active Workers")
            .borders(Borders::ALL)
            .border_style(Style::default().fg(theme.border))
            .style(Style::default().bg(theme.background));

        if self.state.worker_list.is_empty() {
            let placeholder = Paragraph::new("No active workers")
                .style(theme.muted_style())
                .alignment(Alignment::Center)
                .block(block);
            frame.render_widget(placeholder, area);
            return;
        }

        // Build table rows
        let rows: Vec<Row> = self
            .state
            .worker_list
            .iter()
            .enumerate()
            .map(|(idx, worker)| {
                let is_selected = self.state.selected_worker_index == Some(idx);
                let style = if is_selected {
                    Style::default()
                        .fg(theme.background)
                        .bg(theme.accent)
                        .bold()
                } else {
                    Style::default().fg(theme.text)
                };

                // Check if this worker should show the search pointer (appended to last cell)
                let pointer: &str = self.state.search_highlight.as_ref()
                    .filter(|h| h.matches(&worker.worker_id))
                    .map_or("", |h| h.pointer());

                // Build last cell with optional pointer
                let mem_cell = if pointer.is_empty() {
                    format!("{:.1}%", worker.memory_percent.unwrap_or(0.0))
                } else {
                    format!("{:.1}% {}", worker.memory_percent.unwrap_or(0.0), pointer)
                };

                Row::new(vec![
                    Cell::from(worker.worker_id.clone()),
                    Cell::from(worker.hostname.clone()),
                    Cell::from(format!("{}", worker.pid)),
                    Cell::from(format!("{}/{}", worker.tasks_running, worker.processes)),
                    Cell::from(format!("{:.1}%", worker.cpu_percent.unwrap_or(0.0))),
                    Cell::from(mem_cell),
                ])
                .style(style)
            })
            .collect();

        let widths = [
            Constraint::Fill(2),   // Worker ID (takes more space)
            Constraint::Fill(2),   // Hostname (takes more space)
            Constraint::Min(8),    // PID (min 8 cols)
            Constraint::Min(8),    // Tasks (min 8 cols)
            Constraint::Min(8),    // CPU% (min 8 cols)
            Constraint::Min(10),   // Mem% (min 10 cols to accommodate pointer)
        ];

        let table = Table::new(rows, widths)
            .header(
                Row::new(vec!["Worker ID", "Hostname", "PID", "Tasks", "CPU%", "Mem%"])
                    .style(Style::default().fg(theme.accent).bold())
                    .bottom_margin(1),
            )
            .block(block)
            .row_highlight_style(Style::default().bg(theme.accent))
            .style(Style::default().bg(theme.background).fg(theme.text));

        frame.render_widget(table, area);
    }

    /// Render worker details header (identity & uptime)
    fn render_worker_header(&self, frame: &mut Frame, area: Rect, theme: &Theme) {
        let block = Block::default()
            .title("Worker Details")
            .borders(Borders::ALL)
            .border_style(Style::default().fg(theme.border))
            .style(Style::default().bg(theme.background));

        let Some(worker_id) = self.state.selected_worker_id.as_ref() else {
            let placeholder = Paragraph::new("← Select a worker from the list")
                .style(theme.muted_style())
                .alignment(Alignment::Center)
                .block(block);
            frame.render_widget(placeholder, area);
            return;
        };

        let inner = block.inner(area);
        frame.render_widget(block, area);

        // Get worker uptime and queues data
        let uptime = self.state.worker_uptime.get(worker_id);
        let queues = self.state.worker_queues.get(worker_id);

        let mut lines = Vec::new();

        // Worker identity
        lines.push(Line::from(vec![
            Span::styled("Worker: ", theme.muted_style()),
            Span::styled(worker_id.clone(), Style::default().fg(theme.accent).bold()),
        ]));

        if let Some(uptime_row) = uptime {
            lines.push(Line::from(vec![
                Span::styled("Hostname: ", theme.muted_style()),
                Span::styled(
                    uptime_row.hostname.clone(),
                    Style::default().fg(theme.text),
                ),
            ]));

            // Format uptime
            lines.push(Line::from(vec![
                Span::styled("Uptime: ", theme.muted_style()),
                Span::styled(
                    format!("{:?}", uptime_row.uptime),
                    Style::default().fg(theme.text),
                ),
            ]));

            lines.push(Line::from(vec![
                Span::styled("Started: ", theme.muted_style()),
                Span::styled(
                    uptime_row.worker_started_at.format("%Y-%m-%d %H:%M:%S").to_string(),
                    Style::default().fg(theme.text),
                ),
            ]));
        }

        if let Some(queues_row) = queues {
            lines.push(Line::from(""));
            lines.push(Line::from(vec![
                Span::styled("Queues: ", theme.muted_style()),
                Span::styled(
                    queues_row.queues.join(", "),
                    Style::default().fg(theme.text),
                ),
            ]));

            lines.push(Line::from(vec![
                Span::styled("Tasks: ", theme.muted_style()),
                Span::styled(
                    format!("Running: {}, Claimed: {}", queues_row.tasks_running, queues_row.tasks_claimed),
                    Style::default().fg(theme.text),
                ),
            ]));
        }

        let paragraph = Paragraph::new(lines)
            .style(Style::default().bg(theme.background));
        frame.render_widget(paragraph, inner);
    }

    /// Render worker load charts with configurable time window
    fn render_worker_charts(&self, frame: &mut Frame, area: Rect, theme: &Theme) {
        let time_window_label = self.state.selected_time_window.label();
        let block = Block::default()
            .title(format!("Load History ({}) [use [ ] to change]", time_window_label))
            .borders(Borders::ALL)
            .border_style(Style::default().fg(theme.border))
            .style(Style::default().bg(theme.background));

        let Some(worker_id) = self.state.selected_worker_id.as_ref() else {
            let placeholder = Paragraph::new("No worker selected")
                .style(theme.muted_style())
                .alignment(Alignment::Center)
                .block(block);
            frame.render_widget(placeholder, area);
            return;
        };

        let Some(load_history) = self.state.worker_load_history.get(worker_id) else {
            let placeholder = Paragraph::new("No load history available")
                .style(theme.muted_style())
                .alignment(Alignment::Center)
                .block(block);
            frame.render_widget(placeholder, area);
            return;
        };

        if load_history.is_empty() {
            let placeholder = Paragraph::new("No load history data yet")
                .style(theme.muted_style())
                .alignment(Alignment::Center)
                .block(block);
            frame.render_widget(placeholder, area);
            return;
        }

        let inner = block.inner(area);
        frame.render_widget(block, area);

        // Split into two rows for different charts
        let chart_areas = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
            .split(inner);

        // Prepare data using actual timestamps (safe after empty check above)
        let Some(oldest) = load_history.first() else {
            return;
        };
        let now = chrono::Utc::now();
        let oldest_time = oldest.snapshot_at;
        let time_span = (now - oldest_time).num_seconds() as f64;

        // Convert to (x, y) coordinates using seconds from oldest
        let tasks_running_data: Vec<(f64, f64)> = load_history
            .iter()
            .map(|p| {
                let x = (p.snapshot_at - oldest_time).num_seconds() as f64;
                let y = p.tasks_running as f64;
                (x, y)
            })
            .collect();

        let tasks_claimed_data: Vec<(f64, f64)> = load_history
            .iter()
            .map(|p| {
                let x = (p.snapshot_at - oldest_time).num_seconds() as f64;
                let y = p.tasks_claimed as f64;
                (x, y)
            })
            .collect();

        let cpu_data: Vec<(f64, f64)> = load_history
            .iter()
            .map(|p| {
                let x = (p.snapshot_at - oldest_time).num_seconds() as f64;
                let y = p.cpu_percent.unwrap_or(0.0);
                (x, y)
            })
            .collect();

        let memory_data: Vec<(f64, f64)> = load_history
            .iter()
            .map(|p| {
                let x = (p.snapshot_at - oldest_time).num_seconds() as f64;
                let y = p.memory_percent.unwrap_or(0.0);
                (x, y)
            })
            .collect();

        // Calculate Y-axis bounds in a single pass
        let (max_tasks, max_cpu, max_mem) = load_history.iter().fold(
            (10i32, 0.0f64, 0.0f64),
            |(max_t, max_c, max_m), p| (
                max_t.max(p.tasks_running.max(p.tasks_claimed)),
                max_c.max(p.cpu_percent.unwrap_or(0.0)),
                max_m.max(p.memory_percent.unwrap_or(0.0)),
            ),
        );
        let tasks_y_max = (max_tasks as f64 * 1.2).max(5.0);
        let resources_y_max = (max_cpu.max(max_mem) * 1.2).max(1.0);

        // Get current (latest) values (safe after empty check above)
        let Some(latest) = load_history.last() else {
            return;
        };
        let current_running = latest.tasks_running;
        let current_claimed = latest.tasks_claimed;
        let current_cpu = latest.cpu_percent.unwrap_or(0.0);
        let current_memory = latest.memory_percent.unwrap_or(0.0);

        // Task Load Chart
        let tasks_datasets = vec![
            Dataset::default()
                .name(format!("Running: {}", current_running))
                .marker(symbols::Marker::Braille)
                .graph_type(GraphType::Line)
                .style(Style::default().fg(theme.accent))
                .data(&tasks_running_data),
            Dataset::default()
                .name(format!("Claimed: {}", current_claimed))
                .marker(symbols::Marker::Braille)
                .graph_type(GraphType::Line)
                .style(Style::default().fg(theme.success))
                .data(&tasks_claimed_data),
        ];

        // Create time labels for X-axis
        let time_labels = vec![
            Span::raw(format!("{}s ago", time_span as i64)),
            Span::raw(format!("{}s", (time_span / 2.0) as i64)),
            Span::raw("now"),
        ];

        let tasks_x_axis = Axis::default()
            .title("Time")
            .style(Style::default().fg(theme.text))
            .bounds([0.0, time_span])
            .labels(time_labels.clone());

        let tasks_y_axis = Axis::default()
            .title("Tasks")
            .style(Style::default().fg(theme.text))
            .bounds([0.0, tasks_y_max])
            .labels(vec![
                Span::raw("0"),
                Span::raw(format!("{:.0}", tasks_y_max / 2.0)),
                Span::raw(format!("{:.0}", tasks_y_max)),
            ]);

        let tasks_chart = Chart::new(tasks_datasets)
            .block(Block::default().title("Task Load").borders(Borders::NONE))
            .x_axis(tasks_x_axis)
            .y_axis(tasks_y_axis);

        frame.render_widget(tasks_chart, chart_areas[0]);

        // Resource Usage Chart
        let resources_datasets = vec![
            Dataset::default()
                .name(format!("CPU: {:.2}%", current_cpu))
                .marker(symbols::Marker::Braille)
                .graph_type(GraphType::Line)
                .style(Style::default().fg(theme.warning))
                .data(&cpu_data),
            Dataset::default()
                .name(format!("Mem: {:.2}%", current_memory))
                .marker(symbols::Marker::Braille)
                .graph_type(GraphType::Line)
                .style(Style::default().fg(Color::Cyan))
                .data(&memory_data),
        ];

        let resources_x_axis = Axis::default()
            .title("Time")
            .style(Style::default().fg(theme.text))
            .bounds([0.0, time_span])
            .labels(time_labels);

        let resources_y_axis = Axis::default()
            .title("%")
            .style(Style::default().fg(theme.text))
            .bounds([0.0, resources_y_max])
            .labels(vec![
                Span::raw("0"),
                Span::raw(format!("{:.2}", resources_y_max / 2.0)),
                Span::raw(format!("{:.2}", resources_y_max)),
            ]);

        let resources_chart = Chart::new(resources_datasets)
            .block(
                Block::default()
                    .title("Resource Usage (dynamic scale)")
                    .borders(Borders::NONE),
            )
            .x_axis(resources_x_axis)
            .y_axis(resources_y_axis);

        frame.render_widget(resources_chart, chart_areas[1]);
    }

    /// Render dead workers section (bottom)
    fn render_dead_workers(&self, frame: &mut Frame, area: Rect, theme: &Theme) {
        let block = Block::default()
            .title("Dead Workers")
            .borders(Borders::ALL)
            .border_style(Style::default().fg(theme.border))
            .style(Style::default().bg(theme.background));

        if self.state.dead_workers.is_empty() {
            let placeholder = Paragraph::new("No dead workers")
                .style(Style::default().fg(theme.success))
                .alignment(Alignment::Center)
                .block(block);
            frame.render_widget(placeholder, area);
            return;
        }

        // Build table rows
        let rows: Vec<Row> = self
            .state
            .dead_workers
            .iter()
            .map(|worker| {
                Row::new(vec![
                    Cell::from(worker.worker_id.clone()),
                    Cell::from(worker.hostname.clone()),
                    Cell::from(format!("{}", worker.pid)),
                    Cell::from(worker.last_seen.format("%H:%M:%S").to_string()),
                    Cell::from(format!("{}", worker.tasks_at_death)),
                ])
                .style(Style::default().fg(theme.error))
            })
            .collect();

        let widths = [
            Constraint::Fill(2),   // Worker ID
            Constraint::Fill(2),   // Hostname
            Constraint::Min(8),    // PID
            Constraint::Fill(1),   // Last Seen
            Constraint::Min(10),   // Tasks at Death
        ];

        let table = Table::new(rows, widths)
            .header(
                Row::new(vec!["Worker ID", "Hostname", "PID", "Last Seen", "Tasks"])
                    .style(Style::default().fg(theme.accent).bold())
                    .bottom_margin(1),
            )
            .block(block)
            .style(Style::default().bg(theme.background).fg(theme.text));

        frame.render_widget(table, area);
    }
}

impl<'a> Component for Workers<'a> {
    fn update(&mut self, _action: Action) -> Result<Option<Action>> {
        Ok(None)
    }

    fn draw(&mut self, frame: &mut Frame, area: Rect, theme: &Theme) -> Result<()> {
        // Main horizontal split: left (worker list) and right (details)
        // Use Min/Fill for responsive layout on wide screens
        let main_chunks = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Min(60),  // Left: Worker list (min 60 cols, won't expand unnecessarily)
                Constraint::Fill(1),  // Right: Details (takes remaining space)
            ])
            .split(area);

        // Render worker list on the left
        self.render_worker_list(frame, main_chunks[0], theme);

        // Split right side vertically: header, charts, dead workers
        let right_chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(10), // Header: Identity & uptime
                Constraint::Min(8),     // Charts: Load history
                Constraint::Length(8),  // Dead workers
            ])
            .split(main_chunks[1]);

        self.render_worker_header(frame, right_chunks[0], theme);
        self.render_worker_charts(frame, right_chunks[1], theme);
        self.render_dead_workers(frame, right_chunks[2], theme);

        Ok(())
    }
}