summaryrefslogtreecommitdiff
path: root/test/tty.zig
blob: d139cb6add2eae46c51f79ba75193eefa7442c72 (plain) (blame)
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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
//! A pardes in a pty of its own, driven as a terminal user drives it: keys
//! and the mouse as a terminal's bytes, its screen read back through its
//! own ghostty-vt (e2e_harness.zig). The tty cases (test/process/tty_*.zig)
//! are what the tty frontend draws and how it reads its input, which no
//! in-process session sees: each case's captures (`snap` the text and the
//! cursor, `style` every cell's ink, `snap9p` the core's own /screen,
//! `snapFile` a file on disk) are compared at `done` with
//! test/snapshots/<name>.golden, which `zig build process-test -- --update
//! <filter>` rewrites (one case at a time, then a plain run, and a diff of
//! the golden for moved shell output, a flake, before keeping it).
//!
//! A case runs in a fixed directory, /tmp/pardes-snap/<name>/cwd, whose
//! path the goldens record, with a fake home: bash with a `$ ` prompt (a
//! golden taken against this machine's login shell would be a golden for
//! this machine), messages that leave when dismissed, no wall clock
//! (PARDES_NOTIME), a virtual core clock (PARDES_TEST_CLOCK), and language
//! servers off but the mock `.rs` speaks to. `init` sets this process's
//! environment and directory for it: process_test.zig runs each tty case in
//! a child of its own, several at once.
//!
//! A capture is a DELTA against the previous capture of the same kind: the
//! first one (and any after a resize or a new start) is the whole screen as
//! `|<row>`, the rest only the rows that changed, as `|<n>: <row>`. Before
//! this, every frame restated every row, so 82% of golden lines were a copy
//! of the line above and one added builtin word rewrote 78 goldens.
//!
//! A mouse column may be `@Word`, `@Word#2` or `@Word+4` instead of a
//! number: the column of a word on that row of the live grid (resolveCol).
//! Chrome words move, and a frozen column silently clicks whatever moved
//! into it.
const std = @import("std");
const libc = std.c;
const ghostty_vt = @import("ghostty-vt");
const eh = @import("e2e_harness.zig");
const process = @import("process.zig");

extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;
extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int;
extern "c" fn system(cmd: [*:0]const u8) c_int;

/// `--update`: each case's captures written to its golden, not compared.
pub var update = false;
/// The repository's test/snapshots, absolute: a case runs elsewhere.
pub var goldens: []const u8 = "test/snapshots";
/// The deterministic mock language server `.rs` files speak to
/// (`--lspmock=`); empty leaves every language client off.
pub var lspmock: []const u8 = "";
const base_dir = "/tmp/pardes-snap";
const gpa = std.heap.page_allocator;

