cindy-cli 0.2.1

Managing infrastructure at breakneck speed.
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
//! Live per-host run view.
//!
//! Each deployment future reports into an mpsc channel: stderr lines and
//! the final status (derived purely from why its stdio closed — no special
//! wire protocol). When stderr is a tty we draw a two-pane TUI (host list +
//! selected host's output) that stays up until the user quits with `q`→`y`.
//! When it isn't (CI, pipe, `> log`), we fall back to today's prefixed
//! line-stream so nothing about non-interactive use changes.

use std::io::IsTerminal as _;

use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use crossterm::event::EventStream;
use ratatui::crossterm::event::{
    DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind, KeyModifiers,
    MouseEventKind,
};
use ratatui::crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use ratatui::crossterm::execute;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, List, ListItem, ListState, Paragraph};
use futures_util::StreamExt as _;

use std::sync::{Mutex, OnceLock};

/// Width of the host-list pane, as a percentage of the terminal. Used both
/// for the layout split and the mouse hit-test, so they can't drift apart.
const LIST_PCT: u16 = 30;

/// Shared sink for the CLI's own `tracing` output so it can be shown in a
/// pane instead of corrupting the alternate screen. Lines accumulate here;
/// the TUI reads them each frame.
static LOG: OnceLock<Mutex<Vec<String>>> = OnceLock::new();

fn log_buffer() -> &'static Mutex<Vec<String>> {
    LOG.get_or_init(|| Mutex::new(Vec::new()))
}

/// A `tracing_subscriber` writer that appends formatted log lines to the
/// shared buffer (one entry per write, trimmed of the trailing newline).
pub struct LogWriter;

