ratto 0.8.0

Ratatui-powered terminal primitives for shell dashboards: flicker-free repaints, progress bars, prompts, and portable time tools
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
mod common;

use assert_cmd::Command;

fn rat() -> Command {
    let mut cmd = common::rat();
    cmd.env_remove("NO_COLOR");
    cmd
}

/// Path to the rat binary, used as a portable child process: shell
/// utilities like sh, echo, and printf do not exist everywhere.
fn rat_bin() -> String {
    assert_cmd::cargo::cargo_bin("rat").display().to_string()
}

/// Write a fixture and hand back its path. Commands are interpolated so
/// every pane runs the rat binary under test. The backslash escape
/// keeps a Windows binary path a valid KDL quoted string.
fn fixture(dir: &std::path::Path, name: &str, body: &str) -> String {
    let path = dir.join(name);
    std::fs::write(&path, body).expect("write fixture");
    path.display().to_string()
}

#[test]
fn a_dashboard_renders_its_panes_once() {
    let dir = tempfile::tempdir().expect("tempdir");
    let file = fixture(
        dir.path(),
        "board.kdl",
        &format!(
            r#"
defaults {{
    height 3
    chrome #false
}}

pane "left" {{
    command "{bin}" "style" "hello"
}}

pane "right" {{
    command "{bin}" "style" "world"
}}
"#,
            bin = rat_bin().replace('\\', "\\\\")
        ),
    );
    rat()
        .env("NO_COLOR", "1")
        .args(["dashboard", &file, "--once"])
        .assert()
        .success()
        .stdout(predicates::str::contains("hello"))
        .stdout(predicates::str::contains("world"));
}

#[test]
fn a_pane_child_is_told_its_inner_geometry() {
    // A Cells pane with no border and no padding has an inner width
    // equal to its declared cells, whatever the terminal is — so the
    // assertion is exact and does not depend on the harness having a
    // tty.
    let dir = tempfile::tempdir().expect("tempdir");
    let bin = rat_bin().replace('\\', "\\\\");
    let file = fixture(
        dir.path(),
        "geom.kdl",
        &format!(
            r#"
defaults height=3 chrome=#false border="none" padding="0" width="20"

pane "cols" {{
    command "{bin}" "__env" "RAT_WIDTH"
}}

pane "rows" {{
    command "{bin}" "__env" "RAT_HEIGHT"
}}

pane "whoami" {{
    command "{bin}" "__env" "RAT_PANE"
}}
"#
        ),
    );
    let assert = rat()
        .env("NO_COLOR", "1")
        .args(["dashboard", &file, "--once"])
        .assert()
        .success();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    assert!(
        stdout.contains("20"),
        "RAT_WIDTH is the pane's cells: {stdout:?}"
    );
    assert!(
        stdout.contains('3'),
        "RAT_HEIGHT is the pane's inner rows: {stdout:?}"
    );
    assert!(
        stdout.contains("whoami"),
        "RAT_PANE is the pane's name: {stdout:?}"
    );
}

#[test]
fn a_pane_taller_than_its_box_is_truncated_keep_top() {
    // `rat style` joins multiple arguments with newlines, so this child
    // prints five lines into a three-row box.
    let dir = tempfile::tempdir().expect("tempdir");
    let bin = rat_bin().replace('\\', "\\\\");
    let file = fixture(
        dir.path(),
        "tall.kdl",
        &format!(
            r#"
pane "tall" {{
    height 3
    chrome #false
    border "none"
    command "{bin}" "style" "AAA" "BBB" "CCC" "DDD" "EEE"
}}
"#
        ),
    );
    let assert = rat()
        .env("NO_COLOR", "1")
        .args(["dashboard", &file, "--once"])
        .assert()
        .success();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    assert!(
        stdout.contains("AAA"),
        "keep-top keeps the head: {stdout:?}"
    );
    assert!(
        !stdout.contains("EEE"),
        "the pin truncated nothing: {stdout:?}"
    );
}

#[test]
fn a_pane_that_has_not_run_renders_blank_at_its_declared_size() {
    // The composed frame's row count is run-constant, so however the
    // two completions interleave, every frame written is exactly the
    // declared height. A pane that has not posted yet is blank rows,
    // never a shorter frame.
    let dir = tempfile::tempdir().expect("tempdir");
    let bin = rat_bin().replace('\\', "\\\\");
    let file = fixture(
        dir.path(),
        "stack.kdl",
        &format!(
            r#"
defaults {{
    height 3
    chrome #false
    border "none"
}}

pane "a" {{
    command "{bin}" "style" "one"
}}

pane "b" {{
    command "{bin}" "style" "two"
}}
"#
        ),
    );
    let assert = rat()
        .env("NO_COLOR", "1")
        .args(["dashboard", &file, "--once"])
        .assert()
        .success();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    let rows = stdout.lines().count();
    assert!(rows >= 6, "a whole frame is 6 rows, got {rows}: {stdout:?}");
    assert_eq!(
        rows % 6,
        0,
        "every frame is exactly 6 rows; got {rows}: {stdout:?}"
    );
}

