scsh 1.1.0

Scoped Skills Helper — preflight a git repo and run its scoped skills in ephemeral containers.
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
//! The interactive live board's **pure model** — everything that decides *what the screen
//! shows*, with no terminal I/O, so it can be unit-tested exhaustively. The terminal driver
//! (raw mode, mouse, redraw) lives in [`super::screen`] and is the only side-effecting part.
//!
//! A run is a list of [`Proc`]s (the image build, then one per skill). Each is a collapsible
//! row: a ▶/▼ triangle, a status glyph, the label, a smart elapsed clock, and a dim note.
//! Click a row (the driver maps the mouse to a proc) to [`Model::toggle`] it; expanding shows
//! that proc's captured output, every line stamped with `+<elapsed>` **relative to when that
//! proc started**. The view scrolls (the model owns the scroll offset and a "follow the tail"
//! flag); rows never wrap — each is clipped to the width the driver passes in.

use super::clock::format_elapsed;
use super::FRAMES;

/// A proc's lifecycle state, which drives its glyph and colour.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Status {
  /// Declared but not started yet (e.g. a skill waiting for the image build).
  Queued,
  Running,
  Ok,
  Fail,
}

/// One captured output line, with the time (seconds since the proc started) it arrived — so the
/// expanded view can stamp it `+1.2s` relative to that proc's own start.
#[derive(Clone, Debug, PartialEq)]
pub struct Line {
  pub at: f64,
  pub text: String,
}

/// One collapsible process row plus its captured output.
#[derive(Clone, Debug)]
pub struct Proc {
  pub label: String,
  pub status: Status,
  /// Elapsed seconds, refreshed by the driver each tick while running (and frozen at finish).
  pub elapsed: f64,
  /// Every captured output line, in arrival order, each tagged with its relative time.
  pub lines: Vec<Line>,
  /// The dim trailing note on the header — the latest output line while running.
  pub note: Option<String>,
  /// The dim/red detail on the header once finished (e.g. the result headline, or why it failed).
  pub detail: Option<String>,
  pub expanded: bool,
}

/// A styled run of text within a rendered row. The driver maps [`Sty`] to terminal colour; tests
/// read [`Row::plain`] (the concatenated text), so the model stays output-format-agnostic.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Sty {
  Plain,
  Dim,
  Bold,
  Cyan,
  Green,
  Red,
}

#[derive(Clone, Debug, PartialEq)]
pub struct Seg {
  pub text: String,
  pub sty: Sty,
}

impl Seg {
  fn new(text: impl Into<String>, sty: Sty) -> Seg {
    Seg { text: text.into(), sty }
  }
}

/// One rendered line of the board. `proc` is `Some(i)` for a clickable header row (so the driver
/// can map a mouse click back to a proc) and `None` for an output/detail line.
#[derive(Clone, Debug, PartialEq)]
pub struct Row {
  pub proc: Option<usize>,
  pub segs: Vec<Seg>,
}

impl Row {
  /// The row's text with styling discarded — what tests assert on, and what width is measured by.
  pub fn plain(&self) -> String {
    self.segs.iter().map(|s| s.text.as_str()).collect()
  }
}

/// The whole live board: the procs, the scroll offset, and whether to keep following the tail.
#[derive(Debug, Default)]
pub struct Model {
  pub procs: Vec<Proc>,
  /// Index of the first laid-out row shown at the top of the viewport.
  scroll: usize,
  /// While true, the viewport sticks to the bottom as new rows arrive (like `tail -f`). The user
  /// turns it off by scrolling up, and back on by scrolling to the bottom.
  follow: bool,
}

impl Model {
  pub fn new() -> Model {
    Model { procs: Vec::new(), scroll: 0, follow: true }
  }

  /// Add a proc, returning its index (the handle the driver/worker uses to update it).
  pub fn add(&mut self, label: impl Into<String>) -> usize {
    self.procs.push(Proc {
      label: label.into(),
      status: Status::Queued,
      elapsed: 0.0,
      lines: Vec::new(),
      note: None,
      detail: None,
      expanded: false,
    });
    self.procs.len() - 1
  }

  pub fn set_status(&mut self, i: usize, status: Status) {
    if let Some(p) = self.procs.get_mut(i) {
      p.status = status;
    }
  }

  pub fn set_elapsed(&mut self, i: usize, elapsed: f64) {
    if let Some(p) = self.procs.get_mut(i) {
      p.elapsed = elapsed;
    }
  }