pub const Tty = struct {
    arena: std.mem.Allocator,
    exe: [:0]const u8,
    name: []const u8,
    /// /tmp/pardes-snap/<name>: home/, cwd/, dump.zon.
    base: []const u8,
    config_home: []const u8,
    /// The dump path the session's Dump writes and `-l` reads back
    /// (PARDES_DUMP): per case, so cases need not take turns.
    dump: [:0]const u8,
    h: ?eh.Harness = null,
    /// Captures are deltas against these (see Prev).
    prev: Prev = .{},
    out: std.ArrayList(u8) = .empty,

    pub fn init(_: std.mem.Allocator, exe: [:0]const u8, name: []const u8) !Tty {
        // A child's, never freed: the child exits with the case.
        const arena_state = try gpa.create(std.heap.ArenaAllocator);
        arena_state.* = .init(gpa);
        const arena = arena_state.allocator();
        // Another run of the same case (another checkout's) would trample
        // the fixed directory its golden records: wait for it instead. The
        // lock is held until this child exits; CLOEXEC, or an orphaned bash
        // the case forked would hold it for ever.
        try mkdir(arena, base_dir, true);
        const lock = libc.open(try std.fmt.allocPrintSentinel(arena, "{s}/{s}.lock", .{ base_dir, name }, 0), .{ .ACCMODE = .WRONLY, .CREAT = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644));
        if (lock >= 0) _ = libc.flock(lock, std.posix.LOCK.EX);
        const base = try std.fmt.allocPrint(arena, "{s}/{s}", .{ base_dir, name });
        rmrf(base);
        try mkdir(arena, base, false);
        const home = try std.fmt.allocPrint(arena, "{s}/home", .{base});
        const work = try std.fmt.allocPrint(arena, "{s}/cwd", .{base});
        try mkdir(arena, home, false);
        try mkdir(arena, work, false);
        // deterministic shell: fixed prompt, no history, no user rc leakage
        try eh.writeFile(try std.fmt.allocPrintSentinel(arena, "{s}/.bashrc", .{home}, 0), "PS1='$ '\nHISTFILE=\n");
        _ = setenv("HOME", try arena.dupeSentinel(u8, home, 0), 1);
        // Hermetic even when the developer exports an XDG directory that
        // points outside this fake home: its config, and its data directory
        // (dumps, the addons its start scan loads).
        const config_home = try std.fmt.allocPrintSentinel(arena, "{s}/.config", .{home}, 0);
        _ = setenv("XDG_CONFIG_HOME", config_home, 1);
        const data_home = try std.fmt.allocPrintSentinel(arena, "{s}/.local/share", .{home}, 0);
        _ = setenv("XDG_DATA_HOME", data_home, 1);
        if (process.naddons > 0) for ([_][]const u8{ "/.local", "/.local/share", "/.local/share/pardes", "/.local/share/pardes/addons" }) |sub| try mkdir(arena, try std.fmt.allocPrint(arena, "{s}{s}", .{ home, sub }), true);
        for (process.addons[0..process.naddons]) |lib| {
            // libpdf.so as pdf.so: the name a build installs it as.
            const lib_name = std.fs.path.basename(lib);
            const installed = if (std.mem.startsWith(u8, lib_name, "lib")) lib_name[3..] else lib_name;
            if (libc.symlink(lib, try std.fmt.allocPrintSentinel(arena, "{s}/pardes/addons/{s}", .{ data_home, installed }, 0)) != 0) return error.SymlinkFailed;
        }
        // The default shell is $SHELL, whatever this machine's user logs in
        // with (fish's prompt carries a hostname): every case runs bash, set
        // through the ordinary startup config. Messages leave the moment
        // they are dismissed: a linger is time, and time cannot be a golden.
        try mkdir(arena, config_home, false);
        try mkdir(arena, try std.fmt.allocPrint(arena, "{s}/pardes", .{config_home}), false);
        try eh.writeFile(try std.fmt.allocPrintSentinel(arena, "{s}/pardes/init", .{config_home}, 0), "Shell bash\nMessageLinger 0\n");
        _ = setenv("TERM", "xterm-256color", 1);
        _ = setenv("LC_ALL", "C", 1);
        // No wall clock (the language views' durations, a message's time of
        // day), and a virtual core clock: animation moves a frame per
        // timed-out wait, whatever the machine's load (host_io.testClock).
        _ = setenv("PARDES_NOTIME", "1", 1);
        _ = setenv("PARDES_TEST_CLOCK", "1", 1);
        // Hermetic language clients: `.rs` speaks to the mock, every other
        // spec is off, so a stray `.c` never spawns this machine's clangd.
        _ = setenv("PARDES_LSP_RS", try arena.dupeSentinel(u8, lspmock, 0), 1);
        for ([_][*:0]const u8{ "PARDES_LSP_C", "PARDES_LSP_GO", "PARDES_LSP_TS", "PARDES_LSP_PY" }) |v| _ = setenv(v, "", 1);
        const dump = try std.fmt.allocPrintSentinel(arena, "{s}/dump.zon", .{base}, 0);
        _ = setenv("PARDES_DUMP", dump, 1);
        if (libc.chdir(try arena.dupeSentinel(u8, work, 0)) < 0) return error.ChdirFailed;
        return .{ .arena = arena, .exe = exe, .name = name, .base = base, .config_home = config_home, .dump = dump };
    }

    pub fn deinit(t: *Tty) void {
        if (t.h) |*h| h.deinit();
    }

    /// The captures against the golden, or written to it under `--update`.
    pub fn done(t: *Tty) !void {
        const path = try std.fmt.allocPrint(t.arena, "{s}/{s}.golden", .{ goldens, t.name });
        if (update) return eh.writeFile(try t.arena.dupeSentinel(u8, path, 0), t.out.items);
        const want = readFileAlloc(t.arena, path) catch "";
        if (std.mem.eql(u8, want, t.out.items)) return;
        const drew = try std.fmt.allocPrint(t.arena, "{s}/drew.golden", .{t.base});
        try eh.writeFile(try t.arena.dupeSentinel(u8, drew, 0), t.out.items);
        std.debug.print("  {s}: not its golden {s} (what it drew: {s})\n", .{ t.name, path, drew });
        printFirstDiff(want, t.out.items);
        return error.GoldenMismatch;
    }

    /// A setting appended to the startup config the fake home has, so a
    /// case can pin one instead of spelling out what a default implies.
    /// Before `start`.
    pub fn config(t: *Tty, line: []const u8) !void {
        try eh.appendFile(try std.fmt.allocPrintSentinel(t.arena, "{s}/pardes/init", .{t.config_home}, 0), try std.fmt.allocPrint(t.arena, "{s}\n", .{line}));
    }

    /// A file in the case's directory.
    pub fn file(t: *Tty, name: []const u8, data: []const u8) !void {
        try eh.writeFile(try t.arena.dupeSentinel(u8, name, 0), data);
    }

    /// A file of `n` lines, `line <i><tail>` each: long AND wide, which
    /// a horizontal scroll needs.
    pub fn lines(t: *Tty, name: []const u8, n: usize, tail: []const u8) !void {
        try t.file(name, try numberedLines(t.arena, n, tail));
    }

    /// The diagonal-split test picture of the old e2e (white over blue),
    /// 512x512 with the white half a fixed LCG noise, at `name`. Both
    /// halves are load-bearing: the clean edge is what the block and
    /// sextant glyphs match exactly, the noise is fine enough (one source
    /// pixel per matcher subcell at this size) that the ASCII bitmaps win
    /// instead, so the Ascii toggle visibly changes the art, which a 64x64
    /// picture cannot show (its cells average down to a flat colour).
    pub fn ppmDiag(t: *Tty, name: []const u8) !void {
        try t.file(name, try diagonal(t.arena));
    }

    pub fn dir(t: *Tty, name: []const u8) !void {
        try mkdir(t.arena, name, false);
    }

    /// A writer that is NOT a pardes pane, run in the case's directory as a
    /// child of the runner: a rename-over is how a formatter replaces a
    /// file, a different inotify event from a pane's write, and whatever the
    /// app then shows it woke up for by itself.
    pub fn run(t: *Tty, cmd: []const u8) !void {
        if (system(try t.arena.dupeSentinel(u8, cmd, 0)) != 0) return error.RunFailed;
    }

    /// The app started in a pty `rows` by `cols`, with `args`; a case may
    /// start it again (a dump, then `-l`), a new screen captured whole.
    pub fn start(t: *Tty, rows: u16, cols: u16, args: []const []const u8) !void {
        var argv: [6]?[*:0]const u8 = @splat(null);
        for (args, 0..) |a, i| argv[i] = (try t.arena.dupeSentinel(u8, a, 0)).ptr;
        if (t.h) |*h| h.deinit();
        t.prev = .{};
        t.h = try eh.Harness.initArgv(gpa, t.exe.ptr, rows, cols, argv[0..args.len]);
    }

    /// A file's contents as a capture, base64 payloads elided: they encode
    /// raw pty byte history, whose micro-timing differs run to run.
    pub fn snapFile(t: *Tty, label: []const u8, path: []const u8) !void {
        try t.out.appendSlice(t.arena, try snapFileText(t.arena, label, try readFileAlloc(t.arena, path)));
    }

    /// Pump until `needle` is on the grid.
    pub fn wait(t: *Tty, ms: i64, needle: []const u8) !void {
        try t.live().expectWaitFor(needle, ms, "tty wait");
    }

    /// Pump for a fixed time.
    pub fn settle(t: *Tty, ms: i64) !void {
        try t.live().pump(ms);
    }

    /// Pump until the screen holds still (waitStable).
    pub fn stable(t: *Tty, quiet: i64, timeout: i64) !void {
        try waitStable(t.live(), quiet, timeout);
    }

    /// Bytes typed at the terminal.
    pub fn send(t: *Tty, bytes: []const u8) !void {
        try t.live().send(bytes);
    }

    /// Keys by name, space-separated: enter esc tab bs space up down left
    /// right home end pgup pgdn, a character, c-<ch> and a-<ch>. After esc,
    /// settle: vaxis reads the next byte in the same batch as alt-<ch>.
    pub fn key(t: *Tty, names: []const u8) !void {
        var it = std.mem.tokenizeScalar(u8, names, ' ');
        while (it.next()) |name| try t.live().send(keyBytes(name) orelse return error.BadKey);
    }

    /// An SGR mouse press, release or drag (motion with it held) of
    /// `[ctrl-|shift-]left|middle|right` at a 1-based cell.
    pub fn press(t: *Tty, button: []const u8, col: []const u8, row: u16) !void {
        try t.mouse(button, col, row, 0, 'M');
    }
    pub fn release(t: *Tty, button: []const u8, col: []const u8, row: u16) !void {
        try t.mouse(button, col, row, 0, 'm');
    }
    pub fn drag(t: *Tty, button: []const u8, col: []const u8, row: u16) !void {
        try t.mouse(button, col, row, 32, 'M');
    }

    fn mouse(t: *Tty, button: []const u8, col_spec: []const u8, row: u16, add: u16, fin: u8) !void {
        const b = buttonCode(button) orelse return error.BadButton;
        const col = try resolveCol(t.live(), col_spec, row);
        try t.live().send(try std.fmt.allocPrint(t.arena, "\x1b[<{d};{d};{d}{c}", .{ b + add, col, row, fin }));
    }

    /// Button-less motion (hover).
    pub fn motion(t: *Tty, col_spec: []const u8, row: u16) !void {
        const col = try resolveCol(t.live(), col_spec, row);
        try t.live().send(try std.fmt.allocPrint(t.arena, "\x1b[<35;{d};{d}M", .{ col, row }));
    }

    /// One wheel tick, `up` or `down`.
    pub fn wheel(t: *Tty, dir_name: []const u8, col_spec: []const u8, row: u16) !void {
        const b: u16 = if (std.mem.eql(u8, dir_name, "up")) 64 else 65;
        const col = try resolveCol(t.live(), col_spec, row);
        try t.live().send(try std.fmt.allocPrint(t.arena, "\x1b[<{d};{d};{d}M", .{ b, col, row }));
    }

    pub fn resize(t: *Tty, rows: u16, cols: u16) !void {
        try t.live().resize(rows, cols);
    }

    /// The grid's text and cursor (snapText).
    pub fn snap(t: *Tty, label: []const u8) !void {
        try t.out.appendSlice(t.arena, try snapText(t.arena, t.live(), label, &t.prev));
    }

    /// Every cell's ink, as style runs (snapStyle).
    pub fn style(t: *Tty, label: []const u8) !void {
        try t.out.appendSlice(t.arena, try snapStyle(t.arena, t.live(), label, &t.prev));
    }

    /// The core's own cells and styles, read over its 9P socket (snap9p).
    pub fn snap9p(t: *Tty, label: []const u8) !void {
        try t.out.appendSlice(t.arena, try snap9pText(t.arena, t.live(), label, &t.prev));
    }

    fn live(t: *Tty) *eh.Harness {
        if (t.h) |*h| return h;
        @panic("a tty case used the app before `start`");
    }
};