impl std::io::Write for LogWriter {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        let s = String::from_utf8_lossy(buf);
        let line = s.trim_end_matches('\n');
        if !line.is_empty() {
            log_buffer().lock().unwrap().push(line.to_owned());
        }
        Ok(buf.len())
    }
    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for LogWriter {
    type Writer = LogWriter;
    fn make_writer(&'a self) -> Self::Writer {
        LogWriter
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Status {
    Running,
    Finished,
    Failed,
}

impl Status {
    fn color(self) -> Color {
        match self {
            Status::Running => Color::Yellow,
            Status::Finished => Color::Green,
            Status::Failed => Color::Red,
        }
    }
    fn glyph(self) -> &'static str {
        match self {
            Status::Running => "",
            Status::Finished => "",
            Status::Failed => "",
        }
    }
}

/// Which process a captured line came from. Rendered in different colours
/// so orchestrator (local) and worker (remote) output are distinguishable.
#[derive(Clone, Copy)]
pub enum Source {
    Orchestrator,
    Worker,
}

/// A message from `main`/a deployment future to the progress view.
pub enum Msg {
    /// Register a host in the list. Hosts are appended in send order, so the
    /// nth `AddHost` is host `idx == n`, matching the `idx` later carried by
    /// `Line`/`Status`. Sent once discovery knows the targets — the view is
    /// already on screen before this arrives (showing the log pane).
    AddHost { name: String, tags: Vec<String> },
    /// One stderr line from host `idx`, tagged with its source.
    Line(usize, Source, String),
    /// Host `idx` reached a terminal state.
    Status(usize, Status),
}

struct Host {
    name: String,
    tags: Vec<String>,
    status: Status,
    lines: Vec<(Source, String)>,
}

/// Output-pane scroll position for the selected host.
#[derive(Default)]
struct OutputScroll {
    /// Lines *above* the live tail: 0 follows the newest output, larger
    /// values scroll back into history.
    vert: u16,
    /// Columns panned right, for long lines (wide diffs etc.). Clamped to the
    /// widest visible line in `draw_output`.
    horiz: u16,
}

/// Render messages from `rx`. The host list starts empty and grows as
/// `Msg::AddHost`s arrive, so the view can be shown immediately — during the
/// (potentially slow) compile/discovery phase the log pane already reflects
/// the CLI's `tracing` output, so it never looks frozen. Returns when the
/// user quits (tty) or the channel closes after all hosts finish (non-tty).
pub async fn run(rx: tokio::sync::mpsc::UnboundedReceiver<Msg>) {
    if std::io::stderr().is_terminal() {
        if let Err(e) = tui(rx).await {
            eprintln!("progress view error: {e:?}");
        }
    } else {
        stream(rx).await;
    }
}

fn add_host(hosts: &mut Vec<Host>, name: String, tags: Vec<String>) {
    hosts.push(Host {
        name,
        tags,
        status: Status::Running,
        lines: Vec::new(),
    });
}

/// Non-interactive fallback: prefix every line with its host and print it.
/// The loop ends on its own when every sender is dropped (all hosts done).
async fn stream(mut rx: tokio::sync::mpsc::UnboundedReceiver<Msg>) {
    let mut hosts: Vec<Host> = Vec::new();
    while let Some(msg) = rx.recv().await {
        match msg {
            Msg::AddHost { name, tags } => add_host(&mut hosts, name, tags),
            Msg::Line(idx, _src, line) => {
                eprintln!("\x1b[36m[{}]\x1b[0m {}", hosts[idx].name, line);
            }
            Msg::Status(idx, status) => {
                hosts[idx].status = status;
                let label = match status {
                    Status::Finished => "\x1b[32mfinished\x1b[0m",
                    Status::Failed => "\x1b[31mfailed\x1b[0m",
                    Status::Running => continue,
                };
                eprintln!("[{}] {label}", hosts[idx].name);
            }
        }
    }
}

async fn tui(mut rx: tokio::sync::mpsc::UnboundedReceiver<Msg>) -> eyre::Result<()> {
    enable_raw_mode()?;
    execute!(std::io::stderr(), EnterAlternateScreen, EnableMouseCapture)?;

    let mut hosts: Vec<Host> = Vec::new();
    let result = tui_loop(&mut hosts, &mut rx).await;

    let _ = disable_raw_mode();
    let _ = execute!(std::io::stderr(), DisableMouseCapture, LeaveAlternateScreen);

    result
}

async fn tui_loop(
    hosts: &mut Vec<Host>,
    rx: &mut tokio::sync::mpsc::UnboundedReceiver<Msg>,
) -> eyre::Result<()> {
    let backend = CrosstermBackend::new(std::io::stderr());
    let mut terminal = Terminal::new(backend)?;
    let mut events = EventStream::new();

    let mut selected = 0usize;
    let mut list_state = ListState::default();
    let mut confirm_quit = false;
    // Output-pane scroll (vertical tail-offset + horizontal pan) for the
    // selected host. Switching hosts resets it to the tail, column 0.
    let mut scroll = OutputScroll::default();
    // Once every host future has dropped its sender the channel closes; we
    // stop selecting on it (otherwise the closed branch is always ready and
    // would starve input handling), but keep the view up until the user quits.
    let mut channel_open = true;
    // Height of the bottom CLI-log pane, resizable with `+`/`-`.
    let mut log_height: u16 = 6;

    loop {
        list_state.select(Some(selected));
        // `draw` clamps `scroll` against the output pane's real height (the
        // only place that height is known), keeping the two in sync.
        terminal.draw(|f| {
            draw(
                f,
                hosts,
                &mut list_state,
                selected,
                confirm_quit,
                &mut scroll,
                log_height,
            )
        })?;

        tokio::select! {
            biased;
            event = events.next() => {
                match event {
                    Some(Ok(Event::Mouse(m))) => {
                        // The list pane is the left `LIST_PCT`% (matching the
                        // layout split); the rest is the output pane. The wheel
                        // acts on whichever the cursor is over.
                        let list_width = terminal.size()?.width * LIST_PCT / 100;
                        let over_list = m.column < list_width;
                        let shift = m.modifiers.contains(KeyModifiers::SHIFT);
                        match m.kind {
                            // Over the host list the wheel switches hosts.
                            MouseEventKind::ScrollUp if over_list => {
                                selected = selected.saturating_sub(1);
                                scroll = OutputScroll::default();
                            }
                            MouseEventKind::ScrollDown if over_list => {
                                selected = (selected + 1).min(hosts.len().saturating_sub(1));
                                scroll = OutputScroll::default();
                            }
                            // Over the output: plain wheel scrolls vertically,
                            // Shift+wheel scrolls horizontally. Terminals that
                            // emit a native horizontal wheel (ScrollLeft/Right)
                            // are handled below too.
                            MouseEventKind::ScrollUp if shift => {
                                scroll.horiz = scroll.horiz.saturating_sub(6)
                            }
                            MouseEventKind::ScrollDown if shift => {
                                scroll.horiz = scroll.horiz.saturating_add(6)
                            }
                            MouseEventKind::ScrollUp => scroll.vert = scroll.vert.saturating_add(3),
                            MouseEventKind::ScrollDown => {
                                scroll.vert = scroll.vert.saturating_sub(3)
                            }
                            MouseEventKind::ScrollLeft => {
                                scroll.horiz = scroll.horiz.saturating_sub(6)
                            }
                            MouseEventKind::ScrollRight => {
                                scroll.horiz = scroll.horiz.saturating_add(6)
                            }
                            _ => {}
                        }
                    }
                    Some(Ok(Event::Key(key))) if key.kind == KeyEventKind::Press => {
                        if confirm_quit {
                            match key.code {
                                KeyCode::Char('y') => return Ok(()),
                                _ => confirm_quit = false,
                            }
                            continue;
                        }
                        match key.code {
                            KeyCode::Char('q') => confirm_quit = true,
                            // Switch hosts with Tab / Shift+Tab. The vertical
                            // keys now scroll the output (the thing you read),
                            // not the host list.
                            KeyCode::Tab => {
                                selected = (selected + 1).min(hosts.len().saturating_sub(1));
                                scroll = OutputScroll::default();
                            }
                            KeyCode::BackTab => {
                                selected = selected.saturating_sub(1);
                                scroll = OutputScroll::default();
                            }
                            // Scroll the output vertically. `vert` counts lines
                            // above the live tail, so up adds, down subtracts.
                            KeyCode::Up | KeyCode::Char('k') => {
                                scroll.vert = scroll.vert.saturating_add(1)
                            }
                            KeyCode::Down | KeyCode::Char('j') => {
                                scroll.vert = scroll.vert.saturating_sub(1)
                            }
                            KeyCode::PageUp => scroll.vert = scroll.vert.saturating_add(10),
                            KeyCode::PageDown => scroll.vert = scroll.vert.saturating_sub(10),
                            // Scroll the output horizontally for long lines
                            // (wide diffs etc.). `draw_output` clamps `horiz`.
                            KeyCode::Left | KeyCode::Char('h') => {
                                scroll.horiz = scroll.horiz.saturating_sub(8)
                            }
                            KeyCode::Right | KeyCode::Char('l') => {
                                scroll.horiz = scroll.horiz.saturating_add(8)
                            }
                            KeyCode::Home => {
                                scroll.vert = u16::MAX;
                                scroll.horiz = 0;
                            }
                            KeyCode::End => scroll.vert = 0,
                            // Resize the bottom log pane. `0` collapses it.
                            KeyCode::Char('+') | KeyCode::Char('=') => {
                                log_height = (log_height + 1).min(40)
                            }
                            KeyCode::Char('-') => log_height = log_height.saturating_sub(1),
                            _ => {}
                        }
                    }
                    _ => {}
                }
            }
            msg = rx.recv(), if channel_open => {
                match msg {
                    Some(Msg::AddHost { name, tags }) => add_host(hosts, name, tags),
                    Some(Msg::Line(idx, src, line)) => {
                        hosts[idx].lines.push((src, line));
                        // When scrolled back into history (vert > 0), pin the
                        // view to the same absolute lines as new output arrives
                        // — only the tail (vert == 0) follows new output.
                        if idx == selected && scroll.vert > 0 {
                            scroll.vert = scroll.vert.saturating_add(1);
                        }
                    }
                    Some(Msg::Status(idx, status)) => hosts[idx].status = status,
                    None => channel_open = false,
                }
            }
        }
    }
}

fn draw(
    f: &mut ratatui::Frame,
    hosts: &[Host],
    list_state: &mut ListState,
    selected: usize,
    confirm_quit: bool,
    scroll: &mut OutputScroll,
    log_height: u16,
) {
    // Bottom-up: a single-row key legend at the very bottom, the CLI log
    // strip above it, and the rest split into the host list + output panes.
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Min(0),
            Constraint::Length(log_height),
            Constraint::Length(1),
        ])
        .split(f.area());

    let panes = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(LIST_PCT),
            Constraint::Percentage(100 - LIST_PCT),
        ])
        .split(rows[0]);

    draw_list(f, panes[0], hosts, list_state, confirm_quit);
    draw_output(f, panes[1], hosts.get(selected), scroll);
    if log_height > 0 {
        draw_log(f, rows[1]);
    }
    draw_legend(f, rows[2]);
}

