fleetcom 0.9.0

A fleet-view supervisor for arbitrary shell commands.
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
//! Terminal rendering from the client's task and screen snapshots. Frames are
//! buffered and written only when they differ from the previous frame.

use std::io::{self, Stdout, Write};
use std::time::Duration;

use crossterm::{
    cursor::{Hide, MoveTo, Show},
    queue,
    style::{Attribute, Print, SetAttribute},
};

use unicode_width::UnicodeWidthStr;

use crate::{
    app::{App, DirKind, GroupMode, Mode, Row},
    editbuf::EditBuffer,
    format::{pad, rel_time, truncate},
    protocol::{Lifecycle, Preview, PreviewSource, TaskView},
};

pub fn render(out: &mut Stdout, app: &mut App) -> io::Result<()> {
    let mut buf: Vec<u8> = Vec::with_capacity(app.cols as usize * app.rows as usize * 3 + 128);
    match app.mode {
        Mode::Attached => render_attached(&mut buf, app)?,
        Mode::Peek => {
            render_dashboard(&mut buf, app)?;
            render_peek(&mut buf, app)?;
        }
        Mode::PickDir => {
            render_dashboard(&mut buf, app)?;
            render_pickdir(&mut buf, app)?;
        }
        Mode::PickGroup => {
            render_dashboard(&mut buf, app)?;
            render_pickgroup(&mut buf, app)?;
        }
        Mode::LoadSession => {
            render_dashboard(&mut buf, app)?;
            render_session_picker(&mut buf, app)?;
        }
        Mode::Disconnected => render_disconnected(&mut buf, app)?,
        Mode::Dashboard | Mode::Spawn | Mode::SaveSession | Mode::Rename => {
            render_dashboard(&mut buf, app)?
        }
    }
    // Repaint only on change: a stable frame (idle tasks, no input) is a no-op,
    // so there is nothing to flicker and nothing to burn CPU on.
    if buf != app.last_frame {
        out.write_all(&buf)?;
        out.flush()?;
        app.last_frame = buf;
    }
    Ok(())
}

fn put(out: &mut impl Write, y: u16, s: &str, cols: usize) -> io::Result<()> {
    queue!(out, MoveTo(0, y), Print(pad(s, cols)))
}

fn dim(out: &mut impl Write, y: u16, s: &str, cols: usize) -> io::Result<()> {
    queue!(
        out,
        MoveTo(0, y),
        SetAttribute(Attribute::Dim),
        Print(pad(s, cols)),
        SetAttribute(Attribute::Reset)
    )
}

/// Paint a full-width reverse-video line: selection and focused-field styling.
fn rev(out: &mut impl Write, y: u16, s: &str, cols: usize) -> io::Result<()> {
    queue!(
        out,
        MoveTo(0, y),
        SetAttribute(Attribute::Reverse),
        Print(pad(s, cols)),
        SetAttribute(Attribute::Reset)
    )
}