/// A failed case is run again alone: nothing else competes then, so the
/// wider probes are cheap, and its verdict is the one reported.
pub fn beCareful() void {
    probe_after_ms = 40;
    probe_hold_ms = 300;
}

fn copyBytes(out: []u8, pos: *usize, bytes: []const u8) void {
    @memcpy(out[pos.*..][0..bytes.len], bytes);
    pos.* += bytes.len;
}

fn decimalDigits(value: usize) usize {
    var v = value;
    var digits: usize = 1;
    while (v >= 10) : (digits += 1) v /= 10;
    return digits;
}

fn numberedLines(arena: std.mem.Allocator, n: usize, tail: []const u8) ![]u8 {
    var total: usize = 0;
    for (1..n + 1) |i| total += "line ".len + decimalDigits(i) + tail.len + 1;
    const out = try arena.alloc(u8, total);
    var pos: usize = 0;
    for (1..n + 1) |i| {
        const line = try std.fmt.bufPrint(out[pos..], "line {d}{s}\n", .{ i, tail });
        pos += line.len;
    }
    return out;
}

fn diagonal(arena: std.mem.Allocator) ![]u8 {
    const header = "P6\n512 512\n255\n";
    const out = try arena.alloc(u8, header.len + 512 * 512 * 3);
    @memcpy(out[0..header.len], header);
    var pos = header.len;
    var seed: u64 = 12345;
    var py: usize = 0;
    while (py < 512) : (py += 1) {
        var px: usize = 0;
        while (px < 512) : (px += 1) {
            seed = seed *% 1103515245 +% 12345;
            const v: u8 = @truncate(seed >> 16);
            const pixel: [3]u8 = if (px + py < 512) .{ v, v, v } else .{ 0, 0, 255 };
            @memcpy(out[pos..][0..pixel.len], &pixel);
            pos += pixel.len;
        }
    }
    return out;
}

fn snapFileText(arena: std.mem.Allocator, label: []const u8, contents: []const u8) ![]u8 {
    const header = try std.fmt.allocPrint(arena, "== file {s}\n", .{label});
    var total = header.len + "== end file\n".len;
    var lines = std.mem.splitScalar(u8, contents, '\n');
    while (lines.next()) |line| {
        if (std.mem.indexOf(u8, line, "_b64 = \"") != null) {
            const eq = std.mem.indexOfScalar(u8, line, '=').?;
            total += eq + 1 + " <elided>\n".len;
        } else {
            total += line.len + 1;
        }
    }
    const out = try arena.alloc(u8, total);
    var pos: usize = 0;
    copyBytes(out, &pos, header);
    lines = std.mem.splitScalar(u8, contents, '\n');
    while (lines.next()) |line| {
        if (std.mem.indexOf(u8, line, "_b64 = \"") != null) {
            const eq = std.mem.indexOfScalar(u8, line, '=').?;
            copyBytes(out, &pos, line[0 .. eq + 1]);
            copyBytes(out, &pos, " <elided>\n");
        } else {
            copyBytes(out, &pos, line);
            copyBytes(out, &pos, "\n");
        }
    }
    copyBytes(out, &pos, "== end file\n");
    return out;
}

