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
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
use std::borrow::Cow;

use crate::{action::Action, components::Component, errors::Result, models::TaskDetail, state::SearchHighlight, theme::Theme};
use ratatui::{
    prelude::*,
    widgets::{Block, BorderType, Borders, Clear, Padding, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
};

pub struct TaskDetailPanel<'a> {
    task: &'a TaskDetail,
    scroll_offset: u16,
    highlight: Option<&'a SearchHighlight>,
    cached_lines: Option<&'a [Line<'static>]>,
    /// Clamped scroll value computed during draw, readable after render.
    effective_scroll: u16,
    /// The scrollbar track area computed during draw, for mouse hit-testing.
    scrollbar_area: Option<Rect>,
    /// Total content height (line count) computed during draw.
    content_height: u16,
    /// Visible viewport height (line count) computed during draw.
    visible_height: u16,
}

pub struct SearchableLine {
    pub display: String,
    pub search_text: String,
}

struct DetailLine {
    display: Line<'static>,
    display_text: String,
    search_text: String,
}

impl DetailLine {
    fn new(display: Line<'static>) -> Self {
        let display_text = line_to_string(&display);
        Self {
            display,
            search_text: display_text.clone(),
            display_text,
        }
    }
}

fn line_to_string(line: &Line) -> String {
    let mut text = String::new();
    for span in &line.spans {
        text.push_str(span.content.as_ref());
    }
    text
}

impl<'a> TaskDetailPanel<'a> {
    pub fn new(task: &'a TaskDetail, scroll_offset: u16, highlight: Option<&'a SearchHighlight>) -> Self {
        Self::with_cached_lines(task, scroll_offset, highlight, None)
    }