fn render_dashboard(out: &mut impl Write, app: &App) -> io::Result<()> {
    let cols = app.cols as usize;
    let rows = app.rows;

    queue!(out, Hide, MoveTo(0, 0))?;

    // Lifecycle is pre-computed by the core, so the header just tallies it.
    let (mut running, mut idle, mut done) = (0u32, 0u32, 0u32);
    for v in &app.views {
        match v.lifecycle {
            Lifecycle::Active => running += 1,
            Lifecycle::Idle => idle += 1,
            Lifecycle::Ok | Lifecycle::Failed => done += 1,
        }
    }
    // List region: rows 2..=list_bottom. Command line and footer sit below.
    // Scroll over section and task rows together to keep the selection visible.
    let list_top = 2u16;
    let list_bottom = rows.saturating_sub(3);
    let height = (usize::from(list_bottom) + 1).saturating_sub(usize::from(list_top));
    let list = app.list_rows();
    let sel_row = app.selected_row(&list);
    let (start, count) = scroll_window(sel_row.unwrap_or(0), list.len(), height);

    // Daemon-backed is the unmarked default; call out foreground (ephemeral) mode.
    let mode_tag = if app.daemon_backed {
        ""
    } else {
        " · foreground"
    };
    // When the list is clipped, say where the selection sits in the fleet (task
    // position, not row position: section headers don't count).
    let scroll_tag = match sel_row {
        Some(s) if list.len() > height => {
            let pos = list[..=s]
                .iter()
                .filter(|r| matches!(r, Row::Task(_)))
                .count();
            format!(" · {pos}/{}", app.views.len())
        }
        _ => String::new(),
    };
    // Build and pad the complete header before styling each intensity run.
    let prefix = format!("  fleetcom   {running} running · {idle} idle · {done} done      by ");
    let suffix = format!("{mode_tag}{scroll_tag}");
    let segs = header_segments(&prefix, app.group_mode, &suffix);
    let plain: String = segs.iter().map(|(t, _)| t.as_str()).collect();
    let display = pad(&plain, cols);
    let mut chars = display.chars();
    queue!(out, MoveTo(0, 0))?;
    for (text, intensity) in &segs {
        let n = text.chars().count();
        if n == 0 {
            continue;
        }
        let piece: String = chars.by_ref().take(n).collect();
        if piece.is_empty() {
            break; // ran off the truncated end; attributes are already reset
        }
        // Reset between runs so Bold and Dim are not stacked.
        let attr = match intensity {
            Intensity::Bold => Attribute::Bold,
            Intensity::Dim => Attribute::Dim,
        };
        queue!(
            out,
            SetAttribute(attr),
            Print(piece),
            SetAttribute(Attribute::Reset)
        )?;
    }
    // Whatever `pad` appended past the segments is blank padding: unstyled.
    let rest: String = chars.collect();
    if !rest.is_empty() {
        queue!(out, Print(rest))?;
    }
    put(out, 1, "", cols)?;

    let mut y = list_top;
    for row in &list[start..start + count] {
        match row {
            Row::Section(label) => dim(out, y, &format!("  {label}"), cols)?,
            Row::Task(ti) => {
                let v = &app.views[*ti];
                if app.selected_id == Some(v.id) {
                    rev(out, y, &task_row(v, cols), cols)?;
                } else if v.preview.source == PreviewSource::Marker {
                    // The marker is a placeholder, not output: dim the
                    // preview cell so it reads as metadata.
                    dim_preview_row(out, y, v, cols)?;
                } else {
                    put(out, y, &task_row(v, cols), cols)?;
                }
            }
        }
        y += 1;
    }
    while y <= list_bottom {
        put(out, y, "", cols)?;
        y += 1;
    }

    // Command line: input modes show a prompt (with cursor); otherwise a
    // transient save/load notice, else the key hint.
    let cmd_y = rows.saturating_sub(2);
    match cmdline(app) {
        Some((line, _)) => put(out, cmd_y, &line, cols)?,
        None => match &app.status {
            Some(s) => put(out, cmd_y, &format!("  {s}"), cols)?,
            None => dim(
                out,
                cmd_y,
                "  ❯ n run · @ dir · s sort · w save · o load",
                cols,
            )?,
        },
    }

    // Footer hints. In foreground there is no daemon to detach from: both
    // intents stop the in-process core (`ThreadTransport::shutdown` ignores
    // the intent), so advertising `q detach` there would promise survival the
    // tasks don't have.
    let exit_hint = if app.daemon_backed {
        "q detach · Q quit"
    } else {
        "q quit"
    };
    dim(
        out,
        rows.saturating_sub(1),
        &format!(
            "  ↑↓ select · enter attach · space peek · m tag · g group · R rename · r rerun · X kill · {exit_hint}"
        ),
        cols,
    )?;

    match cmdline(app) {
        Some((line, cx)) => {
            let cx = clamp_caret(cx, &line, cols);
            queue!(out, MoveTo(cx, cmd_y), Show)?;
        }
        None => queue!(out, Hide)?,
    }
    Ok(())
}

/// The editable bottom line for the text-input modes (the rendered line and
/// the caret's display column), or `None` when the command line should show a
/// hint/status instead.
fn cmdline(app: &App) -> Option<(String, u16)> {
    let prefix = match app.mode {
        Mode::Spawn => spawn_prefix(app),
        Mode::SaveSession => "  save session as: ".to_string(),
        Mode::Rename => "  rename task: ".to_string(),
        _ => return None,
    };
    Some(caret_line(&prefix, &app.input))
}