/// Pump until the captured state — grid text AND cursor — has not changed for
/// `quiet` ms (bounded by `timeout`). The one sync primitive that needs no
/// needle: used before every snap so a capture is taken at rest, not
/// mid-repaint.
///
/// Same oracle as before, timed continuously instead of in fixed windows. The
/// old loop pumped a whole `quiet` window, compared, and pumped another — so
/// even an app that fell silent immediately cost 2 × 700ms, and 446 `stable`s
/// cost the suite ten minutes. This one sleeps in poll until the app writes,
/// and returns `quiet` ms after the LAST change. Waiting on the change rather
/// than on silence is what keeps it honest: pardes finishes a repaint with a
/// late cursor move, hundreds of ms after its last burst of text.
fn waitStable(h: *eh.Harness, quiet: i64, timeout: i64) !void {
    const t0 = eh.nowMs();
    const deadline = t0 + timeout;
    var prev = try stateKey(h);
    defer h.gpa.free(prev);
    var last_change = t0;
    var asleep_since: i64 = 0;
    while (true) {
        const now = eh.nowMs();
        const since = now - last_change;
        if (since >= quiet) {
            return;
        }
        // Fast path: the screen has held still, the pty is empty in both
        // directions (so the app has CONSUMED everything the case just sent
        // — otherwise an app still asleep in its event loop looks finished),
        // and nothing in its process tree is runnable. Held across two probes,
        // because a pane's shell can write and sleep a scheduler tick before
        // the app wakes to read it.
        if (since >= probe_after_ms and h.pending() == 0 and treeAsleep(h.pid)) {
            if (asleep_since == 0) {
                asleep_since = now;
            } else if (now - asleep_since >= probe_hold_ms) {
                return;
            }
        } else if (since >= probe_after_ms) {
            asleep_since = 0;
        }
        if (now >= deadline) return error.NeverStable;
        const nap = if (since >= probe_after_ms) probe_every_ms else probe_after_ms - since;
        if (!try h.pumpOnce(@min(nap, deadline - now))) continue;
        while (try h.pumpOnce(0)) {} // drain the burst before comparing
        const cur = try stateKey(h);
        if (std.mem.eql(u8, cur, prev)) {
            h.gpa.free(cur);
            continue;
        }
        h.gpa.free(prev);
        prev = cur;
        last_change = eh.nowMs();
        asleep_since = 0;
    }
}

// How long the screen must hold still before the sleep probe is trusted at all,
// how often it is taken, and how long it must stay true.
//
// The hold is the one number that cannot be reasoned down to zero. When the app
// writes to a pane's pty the kernel parks the bytes in a flip buffer and leaves
// the hand-off to a kworker: until that runs, the app is asleep, the shell is
// asleep, nothing is runnable and no /proc or ioctl query can see the round trip
// in flight (a pty master cannot even be reopened through /proc/<pid>/fd — it
// mints a fresh pty). So the hold is a bet on kworker latency, and a loaded
// machine loses it. The parallel pass bets small; the serial re-run that decides
// the verdict bets big.
//
// Only the SUM is the safety margin: a return cannot happen before
// `probe_after_ms + probe_hold_ms` after the last change either way. The split
// is pure cost, and the two halves cost differently - the arm window is one
// `poll()` sleep, while every `probe_every_ms` of hold is a full `treeAsleep()`
// walk of the app's process tree. Measured across the suite: 796 armed probes,
// 54 of them saw a later change, none later than 11ms at 20 jobs. That is the
// scheduler-tick case. The number the sum is really sized for is bigger and
// found by adversarial measurement: a theme transition sleeps
// `pardes.frame_ms` (16ms) between frames with the whole tree asleep, and
// under `taskset -c 0,1` those gaps stretch to 57ms. 60ms total stays.
var probe_after_ms: i64 = 50;
const probe_every_ms: i64 = 5;
var probe_hold_ms: i64 = 10;

/// Is every process in the app's tree asleep? Walks /proc from the app's pid
/// through `children`, checking every thread's run state: `R` (runnable) or
/// `D` (uninterruptible) anywhere means work is still in flight — a repaint,
/// a fork, a shell mid-command — so a quiet pty proves nothing. Anything else
/// (`S`, or a zombie waiting to be reaped) is idle.
///
/// This is what replaces the wall-clock window: the app finishes a keystroke
/// in ~10ms, and the scripts' 400-700ms `stable` windows were insurance
/// against not being able to tell "finished" from "paused mid-fork".
fn treeAsleep(root: libc.pid_t) bool {
    var stack: [64]libc.pid_t = undefined;
    stack[0] = root;
    var n: usize = 1;
    var path_buf: [64:0]u8 = undefined;
    var buf: [4096]u8 = undefined;
    while (n > 0) {
        n -= 1;
        const pid = stack[n];
        const dir_path = std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/task", .{pid}, 0) catch continue;
        const dir = libc.opendir(dir_path) orelse continue; // exited between steps
        defer _ = libc.closedir(dir);
        while (libc.readdir(dir)) |d| {
            const tid = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(&d.name)), 0);
            if (tid[0] == '.') continue;
            const stat = readProc(&buf, std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/task/{s}/stat", .{ pid, tid }, 0) catch continue) orelse continue;
            // "pid (comm) S ..." — comm can hold spaces and parens, so the
            // state is the char two past the LAST ')'
            const close = std.mem.lastIndexOfScalar(u8, stat, ')') orelse continue;
            if (close + 2 >= stat.len) continue;
            switch (stat[close + 2]) {
                // R/D: still working. Z: just exited, so its parent is about to
                // be woken to reap it and carry on — a pane's shell sitting in
                // wait4 over a zombie `ls` looks asleep, but the prompt it is
                // about to print is what hides the echoed command line in the
                // goldens.
                'R', 'D', 'Z' => return false,
                else => {},
            }
            const kids = readProc(&buf, std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/task/{s}/children", .{ pid, tid }, 0) catch continue) orelse continue;
            var it = std.mem.tokenizeAny(u8, kids, " \n");
            while (it.next()) |k| {
                if (n >= stack.len) return false; // deeper than we can walk: assume busy
                stack[n] = std.fmt.parseInt(libc.pid_t, k, 10) catch continue;
                n += 1;
            }
        }
    }
    return true;
}

/// Read a small /proc file into `buf` (procfs needs one read, no stat).
fn readProc(buf: []u8, path: [*:0]const u8) ?[]const u8 {
    const fd = libc.open(path, .{ .ACCMODE = .RDONLY, .CLOEXEC = true });
    if (fd < 0) return null;
    defer _ = libc.close(fd);
    const got = libc.read(fd, buf.ptr, buf.len);
    if (got <= 0) return null;
    return buf[0..@intCast(got)];
}