  pub fn set_note(&mut self, i: usize, note: Option<String>) {
    if let Some(p) = self.procs.get_mut(i) {
      p.note = note;
    }
  }

  pub fn set_detail(&mut self, i: usize, detail: Option<String>) {
    if let Some(p) = self.procs.get_mut(i) {
      p.detail = detail;
    }
  }

  /// Append a captured output line, stamped with `at` seconds since the proc started.
  pub fn push_line(&mut self, i: usize, at: f64, text: impl Into<String>) {
    if let Some(p) = self.procs.get_mut(i) {
      p.lines.push(Line { at, text: text.into() });
    }
  }

  /// Toggle a proc's expanded state (what a mouse click on its header does).
  pub fn toggle(&mut self, i: usize) {
    if let Some(p) = self.procs.get_mut(i) {
      p.expanded = !p.expanded;
    }
  }

  /// Expand or collapse every proc at once (the `e` / `c` keys).
  pub fn set_all_expanded(&mut self, expanded: bool) {
    for p in &mut self.procs {
      p.expanded = expanded;
    }
  }

  /// Lay the whole board out into rows (headers + any expanded output), each clipped to `width`
  /// so nothing wraps. `frame` advances the running spinner glyph. Pure: the driver renders the
  /// returned segments, tests read [`Row::plain`].
  pub fn layout(&self, width: usize, frame: u64) -> Vec<Row> {
    let width = width.max(1);
    let mut rows = Vec::new();
    for (i, p) in self.procs.iter().enumerate() {
      rows.push(fit_row(header_row_framed(i, p, frame), width));
      if p.expanded {
        if p.lines.is_empty() {
          rows.push(fit_row(Row { proc: None, segs: vec![Seg::new("    (no output yet)", Sty::Dim)] }, width));
        } else {
          for line in &p.lines {
            rows.push(fit_row(output_row(line), width));
          }
        }
      }
    }
    rows
  }

  /// Total laid-out row count (independent of the spinner frame, so any frame works).
  pub fn total_rows(&self, width: usize) -> usize {
    self.layout(width, 0).len()
  }

  /// The slice of rows visible in a `height`-tall viewport, plus the scroll offset actually used
  /// (after applying "follow the tail" and clamping). The driver draws the rows and remembers the
  /// offset so it can map a mouse click at screen-row `r` back to laid-out row `offset + r`.
  pub fn view(&self, width: usize, height: usize, frame: u64) -> (Vec<Row>, usize) {
    let all = self.layout(width, frame);
    let height = height.max(1);
    let max_off = all.len().saturating_sub(height);
    let off = if self.follow { max_off } else { self.scroll.min(max_off) };
    let end = (off + height).min(all.len());
    (all[off..end].to_vec(), off)
  }

  /// Scroll by `delta` rows (negative = up/back, positive = down/forward) within a `height`-tall
  /// viewport. Scrolling up drops "follow"; reaching the bottom restores it.
  pub fn scroll_by(&mut self, delta: isize, width: usize, height: usize) {
    let total = self.total_rows(width);
    let height = height.max(1);
    let max_off = total.saturating_sub(height);
    // Resolve the current offset (following pins to the bottom) before nudging it.
    let cur = if self.follow { max_off } else { self.scroll.min(max_off) };
    let next = cur.saturating_add_signed(delta).min(max_off);
    self.scroll = next;
    self.follow = next >= max_off; // back at the bottom ⇒ resume following
  }

  /// Jump to the top (stops following) or the bottom (resumes following).
  pub fn scroll_to_top(&mut self) {
    self.scroll = 0;
    self.follow = false;
  }
  pub fn scroll_to_bottom(&mut self) {
    self.follow = true;
  }
}

/// The status glyph (and its colour) for a proc: an animated spinner while running, else ✓/✗/·.
fn glyph(status: Status, frame: u64) -> Seg {
  match status {
    Status::Queued => Seg::new("·", Sty::Dim),
    Status::Running => Seg::new(FRAMES[(frame as usize) % FRAMES.len()], Sty::Cyan),
    Status::Ok => Seg::new("", Sty::Green),
    Status::Fail => Seg::new("", Sty::Red),
  }
}