/// Compose `prefix` + the buffer text with the caret's display column: the
/// width of the prefix plus the width of the text before the caret. Widths are
/// terminal columns (wide glyphs count 2), not scalar counts. The column is
/// unclamped; `clamp_caret` bounds it to what actually gets painted.
fn caret_line(prefix: &str, buf: &EditBuffer) -> (String, u16) {
    let cx = (prefix.width() + buf.before_caret().width()) as u16;
    (format!("{prefix}{}", buf.as_str()), cx)
}

/// Bound a caret column to the painted, `cols`-truncated line. An overflowing
/// prompt keeps its plain truncation, so a caret past the cut pins at the right
/// edge rather than scrolling the line to stay visible.
fn clamp_caret(cx: u16, line: &str, cols: usize) -> u16 {
    cx.min(truncate(line, cols).width() as u16)
}

/// The `❯` prompt prefix with optional directory and group destinations.
fn spawn_prefix(app: &App) -> String {
    let dir = (app.spawn_cwd != app.invocation_dir).then(|| app.dir_label(&app.spawn_cwd));
    prompt_line(dir.as_deref(), app.spawn_group.as_deref(), "")
}

/// Assemble the spawn prompt from its optional `▸` destination segments.
fn prompt_line(dir: Option<&str>, group: Option<&str>, input: &str) -> String {
    let mut line = String::from("");
    for seg in [dir, group].into_iter().flatten() {
        line.push_str(seg);
        line.push_str("");
    }
    line.push_str(input);
    line
}

/// Header intensity for one output run. Each run emits Bold or Dim, followed
/// by a reset, so the attributes never compete.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Intensity {
    Bold,
    Dim,
}

/// Split the header into styled runs, emphasizing only the active mode.
fn header_segments(prefix: &str, active: GroupMode, suffix: &str) -> Vec<(String, Intensity)> {
    // Keep the displayed order aligned with the grouping cycle.
    const STRIP: [GroupMode; 3] = [GroupMode::State, GroupMode::Dir, GroupMode::Custom];
    let mut segs = vec![(prefix.to_string(), Intensity::Bold)];
    for (i, m) in STRIP.iter().enumerate() {
        if i > 0 {
            segs.push((" · ".to_string(), Intensity::Dim));
        }
        let intensity = if *m == active {
            Intensity::Bold
        } else {
            Intensity::Dim
        };
        segs.push((m.label().to_string(), intensity));
    }
    segs.push((suffix.to_string(), Intensity::Bold));
    segs
}

/// A task's display label: its custom name when set, else the literal command.
fn display_label(v: &TaskView) -> &str {
    v.name.as_deref().unwrap_or(&v.command)
}

/// Attached-bar title: name and command when named, otherwise the command alone.
fn attached_title(v: &TaskView) -> String {
    match &v.name {
        Some(n) => format!("{n} · {}", v.command),
        None => v.command.clone(),
    }
}

/// Age shown for a task: time since exit when finished, last output when
/// parked, or launch otherwise. Missing edge timestamps fall back to launch.
fn row_age(v: &TaskView) -> Duration {
    let edge = match (v.lifecycle, v.parked) {
        (Lifecycle::Ok | Lifecycle::Failed, _) => v.finished_ago,
        (_, true) => v.quiet_ago,
        (_, false) => None,
    };
    edge.unwrap_or(v.started_ago)
}

/// Split a task row into its leading, preview, and time cells so the preview
/// can be styled independently. Each cell is padded to its display-column
/// budget, and the budgets sum to `cols`.
fn task_row_parts(v: &TaskView, cols: usize) -> (String, String, String) {
    let glyph = match v.lifecycle {
        Lifecycle::Active => "",
        Lifecycle::Idle => "",
        Lifecycle::Ok => "",
        Lifecycle::Failed => "",
    };
    let tag = if v.tagged { "" } else { " " };
    let time = rel_time(row_age(v));
    let title_w = 26.min(cols / 3);

    // indent(2) glyph(1) sp(1) tag(1) title(title_w) sp(1) preview(prev_w) sp(1) time
    let used = 2 + 1 + 1 + 1 + title_w + 1 + 1 + time.width();
    let prev_w = cols.saturating_sub(used);
    (
        format!("  {glyph} {tag}{} ", pad(display_label(v), title_w)),
        pad(&v.preview.text, prev_w),
        format!(" {time}"),
    )
}