/// What a capture is made of: grid text, cursor cell, and a compact digest of
/// every cell style. Style used not to matter to `stable`, which let a
/// color-only animation look idle while the TUI frontend was deliberately
/// asleep between frames; a following `snapstyle` then caught a midpoint.
fn stateKey(h: *eh.Harness) ![]u8 {
    const text = try h.screenText();
    defer h.gpa.free(text);
    const c = h.cursor();
    var styles = std.hash.Wyhash.init(0x5354_594c_4553_2121);
    var y: u16 = 0;
    while (y < h.rows) : (y += 1) {
        var x: u16 = 0;
        while (x < h.cols) : (x += 1) {
            var key_buf: [64]u8 = undefined;
            styles.update(cellKey(h, x, y, &key_buf));
            styles.update("\x00");
        }
    }
    return std.fmt.allocPrint(h.gpa, "{d},{d},{x}\n{s}", .{ c.x, c.y, styles.final(), text });
}

/// A mouse column: either a screen column, or `@Word` / `@Word#2` - the column
/// of a WORD found on that row of the LIVE grid.
///
/// Chrome words move. When `Newtty` was added to every tail and `Joincol` and
/// `Changelog` to the topbar, six scripts kept their frozen columns and started
/// clicking a different word: `tutor.snap` clicked `Grep` instead of `Tutor`,
/// `exec.snap`/`respawn.snap`/`tagalign.snap` clicked `Newtty` instead of `Del`,
/// `find.snap` clicked `Joincol` instead of `Find`, `windowops.snap` clicked
/// `Tutor` instead of `Debug` - and `--update` blessed all of it, so 256 golden
/// lines were green while asserting the opposite of their script's first line.
/// Naming the word instead of its column makes that class of drift impossible:
/// the word is either there to be clicked or the case fails loudly.
///
/// The match is boundary-anchored, which is not a detail: `New` is a prefix of
/// `Newcol` and of `Newtty`, and `@New` resolving to `Newcol` is exactly the bug
/// this is here to prevent. `#n` picks the nth occurrence for a row that holds
/// two panes' tags, and `+n`/`-n` addresses a column NEAR a word - which is how
/// a click that means "in the gap the right-aligned builtins leave after the
/// path" is spelled without depending on how wide those builtins are.
fn resolveCol(h: *eh.Harness, spec: []const u8, row: u16) !u16 {
    if (spec.len == 0 or spec[0] != '@') return std.fmt.parseInt(u16, spec, 10);
    var word = spec[1..];
    var want: usize = 1;
    var offset: i32 = 0;
    // parsed off the end, so a word may hold a `-` or a `#` itself
    if (std.mem.lastIndexOfAny(u8, word, "+-")) |sign| {
        if (sign > 0) {
            if (std.fmt.parseInt(i32, word[sign + 1 ..], 10)) |n| {
                offset = if (word[sign] == '-') -n else n;
                word = word[0..sign];
            } else |_| {}
        }
    }
    if (std.mem.lastIndexOfScalar(u8, word, '#')) |hash| {
        if (std.fmt.parseInt(usize, word[hash + 1 ..], 10)) |n| {
            want = n;
            word = word[0..hash];
        } else |_| {}
    }
    if (word.len == 0 or want == 0) return error.BadScript;
    if (row == 0 or row > h.rows) return error.WordRowMissing;
    // One byte per CELL, not per byte of UTF-8: a mouse column is a cell, and
    // a tag row can hold a wide glyph or the U+254E column divider left of the
    // word. Non-ASCII cells become 0xff, which is not a word byte, so they
    // read as boundaries - every chrome word is ASCII.
    var cells: [1024]u8 = undefined;
    const line = rowCells(h, row - 1, &cells);
    var seen: usize = 0;
    var from: usize = 0;
    while (std.mem.indexOfPos(u8, line, from, word)) |at| : (from = at + 1) {
        if (at > 0 and wordByte(line[at - 1])) continue;
        const after = at + word.len;
        if (after < line.len and wordByte(line[after])) continue;
        seen += 1;
        if (seen != want) continue;
        // SGR columns are 1-based
        const col = @as(i32, @intCast(at + 1)) + offset;
        if (col < 1 or col > @as(i32, h.cols)) return error.BadScript;
        return @intCast(col);
    }
    std.debug.print("  no \"{s}\" #{d} on row {d}: {s}\n", .{ word, want, row, std.mem.trimEnd(u8, line, " ") });
    return error.WordNotOnRow;
}

fn rowCells(h: *eh.Harness, y: u16, buf: *[1024]u8) []const u8 {
    const n = @min(h.cols, buf.len);
    var x: u16 = 0;
    while (x < n) : (x += 1) {
        const ci = h.term.screens.active.pages.getCell(.{ .viewport = .{ .x = x, .y = y } });
        buf[x] = blk: {
            const cell = (ci orelse break :blk ' ').cell;
            if (cell.content_tag != .codepoint and cell.content_tag != .codepoint_grapheme) break :blk ' ';
            const cp = cell.content.codepoint.data;
            break :blk if (cp == 0) ' ' else if (cp < 128) @intCast(cp) else 0xff;
        };
    }
    return buf[0..n];
}

fn wordByte(c: u8) bool {
    return std.ascii.isAlphanumeric(c) or c == '_';
}

/// A capture, kept so the NEXT capture of the same kind can be emitted as the
/// rows that changed instead of the whole screen again. 81.7% of re-captured
/// rows used to be byte-identical to the previous capture in the same case,
/// which is why one word added to a tagline rewrote 78 goldens: every frame
/// re-stated every row of chrome. The delta keeps the assertion (a row that
/// moves still shows up, and a capture whose only change is the cursor is
/// exactly the empty delta its case means) and drops the restatement.
const Prev = struct {
    snap: []const []const u8 = &.{},
    style: []const []const u8 = &.{},
    ninep: []const []const u8 = &.{},
    // per kind: one shared width let a `snapstyle` between a `resize` and the
    // next `snap` re-arm the guard, and the post-resize frame then came out as
    // a delta against rows of the old width - dropping every row whose text is
    // width-invariant, which is every left-aligned chrome row there is.
    snap_cols: u16 = 0,
    style_cols: u16 = 0,
    ninep_cols: u16 = 0,
};