/// Build the clickable header row for proc `i`: `▼ ⠼ label  1.2s  note`, with the running
/// spinner glyph at `frame`. Full-width; [`fit_row`] clips it to the terminal in [`Model::layout`].
fn header_row_framed(i: usize, p: &Proc, frame: u64) -> Row {
  let triangle = if p.expanded { "" } else { "" };
  // A keyboard-shortcut hint: press Ctrl+<n> (or just the digit) to toggle this row. Only the
  // first nine rows get a single-key shortcut; the rest are still clickable.
  let key = if i < 9 { format!("[Ctrl+{}] ", i + 1) } else { String::new() };
  let mut segs = vec![
    Seg::new(triangle, Sty::Dim),
    Seg::new(key, Sty::Dim),
    glyph(p.status, frame),
    Seg::new(" ", Sty::Plain),
    Seg::new(p.label.clone(), Sty::Bold),
    Seg::new("  ", Sty::Plain),
    Seg::new(format_elapsed(p.elapsed), Sty::Dim),
  ];
  // Trailing note while running, or the final detail once done (red if it failed).
  let tail = match p.status {
    Status::Ok | Status::Fail => p.detail.as_deref(),
    _ => p.note.as_deref(),
  };
  if let Some(t) = tail.filter(|t| !t.is_empty()) {
    let sty = if p.status == Status::Fail { Sty::Red } else { Sty::Dim };
    segs.push(Seg::new("  ", Sty::Plain));
    segs.push(Seg::new(t.to_string(), sty));
  }
  Row { proc: Some(i), segs }
}

/// Build one expanded output row: `    +1.2s  the line`. Full-width; [`fit_row`] clips it.
fn output_row(line: &Line) -> Row {
  Row {
    proc: None,
    segs: vec![
      Seg::new("    ", Sty::Plain),
      Seg::new(format!("+{}", format_elapsed(line.at)), Sty::Dim),
      Seg::new("  ", Sty::Plain),
      Seg::new(line.text.clone(), Sty::Plain),
    ],
  }
}

/// Clip a row's segments so its total display width never exceeds `width` (rows never wrap):
/// keep whole segments while they fit, clip the one that straddles the edge (with an ellipsis),
/// and drop the rest.
fn fit_row(row: Row, width: usize) -> Row {
  let mut out = Vec::new();
  let mut used = 0usize;
  for seg in row.segs {
    if used >= width {
      break;
    }
    let w = display_width(&seg.text);
    if used + w <= width {
      used += w;
      out.push(seg);
    } else {
      let clipped = clip(&seg.text, width - used);
      if !clipped.is_empty() {
        out.push(Seg { text: clipped, sty: seg.sty });
      }
      break;
    }
  }
  Row { proc: row.proc, segs: out }
}

/// Display width of a string (Unicode-aware, ANSI already stripped upstream by `clean_line`).
fn display_width(s: &str) -> usize {
  console::measure_text_width(s)
}