fn task_row(v: &TaskView, cols: usize) -> String {
    let (lead, preview, time) = task_row_parts(v, cols);
    format!("{lead}{preview}{time}")
}

/// Paint a task row with only its padded preview cell dimmed.
fn dim_preview_row(out: &mut impl Write, y: u16, v: &TaskView, cols: usize) -> io::Result<()> {
    // Clamp each styled cell to the display columns still available.
    let (lead, preview, time) = task_row_parts(v, cols);
    let lead = truncate(&lead, cols);
    let mut rem = cols - lead.width();
    let preview = truncate(&preview, rem);
    rem -= preview.width();
    queue!(
        out,
        MoveTo(0, y),
        Print(lead),
        SetAttribute(Attribute::Dim),
        Print(preview),
        SetAttribute(Attribute::Reset),
        Print(pad(&time, rem))
    )
}

/// Build a labeled peek-box border exactly `inner_w` display columns wide.
fn peek_top_border(label: &str, inner_w: usize) -> String {
    let mut border = format!("{} ", truncate(label, inner_w.saturating_sub(4)));
    let w = border.width();
    if w < inner_w {
        border.extend(std::iter::repeat_n('', inner_w - w));
    }
    border
}

fn render_peek(out: &mut impl Write, app: &App) -> io::Result<()> {
    let Some(i) = app.selected_task() else {
        return Ok(());
    };
    let v = &app.views[i];
    let cols = app.cols as usize;
    let rows = app.rows as usize;

    let bw = (cols * 3 / 4).clamp(24, cols.max(24));
    let bh = rows.saturating_sub(6).clamp(5, 16);
    let x0 = cols.saturating_sub(bw) / 2;
    let y0 = rows.saturating_sub(bh) / 2;
    let inner_w = bw.saturating_sub(2);
    let inner_h = bh.saturating_sub(2);

    // Screen lines for the selected task, once the core has streamed them. Empty
    // until then (or if the watch just switched); the box still frames cleanly.
    let empty: Vec<String> = Vec::new();
    let lines = app.screen_for(v.id).map(|s| &s.lines).unwrap_or(&empty);
    let start = lines.len().saturating_sub(inner_h);
    let tail = &lines[start..];

    queue!(
        out,
        MoveTo(x0 as u16, y0 as u16),
        Print(format!("{}", peek_top_border(display_label(v), inner_w)))
    )?;

    for k in 0..inner_h {
        let line = tail.get(k).map(String::as_str).unwrap_or("");
        queue!(
            out,
            MoveTo(x0 as u16, (y0 + 1 + k) as u16),
            Print(format!("{}", pad(line, inner_w)))
        )?;
    }

    let by = (y0 + 1 + inner_h) as u16;
    queue!(
        out,
        MoveTo(x0 as u16, by),
        Print(format!("{}", "".repeat(inner_w)))
    )?;
    // The peek footer identifies the preview source and in-process matcher.
    let footer = format!(
        " space/esc close · enter attach · preview: {} ",
        preview_provenance(&v.preview)
    );
    queue!(
        out,
        MoveTo((x0 + 2) as u16, by),
        SetAttribute(Attribute::Dim),
        Print(truncate(&footer, inner_w)),
        SetAttribute(Attribute::Reset)
    )?;
    Ok(())
}

/// The peek footer's provenance label: source, then the matcher rule when
/// one produced it, then the frozen flag. Examples: `title`, `floor (frozen)`.
fn preview_provenance(p: &Preview) -> String {
    let mut s = p.source.label().to_string();
    if let Some(rule) = p.rule {
        s.push('/');
        s.push_str(rule);
    }
    if p.frozen {
        s.push_str(" (frozen)");
    }
    s
}