const Screen9p = struct {
    cols: u16,
    rows: u16,
    cursor: ?struct { x: u16, y: u16, bar: bool },
    cells: []const struct { []const u8, usize },
    styles: []const struct {
        fg: Color,
        bg: Color,
        bold: bool,
        dim: bool,
        italic: bool,
        blink: bool,
        reverse: bool,
        invisible: bool,
        strikethrough: bool,
        ul: enum { off, single, double, curly, dotted, dashed },
        font_role: enum { body, tagline },
    },

    const Color = union(enum) {
        default,
        index: u8,
        rgb: [3]u8,

        fn text(color: Color, buf: *[16]u8) []const u8 {
            return switch (color) {
                .default => "d",
                .index => |index| std.fmt.bufPrint(buf, "p{d}", .{index}) catch unreachable,
                .rgb => |rgb| std.fmt.bufPrint(buf, "#{x:0>2}{x:0>2}{x:0>2}", .{ rgb[0], rgb[1], rgb[2] }) catch unreachable,
            };
        }
    };
};

fn snap9pText(arena: std.mem.Allocator, h: *eh.Harness, label: []const u8, prev: *Prev) ![]u8 {
    var files = process.of(gpa, h);
    defer files.deinit();
    const bytes = try files.read("/screen");
    const parsed = try std.json.parseFromSlice(Screen9p, gpa, bytes, .{});
    defer parsed.deinit();
    const screen = parsed.value;
    if (screen.cols != h.cols or screen.rows != h.rows or screen.cols == 0 or screen.rows == 0 or
        screen.cells.len != @as(usize, screen.cols) * screen.rows or screen.styles.len == 0)
        return error.Screen9pDimensions;
    if (screen.cursor) |cursor| {
        if (cursor.x >= screen.cols or cursor.y >= screen.rows) return error.Screen9pCursor;
    }
    for (screen.cells) |cell| {
        if (cell[1] >= screen.styles.len or !std.unicode.utf8ValidateSlice(cell[0])) return error.Screen9pCell;
    }

    const keys = try arena.alloc([]const u8, screen.styles.len);
    for (screen.styles, keys) |style, *key| {
        var flags: [8]u8 = undefined;
        var len: usize = 0;
        inline for (.{ "bold", "dim", "italic", "blink", "reverse", "invisible", "strikethrough" }, "bfikrvx") |field, flag| {
            if (@field(style, field)) {
                flags[len] = flag;
                len += 1;
            }
        }
        if (style.ul != .off) {
            flags[len] = switch (style.ul) {
                .off => unreachable,
                .single => 'u',
                .double => 'U',
                .curly => '~',
                .dotted => '.',
                .dashed => '-',
            };
            len += 1;
        }
        var fg_buf: [16]u8 = undefined;
        var bg_buf: [16]u8 = undefined;
        key.* = try std.fmt.allocPrint(arena, "{s},{s},{s},{s}", .{
            style.fg.text(&fg_buf), style.bg.text(&bg_buf), flags[0..len], @tagName(style.font_role),
        });
    }

    var out: std.ArrayList(u8) = .empty;
    try out.appendSlice(arena, try std.fmt.allocPrint(arena, "== 9p {s} grid={d}x{d} cursor=", .{ label, screen.cols, screen.rows }));
    try out.appendSlice(arena, if (screen.cursor) |c|
        try std.fmt.allocPrint(arena, "{d},{d},{s}\n", .{ c.x, c.y, if (c.bar) "bar" else "block" })
    else
        "none\n");

    const rows = try arena.alloc([]const u8, screen.rows);
    const delta = prev.ninep.len == rows.len and prev.ninep_cols == screen.cols;
    for (rows, 0..) |*row, y| {
        var text_row: std.ArrayList(u8) = .empty;
        const cells = screen.cells[y * screen.cols ..][0..screen.cols];
        for (cells) |cell| try text_row.appendSlice(arena, cell[0]);
        var capture: std.ArrayList(u8) = .empty;
        const trimmed = std.mem.trimEnd(u8, text_row.items, " ");
        try capture.appendSlice(arena, if (trimmed.len == 0)
            try std.fmt.allocPrint(arena, "|{d}:\n", .{y})
        else
            try std.fmt.allocPrint(arena, "|{d}: {s}\n", .{ y, trimmed }));
        var annotated = false;
        for (cells, 0..) |cell, x| {
            if (cell[0].len == 1) continue;
            if (!annotated) try capture.appendSlice(arena, try std.fmt.allocPrint(arena, "+{d}:", .{y}));
            const glyph = try std.json.Stringify.valueAlloc(arena, cell[0], .{});
            try capture.appendSlice(arena, try std.fmt.allocPrint(arena, " {d}={s}", .{ x, glyph }));
            annotated = true;
        }
        if (annotated) try capture.append(arena, '\n');
        try capture.appendSlice(arena, try std.fmt.allocPrint(arena, "@{d}:", .{y}));
        var start: usize = 0;
        for (1..cells.len + 1) |x| {
            const key = keys[cells[start][1]];
            if (x != cells.len and std.mem.eql(u8, key, keys[cells[x][1]])) continue;
            try capture.appendSlice(arena, try std.fmt.allocPrint(arena, " {d}-{d} {s}", .{ start, x - 1, key }));
            start = x;
        }
        try capture.append(arena, '\n');
        row.* = capture.items;
        if (!delta or !std.mem.eql(u8, row.*, prev.ninep[y])) try out.appendSlice(arena, row.*);
    }
    prev.ninep = rows;
    prev.ninep_cols = screen.cols;
    return out.items;
}