/// Clip `s` to at most `max` display columns, adding an ellipsis when it overflows.
fn clip(s: &str, max: usize) -> String {
  if max == 0 {
    return String::new();
  }
  console::truncate_str(s, max, "").into_owned()
}

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

  fn demo_model() -> Model {
    let mut m = Model::new();
    let b = m.add("build");
    m.set_status(b, Status::Ok);
    m.set_elapsed(b, 4.0);
    m.push_line(b, 0.5, "STEP 1/3");
    m.push_line(b, 3.9, "done");
    let s = m.add("opencode: add");
    m.set_status(s, Status::Running);
    m.set_elapsed(s, 1.2);
    m.set_note(s, Some("2 + 3 = 5".into()));
    m.push_line(s, 1.0, "running add");
    m
  }

  #[test]
  fn collapsed_layout_is_one_row_per_proc() {
    let m = demo_model();
    let rows = m.layout(80, 0);
    assert_eq!(rows.len(), 2, "collapsed: one header each");
    assert_eq!(rows[0].proc, Some(0));
    assert_eq!(rows[1].proc, Some(1));
    // The collapsed header carries the triangle, glyph, label and clock.
    assert!(rows[0].plain().starts_with("▶ [Ctrl+1] "), "collapsed triangle + shortcut: {:?}", rows[0].plain());
    assert!(rows[0].plain().contains("build"));
    assert!(rows[0].plain().contains("4s"));
  }

  #[test]
  fn expanding_reveals_timestamped_output() {
    let mut m = demo_model();
    m.toggle(0);
    let rows = m.layout(80, 0);
    // header + 2 output lines + the second proc's header.
    assert_eq!(rows.len(), 4);
    assert!(rows[0].plain().starts_with("▼ [Ctrl+1] "), "expanded triangle + shortcut");
    assert_eq!(rows[1].proc, None, "output line is not a click target");
    assert!(rows[1].plain().contains("+0.5s") && rows[1].plain().contains("STEP 1/3"), "{:?}", rows[1].plain());
    assert!(rows[2].plain().contains("+3s") && rows[2].plain().contains("done"), "{:?}", rows[2].plain());
  }

  #[test]
  fn expanded_with_no_output_shows_a_placeholder() {
    let mut m = Model::new();
    let i = m.add("empty");
    m.toggle(i);
    let rows = m.layout(80, 0);
    assert_eq!(rows.len(), 2);
    assert!(rows[1].plain().contains("no output"), "{:?}", rows[1].plain());
  }

  #[test]
  fn running_glyph_animates_with_the_frame() {
    let m = demo_model();
    // segs: [0] = triangle, [1] = the [Ctrl+N] shortcut, [2] = the animated status glyph.
    let g0 = m.layout(80, 0)[1].segs[2].text.clone();
    let g1 = m.layout(80, 1)[1].segs[2].text.clone();
    assert_ne!(g0, g1, "the running spinner glyph should advance with the frame");
    assert!(FRAMES.contains(&g0.as_str()) && FRAMES.contains(&g1.as_str()));
  }

  #[test]
  fn running_shows_note_finished_shows_detail() {
    let mut m = Model::new();
    let i = m.add("s");
    m.set_status(i, Status::Running);
    m.set_note(i, Some("latest line".into()));
    m.set_detail(i, Some("final detail".into()));
    assert!(m.layout(80, 0)[0].plain().contains("latest line"), "running uses note");
    m.set_status(i, Status::Ok);
    assert!(m.layout(80, 0)[0].plain().contains("final detail"), "finished uses detail");
  }

  #[test]
  fn rows_never_exceed_the_width() {
    let mut m = Model::new();
    let i = m.add("a-very-long-skill-label-that-keeps-going-and-going");
    m.set_status(i, Status::Running);
    m.set_note(i, Some("an extremely long trailing note ".repeat(20)));
    m.toggle(i);
    m.push_line(i, 1.0, "x".repeat(500));
    for w in [10usize, 20, 40, 80] {
      for row in m.layout(w, 0) {
        assert!(display_width(&row.plain()) <= w, "row '{}' exceeds width {w}", row.plain());
      }
    }
  }

  #[test]
  fn view_follows_the_tail_then_honors_scroll() {
    let mut m = Model::new();
    let i = m.add("s");
    m.toggle(i);
    for n in 0..20 {
      m.push_line(i, n as f64, format!("line {n}"));
    }
    let total = m.total_rows(80);
    assert_eq!(total, 21, "1 header + 20 lines");

    // Following: the viewport sticks to the bottom.
    let (vis, off) = m.view(80, 5, 0);
    assert_eq!(vis.len(), 5);
    assert_eq!(off, total - 5, "follow pins to the bottom");
    assert!(vis.last().unwrap().plain().contains("line 19"));

    // Scroll up: follow turns off, the offset moves back.
    m.scroll_by(-3, 80, 5);
    let (_, off2) = m.view(80, 5, 0);
    assert_eq!(off2, total - 5 - 3);

    // Scrolling back to the bottom resumes following.
    m.scroll_by(100, 80, 5);
    assert_eq!(m.view(80, 5, 0).1, total - 5);
  }

  #[test]
  fn scroll_to_top_and_bottom() {
    let mut m = Model::new();
    let i = m.add("s");
    m.toggle(i);
    for n in 0..30 {
      m.push_line(i, n as f64, format!("l{n}"));
    }
    m.scroll_to_top();
    assert_eq!(m.view(80, 5, 0).1, 0);
    m.scroll_to_bottom();
    assert_eq!(m.view(80, 5, 0).1, m.total_rows(80) - 5);
  }

  #[test]
  fn toggle_flips_only_the_target_proc() {
    let mut m = demo_model();
    assert!(!m.procs[0].expanded && !m.procs[1].expanded);
    m.toggle(1);
    assert!(!m.procs[0].expanded && m.procs[1].expanded);
    m.set_all_expanded(true);
    assert!(m.procs[0].expanded && m.procs[1].expanded);
    m.set_all_expanded(false);
    assert!(!m.procs[0].expanded && !m.procs[1].expanded);
  }
}