#[test]
fn an_unreadable_file_names_the_path() {
    let missing = "definitely-no-such-dashboard-xyz.kdl";
    rat()
        .args(["dashboard", missing])
        .assert()
        .code(1)
        .stderr(predicates::str::contains(missing));
}

/// A file that is not KDL fails as a parse error carrying the path —
/// there is no format selection left to point at.
#[test]
fn a_file_that_is_not_kdl_names_the_path() {
    let dir = tempfile::tempdir().expect("tempdir");
    let file = fixture(dir.path(), "board.conf", "gap = 0\n");
    rat()
        .args(["dashboard", &file])
        .assert()
        .code(1)
        .stderr(predicates::str::contains("board.conf"));
}

/// The failure lives in the failing pane's own box — its text, its
/// exit badge — and the dashboard around it is untouched. The height
/// pin is what makes that structural: two 5-row panes compose to
/// exactly ten rows whether they succeed or fail.
#[test]
fn a_failing_pane_shows_its_exit_code_and_the_rest_of_the_dashboard_survives() {
    let dir = tempfile::tempdir().expect("tempdir");
    let steady = dir.path().join("steady");
    std::fs::write(&steady, "steady-content").expect("seed");
    let decl = dir.path().join("dash.kdl");
    std::fs::write(
        &decl,
        format!(
            r#"
row-gap 0

defaults {{
    height 5
    border "rounded"
}}

pane "broken" {{
    command "{rat}" "__exitcode" "3" "boom-from-stderr"
}}

pane "steady" {{
    command "{rat}" "__cat" "{steady}"
}}
"#,
            rat = rat_bin().escape_default(),
            steady = steady.display().to_string().escape_default(),
        ),
    )
    .expect("write declaration");

    let assert = rat()
        .env("NO_COLOR", "1")
        .args(["dashboard", "--once", &decl.display().to_string()])
        .assert()
        .success();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();

    // The failing pane's own box carries its stderr and its badge.
    assert!(stdout.contains("boom-from-stderr"), "{stdout:?}");
    assert!(stdout.contains(" · exit 3"), "{stdout:?}");
    // The neighbour rendered normally: a failure never truncates it.
    assert!(stdout.contains("steady-content"), "{stdout:?}");
    // Both declared heights intact — the whole point of the pin.
    assert_eq!(
        stdout.trim_end_matches('\n').split('\n').count(),
        10,
        "declared heights must survive a failure: {stdout:?}"
    );
    // Nothing writes outside the frame engine. The failing child's
    // stderr went into its pane, not to the terminal.
    assert_eq!(
        String::from_utf8_lossy(&assert.get_output().stderr),
        "",
        "a failing pane must not leak to the terminal"
    );
}

/// Stream the piped dashboard's stdout through a channel so waiting for
/// a frame is bounded: a blocking read cannot swallow the deadline.
/// Duplicated from the watch suite's local helpers, never lifted — that
/// file is the byte-identity witness.
fn stdout_stream(stdout: std::process::ChildStdout) -> std::sync::mpsc::Receiver<Vec<u8>> {
    use std::io::Read;
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let mut stdout = stdout;
        let mut buf = [0u8; 4096];
        while let Ok(n) = stdout.read(&mut buf) {
            if n == 0 || tx.send(buf[..n].to_vec()).is_err() {
                return;
            }
        }
    });
    rx
}

/// Drain the stream until the needle appears — a missing frame is a
/// clean failure, never a hang.
fn read_until(stream: &std::sync::mpsc::Receiver<Vec<u8>>, seen: &mut String, needle: &str) {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    loop {
        if seen.contains(needle) {
            return;
        }
        let left = deadline.saturating_duration_since(std::time::Instant::now());
        assert!(!left.is_zero(), "never saw {needle:?} in {seen:?}");
        match stream.recv_timeout(left) {
            Ok(chunk) => seen.push_str(&String::from_utf8_lossy(&chunk)),
            Err(_) => panic!("never saw {needle:?} in {seen:?}"),
        }
    }
}

/// Reap the dashboard even when an assertion panics: an orphaned child
/// holds the harness's stdout pipe open and hangs the whole run.
struct KillOnDrop(std::process::Child);

impl Drop for KillOnDrop {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}