/// `== snap <label> grid=CxR cursor=X,Y` then either the whole screen as
/// `|<row text>` (first capture of a case, or after a resize) or just the
/// rows that changed as `|<n>: <row text>`. An indexed row is a patch against
/// the previous capture; an unindexed one is a frame.
fn snapText(arena: std.mem.Allocator, h: *eh.Harness, label: []const u8, prev: *Prev) ![]u8 {
    const text = try h.screenText();
    defer h.gpa.free(text);
    const c = h.cursor();
    const rows = try arena.alloc([]const u8, h.rows);
    var it = std.mem.splitScalar(u8, text, '\n');
    for (rows) |*r| r.* = try arena.dupe(u8, std.mem.trimEnd(u8, it.next() orelse "", " "));

    var out: std.ArrayList(u8) = .empty;
    try out.appendSlice(arena, try std.fmt.allocPrint(arena, "== snap {s} grid={d}x{d} cursor={d},{d}\n", .{
        label, h.cols, h.rows, c.x, c.y,
    }));
    if (prev.snap.len == rows.len and prev.snap_cols == h.cols) {
        for (rows, prev.snap, 0..) |now, was, i| {
            if (std.mem.eql(u8, now, was)) continue;
            // no trailing space when a row goes blank: a whitespace-trimming
            // editor or `git apply --whitespace=fix` would rewrite it and the
            // golden would then fail like a regression
            try out.appendSlice(arena, if (now.len == 0)
                try std.fmt.allocPrint(arena, "|{d}:\n", .{i})
            else
                try std.fmt.allocPrint(arena, "|{d}: {s}\n", .{ i, now }));
        }
    } else {
        // A full frame stops at the last row with anything on it: the blank
        // tail of the grid is the same information as the `grid=CxR` header.
        var end = rows.len;
        while (end > 0 and rows[end - 1].len == 0) end -= 1;
        for (rows[0..end]) |r| {
            try out.appendSlice(arena, "|");
            try out.appendSlice(arena, r);
            try out.appendSlice(arena, "\n");
        }
    }
    prev.snap = rows;
    prev.snap_cols = h.cols;
    return out.items;
}

/// Per-row style runs from the harness emulator: `|y: x0-x1 fg,bg,attrs ...`.
/// fg/bg: d (default) | pN (palette) | #rrggbb. attrs: b f i k r v x + u U ~ . -
/// for underline single/double/curly/dotted/dashed. Deltas the same way
/// `snapText` does - the row already carries its own index, so a patch and a
/// frame are spelled identically here. The header carries the grid because a
/// style capture has no cursor: without it an unchanged style would be a label
/// line asserting nothing at all.
fn snapStyle(arena: std.mem.Allocator, h: *eh.Harness, label: []const u8, prev: *Prev) ![]u8 {
    const rows = try styleRows(arena, h);
    var out: std.ArrayList(u8) = .empty;
    try out.appendSlice(arena, try std.fmt.allocPrint(arena, "== style {s} grid={d}x{d}\n", .{ label, h.cols, h.rows }));
    const delta = prev.style.len == rows.len and prev.style_cols == h.cols;
    for (rows, 0..) |now, i| {
        if (delta and std.mem.eql(u8, now, prev.style[i])) continue;
        try out.appendSlice(arena, "|");
        try out.appendSlice(arena, now);
        try out.appendSlice(arena, "\n");
    }
    prev.style = rows;
    prev.style_cols = h.cols;
    return out.items;
}

fn styleRows(arena: std.mem.Allocator, h: *eh.Harness) ![]const []const u8 {
    const out = try arena.alloc([]const u8, h.rows);
    for (out, 0..) |*dst, y_usize| {
        const y: u16 = @intCast(y_usize);
        var row: std.ArrayList(u8) = .empty;
        try row.appendSlice(arena, try std.fmt.allocPrint(arena, "{d}:", .{y}));
        var key_buf: [64]u8 = undefined;
        var run_key: [64]u8 = undefined;
        var run_len: usize = 0;
        var run_start: u16 = 0;
        // A blank's ink shows nowhere, and the tty leaves whatever ink the
        // terminal had there (tui.zig blankInk), so it depends on the frames
        // before: a blank is written with the ink of the cell before it.
        var ink_buf: [16]u8 = undefined;
        var ink: []const u8 = "d";
        var x: u16 = 0;
        while (x <= h.cols) : (x += 1) {
            var key: []const u8 = if (x == h.cols) "\x00end" else cellKey(h, x, y, &key_buf);
            if (x < h.cols) {
                const comma = std.mem.indexOfScalar(u8, key, ',') orelse key.len;
                if (inklessBlank(h, x, y)) {
                    var joined: [64]u8 = undefined;
                    const rest = key[comma..];
                    @memcpy(joined[0..ink.len], ink);
                    @memcpy(joined[ink.len..][0..rest.len], rest);
                    @memcpy(key_buf[0 .. ink.len + rest.len], joined[0 .. ink.len + rest.len]);
                    key = key_buf[0 .. ink.len + rest.len];
                } else {
                    @memcpy(ink_buf[0..comma], key[0..comma]);
                    ink = ink_buf[0..comma];
                }
            }
            if (x == 0) {
                @memcpy(run_key[0..key.len], key);
                run_len = key.len;
                continue;
            }
            if (std.mem.eql(u8, key, run_key[0..run_len])) continue;
            try row.appendSlice(arena, try std.fmt.allocPrint(arena, " {d}-{d} ", .{ run_start, x - 1 }));
            try row.appendSlice(arena, run_key[0..run_len]);
            @memcpy(run_key[0..key.len], key);
            run_len = key.len;
            run_start = x;
        }
        dst.* = row.items;
    }
    return out;
}

/// A cell whose ink shows nowhere: no text but a space, and no underline,
/// strike or reverse to draw with it.
fn inklessBlank(h: *eh.Harness, x: u16, y: u16) bool {
    const ci = h.term.screens.active.pages.getCell(.{ .viewport = .{ .x = x, .y = y } }) orelse return false;
    if (ci.cell.wide == .spacer_tail) return false;
    if (ci.cell.hasText() and ci.cell.codepoint() != ' ') return false;
    const flags = ci.style().flags;
    return !flags.inverse and !flags.strikethrough and flags.underline == .none;
}

fn cellKey(h: *eh.Harness, x: u16, y: u16, buf: *[64]u8) []const u8 {
    const ci = h.term.screens.active.pages.getCell(.{ .viewport = .{ .x = x, .y = y } }) orelse return "d,d,";
    if (ci.cell.wide == .spacer_tail) return "d,d,";
    const style = ci.style();
    var n: usize = 0;
    var tmp: [16]u8 = undefined;
    const fg = colorStr(style.fg_color, &tmp);
    @memcpy(buf[n..][0..fg.len], fg);
    n += fg.len;
    buf[n] = ',';
    n += 1;
    var tmp2: [16]u8 = undefined;
    const bg: []const u8 = switch (ci.cell.content_tag) {
        .bg_color_palette => std.fmt.bufPrint(&tmp2, "p{d}", .{ci.cell.content.color_palette.data}) catch "?",
        .bg_color_rgb => blk: {
            const rgb = ci.cell.content.color_rgb;
            break :blk std.fmt.bufPrint(&tmp2, "#{x:0>2}{x:0>2}{x:0>2}", .{ rgb.r, rgb.g, rgb.b }) catch "?";
        },
        else => colorStr(style.bg_color, &tmp2),
    };
    @memcpy(buf[n..][0..bg.len], bg);
    n += bg.len;
    buf[n] = ',';
    n += 1;
    if (style.flags.bold) {
        buf[n] = 'b';
        n += 1;
    }
    if (style.flags.faint) {
        buf[n] = 'f';
        n += 1;
    }
    if (style.flags.italic) {
        buf[n] = 'i';
        n += 1;
    }
    if (style.flags.blink) {
        buf[n] = 'k';
        n += 1;
    }
    if (style.flags.inverse) {
        buf[n] = 'r';
        n += 1;
    }
    if (style.flags.invisible) {
        buf[n] = 'v';
        n += 1;
    }
    if (style.flags.strikethrough) {
        buf[n] = 'x';
        n += 1;
    }
    const ul: []const u8 = switch (style.flags.underline) {
        .none => "",
        .single => "u",
        .double => "U",
        .curly => "~",
        .dotted => ".",
        .dashed => "-",
    };
    @memcpy(buf[n..][0..ul.len], ul);
    n += ul.len;
    return buf[0..n];
}