/// The varying content of a bottom-panel picker; `render_panel` owns the
/// shared skeleton.
struct Panel<'a> {
    /// Header line, painted reverse-video as the focused field.
    header: String,
    /// Preformatted row labels; the skeleton indents and `▸`-marks them.
    labels: &'a [String],
    /// Index of the highlighted row.
    sel: usize,
    /// Row cap before the list scrolls.
    max_rows: usize,
    /// Footer hint; the skeleton appends the `x/y` position when clipped.
    hint: String,
    /// Dim placeholder shown instead of rows when `labels` is empty.
    empty: Option<&'a str>,
    /// Cursor column on the header line; `None` hides the cursor.
    cursor: Option<u16>,
}

/// Bottom-panel skeleton shared by the dir, group, and session pickers,
/// anchored above the footer and sized so the selected row stays visible.
fn render_panel(out: &mut impl Write, app: &App, p: &Panel) -> io::Result<()> {
    let cols = app.cols as usize;
    let rows = app.rows;
    let total = p.labels.len();

    let max_list = p.max_rows.min((rows as usize).saturating_sub(4)).max(1);
    // Keep the selected row visible.
    let (start, visible) = scroll_window(p.sel, total, max_list);
    let body = visible.max(1);
    let panel_h = (body + 2) as u16;
    let top = rows.saturating_sub(panel_h).max(2);

    rev(out, top, &p.header, cols)?;

    if total == 0 {
        if let Some(msg) = p.empty {
            dim(out, top + 1, msg, cols)?;
        }
    } else {
        for row in 0..visible {
            let idx = start + row;
            let y = top + 1 + row as u16;
            let marker = if idx == p.sel { "" } else { "  " };
            let line = format!("    {marker}{}", p.labels[idx]);
            if idx == p.sel {
                rev(out, y, &line, cols)?;
            } else {
                put(out, y, &line, cols)?;
            }
        }
    }

    let pos = if total > visible {
        format!(" · {}/{}", p.sel + 1, total)
    } else {
        String::new()
    };
    dim(
        out,
        top + 1 + body as u16,
        &format!("  {}{pos}", p.hint),
        cols,
    )?;

    match p.cursor {
        Some(cx) => queue!(out, MoveTo(cx, top), Show),
        None => queue!(out, Hide),
    }
}

/// The `@` picker: a bottom panel over the dashboard. A typed-path input plus
/// the matching subdirectories, `dir_sel` highlighted.
fn render_pickdir(out: &mut impl Write, app: &App) -> io::Result<()> {
    let labels: Vec<String> = app
        .dir_candidates
        .iter()
        .map(|c| {
            // Don't double the slash if the label is already a rooted path.
            let sep = if c.label.ends_with('/') { "" } else { "/" };
            format!("{}{sep}", c.label)
        })
        .collect();
    // Hint reflects what Enter does on the highlighted row.
    let action = match app.dir_candidates.get(app.dir_sel).map(|c| c.kind) {
        Some(DirKind::Use) => "enter run here",
        Some(DirKind::Jump) => "enter run here · tab browse",
        Some(DirKind::Into) => "enter/tab open",
        None => "",
    };
    let (line, cx) = caret_line("  @ ", &app.dir_input);
    let cx = clamp_caret(cx, &line, app.cols as usize);
    render_panel(
        out,
        app,
        &Panel {
            header: format!("  @ {}   ", app.dir_input.as_str()),
            labels: &labels,
            sel: app.dir_sel,
            max_rows: 8,
            hint: format!("{action} · ↑↓ pick · esc"),
            empty: Some("    (no matching directories)"),
            cursor: Some(cx),
        },
    )
}