/// Per-pane triggers: a fire routes to the pane that DECLARED it. The
/// declarer is deliberately the SECOND source: a wiring that routes
/// every fire to source 0 (a shared gate, a hardcoded index) re-runs
/// alpha instead — whose bytes are unchanged, so the gated pipe writes
/// nothing and v1 never appears.
#[test]
fn a_file_trigger_refreshes_only_its_own_pane() {
    let dir = tempfile::tempdir().expect("tempdir");
    let steady = dir.path().join("steady");
    let shared = dir.path().join("shared");
    let untouched = dir.path().join("untouched");
    std::fs::write(&steady, "a0").expect("seed");
    std::fs::write(&shared, "v0").expect("seed");
    std::fs::write(&untouched, "x").expect("seed");
    let decl = dir.path().join("dash.kdl");
    std::fs::write(
        &decl,
        format!(
            r#"
row-gap 0

defaults {{
    height 1
    border "none"
    chrome #false
    interval "never"
    trigger-debounce "0ms"
}}

pane "alpha" {{
    command "{rat}" "__cat" "{steady}"
    trigger "file:{untouched}"
}}

pane "beta" {{
    command "{rat}" "__cat" "{shared}"
    trigger "file:{shared}"
}}
"#,
            rat = rat_bin().escape_default(),
            steady = steady.display().to_string().escape_default(),
            shared = shared.display().to_string().escape_default(),
            untouched = untouched.display().to_string().escape_default(),
        ),
    )
    .expect("write declaration");

    let dash = std::process::Command::new(rat_bin())
        .args(["dashboard", &decl.display().to_string()])
        .stdout(std::process::Stdio::piped())
        .spawn()
        .expect("spawn rat dashboard piped");
    let mut dash = KillOnDrop(dash);
    let stream = stdout_stream(dash.0.stdout.take().expect("piped stdout"));
    let mut seen = String::new();
    read_until(&stream, &mut seen, "v0"); // both panes' first tick

    std::fs::write(&shared, "v1").expect("mtime change");
    read_until(&stream, &mut seen, "v1"); // beta's trigger-driven frame

    // The panes stack in declaration order: in the refreshed frame,
    // alpha's retained row still precedes beta's new one.
    let last_frame = seen.rfind("a0").expect("alpha's retained row");
    assert!(
        seen[last_frame..].contains("v1"),
        "the refreshed frame keeps declaration order: {seen:?}"
    );
    // KillOnDrop reaps: kill only SENDS the signal, and an unreaped
    // child zombies (unix) and races tempdir cleanup.
}

/// Every change fires, not just the first. The loop now stats the watched
/// union on its own account, to learn whether a path ever moves while the
/// dashboard is idle — and that observer keeps its OWN baselines. If it ever
/// shared them with the trigger, its stat would consume the fire and the pane
/// would quietly stop refreshing, which is the failure this guards.
#[test]
fn successive_trigger_changes_each_refresh_the_pane() {
    let dir = tempfile::tempdir().expect("tempdir");
    let watched = dir.path().join("watched");
    std::fs::write(&watched, "v0").expect("seed");
    let decl = dir.path().join("dash.kdl");
    std::fs::write(
        &decl,
        format!(
            r#"
row-gap 0

defaults {{
    height 1
    border "none"
    chrome #false
    interval "never"
    trigger-debounce "0ms"
}}

pane "only" {{
    command "{rat}" "__cat" "{watched}"
    trigger "file:{watched}"
}}
"#,
            rat = rat_bin().escape_default(),
            watched = watched.display().to_string().escape_default(),
        ),
    )
    .expect("write declaration");

    let dash = std::process::Command::new(rat_bin())
        .args(["dashboard", &decl.display().to_string()])
        .stdout(std::process::Stdio::piped())
        .spawn()
        .expect("spawn rat dashboard piped");
    let mut dash = KillOnDrop(dash);
    let stream = stdout_stream(dash.0.stdout.take().expect("piped stdout"));
    let mut seen = String::new();
    read_until(&stream, &mut seen, "v0");

    // Three in a row: a shared baseline would swallow one of them.
    for value in ["v1", "v2", "v3"] {
        std::fs::write(&watched, value).expect("mtime change");
        read_until(&stream, &mut seen, value);
    }
}