fn colorStr(color: ghostty_vt.Style.Color, buf: *[16]u8) []const u8 {
    return switch (color) {
        .none => "d",
        .palette => |idx| std.fmt.bufPrint(buf, "p{d}", .{idx}) catch "?",
        .rgb => |rgb| std.fmt.bufPrint(buf, "#{x:0>2}{x:0>2}{x:0>2}", .{ rgb.r, rgb.g, rgb.b }) catch "?",
    };
}

fn keyBytes(name: []const u8) ?[]const u8 {
    const map = .{
        .{ "enter", "\r" },     .{ "esc", "\x1b" },     .{ "tab", "\t" },
        .{ "bs", "\x7f" },      .{ "space", " " },      .{ "up", "\x1b[A" },
        .{ "down", "\x1b[B" },  .{ "right", "\x1b[C" }, .{ "left", "\x1b[D" },
        .{ "home", "\x1b[H" },  .{ "end", "\x1b[F" },   .{ "pgup", "\x1b[5~" },
        .{ "pgdn", "\x1b[6~" },
    };
    inline for (map) |e| if (std.mem.eql(u8, name, e[0])) return e[1];
    const S = struct {
        var buf: [2]u8 = undefined;
    };
    if (name.len == 1) {
        S.buf[0] = name[0];
        return S.buf[0..1];
    }
    if (name.len == 3 and name[1] == '-') {
        if (name[0] == 'c' and name[2] >= 'a' and name[2] <= 'z') {
            S.buf[0] = name[2] - 'a' + 1;
            return S.buf[0..1];
        }
        if (name[0] == 'a') {
            S.buf = .{ 0x1b, name[2] };
            return S.buf[0..2];
        }
    }
    return null;
}

/// SGR button code, with an optional `ctrl-` prefix folded in as bit 4 —
/// which is exactly how a terminal encodes a modified click, and how vaxis
/// decodes one (Parser.zig mouse_bits.ctrl = 0b00010000).
fn buttonCode(name: []const u8) ?u16 {
    if (std.mem.startsWith(u8, name, "ctrl-")) {
        const base = buttonCode(name["ctrl-".len..]) orelse return null;
        return base + 16;
    }
    // Shift: over a program that tracks the mouse, pardes's own gesture.
    if (std.mem.startsWith(u8, name, "shift-")) {
        const base = buttonCode(name["shift-".len..]) orelse return null;
        return base + 4;
    }
    if (std.mem.eql(u8, name, "left")) return 0;
    if (std.mem.eql(u8, name, "middle")) return 1;
    if (std.mem.eql(u8, name, "right")) return 2;
    return null;
}

fn readFileAlloc(arena: std.mem.Allocator, path: []const u8) ![]u8 {
    const path_z = try arena.dupeSentinel(u8, path, 0);
    const fd = libc.open(path_z, .{ .ACCMODE = .RDONLY });
    if (fd < 0) return error.OpenFailed;
    defer _ = libc.close(fd);
    const end = libc.lseek(fd, 0, libc.SEEK.END);
    if (end < 0 or libc.lseek(fd, 0, libc.SEEK.SET) < 0) return error.ReadFailed;
    const buf = try arena.alloc(u8, @intCast(end));
    var pos: usize = 0;
    while (pos < buf.len) {
        const n = libc.read(fd, buf[pos..].ptr, buf.len - pos);
        if (n < 0) {
            if (libc.errno(n) == .INTR) continue;
            return error.ReadFailed;
        }
        if (n == 0) return error.ReadFailed;
        pos += @intCast(n);
    }
    var extra: [1]u8 = undefined;
    while (true) {
        const n = libc.read(fd, &extra, extra.len);
        if (n < 0 and libc.errno(n) == .INTR) continue;
        if (n != 0) return error.ReadFailed;
        break;
    }
    return buf;
}

fn mkdir(arena: std.mem.Allocator, path: []const u8, exist_ok: bool) !void {
    const path_z = try arena.dupeSentinel(u8, path, 0);
    const rc = libc.mkdir(path_z, 0o755);
    if (rc != 0) {
        if (exist_ok and libc.errno(rc) == .EXIST) return;
        return error.MkdirFailed;
    }
}

fn rmrf(path: []const u8) void {
    var path_buf: [4096:0]u8 = undefined;
    if (path.len >= path_buf.len) return;
    @memcpy(path_buf[0..path.len], path);
    path_buf[path.len] = 0;
    const pid = libc.fork();
    if (pid == 0) {
        const argv: [4:null]?[*:0]const u8 = .{ "rm", "-rf", @as([*:0]const u8, @ptrCast(&path_buf)), null };
        _ = execvp("rm", &argv);
        libc._exit(127);
    }
    if (pid < 0) return;
    var status: c_int = 0;
    _ = libc.waitpid(pid, &status, 0);
}

fn printFirstDiff(golden: []const u8, actual: []const u8) void {
    var gi = std.mem.splitScalar(u8, golden, '\n');
    var ai = std.mem.splitScalar(u8, actual, '\n');
    var n: usize = 1;
    while (true) : (n += 1) {
        const g = gi.next();
        const a = ai.next();
        if (g == null and a == null) return;
        if (g != null and a != null and std.mem.eql(u8, g.?, a.?)) continue;
        std.debug.print("  first diff at golden line {d}:\n  -{s}\n  +{s}\n", .{ n, g orelse "<eof>", a orelse "<eof>" });
        return;
    }
}