    pub fn with_cached_lines(
        task: &'a TaskDetail,
        scroll_offset: u16,
        highlight: Option<&'a SearchHighlight>,
        cached_lines: Option<&'a [Line<'static>]>,
    ) -> Self {
        Self {
            task,
            scroll_offset,
            highlight,
            cached_lines,
            effective_scroll: 0,
            scrollbar_area: None,
            content_height: 0,
            visible_height: 0,
        }
    }

    /// Return the clamped scroll value computed during the last draw call.
    pub fn effective_scroll(&self) -> u16 {
        self.effective_scroll
    }

    /// Return the scrollbar track area computed during the last draw call.
    pub fn scrollbar_area(&self) -> Option<Rect> {
        self.scrollbar_area
    }

    /// Return the total content height computed during the last draw call.
    pub fn content_height(&self) -> u16 {
        self.content_height
    }

    /// Return the visible viewport height computed during the last draw call.
    pub fn visible_height(&self) -> u16 {
        self.visible_height
    }

    /// Calculate centered rect for the detail modal
    fn centered_rect(percent_x: u16, percent_y: u16, area: Rect) -> Rect {
        let popup_layout = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Percentage((100 - percent_y) / 2),
                Constraint::Percentage(percent_y),
                Constraint::Percentage((100 - percent_y) / 2),
            ])
            .split(area);

        Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage((100 - percent_x) / 2),
                Constraint::Percentage(percent_x),
                Constraint::Percentage((100 - percent_x) / 2),
            ])
            .split(popup_layout[1])[1]
    }

    fn format_timestamp(dt: &Option<chrono::DateTime<chrono::Utc>>) -> Cow<'static, str> {
        match dt {
            Some(t) => Cow::Owned(t.format("%Y-%m-%d %H:%M:%S UTC").to_string()),
            None => Cow::Borrowed("-"),
        }
    }

    fn status_color(status: &str, theme: &Theme) -> Color {
        if status.eq_ignore_ascii_case("PENDING") {
            Color::Yellow
        } else if status.eq_ignore_ascii_case("CLAIMED") {
            Color::Cyan
        } else if status.eq_ignore_ascii_case("RUNNING") {
            Color::Blue
        } else if status.eq_ignore_ascii_case("COMPLETED") {
            theme.success
        } else if status.eq_ignore_ascii_case("FAILED") {
            theme.error
        } else if status.eq_ignore_ascii_case("CANCELLED") {
            theme.muted
        } else if status.eq_ignore_ascii_case("EXPIRED") {
            Color::DarkGray
        } else {
            theme.text
        }
    }

    fn format_json(json_str: &Option<String>) -> Vec<String> {
        match json_str {
            Some(s) if !s.is_empty() => {
                // Try to pretty-print JSON with recursive string parsing
                if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(s) {
                    let expanded = Self::expand_nested_json(parsed);
                    if let Ok(pretty) = serde_json::to_string_pretty(&expanded) {
                        return pretty.lines().map(String::from).collect();
                    }
                }
                // Fallback: show raw string (split long lines)
                s.lines().map(String::from).collect()
            }
            _ => vec!["-".to_string()],
        }
    }

    /// Recursively expand JSON strings that contain escaped JSON
    fn expand_nested_json(value: serde_json::Value) -> serde_json::Value {
        use serde_json::Value;

        match value {
            Value::String(s) => {
                // Try to parse the string as JSON
                if s.starts_with('{') || s.starts_with('[') {
                    if let Ok(inner) = serde_json::from_str::<Value>(&s) {
                        return Self::expand_nested_json(inner);
                    }
                }
                Value::String(s)
            }
            Value::Array(arr) => {
                Value::Array(arr.into_iter().map(Self::expand_nested_json).collect())
            }
            Value::Object(obj) => {
                Value::Object(
                    obj.into_iter()
                        .map(|(k, v)| (k, Self::expand_nested_json(v)))
                        .collect(),
                )
            }
            other => other,
        }
    }

    fn build_detail_lines(&self, theme: &Theme) -> Vec<DetailLine> {
        let mut lines: Vec<DetailLine> = Vec::new();

        // Header section
        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("Task Name:    ", Style::default().fg(theme.muted)),
            Span::styled(self.task.task_name.clone(), Style::default().fg(theme.accent).bold()),
        ])));

        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("Queue:        ", Style::default().fg(theme.muted)),
            Span::styled(self.task.queue_name.clone(), Style::default().fg(theme.text)),
        ])));

        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("Status:       ", Style::default().fg(theme.muted)),
            Span::styled(
                self.task.status.clone(),
                Style::default().fg(Self::status_color(&self.task.status, theme)).bold(),
            ),
        ])));

        if let Some(ref code) = self.task.error_code {
            lines.push(DetailLine::new(Line::from(vec![
                Span::styled("Error Code:   ", Style::default().fg(theme.muted)),
                Span::styled(code.clone(), Style::default().fg(theme.error).bold()),
            ])));
        }

        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("Priority:     ", Style::default().fg(theme.muted)),
            Span::styled(format!("{}", self.task.priority), Style::default().fg(theme.text)),
        ])));

        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("Retries:      ", Style::default().fg(theme.muted)),
            Span::styled(
                format!("{} / {}", self.task.retry_count, self.task.max_retries),
                Style::default().fg(theme.text),
            ),
        ])));

        lines.push(DetailLine::new(Line::from("")));

        // Worker section
        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("Worker Info", Style::default().fg(theme.accent).bold()),
        ])));
        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("  Worker ID:  ", Style::default().fg(theme.muted)),
            Span::styled(
                self.task
                    .claimed_by_worker_id
                    .clone()
                    .unwrap_or_else(|| "-".to_string()),
                Style::default().fg(theme.text),
            ),
        ])));
        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("  Hostname:   ", Style::default().fg(theme.muted)),
            Span::styled(
                self.task
                    .worker_hostname
                    .clone()
                    .unwrap_or_else(|| "-".to_string()),
                Style::default().fg(theme.text),
            ),
        ])));
        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("  PID:        ", Style::default().fg(theme.muted)),
            Span::styled(
                self.task.worker_pid.map(|p| p.to_string()).unwrap_or_else(|| "-".to_string()),
                Style::default().fg(theme.text),
            ),
        ])));
        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("  Process:    ", Style::default().fg(theme.muted)),
            Span::styled(
                self.task.worker_process_name.clone().unwrap_or_else(|| "-".to_string()),
                Style::default().fg(theme.text),
            ),
        ])));

        lines.push(DetailLine::new(Line::from("")));

        // Timestamps section
        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("Timeline", Style::default().fg(theme.accent).bold()),
        ])));
        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("  Created:    ", Style::default().fg(theme.muted)),
            Span::styled(
                self.task.created_at.format("%Y-%m-%d %H:%M:%S UTC").to_string(),
                Style::default().fg(theme.text),
            ),
        ])));
        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("  Sent:       ", Style::default().fg(theme.muted)),
            Span::styled(Self::format_timestamp(&self.task.sent_at), Style::default().fg(theme.text)),
        ])));
        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("  Enqueued:   ", Style::default().fg(theme.muted)),
            Span::styled(self.task.enqueued_at.format("%Y-%m-%d %H:%M:%S UTC").to_string(), Style::default().fg(theme.text)),
        ])));
        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("  Claimed:    ", Style::default().fg(theme.muted)),
            Span::styled(Self::format_timestamp(&self.task.claimed_at), Style::default().fg(theme.text)),
        ])));
        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("  Started:    ", Style::default().fg(theme.muted)),
            Span::styled(Self::format_timestamp(&self.task.started_at), Style::default().fg(theme.text)),
        ])));
        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("  Completed:  ", Style::default().fg(theme.muted)),
            Span::styled(Self::format_timestamp(&self.task.completed_at), Style::default().fg(theme.text)),
        ])));
        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("  Failed:     ", Style::default().fg(theme.muted)),
            Span::styled(Self::format_timestamp(&self.task.failed_at), Style::default().fg(theme.text)),
        ])));

        lines.push(DetailLine::new(Line::from("")));

        // Attempts section
        if !self.task.attempts.is_empty() {
            lines.push(DetailLine::new(Line::from(vec![
                Span::styled("Attempts", Style::default().fg(theme.accent).bold()),
            ])));
            for (i, attempt) in self.task.attempts.iter().enumerate() {
                let retry_label = if attempt.will_retry { "yes" } else { "no" };
                let outcome_color = match attempt.outcome.as_str() {
                    "COMPLETED" => theme.success,
                    "FAILED" => theme.error,
                    "WORKER_FAILURE" => theme.error,
                    _ => theme.text,
                };
                lines.push(DetailLine::new(Line::from(vec![
                    Span::styled(
                        format!("  Attempt {} | ", attempt.attempt),
                        Style::default().fg(theme.muted),
                    ),
                    Span::styled(
                        attempt.outcome.clone(),
                        Style::default().fg(outcome_color).bold(),
                    ),
                    Span::styled(
                        format!(" | retry={}", retry_label),
                        Style::default().fg(theme.muted),
                    ),
                ])));
                lines.push(DetailLine::new(Line::from(vec![
                    Span::styled("    Started:  ", Style::default().fg(theme.muted)),
                    Span::styled(
                        attempt.started_at.format("%Y-%m-%d %H:%M:%S UTC").to_string(),
                        Style::default().fg(theme.text),
                    ),
                ])));
                lines.push(DetailLine::new(Line::from(vec![
                    Span::styled("    Finished: ", Style::default().fg(theme.muted)),
                    Span::styled(
                        attempt.finished_at.format("%Y-%m-%d %H:%M:%S UTC").to_string(),
                        Style::default().fg(theme.text),
                    ),
                ])));
                if let Some(ref code) = attempt.error_code {
                    lines.push(DetailLine::new(Line::from(vec![
                        Span::styled("    Error Code:    ", Style::default().fg(theme.muted)),
                        Span::styled(code.clone(), Style::default().fg(theme.error)),
                    ])));
                }
                if let Some(ref msg) = attempt.error_message {
                    lines.push(DetailLine::new(Line::from(vec![
                        Span::styled("    Error Message: ", Style::default().fg(theme.muted)),
                        Span::styled(msg.clone(), Style::default().fg(theme.error)),
                    ])));
                }
                if let Some(ref reason) = attempt.failed_reason {
                    lines.push(DetailLine::new(Line::from(vec![
                        Span::styled("    Failed Reason: ", Style::default().fg(theme.muted)),
                        Span::styled(reason.clone(), Style::default().fg(theme.error)),
                    ])));
                }
                // Worker info line when any worker field is present
                let has_worker = attempt.worker_id.is_some()
                    || attempt.worker_hostname.is_some()
                    || attempt.worker_pid.is_some()
                    || attempt.worker_process_name.is_some();
                if has_worker {
                    let parts: Vec<String> = [
                        attempt.worker_id.clone(),
                        attempt.worker_hostname.clone(),
                        attempt.worker_pid.map(|p| p.to_string()),
                        attempt.worker_process_name.clone(),
                    ]
                    .into_iter()
                    .flatten()
                    .collect();
                    lines.push(DetailLine::new(Line::from(vec![
                        Span::styled("    Worker: ", Style::default().fg(theme.muted)),
                        Span::styled(parts.join(" | "), Style::default().fg(theme.text)),
                    ])));
                }
                // Blank line between attempts (except after the last one)
                if i < self.task.attempts.len() - 1 {
                    lines.push(DetailLine::new(Line::from("")));
                }
            }
            lines.push(DetailLine::new(Line::from("")));
        }

        // Arguments section
        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("Arguments", Style::default().fg(theme.accent).bold()),
        ])));
        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("  args:   ", Style::default().fg(theme.muted)),
        ])));
        for arg_line in Self::format_json(&self.task.args) {
            lines.push(DetailLine::new(Line::from(vec![
                Span::styled(format!("    {}", arg_line), Style::default().fg(theme.text)),
            ])));
        }
        lines.push(DetailLine::new(Line::from(vec![
            Span::styled("  kwargs: ", Style::default().fg(theme.muted)),
        ])));
        for kwarg_line in Self::format_json(&self.task.kwargs) {
            lines.push(DetailLine::new(Line::from(vec![
                Span::styled(format!("    {}", kwarg_line), Style::default().fg(theme.text)),
            ])));
        }

        lines.push(DetailLine::new(Line::from("")));

        // Result/Error section
        if self.task.status.to_uppercase() == "COMPLETED" {
            lines.push(DetailLine::new(Line::from(vec![
                Span::styled("Result", Style::default().fg(theme.success).bold()),
            ])));
            for result_line in Self::format_json(&self.task.result) {
                lines.push(DetailLine::new(Line::from(vec![
                    Span::styled(format!("  {}", result_line), Style::default().fg(theme.text)),
                ])));
            }
        } else if self.task.status.to_uppercase() == "FAILED" {
            lines.push(DetailLine::new(Line::from(vec![
                Span::styled("Error", Style::default().fg(theme.error).bold()),
            ])));

            let has_failed_reason = self.task.failed_reason.as_ref().is_some_and(|s| !s.is_empty());
            let has_result = self.task.result.as_ref().is_some_and(|s| !s.is_empty());

            if has_failed_reason {
                lines.push(DetailLine::new(Line::from(vec![
                    Span::styled("  Reason:", Style::default().fg(theme.error).bold()),
                ])));
                for error_line in Self::format_json(&self.task.failed_reason) {
                    lines.push(DetailLine::new(Line::from(vec![
                        Span::styled(format!("    {}", error_line), Style::default().fg(theme.error)),
                    ])));
                }
            }

            if has_result {
                if has_failed_reason {
                    lines.push(DetailLine::new(Line::from("")));
                }
                lines.push(DetailLine::new(Line::from(vec![
                    Span::styled("  Result:", Style::default().fg(theme.error).bold()),
                ])));
                for result_line in Self::format_json(&self.task.result) {
                    lines.push(DetailLine::new(Line::from(vec![
                        Span::styled(format!("    {}", result_line), Style::default().fg(theme.error)),
                    ])));
                }
            }

            if !has_failed_reason && !has_result {
                lines.push(DetailLine::new(Line::from(vec![
                    Span::styled("  -", Style::default().fg(theme.error)),
                ])));
            }
        }

        lines
    }

    pub fn build_search_lines(&self, theme: &Theme) -> Vec<SearchableLine> {
        self.build_detail_lines(theme)
            .into_iter()
            .map(|line| SearchableLine {
                display: line.display_text,
                search_text: line.search_text,
            })
            .collect()
    }

    pub fn build_display_lines(&self, theme: &Theme) -> Vec<Line<'static>> {
        self.build_detail_lines(theme)
            .into_iter()
            .map(|line| line.display)
            .collect()
    }
}

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

    fn draw(&mut self, frame: &mut Frame, area: Rect, theme: &Theme) -> Result<()> {
        let popup_area = Self::centered_rect(80, 85, area);

        // Clear the background
        frame.render_widget(Clear, popup_area);

        let title = format!(" Task: {} - Esc: close | ↑↓/PgUp/PgDn/Home/End: scroll | []: prev/next | y: copy ", self.task.id);
        let block = Block::default()
            .title(title)
            .borders(Borders::ALL)
            .border_style(Style::default().fg(theme.accent))
            .border_type(BorderType::Rounded)
            .padding(Padding::uniform(1))
            .style(Style::default().bg(theme.surface));

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

        let owned_lines;
        let source_lines: &[Line<'static>] = if let Some(cached) = self.cached_lines {
            cached
        } else {
            owned_lines = self.build_display_lines(theme);
            &owned_lines
        };

        // Calculate total content height for scrollbar
        let content_height = source_lines.len() as u16;
        let visible_height = inner.height;
        self.content_height = content_height;
        self.visible_height = visible_height;

        // Apply scroll offset (clamp to valid range).
        // Without Wrap, logical lines == visual lines so manual slicing is correct.
        let scroll = self.scroll_offset.min(content_height.saturating_sub(visible_height));
        self.effective_scroll = scroll;
        let start = scroll as usize;
        let end = (start + visible_height as usize).min(source_lines.len());
        let mut visible_lines: Vec<Line> = source_lines[start..end].iter().cloned().collect();

        // Add search pointer only for visible highlighted lines.
        if let Some(highlight) = &self.highlight {
            for (offset, line) in visible_lines.iter_mut().enumerate() {
                if highlight.matches_line(start + offset) {
                    line.spans.push(Span::styled(
                        format!(" {}", highlight.pointer()),
                        Style::default().fg(theme.accent),
                    ));
                }
            }
        }

        let paragraph = Paragraph::new(visible_lines)
            .style(Style::default().bg(theme.background).fg(theme.text))
            .scroll((0, 0));

        frame.render_widget(paragraph, inner);

        // Render scrollbar if content overflows
        if content_height > visible_height {
            let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight)
                .begin_symbol(Some(""))
                .end_symbol(Some(""))
                .track_symbol(Some(""))
                .thumb_symbol("");

            let scrollbar_track = inner.inner(Margin { vertical: 1, horizontal: 0 });
            self.scrollbar_area = Some(scrollbar_track);

            let mut scrollbar_state = ScrollbarState::new(content_height as usize)
                .position(scroll as usize)
                .viewport_content_length(visible_height as usize);

            frame.render_stateful_widget(
                scrollbar,
                scrollbar_track,
                &mut scrollbar_state,
            );
        } else {
            self.scrollbar_area = None;
        }

        Ok(())
    }
}