/// The `g` picker: a bottom panel with the typed name and matching groups,
/// `group_sel` highlighted. Row 0 always provides Unassigned, so the list
/// cannot be empty.
fn render_pickgroup(out: &mut impl Write, app: &App) -> io::Result<()> {
    let labels: Vec<String> = app
        .group_candidates
        .iter()
        .map(|c| c.label.clone())
        .collect();
    // Hint reflects what Enter does: create when the typed text matches nothing
    // (nothing matched), otherwise act on the highlighted row.
    let action = if !app.group_input.is_empty() && app.group_candidates.len() < 2 {
        "enter create"
    } else {
        match app.group_candidates.get(app.group_sel) {
            Some(c) if c.group.is_some() => "enter assign",
            Some(_) => "enter clear",
            None => "",
        }
    };
    let (line, cx) = caret_line("  g ", &app.group_input);
    let cx = clamp_caret(cx, &line, app.cols as usize);
    render_panel(
        out,
        app,
        &Panel {
            header: format!("  g {}   ", app.group_input.as_str()),
            labels: &labels,
            sel: app.group_sel,
            max_rows: 8,
            hint: format!("{action} · ↑↓ pick · esc"),
            empty: None,
            cursor: Some(cx),
        },
    )
}

/// The `o` load-session picker: a bottom panel listing saved session names.
fn render_session_picker(out: &mut impl Write, app: &App) -> io::Result<()> {
    render_panel(
        out,
        app,
        &Panel {
            header: "  load session".to_string(),
            labels: &app.session_names,
            sel: app.session_sel,
            max_rows: 10,
            hint: "↑↓ pick · enter load · esc".to_string(),
            empty: Some("    (no saved sessions)"),
            cursor: None,
        },
    )
}

/// Center `s` in `width` columns (a full-width string, so it overwrites the row).
fn center(s: &str, width: usize) -> String {
    let len = s.width();
    if len >= width {
        return truncate(s, width);
    }
    let mut out = " ".repeat((width - len) / 2);
    out.push_str(s);
    let cur = out.width();
    out.push_str(&" ".repeat(width - cur));
    out
}

/// Full-screen reconnect prompt shown after a daemon connection drops.
fn render_disconnected(out: &mut impl Write, app: &App) -> io::Result<()> {
    let cols = app.cols as usize;
    let rows = app.rows;

    queue!(out, Hide)?;
    for y in 0..rows {
        put(out, y, "", cols)?;
    }

    // A `--foreground` core has no daemon: naming one on this screen would
    // contradict the mode, and there is no external process to reconnect to.
    let (title, hint) = if app.daemon_backed {
        ("⚠  daemon connection lost", "r  reconnect        q  quit")
    } else {
        ("⚠  core stopped", "q  quit")
    };
    let mid = rows / 2;
    put(out, mid.saturating_sub(1), &center(title, cols), cols)?;
    dim(out, mid + 1, &center(hint, cols), cols)?;
    Ok(())
}

fn render_attached(out: &mut impl Write, app: &App) -> io::Result<()> {
    let Some(i) = app.focused_task() else {
        return Ok(());
    };
    let v = &app.views[i];
    let screen = app.screen_for(v.id);

    queue!(out, Hide, MoveTo(0, 0))?;
    if let Some(s) = screen {
        out.write_all(&s.formatted)?;
    }

    let cols = app.cols as usize;
    // Display the scrollback offset when viewing history.
    let title = attached_title(v);
    let bar = match screen.map_or(0, |s| s.scrollback) {
        0 => format!("  [attached] {title}    Ctrl-\\ background"),
        n => {
            format!("  [scroll ↑{n}] {title}    Esc live · PgUp/PgDn move · Ctrl-\\ background")
        }
    };
    rev(out, app.rows.saturating_sub(1), &bar, cols)?;

    // Place the real cursor where the child's is, so typing feels native.
    match screen {
        Some(s) if !s.hide_cursor => queue!(out, MoveTo(s.cursor.1, s.cursor.0), Show)?,
        _ => queue!(out, Hide)?,
    }
    Ok(())
}