/// Single full-width row of key hints at the very bottom of the screen. On
/// its own row (not a pane border) so it's never clipped and reads cleanly.
fn draw_legend(f: &mut ratatui::Frame, area: Rect) {
    let legend = Paragraph::new(Line::from(Span::styled(
        " scroll: arrows/jk · pan: h/l · host: Tab · page: PgUp/Dn · top/tail: Home/End · quit: q",
        Style::default().fg(Color::DarkGray),
    )));
    f.render_widget(legend, area);
}

/// Parse a line that may contain ANSI escape codes into a styled ratatui
/// line, falling back to plain text if it doesn't parse.
fn ansi_line(s: &str) -> Line<'static> {
    use ansi_to_tui::IntoText as _;
    s.into_text()
        .ok()
        .and_then(|t| t.lines.into_iter().next())
        .unwrap_or_else(|| Line::raw(s.to_owned()))
}

/// Render a captured line with a fixed-width, colour-coded source prefix,
/// preserving the line's own ANSI styling. The prefix is the same width for
/// both sources so the content columns stay aligned.
fn source_line(src: Source, s: &str) -> Line<'static> {
    let (glyph, color) = match src {
        Source::Orchestrator => ("", Color::Magenta),
        Source::Worker => ("", Color::Cyan),
    };
    let mut line = ansi_line(s);
    line.spans
        .insert(0, Span::styled(glyph, Style::default().fg(color)));
    line
}

