termlens 0.8.0

Headless PTY test harness for CLI/TUI apps — spawn in a real PTY, assert on the rendered screen
Documentation
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
//! `wait_frame` (DEC 2026 synchronized output): predicates run only on
//! complete frames, torn repaints are never observable, and apps that
//! don't speak synchronized output fail with guidance instead of silence.

use std::time::{Duration, Instant};

use termlens::{Error, FrameTiming, Key, Terminal};

mod common;
use common as util;

fn spawn_form_echo() -> termlens::Result<Terminal> {
    Terminal::builder()
        .size(80, 24)
        .timeout(Duration::from_secs(10))
        .env_clear()
        .spawn(util::fixture_bin("form-echo"))
}

#[test]
fn the_frame_completed_before_the_call_is_evaluated() -> termlens::Result<()> {
    let mut t = spawn_form_echo()?;
    // The fixture's first synchronized frame has long completed by the time
    // this wait starts; entry evaluation must still see it.
    t.wait_frame(|s| s.contains("form-echo ready"))?;
    t.send(Key::Esc)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

#[test]
fn a_frame_is_internally_consistent() -> termlens::Result<()> {
    let mut t = spawn_form_echo()?;
    t.wait_frame(|s| s.contains("form-echo ready"))?;

    t.send_str("hi")?;
    // Both the input line and the last-key line are painted in the same
    // synchronized update, so a frame satisfying one must satisfy the
    // other. The returned frame is what the predicate saw, so the sibling
    // row is checked on that exact instant rather than on a later
    // `screen()` that may already have moved on.
    let frame = t.wait_frame(|s| s.contains("input: hi"))?;
    assert!(
        frame.contains("last: char:i"),
        "frame satisfied one row but not its sibling:\n{frame}"
    );

    t.send(Key::Esc)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

#[test]
fn a_torn_repaint_is_never_observed() -> termlens::Result<()> {
    let mut t = spawn_form_echo()?;
    t.wait_frame(|s| s.contains("form-echo ready"))?;

    // F2 paints "torn: left", flushes, sleeps 150ms, then paints " right"
    // and ends the synchronized update. The bytes arrive in two bursts;
    // the frame completes only with the second.
    t.send(Key::F(2))?;
    let row = t.wait_frame(|s| s.contains("torn: left"))?.row_text(5);
    assert!(
        row.contains("torn: left right"),
        "wait_frame observed a torn frame: {row:?}"
    );

    t.send(Key::Esc)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

#[test]
fn apps_without_synchronized_output_time_out_with_guidance() {
    // hello-tui never emits DEC 2026.
    let mut t = Terminal::builder()
        .size(80, 24)
        // Generous default: the fixture's first paint is not what is under
        // test here, and on a loaded runner it can take a while. The
        // deadline that matters is the per-call one below.
        .timeout(Duration::from_secs(10))
        .env_clear()
        .spawn(util::fixture_bin("hello-tui"))
        .unwrap();
    t.wait_until(|s| s.contains("")).unwrap();

    let start = Instant::now();
    let err = t
        .wait_frame_for(|_| true, Duration::from_millis(500))
        .unwrap_err();
    assert!(start.elapsed() >= Duration::from_millis(500));

    let msg = err.to_string();
    assert!(msg.contains("2026"), "no guidance in: {msg}");
    assert!(msg.contains("wait_until"), "no alternative named in: {msg}");
    assert!(err.screen().is_some(), "timeout must still embed a screen");

    t.send(Key::Char('q')).unwrap();
    assert!(t.wait_exit().unwrap().success());
}

/// The timeout error must show the screen as it is *now*, like every
/// other wait: its header says so, and in CI the embedded dump is often
/// the only evidence available. The last completed frame can be
/// arbitrarily old.
#[test]
fn wait_frame_timeouts_embed_the_live_screen_not_the_last_frame() {
    let mut t = Terminal::builder()
        .timeout(Duration::from_millis(400))
        .args([
            "-c",
            // One synchronized frame, then unbracketed output that will
            // never complete a frame.
            r"printf '\033[?2026h\033[HOLD FRAME\033[?2026l'; printf '\r\nLIVE SCREEN'; read quit",
        ])
        .spawn("sh")
        .unwrap();
    t.wait_frame(|s| s.contains("OLD FRAME")).unwrap();
    t.wait_until(|s| s.contains("LIVE SCREEN")).unwrap();

    let err = t.wait_frame(|s| s.contains("never painted")).unwrap_err();
    let screen = err.screen().expect("timeouts embed a screen");
    assert!(
        screen.contains("LIVE SCREEN"),
        "the embedded screen is stale — it must match the header:\n{screen}"
    );
    // The only frame drawn was already returned, so the message says the
    // application has not repainted rather than blaming the predicate.
    let msg = err.to_string();
    assert!(
        msg.contains("has not completed a repaint") && msg.contains("1 complete frame in total"),
        "the frame count and the reason belong in the message: {msg}"
    );
}

/// Several frames can complete inside one read. Each must stay
/// observable, in the order the application drew them — a progress
/// counter ticking 1, 2, 3 in a single write used to be visible only
/// at 3.
#[test]
fn every_frame_of_a_burst_is_observable_in_order() -> termlens::Result<()> {
    let mut t = Terminal::builder()
        .timeout(Duration::from_secs(10))
        .args([
            "-c",
            // Three complete frames in ONE write, then park.
            concat!(
                r"printf '\033[?2026h\033[HSTEP 1\033[?2026l",
                r"\033[?2026h\033[HSTEP 2\033[?2026l",
                r"\033[?2026h\033[HSTEP 3\033[?2026l'; read guard"
            ),
        ])
        .spawn("sh")?;

    // Settle on the live screen first, so all three frames have certainly
    // arrived (and been coalesced into as few reads as the OS chose)
    // before any of them is consumed. `wait_until` observes the grid, not
    // the frame ring, so it leaves the cursor where it is.
    t.wait_until(|s| s.contains("STEP 3"))?;

    // Now every frame of the burst is observable, oldest first, and each
    // call returns the frame it matched.
    assert!(t.wait_frame(|s| s.contains("STEP 1"))?.contains("STEP 1"));
    assert!(t.wait_frame(|s| s.contains("STEP 2"))?.contains("STEP 2"));
    assert!(t.wait_frame(|s| s.contains("STEP 3"))?.contains("STEP 3"));

    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

/// The retention bound is real and documented: beyond it, the oldest
/// frames are dropped.
#[test]
fn a_burst_longer_than_the_retention_bound_drops_its_oldest_frames() -> termlens::Result<()> {
    // 12 frames in one write, against a retention bound of 8.
    let mut script = String::new();
    for n in 1..=12 {
        script.push_str(&format!(r"\033[?2026h\033[HFRAME {n:02}\033[?2026l"));
    }
    let mut t = Terminal::builder()
        .timeout(Duration::from_millis(600))
        .args(["-c", &format!("printf '{script}'; read guard")])
        .spawn("sh")?;

    t.wait_until(|s| s.contains("FRAME 12"))?;
    // The most recent 8 are retained: 05..=12, so 05 is the oldest that
    // can still be observed.
    t.wait_frame(|s| s.contains("FRAME 05"))?;
    // The first four are gone, and the error says how many were seen.
    let err = t.wait_frame(|s| s.contains("FRAME 01")).unwrap_err();
    assert!(
        err.to_string().contains("12 in total"),
        "the frame count belongs in the message: {err}"
    );
    Ok(())
}

#[test]
fn wait_frame_fails_fast_on_eof() {
    let mut t = Terminal::builder()
        .timeout(Duration::from_secs(30))
        .args(["-c", r"printf '\033[?2026hdone\033[?2026l'; read guard"])
        .spawn("sh")
        .unwrap();
    t.wait_frame(|s| s.contains("done")).unwrap();
    t.send(Key::Enter).unwrap();

    let start = Instant::now();
    let err = t.wait_frame(|s| s.contains("never painted")).unwrap_err();
    assert!(matches!(err, Error::Eof { .. }), "expected Eof, got: {err}");
    assert!(
        start.elapsed() < Duration::from_secs(10),
        "EOF should fail fast"
    );
}

#[test]
fn wait_idle_does_not_resolve_inside_an_open_synchronized_update() {
    // The frame never ends: BSU, content, then the app parks on `read`.
    let mut t = Terminal::builder()
        .timeout(Duration::from_millis(600))
        .args(["-c", r"printf '\033[?2026hhalf a frame'; read guard"])
        .spawn("sh")
        .unwrap();
    t.wait_until(|s| s.contains("half a frame")).unwrap();

    let err = t.wait_idle(Duration::from_millis(100)).unwrap_err();
    assert!(
        matches!(err, Error::Timeout { .. }),
        "an open synchronized update must not count as idle: {err}"
    );
    // Drop kills the parked child.
}

#[test]
fn an_unmatched_end_publishes_no_frame() {
    // `?2026l` with no Begin must not manufacture a frame out of whatever
    // is on the grid — and must leave the frame count at zero, since that
    // is what gates the diagnosis below.
    let mut t = Terminal::builder()
        .timeout(Duration::from_millis(600))
        .args([
            "-c",
            r"printf '\033[2J\033[HNO-BEGIN\033[?2026l'; read guard",
        ])
        .spawn("sh")
        .unwrap();
    t.wait_until(|s| s.contains("NO-BEGIN")).unwrap();

    let err = t.wait_frame(|s| s.contains("NO-BEGIN")).unwrap_err();
    assert!(
        err.to_string().contains("never emitted"),
        "a phantom frame would both match and suppress the diagnosis: {err}"
    );
}

#[test]
fn a_defensive_mode_reset_keeps_the_never_emitted_diagnosis() {
    // Verbatim from a real crash handler: applications reset terminal modes
    // defensively, and such a string contains `?2026l`. One stray End used
    // to replace the pointed diagnosis with a frame count, which reads as
    // "the app is frame-capable, your predicate is wrong".
    let mut t = Terminal::builder()
        .timeout(Duration::from_millis(600))
        .args([
            "-c",
            concat!(
                r"printf '\033[?2026l\033[?25h\033[?1000l\033[?1002l",
                r"\033[?1003l\033[?2004l\033[?1049l'; ",
                r"printf '\033[2J\033[HPLAIN-PAINT'; read guard"
            ),
        ])
        .spawn("sh")
        .unwrap();
    t.wait_until(|s| s.contains("PLAIN-PAINT")).unwrap();

    let err = t.wait_frame(|s| s.contains("NEVER-DRAWN")).unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("never emitted a DEC 2026 synchronized update"),
        "the reset must not look like a repaint: {msg}"
    );
    assert!(
        !msg.contains("complete frames observed"),
        "no frame was drawn, so no count should be claimed: {msg}"
    );
}

#[test]
fn a_begin_end_pair_that_drew_nothing_is_still_a_frame() {
    // Deliberate: `frames_seen` counts repaints, not changes. An
    // application that opens and closes a synchronized update completed a
    // repaint, even if the result is identical — deciding otherwise would
    // mean diffing grids and calling a genuine no-op repaint a non-event.
    let mut t = Terminal::builder()
        .timeout(Duration::from_secs(5))
        .args([
            "-c",
            r"printf '\033[2J\033[HSTATIC'; printf '\033[?2026h\033[?2026l'; read guard",
        ])
        .spawn("sh")
        .unwrap();
    t.wait_frame(|s| s.contains("STATIC")).unwrap();
    t.send(Key::Enter).unwrap();
}

/// The headline case: `send(key); wait_frame(OLD_STATE)` used to pass on
/// the retained frame, and the assertion after it read the old screen. A
/// regression in which the key stopped working was invisible.
#[test]
fn a_superseded_frame_no_longer_satisfies_a_wait() -> termlens::Result<()> {
    let mut t = Terminal::builder()
        .timeout(Duration::from_secs(10))
        .args([
            "-c",
            concat!(
                r"printf '\033[?2026h\033[2J\033[HSTATE-A\033[?2026l'; read a; ",
                r"printf '\033[?2026h\033[2J\033[HSTATE-B\033[?2026l'; read b"
            ),
        ])
        .spawn("sh")?;

    assert!(t.wait_frame(|s| s.contains("STATE-A"))?.contains("STATE-A"));
    t.send(Key::Enter)?;

    let stale = t.wait_frame_for(|s| s.contains("STATE-A"), Duration::from_millis(700));
    assert!(
        matches!(stale, Err(Error::Timeout { .. })),
        "waiting for the superseded state must fail: {stale:?}"
    );

    // The frame the application actually drew is there for the asking.
    assert!(t.wait_frame(|s| s.contains("STATE-B"))?.contains("STATE-B"));

    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

#[test]
fn one_frame_cannot_satisfy_two_waits() -> termlens::Result<()> {
    let mut t = Terminal::builder()
        .timeout(Duration::from_secs(10))
        .args([
            "-c",
            r"printf '\033[?2026h\033[2J\033[HONLY-FRAME\033[?2026l'; read guard",
        ])
        .spawn("sh")?;

    t.wait_frame(|s| s.contains("ONLY-FRAME"))?;
    let again = t.wait_frame_for(|s| s.contains("ONLY-FRAME"), Duration::from_millis(700));
    assert!(
        matches!(again, Err(Error::Timeout { .. })),
        "one repaint must not satisfy two waits: {again:?}"
    );

    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

/// The burst is observable in emission order, which means out of order it
/// is *not*: a frame already returned is behind the cursor.
#[test]
fn a_burst_frame_asked_for_out_of_order_is_gone() -> termlens::Result<()> {
    let mut t = Terminal::builder()
        .timeout(Duration::from_millis(700))
        .args([
            "-c",
            concat!(
                r"printf '\033[?2026h\033[HSTEP 1\033[?2026l",
                r"\033[?2026h\033[HSTEP 2\033[?2026l",
                r"\033[?2026h\033[HSTEP 3\033[?2026l'; read guard"
            ),
        ])
        .spawn("sh")?;

    t.wait_until(|s| s.contains("STEP 3"))?;
    t.wait_frame(|s| s.contains("STEP 3"))?;

    let backwards = t.wait_frame(|s| s.contains("STEP 1"));
    assert!(
        matches!(backwards, Err(Error::Timeout { .. })),
        "STEP 1 was already passed over: {backwards:?}"
    );
    Ok(())
}

/// `wait_frame` returns the instant the predicate saw, which can differ
/// from the live grid by the time the call returns.
#[test]
fn the_returned_frame_is_the_matched_instant_not_the_live_screen() -> termlens::Result<()> {
    let mut t = Terminal::builder()
        .timeout(Duration::from_secs(10))
        .args([
            "-c",
            // One complete frame, then unbracketed output that lands after
            // the frame was published.
            r"printf '\033[?2026h\033[2J\033[HFRAMED\033[?2026l'; printf '\r\nLIVE'; read guard",
        ])
        .spawn("sh")?;

    let frame = t.wait_frame(|s| s.contains("FRAMED"))?;
    t.wait_until(|s| s.contains("LIVE"))?;

    assert!(
        !frame.contains("LIVE"),
        "the returned frame must be the instant the update ended:\n{frame}"
    );
    assert!(
        t.screen().contains("LIVE"),
        "the live screen has moved on:\n{}",
        t.screen()
    );

    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

/// A frame drawn at the old size is not the repaint that answers a
/// resize, which is what makes the advice in `resize`'s stale-frame trap
/// hold for `wait_frame`.
#[test]
fn a_resize_stops_offering_frames_drawn_at_the_old_size() -> termlens::Result<()> {
    let mut t = Terminal::builder()
        .size(80, 24)
        .timeout(Duration::from_millis(700))
        .args([
            "-c",
            // Paints one frame, then ignores SIGWINCH and never repaints.
            r"printf '\033[?2026h\033[2J\033[HBEFORE-RESIZE\033[?2026l'; read guard",
        ])
        .spawn("sh")?;

    // Deliberately not consumed: this proves the resize moves the cursor,
    // not that an earlier wait did.
    t.wait_until(|s| s.contains("BEFORE-RESIZE"))?;
    t.resize(40, 10)?;

    let stale = t.wait_frame(|s| s.contains("BEFORE-RESIZE"));
    assert!(
        matches!(stale, Err(Error::Timeout { .. })),
        "a pre-resize frame must not answer a post-resize wait: {stale:?}"
    );
    Ok(())
}

/// The repaint that answers a resize is offered to `wait_frame`, however fast
/// the application is, and it is drawn into the resized grid. The frame
/// cursor used to be taken *after* the SIGWINCH went out, so an acknowledging
/// repaint that completed in that gap was counted as a pre-resize frame and
/// never offered — found by the stress workflow at 16 threads, once in 25
/// runs. The grid is now resized and the cursor taken before the signal,
/// under one lock, so there is no gap for a frame to fall into.
#[test]
fn the_repaint_answering_a_resize_is_offered_to_wait_frame() -> termlens::Result<()> {
    let mut t = spawn_form_echo()?;
    t.wait_frame(|s| s.contains("form-echo ready"))?;
    for (cols, rows) in [(60u16, 12u16), (40, 8), (100, 30)] {
        t.resize(cols, rows)?;
        let frame = t.wait_frame(|s| s.contains(&format!("last: resize:{cols}x{rows}")))?;
        // Drawn into the resized grid, not clipped out of the old one.
        assert_eq!(frame.size(), (cols, rows), "{frame}");
    }
    t.send(Key::Esc)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

/// `screen()` is the live grid even for an application that brackets
/// every repaint — the tear is real, documented, and wanted for
/// diagnosis. `wait_frame`'s return value is the frame-consistent read.
#[test]
fn a_snapshot_can_be_mid_frame_for_a_synchronized_application() -> termlens::Result<()> {
    let mut t = Terminal::builder()
        .size(80, 24)
        .timeout(Duration::from_secs(10))
        .args([
            "-c",
            concat!(
                // Frame OPEN, one of two rows painted.
                r"printf '\033[?2026h\033[2J\033[HROW-ONE'; read a; ",
                // Second row, then the frame closes.
                r"printf '\033[2;1HROW-TWO\033[?2026l'; read b"
            ),
        ])
        .spawn("sh")?;

    t.wait_until(|s| s.contains("ROW-ONE"))?;
    let torn = t.screen();
    assert!(torn.contains("ROW-ONE"), "row 0 is painted:\n{torn}");
    assert!(
        torn.row_text(1).trim_end().is_empty(),
        "the frame is not finished, and screen() says so:\n{torn}"
    );

    t.send(Key::Enter)?;
    // The frame-consistent read has both rows, by construction.
    let frame = t.wait_frame(|s| s.contains("ROW-TWO"))?;
    assert!(
        frame.contains("ROW-ONE") && frame.contains("ROW-TWO"),
        "{frame}"
    );

    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

/// A terminal that is silent *because* it is stuck mid-repaint used to
/// time out "waiting for 100ms of output silence", which reads as
/// nonsense next to a quiet terminal.
#[test]
fn a_wait_idle_timeout_names_an_unfinished_frame() {
    let mut t = Terminal::builder()
        .timeout(Duration::from_millis(600))
        .args(["-c", r"printf '\033[?2026hhalf a frame'; read guard"])
        .spawn("sh")
        .unwrap();
    t.wait_until(|s| s.contains("half a frame")).unwrap();

    let err = t.wait_idle(Duration::from_millis(100)).unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("unfinished DEC 2026 synchronized update"),
        "the real state must be named: {msg}"
    );
    assert!(
        msg.contains("half-painted frame"),
        "and what the embedded screen is: {msg}"
    );
}

/// A repaint that got slower, or bigger, is the most common TUI regression
/// and no content predicate sees either. form-echo's F2 draw sleeps 150ms
/// *inside* one synchronized update, so it is the outlier the series has to
/// show.
#[test]
fn the_timing_series_shows_a_deliberately_slow_repaint() -> termlens::Result<()> {
    let mut t = spawn_form_echo()?;
    t.wait_frame(|s| s.contains("form-echo ready"))?;

    // A few ordinary repaints first, to have something to be an outlier
    // against.
    for c in ['a', 'b', 'c'] {
        t.send(Key::Char(c))?;
        t.wait_frame(|s| s.contains(&format!("input: {}", "abc".split(c).next().unwrap_or(""))))?;
    }
    let quick = t.frame_timings();
    assert!(quick.len() >= 4, "one per repaint so far: {}", quick.len());
    let slowest_quick = quick.iter().map(|f| f.duration()).max().unwrap();

    t.send(Key::F(2))?;
    let torn = t.wait_frame(|s| s.contains("torn: left") && s.contains("right"))?;
    assert!(torn.contains("torn: left right"), "{torn}");

    let all = t.frame_timings();
    let slow = all.last().expect("the torn frame");
    assert_eq!(
        slow.index(),
        torn.repaints(),
        "the series and the frame count agree on which repaint this was"
    );
    // A tolerance, not a floor at exactly 150ms — and the reason is a real
    // property of the measurement rather than slack for its own sake. Both
    // ends are stamped when *we* consume the marker byte, so if the opening
    // bytes reach the reader a fraction late while the End still arrives
    // 150ms after the application's flush, the span measures marginally
    // *under* the sleep. Stress caught it at 149.72ms — 276µs short.
    assert!(
        slow.duration() >= Duration::from_millis(140),
        "the deliberate 150ms sleep must be inside the span: {:?}",
        slow.duration()
    );
    // Deliberately *not* "the slow frame is 5x the quick ones". Under a
    // loaded runner an ordinary repaint can take tens of milliseconds, so a
    // ratio is a claim about the machine rather than about the measurement.
    // The 150ms floor above is the property that holds regardless, and it is
    // the one the fixture actually creates.
    assert!(
        slow.duration() > slowest_quick,
        "the slowed repaint must still be the slowest: {:?} vs {slowest_quick:?}",
        slow.duration()
    );

    // The size half of the same question: every repaint drew something, and
    // the count is per character.
    assert!(
        all.iter().all(|f| f.printable_chars() > 0),
        "each repaint drew something: {:?}",
        all.iter()
            .map(FrameTiming::printable_chars)
            .collect::<Vec<_>>()
    );
    // "torn: left" + " right" = 16 printable characters, and nothing else in
    // that update is printable.
    assert_eq!(slow.printable_chars(), 16, "{slow:?}");

    t.send(Key::Esc)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

/// Timings are per frame even when a burst arrives in one read — the markers
/// are stamped at the byte that carried them, not when the read landed.
#[test]
fn a_burst_in_one_read_is_timed_per_frame() -> termlens::Result<()> {
    let mut t = Terminal::builder()
        .size(40, 6)
        .timeout(Duration::from_secs(10))
        .args([
            "-c",
            concat!(
                r"printf READY; read a; ",
                // Three frames in a single write, so they arrive as one read.
                r"printf '\033[?2026hone\033[?2026l\033[?2026htwotwo\033[?2026l\033[?2026hthree!\033[?2026l'; ",
                r"printf ' DONE'; read b"
            ),
        ])
        .spawn("/bin/sh")?;
    t.wait_until(|s| s.contains("READY"))?;
    assert!(t.frame_timings().is_empty(), "nothing has repainted yet");

    t.send(Key::Enter)?;
    t.wait_until(|s| s.contains("DONE"))?;

    let timings = t.frame_timings();
    assert_eq!(timings.len(), 3, "three frames, three timings: {timings:?}");
    assert_eq!(
        timings.iter().map(FrameTiming::index).collect::<Vec<_>>(),
        vec![1, 2, 3],
        "numbered in emission order"
    );
    // Each frame is credited with what *it* drew, not the whole read.
    assert_eq!(
        timings
            .iter()
            .map(FrameTiming::printable_chars)
            .collect::<Vec<_>>(),
        vec![3, 6, 6],
        "one/twotwo/three! — per frame, not per read"
    );
    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}