/// `--once` prints ONE complete frame: a staggered pane must not make
/// the partial composition reach the pipe first.
#[test]
fn once_emits_exactly_one_complete_frame() {
    let dir = tempfile::tempdir().expect("tempdir");
    let bin = rat_bin().replace('\\', "\\\\");
    let file = fixture(
        dir.path(),
        "staggered.kdl",
        &format!(
            r#"
row-gap 0

defaults {{
    height 1
    chrome #false
    border "none"
}}

pane "quick" {{
    command "{bin}" "style" "one"
}}

pane "slow" {{
    command "{bin}" "__sleep" "300" "two"
}}
"#
        ),
    );
    let assert = rat()
        .env("NO_COLOR", "1")
        .args(["dashboard", &file, "--once"])
        .assert()
        .success();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    assert_eq!(
        stdout.trim_end_matches('\n').split('\n').count(),
        2,
        "one frame, both panes: {stdout:?}"
    );
    assert_eq!(
        stdout.matches("one").count(),
        1,
        "the quick pane printed once: {stdout:?}"
    );
    assert!(stdout.contains("two"), "the slow pane arrived: {stdout:?}");
}

/// Piped mode honors the handed-down geometry: a nested one-shot
/// dashboard sizes itself to its pane instead of a hardcoded 80
/// columns.
#[test]
fn a_piped_dashboard_sizes_from_rat_width() {
    let dir = tempfile::tempdir().expect("tempdir");
    let bin = rat_bin().replace('\\', "\\\\");
    let file = fixture(
        dir.path(),
        "sized.kdl",
        &format!(
            r#"
pane "wide" {{
    height 2
    chrome #false
    border "none"
    command "{bin}" "style" "x"
}}
"#
        ),
    );
    let assert = rat()
        .env("NO_COLOR", "1")
        .env("RAT_WIDTH", "40")
        .env("RAT_HEIGHT", "20")
        .args(["dashboard", &file, "--once"])
        .assert()
        .success();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    for line in stdout.trim_end_matches('\n').split('\n') {
        assert_eq!(line.chars().count(), 40, "a 40-cell frame: {line:?}");
    }
}

/// Nested layout nodes: a row holding a column beside a pane renders
/// as a grid — the engine's tree was recursive from day one, and the
/// declaration now reaches it.
#[test]
fn a_nested_layout_renders_a_grid() {
    let dir = tempfile::tempdir().expect("tempdir");
    let bin = rat_bin().replace('\\', "\\\\");
    let file = fixture(
        dir.path(),
        "grid.kdl",
        &format!(
            r#"
defaults height=1 chrome=#false border="none"

row {{
    column {{
        pane "a" {{
            command "{bin}" "style" "one"
        }}
        pane "b" {{
            command "{bin}" "style" "two"
        }}
    }}
    pane "c" height=2 {{
        command "{bin}" "style" "three"
    }}
}}
"#
        ),
    );
    let assert = rat()
        .env("NO_COLOR", "1")
        .env("RAT_WIDTH", "40")
        .args(["dashboard", &file, "--once"])
        .assert()
        .success();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();
    let rows: Vec<&str> = stdout.trim_end_matches('\n').split('\n').collect();
    assert_eq!(rows.len(), 2, "a 2-row grid: {stdout:?}");
    assert!(
        rows[0].contains("one") && rows[0].contains("three"),
        "top of the column beside the tall pane: {stdout:?}"
    );
    assert!(
        rows[1].contains("two"),
        "bottom of the column on the second grid row: {stdout:?}"
    );
}

#[test]
fn a_flooding_pane_wears_the_marker_on_its_own_chrome_row() {
    // The pane route's own end-to-end proof. The unit tests show the
    // badge renders and joins the signature; only this shows the count
    // reaching it from a real child, through the reader, the outcome
    // and the drain. A shared decision covered on one route only is
    // covered on neither.
    let dir = tempfile::tempdir().expect("tempdir");
    let bin = rat_bin().replace('\\', "\\\\");
    let file = fixture(
        dir.path(),
        "flood.kdl",
        &format!(
            r#"
defaults height=6 width="60" border="none" padding="0"

pane "flood" {{
    command "{bin}" "__lines" "1500"
}}

pane "quiet" {{
    command "{bin}" "style" "calm"
}}
"#
        ),
    );
    let assert = rat()
        .env("NO_COLOR", "1")
        .args(["dashboard", &file, "--once"])
        .assert()
        .success();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).into_owned();

    assert!(
        stdout.contains("500 lines dropped"),
        "the flooding pane must say so; got {stdout:?}"
    );
    // The default overflow keeps the head, so the pane retained lines
    // 0..999 and paints the first of them. The last line the child
    // printed is gone — the direction working, not a fault.
    assert!(
        stdout.starts_with('0'),
        "a keep-top pane shows its head: {stdout:?}"
    );
    assert!(
        !stdout.contains("1499"),
        "and its tail is what went: {stdout:?}"
    );
    // One pane overflowed, not both: the marker is per-pane state and
    // the quiet pane's chrome row must stay clean.
    assert_eq!(
        stdout.matches("lines dropped").count(),
        1,
        "only the flooding pane wears it: {stdout:?}"
    );
}