fn draw_log(f: &mut ratatui::Frame, area: Rect) {
    let buf = log_buffer().lock().unwrap();
    let view = area.height.saturating_sub(2);
    let start = buf.len().saturating_sub(view as usize);
    let body: Vec<Line> = buf[start..].iter().map(|l| ansi_line(l)).collect();
    let para = Paragraph::new(body)
        .block(Block::default().borders(Borders::ALL).title(" cli log "));
    f.render_widget(para, area);
}

fn draw_list(
    f: &mut ratatui::Frame,
    area: Rect,
    hosts: &[Host],
    list_state: &mut ListState,
    confirm_quit: bool,
) {
    let (mut running, mut done, mut failed) = (0, 0, 0);
    for h in hosts {
        match h.status {
            Status::Running => running += 1,
            Status::Finished => done += 1,
            Status::Failed => failed += 1,
        }
    }

    let items: Vec<ListItem> = hosts
        .iter()
        .map(|h| {
            let mut spans = vec![
                Span::styled(
                    format!("{} ", h.status.glyph()),
                    Style::default().fg(h.status.color()),
                ),
                Span::raw(h.name.clone()),
            ];
            if !h.tags.is_empty() {
                spans.push(Span::styled(
                    format!("  {}", h.tags.join(",")),
                    Style::default().fg(Color::Cyan).add_modifier(Modifier::DIM),
                ));
            }
            ListItem::new(Line::from(spans))
        })
        .collect();

    let title = format!(" {running} running · {done} done · {failed} failed ");
    let list = List::new(items)
        .block(Block::default().borders(Borders::ALL).title(title))
        .highlight_style(Style::default().add_modifier(Modifier::REVERSED));
    f.render_stateful_widget(list, area, list_state);

    if confirm_quit {
        let hint = Paragraph::new("quit? y/n").style(Style::default().fg(Color::Red));
        let bar = Rect {
            x: area.x + 1,
            y: area.y + area.height.saturating_sub(1),
            width: area.width.saturating_sub(2),
            height: 1,
        };
        f.render_widget(hint, bar);
    }
}

fn draw_output(f: &mut ratatui::Frame, area: Rect, host: Option<&Host>, scroll: &mut OutputScroll) {
    let (name, body): (Option<&str>, Vec<Line>) = match host {
        Some(h) => (
            Some(h.name.as_str()),
            h.lines.iter().map(|(src, l)| source_line(*src, l)).collect(),
        ),
        None => (None, Vec::new()),
    };
    let total = body.len() as u16;
    // Visible rows/cols inside the bordered block.
    let view = area.height.saturating_sub(2);
    let view_w = area.width.saturating_sub(2);
    // `max_top` shows the tail (last line at the bottom). `scroll` is how many
    // lines above the tail we've moved; clamp it here, where the pane's real
    // height is known, so it can never run past the oldest line.
    let max_top = total.saturating_sub(view);
    scroll.vert = scroll.vert.min(max_top);
    let top = max_top - scroll.vert;
    // Lines aren't wrapped, so clamp the horizontal pan to the widest line
    // (minus the visible width) — panning further would only reveal blank
    // space. Done here because the pane's real width is known.
    let widest = body.iter().map(|l| l.width() as u16).max().unwrap_or(0);
    let max_left = widest.saturating_sub(view_w);
    scroll.horiz = scroll.horiz.min(max_left);

    // Title carries the live line count (so you can see output still growing
    // even while scrolled back), plus a marker when not following the tail.
    let title = match name {
        Some(name) if scroll.vert > 0 => {
            format!(" {name} · {total} lines · ↑{} ", scroll.vert)
        }
        Some(name) => format!(" {name} · {total} lines "),
        None => " output ".to_string(),
    };

    let para = Paragraph::new(body)
        .block(Block::default().borders(Borders::ALL).title(title))
        .scroll((top, scroll.horiz));
    f.render_widget(para, area);
}