/// Visible `(start, count)` window that includes the selected list item.
pub fn scroll_window(sel: usize, total: usize, max: usize) -> (usize, usize) {
    if total == 0 || max == 0 {
        return (0, 0);
    }
    let count = total.min(max);
    let start = if sel >= count { sel + 1 - count } else { 0 };
    (start, count)
}

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

    #[test]
    fn scroll_window_keeps_selection_visible() {
        assert_eq!(scroll_window(0, 5, 8), (0, 5)); // fits, no scroll
        assert_eq!(scroll_window(4, 5, 8), (0, 5));
        assert_eq!(scroll_window(7, 20, 8), (0, 8)); // last row of first window
        assert_eq!(scroll_window(8, 20, 8), (1, 8)); // scrolls one
        assert_eq!(scroll_window(19, 20, 8), (12, 8)); // last item
        for sel in 0..20 {
            let (start, count) = scroll_window(sel, 20, 8);
            assert!(sel >= start && sel < start + count, "sel {sel} off-window");
        }
    }

    /// Directory and group destinations appear only when present.
    #[test]
    fn spawn_prompt_decoration_shapes() {
        assert_eq!(prompt_line(None, None, "cargo test"), "  ❯ cargo test");
        assert_eq!(
            prompt_line(Some("~/x"), None, "cargo test"),
            "  ❯ ~/x ▸ cargo test"
        );
        assert_eq!(
            prompt_line(None, Some("alpha"), "cargo test"),
            "  ❯ alpha ▸ cargo test"
        );
        assert_eq!(
            prompt_line(Some("~/x"), Some("alpha"), "cargo test"),
            "  ❯ ~/x ▸ alpha ▸ cargo test"
        );
    }

    /// Minimal task snapshot for display-label tests.
    fn view(name: Option<&str>) -> TaskView {
        TaskView {
            id: 1,
            command: "cargo test".into(),
            cwd: std::path::PathBuf::from("/tmp"),
            tagged: false,
            group: None,
            name: name.map(str::to_string),
            lifecycle: Lifecycle::Active,
            parked: false,
            preview: Preview::floor(String::new()),
            started_ago: std::time::Duration::from_secs(5),
            quiet_ago: None,
            finished_ago: None,
        }
    }

    /// `view()` with the time-column inputs set; launched 2 h ago so the
    /// launch-age fallback ("2h") cannot collide with an edge age.
    fn timed_view(
        lifecycle: Lifecycle,
        parked: bool,
        quiet_ago: Option<Duration>,
        finished_ago: Option<Duration>,
    ) -> TaskView {
        TaskView {
            lifecycle,
            parked,
            quiet_ago,
            finished_ago,
            started_ago: Duration::from_secs(2 * 60 * 60),
            ..view(None)
        }
    }

    /// The time column uses exit, quiet, or launch age according to task state.
    #[test]
    fn task_row_time_column_follows_the_debounced_state() {
        let quiet = Some(Duration::from_secs(4 * 60)); // renders "4m"
        let exited = Some(Duration::from_secs(3)); // renders "3s"
        let cases = [
            (Lifecycle::Ok, false, None, exited, "3s"),
            (Lifecycle::Failed, false, None, exited, "3s"),
            (Lifecycle::Idle, true, quiet, None, "4m"),
            (Lifecycle::Idle, true, None, None, "2h"), // missing quiet timestamp
            (Lifecycle::Active, false, None, None, "2h"),
            (Lifecycle::Ok, false, None, None, "2h"), // missing exit timestamp
        ];
        for (lifecycle, parked, quiet_ago, finished_ago, want) in cases {
            let row = task_row(&timed_view(lifecycle, parked, quiet_ago, finished_ago), 80);
            assert!(
                row.ends_with(want),
                "{lifecycle:?} parked={parked} wanted {want:?}: {row:?}"
            );
        }
    }

    /// The dashboard row titles a task by its custom name when one is set.
    #[test]
    fn task_row_prefers_the_custom_name() {
        let row = task_row(&view(None), 80);
        assert!(row.contains("cargo test"), "row was {row:?}");

        let row = task_row(&view(Some("api server")), 80);
        assert!(row.contains("api server"), "row was {row:?}");
        assert!(
            !row.contains("cargo test"),
            "the name replaces the command: {row:?}"
        );
    }

    /// Rows remain column-exact with wide and combining glyphs.
    #[test]
    fn task_row_is_column_exact_for_wide_glyphs() {
        let titles = [
            "plain ascii title",
            "日本語のタスクタイトルです", // 13 wide chars: fills title_w exactly at 80 cols
            "🚀 emoji 🚀 title",
            "e\u{0301}e\u{0301} combining", // combining marks are zero-width
        ];
        let previews = [
            "build ok",
            "ビルド中の😀プレビュー出力がここに続いています",
            "",
        ];
        for cols in [40usize, 80] {
            for title in titles {
                for preview in previews {
                    let mut v = timed_view(Lifecycle::Active, false, None, None);
                    v.name = Some(title.to_string());
                    v.preview = Preview::floor(preview.to_string());
                    let row = task_row(&v, cols);
                    assert_eq!(
                        row.width(),
                        cols,
                        "cols {cols} title {title:?} preview {preview:?}: {row:?}"
                    );
                    assert!(row.ends_with(" 2h"), "time cell lost: {row:?}");
                }
            }
        }
    }

    /// Row-cell display widths depend on `cols`, not their contents.
    #[test]
    fn task_row_cells_hold_their_column_budgets() {
        let cols = 72;
        let ascii = timed_view(Lifecycle::Active, false, None, None);
        let mut wide = timed_view(Lifecycle::Active, false, None, None);
        wide.name = Some("日本語のテスト".into());
        wide.preview = Preview::floor("進捗 50% 😀".into());
        let (al, ap, at) = task_row_parts(&ascii, cols);
        let (wl, wp, wt) = task_row_parts(&wide, cols);
        assert_eq!(al.width(), wl.width(), "lead width varies with content");
        assert_eq!(ap.width(), wp.width(), "preview width varies with content");
        assert_eq!(at.width(), wt.width(), "time width varies with content");
        assert_eq!(wl.width() + wp.width() + wt.width(), cols);
    }

    /// Peek borders remain column-exact for wide and overlong labels.
    #[test]
    fn peek_top_border_fills_to_inner_width() {
        for label in ["cargo test", "日本語のテスト", "🚀 build", "e\u{0301}", ""] {
            let b = peek_top_border(label, 40);
            assert_eq!(b.width(), 40, "label {label:?}: {b:?}");
        }
        // Overlong labels truncate inside the border rather than widening it.
        let b = peek_top_border(&"".repeat(40), 40);
        assert_eq!(b.width(), 40, "{b:?}");
    }

    /// The peek footer's provenance label composes source, rule, and frozen.
    #[test]
    fn preview_provenance_label_shapes() {
        let mut p = Preview::floor(String::new());
        assert_eq!(preview_provenance(&p), "floor");
        p.source = PreviewSource::Title;
        p.frozen = true;
        assert_eq!(preview_provenance(&p), "title (frozen)");
        p.source = PreviewSource::Anchor;
        p.rule = Some("claude-status");
        p.frozen = false;
        assert_eq!(preview_provenance(&p), "anchor/claude-status");
    }

    /// The attached bar shows both the name and the command for a named task.
    #[test]
    fn attached_title_shows_name_and_command() {
        assert_eq!(attached_title(&view(None)), "cargo test");
        assert_eq!(
            attached_title(&view(Some("api server"))),
            "api server · cargo test"
        );
    }

    /// The strip's plain text is fixed; exactly the active mode's label is
    /// bold, every other strip run (labels and separators) is dim, and the
    /// prefix/suffix keep the header's bold.
    #[test]
    fn header_strip_bolds_only_the_active_mode() {
        for active in [GroupMode::State, GroupMode::Dir, GroupMode::Custom] {
            let segs = header_segments("by ", active, " · tail");
            let plain: String = segs.iter().map(|(t, _)| t.as_str()).collect();
            assert_eq!(plain, "by state · dir · custom · tail");

            assert_eq!(segs.first().unwrap(), &("by ".to_string(), Intensity::Bold));
            assert_eq!(
                segs.last().unwrap(),
                &(" · tail".to_string(), Intensity::Bold)
            );
            for (text, intensity) in &segs[1..segs.len() - 1] {
                let expect = if text == active.label() {
                    Intensity::Bold
                } else {
                    Intensity::Dim
                };
                assert_eq!(*intensity, expect, "run {text:?} with active {active:?}");
            }
        }
    }
}