summaryrefslogtreecommitdiff
path: root/src/tty/tty.zig
blob: ad6f04b0a3ae157fe983bc634a6fe8002eef7e7a (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
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
//! The terminal shell: owns the event loop and all IO. Translates vaxis
//! events into core events, performs the core's effects (fork ptys, write
//! them, resize them), and hands the core's Surface to vaxis cell-for-cell —
//! the canonical interface rendered with no interpretation.
const std = @import("std");
const builtin = @import("builtin");
const posix = std.posix;
const libc = std.c;
const linux = std.os.linux;
const vaxis = @import("vaxis");
const pardes = @import("../pardes.zig");
const tracy = @import("../tracy.zig");
const look = @import("../look.zig");
const temp_file = @import("../temp_file.zig");
const shell_bin = @import("../shell_bin.zig");
const message = @import("../message.zig");
const selection_pipe = @import("../selection_pipe.zig");
const nested = @import("../nested.zig");

extern "c" fn forkpty(amaster: *c_int, name: ?[*:0]u8, termp: ?*const anyopaque, winp: ?*const posix.winsize) c_int;
extern "c" fn execv(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int;
extern "c" fn chdir(path: [*:0]const u8) c_int;
extern "c" fn _exit(status: c_int) noreturn;
extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;

// TIOCSWINSZ: absent from std.c.T on darwin — _IOW('t', 103, winsize)
const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467));

pub const Command = struct {
    pub var value: union(enum) {
        nop,
        quit,
        tick,
        key_press: vaxis.Key,
        pty_read: struct { id: usize, bytes: []u8 },
        pty_eof: struct { id: usize, gen: u32 },
        winsize: vaxis.Winsize,
        mouse: vaxis.Mouse,
        paste: []const u8,
        /// a language query finished on a worker; rows are gpa-owned
        lsp_done: struct { id: u32, rows: []u8 },
        /// a selection-filter worker finished; every stdout is gpa-owned
        pipe_done: selection_pipe.Response,
        /// something happened in a watched directory (see watchFiles)
        files_changed,
        /// a pardes launched inside this one sent us a builtin command line
        /// (see lookServer); gpa-owned, like pty_read
        command: []u8,
    } = .nop;
};
const Loop = vaxis.Loop(@TypeOf(Command.value));

/// The files on open panes, watched through ONE inotify instance.
///
/// `wd` is the descriptor for the file's CONTAINING DIRECTORY, not for the
/// file: almost nothing rewrites a file in place. An editor, `git checkout`, a
/// formatter — they write a temp file and rename it over the target, which
/// swaps the inode, and a watch on the file itself keeps reporting on the old
/// unlinked one forever. The directory sees the new inode arrive (MOVED_TO /
/// CREATE). std.Build.Watch marks directories for exactly this reason; it uses
/// fanotify because it watches thousands of them across mount points and needs
/// FID-keyed dedup, whereas sixteen panes' worth of inotify is a third of the
/// code, hands us no privilege question, and has no kernel version floor.
///
/// `hash` is what we last saw ON DISK. A reload only fires when it moves, so
/// pardes's own Save — which restamps the hash from the bytes it just wrote —
/// never looks like an external change and never touches the undo stack.
/// A hash rather than mtime+size because we have to read the file to hand the
/// core its bytes anyway, so the exact answer costs nothing extra and there is
/// no clock granularity to reason about.
const Watch = struct { wd: c_int, hash: u64 };

/// One language query, owned by the worker that runs it. Everything the
/// backend may read is copied in here before the worker starts: the core goes
/// on editing the moment the effect is drained, so a borrowed slice would be a
/// use-after-free the length of one keystroke.
const LspJob = struct {
    id: u32,
    kind: pardes.lsp.Kind,
    offset: u32,
    path: []u8,
    source: [:0]u8,
    arg: []u8,
    root: []u8,

    fn free(j: *LspJob, gpa: std.mem.Allocator) void {
        gpa.free(j.path);
        gpa.free(j.source);
        gpa.free(j.arg);
        gpa.free(j.root);
        gpa.destroy(j);
    }
};

const PipeTask = struct {
    id: u32,
    future: std.Io.Future(anyerror!void),
};

const Pty = struct {
    file: std.Io.File,
    pid: posix.pid_t,
    reader: std.Io.Future(anyerror!void),
};

const KittyPlacement = struct {
    cell_x: u16,
    cell_y: u16,
    cell_cols: u16,
    cell_rows: u16,
    options: vaxis.Image.DrawOptions,
};

fn terminalCellPixels(total_pixels: u16, cells: u16, fallback: u32) u32 {
    if (total_pixels == 0 or cells == 0) return fallback;
    return @max(1, @as(u32, total_pixels) / cells);
}

fn updateCoreTerminalSize(core: *pardes.Pardes, cols: u16, rows: u16, pixel_w: u16, pixel_h: u16) void {
    core.update(.{ .resize = .{
        .cols = cols,
        .rows = rows,
        .cell_pixels = .{
            .w = @intCast(terminalCellPixels(pixel_w, cols, 8)),
            .h = @intCast(terminalCellPixels(pixel_h, rows, 16)),
        },
    } });
}

/// Translate backend-neutral source/destination pixels into Kitty's source
/// crop plus cell-sized placement. Kitty can specify only one scaled axis
/// without distorting the image; the terminal derives the other axis.
fn kittyPlacement(
    place: pardes.ImagePlace,
    screen_cols: u16,
    screen_rows: u16,
    screen_pixel_w: u16,
    screen_pixel_h: u16,
) ?KittyPlacement {
    if (comptime pardes.pdf_enabled) {
        if (place.native.fit == .contain) return null;
        const cell_w = terminalCellPixels(screen_pixel_w, screen_cols, 8);
        const cell_h = terminalCellPixels(screen_pixel_h, screen_rows, 16);
        const body_w = std.math.mul(u32, place.w, cell_w) catch return null;
        const body_h = std.math.mul(u32, place.h, cell_h) catch return null;
        const geometry = place.native.geometry orelse pardes.image.nativeGeometry(
            place.iw,
            place.ih,
            body_w,
            body_h,
            place.native.fit,
            place.native.pan_x,
            place.native.pan_y,
        ) orelse return null;

        // Kitty has a top-left pixel offset but no destination bottom clip.
        // Its missing c/r axis is rounded up to whole terminal cells, so a
        // clipped fragment shorter than one row cannot be represented without
        // painting the following theme gap. Conservatively keep only whole
        // rows contained by geometry.dst and trim the source crop to the same
        // scale. Cached page pixels remain unchanged; an unrepresentable tail
        // is simply left as theme background.
        const safe_rows_u32 = geometry.dst.h / cell_h;
        if (safe_rows_u32 == 0) return null;
        const safe_pixel_h = safe_rows_u32 * cell_h;
        var safe_src_h: u32 = geometry.src.h;
        var declared_cols: u32 = 0;
        var declared_rows: u32 = 0;
        switch (place.native.fit) {
            .width => {
                declared_cols = @intCast(@max(
                    @as(u64, 1),
                    (@as(u64, geometry.dst.w) + cell_w - 1) / cell_w,
                ));
                const declared_pixel_w = @as(u64, declared_cols) * cell_w;
                const max_src_h: u32 = @intCast(
                    @as(u64, safe_pixel_h) * geometry.src.w / declared_pixel_w,
                );
                if (max_src_h == 0) return null;
                safe_src_h = @min(safe_src_h, max_src_h);
                const aspect_pixel_h: u32 = @intCast(
                    (@as(u64, safe_src_h) * declared_pixel_w + geometry.src.w - 1) /
                        geometry.src.w,
                );
                declared_rows = @intCast(
                    (@as(u64, aspect_pixel_h) + cell_h - 1) / cell_h,
                );
            },
            .height => {
                declared_rows = safe_rows_u32;
                safe_src_h = @max(@as(u32, 1), @as(u32, @intCast(
                    @as(u64, safe_pixel_h) * geometry.src.h / geometry.dst.h,
                )));
                safe_src_h = @min(safe_src_h, geometry.src.h);
                const aspect_pixel_w: u32 = @intCast(
                    (@as(u64, geometry.src.w) * safe_pixel_h + safe_src_h - 1) /
                        safe_src_h,
                );
                declared_cols = @intCast(
                    (@as(u64, aspect_pixel_w) + cell_w - 1) / cell_w,
                );
            },
            .contain => unreachable,
        }
        if (declared_rows == 0 or declared_rows > safe_rows_u32) return null;

        // Every Kitty protocol field is u16. Reject an attachment which the
        // wire format cannot represent instead of truncating it.
        const src_x = std.math.cast(u16, geometry.src.x) orelse return null;
        const src_y = std.math.cast(u16, geometry.src.y) orelse return null;
        const src_w = std.math.cast(u16, geometry.src.w) orelse return null;
        const src_h = std.math.cast(u16, safe_src_h) orelse return null;
        const cell_x = std.math.cast(u16, geometry.dst.x / cell_w) orelse return null;
        const cell_y = std.math.cast(u16, geometry.dst.y / cell_h) orelse return null;
        if (cell_x >= place.w or cell_y >= place.h) return null;
        const pixel_x = std.math.cast(u16, geometry.dst.x % cell_w) orelse return null;
        const pixel_y = std.math.cast(u16, geometry.dst.y % cell_h) orelse return null;
        const cell_cols = std.math.cast(u16, @min(
            @as(u32, place.w - cell_x),
            (@as(u64, pixel_x) + @as(u64, declared_cols) * cell_w + cell_w - 1) / cell_w,
        )) orelse return null;
        const cell_rows = std.math.cast(u16, @min(
            @as(u32, place.h - cell_y),
            (@as(u64, pixel_y) + declared_rows * cell_h + cell_h - 1) / cell_h,
        )) orelse return null;
        if (cell_cols == 0 or cell_rows == 0) return null;

        return .{
            .cell_x = cell_x,
            .cell_y = cell_y,
            .cell_cols = cell_cols,
            .cell_rows = cell_rows,
            .options = .{
                .clip_region = .{ .x = src_x, .y = src_y, .width = src_w, .height = src_h },
                .pixel_offset = if (pixel_x != 0 or pixel_y != 0) .{ .x = pixel_x, .y = pixel_y } else null,
                .size = switch (place.native.fit) {
                    .width => .{ .cols = std.math.cast(u16, declared_cols) orelse return null },
                    .height => .{ .rows = std.math.cast(u16, declared_rows) orelse return null },
                    .contain => unreachable,
                },
            },
        };
    } else {
        return null;
    }
}

test "Kitty PDF fragments never declare pixels beyond their clipped bottom" {
    if (comptime !pardes.pdf_enabled) return;

    const base = pardes.ImagePlace{
        .pane = 0,
        .serial = 1,
        .native = .{
            .revision = 1,
            .page = 0,
            .fit = .width,
            .geometry = .{
                .src = .{ .w = 96, .h = 10 },
                .dst = .{ .y = 195, .w = 304, .h = 29 },
            },
        },
        .x = 0,
        .y = 0,
        .w = 38,
        .h = 14,
        .rgba = &.{},
        .iw = 96,
        .ih = 64,
    };
    const width = kittyPlacement(base, 80, 16, 640, 256) orelse
        return error.MissingSafeKittyWidthFragment;
    const width_clip = width.options.clip_region.?;
    const width_size = width.options.size.?;
    try std.testing.expectEqual(@as(u16, 5), width_clip.height.?);
    try std.testing.expectEqual(@as(u16, 38), width_size.cols.?);
    try std.testing.expectEqual(@as(u16, 3), width.options.pixel_offset.?.y);
    const aspect_pixels = (@as(u32, width_size.cols.?) * 8 * width_clip.height.? +
        width_clip.width.? - 1) / width_clip.width.?;
    const inferred_rows = (aspect_pixels + 15) / 16;
    try std.testing.expect(inferred_rows * 16 <= base.native.geometry.?.dst.h);

    var height = base;
    height.native.fit = .height;
    height.native.geometry.?.src.h = 9;
    const height_fragment = kittyPlacement(height, 80, 16, 640, 256) orelse
        return error.MissingSafeKittyHeightFragment;
    try std.testing.expectEqual(@as(u16, 1), height_fragment.options.size.?.rows.?);
    try std.testing.expect(@as(u32, height_fragment.options.size.?.rows.?) * 16 <=
        height.native.geometry.?.dst.h);

    // There is no honest APC for less than one physical row: omitting it is
    // preferable to painting three pixels of the following theme gap.
    height.native.geometry.?.dst.h = 13;
    try std.testing.expect(kittyPlacement(height, 80, 16, 640, 256) == null);
}

fn kittyImageRepresentable(place: pardes.ImagePlace) bool {
    return place.iw > 0 and place.ih > 0 and
        place.iw <= std.math.maxInt(u16) and place.ih <= std.math.maxInt(u16);
}

fn surfaceHasKittyKey(surface: *const pardes.Surface, key: pardes.ImageCacheKey) bool {
    for (surface.images[0..surface.nimages]) |maybe| {
        const place = maybe orelse continue;
        if (comptime pardes.pdf_enabled) if (!kittyImageRepresentable(place)) continue;
        if (place.cacheKey().eql(key)) return true;
    }
    return false;
}

const PdfWheelTarget = struct { pane: usize, page: usize };

/// A native PDF's page geometry is invalid between `setPdfPage` and the next
/// render. Remember the page under a vertical wheel press so the input batch
/// can stop exactly when that press crosses a page boundary. The following
/// queued wheel report then sees the newly rastered page instead of treating
/// missing geometry as another page-wise fallback.
fn nativePdfWheelTarget(core: *const pardes.Pardes, mouse: vaxis.Mouse) ?PdfWheelTarget {
    if (comptime !pardes.pdf_enabled) return null;
    if (!core.native_images or mouse.type != .press or
        (mouse.button != .wheel_up and mouse.button != .wheel_down) or
        mouse.col < 0 or mouse.row < 0) return null;
    const col: u16 = @intCast(mouse.col);
    const row: u16 = @intCast(mouse.row);
    for (core.panes, 0..) |slot, id| {
        const pane = slot orelse continue;
        const rect = core.rects[id];
        if (col < rect.x or col >= rect.x + rect.w or
            row < rect.y or row >= rect.y + rect.h) continue;
        const page = pane.pdfPage() orelse return null;
        return .{ .pane = id, .page = page };
    }
    return null;
}

pub fn run(init: std.process.Init, opts: pardes.Options) !void {
    const io = init.io;
    const gpa = init.gpa;

    // SIGWINCH must never run vaxis's signal handler: it posts the winsize
    // event through std.Io.Mutex/Condition, and when the signal lands on a
    // thread blocked inside an Io.Threaded syscall region (pty readers in
    // read(2), the main thread parked in queue.pop) a contended lock re-enters
    // the Io machinery and Syscall.start hits `unreachable` — panic, then the
    // panic-time terminal restore used to write through the same Io and
    // recurse until stack overflow. Reproduced by resizing the outer terminal
    // (e.g. a font-size change) while shells run. Block it here, before any
    // thread exists (threads inherit the mask, so vaxis's handler never
    // fires), and take it synchronously on the sigwait thread below instead.
    var winch_set = posix.sigemptyset();
    posix.sigaddset(&winch_set, posix.SIG.WINCH);
    posix.sigprocmask(posix.SIG.BLOCK, &winch_set, null);

    var tty_buf: [0x10000]u8 = undefined;
    var tty = try vaxis.Tty.init(io, &tty_buf);
    defer tty.deinit(); // restore cooked termios LAST, after vx flushed its resets
    var vx = try vaxis.init(io, gpa, init.environ_map, .{ .system_clipboard_allocator = gpa });
    defer vx.deinit(gpa, tty.writer());
    try vx.enterAltScreen(tty.writer());
    defer vx.exitAltScreen(tty.writer()) catch {};
    // requests 1002;1003;1004;1006 (cell-coordinate SGR; called pre-query, so
    // vaxis never upgrades to 1016 pixel mode). Note: ghostty's GTK apprt drops
    // middle press+release BEFORE mouse reporting when the desktop sets
    // gtk-enable-primary-paste=false — no mode we request can surface middle
    // clicks there (see test/snapshots/ghostty-mid.snap).
    try vx.setMouseMode(tty.writer(), true);

    var frame_arena: std.heap.ArenaAllocator = .init(gpa);
    defer frame_arena.deinit();

    // stb_image allocator for image panes
    pardes.image.start(io, gpa);
    defer pardes.image.stop();

    var core = if (opts.load_path) |lp| blk: {
        const bytes = try look.readFile(gpa, lp);
        defer gpa.free(bytes);
        break :blk try pardes.Pardes.initFromDump(gpa, opts, bytes);
    } else try pardes.Pardes.init(gpa, opts);
    defer core.deinit();

    // shells emit OSC 133 prompt marks via this rc (prompt hiding, click-move)
    writeFile(shell_bin.bash_rc_path, shell_bin.bash_rc);
    writeFile(shell_bin.fish_rc_path, shell_bin.fish_rc);
    // macos: apple's bash 3.2 prints the zsh-deprecation banner into every
    // pane unless this is in the env BEFORE bash starts (the rc is too late)
    if (comptime builtin.os.tag.isDarwin()) _ = setenv("BASH_SILENCE_DEPRECATION_WARNING", "1", 1);

    var kitty_handles = std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image).init(gpa);
    defer {
        var iterator = kitty_handles.valueIterator();
        while (iterator.next()) |handle| vx.freeImage(tty.writer(), handle.id);
        kitty_handles.deinit();
    }
    var ptys: [pardes.MAX_PANES]?Pty = @splat(null);
    // per-slot spawn generation: a reused pane id ignores the old shell's
    // late pty_eof (which would otherwise close the NEW pty on that slot)
    var gens: [pardes.MAX_PANES]u32 = @splat(0);
    // the single in-flight language query (see the .lsp effect)
    var lsp_task: ?std.Io.Future(anyerror!void) = null;
    // Selection filters may overlap: a second submit supersedes the first in
    // core without synchronously canceling a possibly slow shell command.
    var pipe_tasks: std.ArrayList(PipeTask) = .empty;
    // One inotify instance for every watched pane, opened here — before any
    // thread exists — so the pre-loop effect drain below can already mark the
    // file a positional path argument opened. -1 off linux: watchPane goes
    // quiet and the core simply never gets a file_changed event.
    var inotify_fd: c_int = if (builtin.os.tag == .linux) libc.inotify_init1(linux.IN.CLOEXEC) else -1;
    var watches: [pardes.MAX_PANES]?Watch = @splat(null);
    var watch_task: ?std.Io.Future(anyerror!void) = null;
    var loop: Loop = .init(io, &tty, &vx);
    defer {
        // reap the reader tasks (cancel interrupts a blocked read) before
        // closing the masters — the runtime joins those threads on exit and a
        // reader stuck in read(2) would hang the process — then drain the
        // queue: leftover events own gpa bytes and would dump as leaks.
        for (&ptys) |*slot| if (slot.*) |*pt| {
            pt.reader.cancel(io) catch {};
            _ = libc.close(pt.file.handle);
            slot.* = null;
        };
        // join the query worker BEFORE the drain below, or its late post
        // lands in a queue nobody empties again and the rows leak
        if (lsp_task) |*t| {
            t.cancel(io) catch {};
            lsp_task = null;
        }
        for (pipe_tasks.items) |*task| task.future.cancel(io) catch {};
        pipe_tasks.deinit(gpa);
        // same contract as the pty readers: cancel unblocks the watcher's
        // read, and only then is the fd safe to close
        if (watch_task) |*t| {
            t.cancel(io) catch {};
            watch_task = null;
        }
        if (inotify_fd >= 0) {
            _ = libc.close(inotify_fd);
            inotify_fd = -1;
        }
        while (loop.tryEvent() catch null) |ev| switch (ev) {
            .pty_read => |pr| gpa.free(pr.bytes),
            .command => |line| gpa.free(line),
            .paste => |b| gpa.free(@constCast(b)),
            .lsp_done => |d| gpa.free(d.rows),
            .pipe_done => |response_value| {
                var response = response_value;
                response.deinit(gpa);
            },
            else => {},
        };
    }

    // The socket a pardes launched inside this one connects to (nested.zig).
    // Declared AFTER the drain above so its teardown runs BEFORE it — the
    // listener thread must be out of the way before the queue is emptied.
    // --nested opted out of the whole mechanism, including being an outer
    // instance; so does any failure to bind, and then children simply open
    // their own session.
    const sock_fd: c_int = if (opts.nested) -1 else nested.listen();
    defer nested.unlisten(sock_fd);

    // Perform the initial spawns BEFORE any worker thread exists: forkpty from
    // a multithreaded process can wedge the child before exec.
    drainEffects(core, &ptys, &gens, io, gpa, &loop, &vx, &tty, &lsp_task, &pipe_tasks, inotify_fd, &watches, false);

    try loop.start();
    defer loop.stop();
    // resize watcher: plain detached thread (not io.concurrent — teardown
    // joins those, and sigwait never returns); dies with the process
    (try std.Thread.spawn(.{}, winchWatch, .{ &loop, &vx, &tty })).detach();
    // ...and the nested-instance listener, detached for the same reason: a
    // blocking accept(2) never returns either, so an io.concurrent task would
    // hang the teardown that joins it.
    if (sock_fd >= 0) (try std.Thread.spawn(.{}, lookServer, .{ gpa, sock_fd, &loop })).detach();
    // Capability handshake — SEND the probes, do not wait on them. This was
    // queryTerminal(2ms), which blocks on a futex until DA1 comes back. The
    // number has to beat one terminal round trip: a local terminal answers in
    // microseconds, `ssh localhost` in under 1ms, and any real link never.
    // Measured over sshd on :22 with the replies delayed to model the wire,
    // 2ms already loses at 5ms RTT and everything above.
    //
    // Losing it is worse than never probing, because vaxis splits detect from
    // enable and only detect respects the deadline. queryTerminal sets
    // queries_done the moment the futex times out, and the two replies vaxis
    // gates on that flag — explicit width and scaled text, both answered as a
    // cursor-position report — stop being recognised as probe replies and are
    // handed to US as shift-F3/alt-F3 keypresses. The replies it does NOT
    // gate (mode 2027, kitty keyboard/graphics, sgr-pixels) keep landing and
    // keep mutating vx.caps from the reader thread, long after
    // enableDetectedFeatures ran and declined to switch those modes on. So
    // over ssh the terminal sat in its default modes while caps claimed
    // otherwise — kitty keyboard was never actually pushed, ever. Raising the
    // timeout only moves the link speed at which that happens.
    //
    // Resolve it on the loop instead. DA1 is last in the probe string and
    // terminals answer in order, so when vaxis's reader flips queries_done
    // every earlier reply is already applied — no window left to miss at any
    // latency, and the enable lands before the next frame (see caps_pending
    // in the render path). A terminal that never answers keeps the defaults,
    // which is what the 2ms timeout produced anyway, and with no caps
    // enableDetectedFeatures writes no bytes — the snapshot goldens, where
    // nothing ever answers, do not move. Startup gets 2ms faster, not slower.
    //
    // ponytail: nothing wakes the loop for DA1 alone. In practice the reply
    // burst carries the mode-2048 size report too, which posts a winsize and
    // turns the loop; a terminal idle from boot that lands DA1 between two
    // parks keeps the defaults until the user's first keystroke (decoded
    // legacy, which vaxis handles). Ceiling accepted because nothing in the
    // render path reads the missing caps: pardes writes one codepoint per
    // cell plus an explicit blank spacer under a wide glyph, and vaxis's
    // Cell.width defaults to 1, so gwidth — the only consumer of
    // caps.unicode — is never called. If that ever changes, wake the loop on
    // vx.query_futex from a one-shot thread instead.
    try vx.queryTerminalSend(tty.writer());
    var caps_pending = true;

    // now threads are fine: start a reader task per pty
    for (&ptys, 0..) |*slot, id| if (slot.*) |*pt| {
        pt.reader = try io.concurrent(readPty, .{ io, gpa, pt.file, id, gens[id], &loop });
    };
    // ...and the one file watcher. Started here rather than lazily on the
    // first watched pane because the fd already exists and an unwatched
    // inotify instance just parks in read(2) — one thread for the process,
    // however many panes come and go.
    if (inotify_fd >= 0) watch_task = io.concurrent(watchFiles, .{ io, inotify_fd, &loop }) catch null;

    var check_files = false;
    var pending: ?@TypeOf(Command.value) = .tick;
    while (!core.quit) {
        var event = if (pending) |ev| blk: {
            pending = null;
            break :blk ev;
        } else try loop.nextEvent();
        const tz_event = tracy.zone(@src(), "event");
        // Apply every queued INPUT event, then render ONCE — the gui shell
        // drains SDL's queue the same way. Without this a wheel flick is fifty
        // full render+repaint (and re-highlight) cycles instead of one. A
        // native PDF page crossing is the one input boundary below: its next
        // wheel report needs geometry produced by this render. Pty output also
        // keeps a frame per chunk so progress paints as it arrives.
        var stop = false;
        var batch: usize = 0;
        while (true) {
            var output = false;
            var native_pdf_page_changed = false;
            switch (event) {
                .nop => {},
                .tick => core.update(.tick),
                .quit => stop = true,
                .winsize => |ws| {
                    try vx.resize(gpa, tty.writer(), ws);
                    if (comptime pardes.pdf_enabled)
                        updateCoreTerminalSize(core, ws.cols, ws.rows, ws.x_pixel, ws.y_pixel)
                    else
                        core.update(.{ .resize = .{ .cols = ws.cols, .rows = ws.rows } });
                },
                .pty_read => |pr| {
                    core.update(.{ .output = .{ .pane = @intCast(pr.id), .bytes = pr.bytes } });
                    gpa.free(pr.bytes);
                    output = true;
                },
                .pty_eof => |e| if (gens[e.id] == e.gen) {
                    if (ptys[e.id]) |*pt| {
                        pt.reader.await(io) catch {}; // reader just finished; join it or its future leaks
                        _ = libc.close(pt.file.handle);
                        ptys[e.id] = null;
                    }
                    core.update(.{ .eof = .{ .pane = @intCast(e.id) } });
                },
                .key_press => |key| core.update(.{ .key = .{
                    .cp = mapKey(effCp(key)),
                    .text = key.text orelse "",
                    .ctrl = key.mods.ctrl,
                    .alt = key.mods.alt,
                    .shift = key.mods.shift,
                } }),
                .mouse => |m| {
                    const pdf_before = nativePdfWheelTarget(core, m);
                    const button: ?pardes.Mouse.Button = switch (m.button) {
                        .left => .left,
                        .middle => .middle,
                        .right => .right,
                        .wheel_up => .wheel_up,
                        .wheel_down => .wheel_down,
                        .wheel_left => .wheel_left,
                        .wheel_right => .wheel_right,
                        .none => .none, // button-less motion: hover tracking
                        else => null,
                    };
                    if (button) |b| core.update(.{ .mouse = .{
                        .button = b,
                        .kind = switch (m.type) {
                            .press => .press,
                            .release => .release,
                            .motion => .motion,
                            .drag => .drag,
                        },
                        .col = @intCast(m.col),
                        .row = @intCast(m.row),
                        .ctrl = m.mods.ctrl,
                    } });
                    if (pdf_before) |before| {
                        if (core.panes[before.pane]) |pane| {
                            if (pane.pdfPage()) |page|
                                native_pdf_page_changed = page != before.page;
                        }
                    }
                },
                .paste => |bytes| {
                    core.update(.{ .paste = bytes });
                    gpa.free(@constCast(bytes));
                },
                .command => |line| {
                    core.update(.{ .command = line });
                    gpa.free(line);
                },
                // Coalesced on purpose: a burst of writes (a formatter, a
                // build, a `git checkout`) collapses into ONE pass below, so
                // it cannot queue a reload — or an undo entry — per write.
                .files_changed => check_files = true,
                .lsp_done => |d| {
                    core.update(.{ .lsp_resp = .{ .id = d.id, .rows = d.rows } });
                    gpa.free(d.rows);
                    // the worker is finished; join it so its future does not
                    // leak (same contract as pty_eof above)
                    if (lsp_task) |*t| {
                        t.await(io) catch {};
                        lsp_task = null;
                    }
                },
                .pipe_done => |response_value| {
                    var response = response_value;
                    core.update(.{ .pipe_resp = .{
                        .id = response.id,
                        .success = response.success,
                        .outputs = response.outputs,
                    } });
                    response.deinit(gpa);
                    for (pipe_tasks.items, 0..) |*task, i| if (task.id == response_value.id) {
                        task.future.await(io) catch {};
                        _ = pipe_tasks.orderedRemove(i);
                        break;
                    };
                },
            }
            batch += 1;
            if (stop or output or native_pdf_page_changed or batch >= 64) break;
            event = (try loop.tryEvent()) orelse break;
        }
        tz_event.end();
        if (stop) break;

        // A watched directory moved. The wake says only THAT something
        // happened, so re-read every watched pane and hand the core the ones
        // whose bytes actually changed — that comparison is what keeps our own
        // Save, and any write that lands on identical content, out of the undo
        // stack. Reading here rather than on the watcher thread because the
        // core is the only thing that knows which pane a path belongs to, and
        // opening a file pane already reads synchronously on this thread.
        if (check_files) {
            check_files = false;
            for (&watches, 0..) |*slot, id| {
                if (slot.* == null) continue;
                const pane = core.panes[id] orelse continue;
                const f = pane.file orelse continue;
                const bytes = look.readFile(gpa, f.path) catch continue;
                defer gpa.free(bytes);
                const h = std.hash.Wyhash.hash(0, bytes);
                if (h == slot.*.?.hash) continue;
                slot.*.?.hash = h;
                core.update(.{ .file_changed = .{ .pane = @intCast(id), .bytes = bytes } });
                // the hash moving IS "someone else wrote this file" (our own
                // Save restamped it above), so the pane says who did what to it
                // — and it says it after the update, which cannot clear a
                // message because only a key or a mouse event does
                var mbuf: [256]u8 = undefined;
                core.setMessage(id, message.stamp(&mbuf, "reloaded", f.path));
            }
        }

        drainEffects(core, &ptys, &gens, io, gpa, &loop, &vx, &tty, &lsp_task, &pipe_tasks, inotify_fd, &watches, true);
        if (core.quit) break;

        // Restore builtin: swap in a core rebuilt from the dump; the live
        // shells die with their masters (readers canceled, gens bumped so
        // their late eofs never touch the replay panes)
        if (core.takeRestore()) |rp| blk: {
            const bytes = look.readFile(gpa, rp) catch break :blk;
            defer gpa.free(bytes);
            var o = core.opts;
            o.cols = core.screen_w;
            o.rows = core.screen_h; // pre-size: dump panes never greet
            const nc = pardes.Pardes.initFromDump(gpa, o, bytes) catch break :blk;
            for (&ptys, 0..) |*slot, pid| if (slot.*) |*pt| {
                pt.reader.cancel(io) catch {};
                _ = libc.close(pt.file.handle);
                slot.* = null;
                gens[pid] +%= 1;
            };
            // the replay core's pane ids mean new things, and the dying core's
            // `watch off` effects go into a queue nobody drains — drop the lot
            // here. The new core emits its own `on`s as it builds its panes.
            for (0..watches.len) |wid| watchPane(inotify_fd, &watches, @intCast(wid), null, 0);
            var image_iterator = kitty_handles.valueIterator();
            while (image_iterator.next()) |handle| vx.freeImage(tty.writer(), handle.id);
            kitty_handles.clearRetainingCapacity();
            nc.native_images = vx.caps.kitty_graphics;
            core.deinit();
            core = nc;
            if (comptime pardes.pdf_enabled) {
                // A restored core did not receive the terminal's earlier
                // winsize event. Reapply both the grid and physical cells
                // before its first PDF frame so pointer/pan geometry stays
                // identical to placement.
                updateCoreTerminalSize(core, vx.screen.width, vx.screen.height, vx.screen.width_pix, vx.screen.height_pix);
            }
        }

        // live cwd for tags/look: cheap per-pane lookup, per frame
        for (&ptys, 0..) |*slot, id| if (slot.*) |pt| {
            var lbuf: [1024]u8 = undefined;
            if (look.shellCwd(pt.pid, &lbuf)) |cwd| core.setCwd(id, cwd);
        };

        // The handshake landed (vaxis's reader flips queries_done on DA1, the
        // last probe answered): put the terminal into the modes the caps now
        // claim, before anything is drawn under them. Polled here rather than
        // done where the replies arrive because that is the reader thread, and
        // this is the only thread allowed to touch the tty writer. The repaint
        // matters as much as the enable: earlier frames were drawn under the
        // pre-handshake caps, and vaxis's shadow grid has to be re-established
        // under the new ones or it keeps skipping cells it thinks are current.
        if (caps_pending and vx.queries_done.load(.unordered)) {
            caps_pending = false;
            vx.enableDetectedFeatures(tty.writer()) catch {};
            // The core was constructed before the asynchronous handshake.
            // Advertise native pixels only now, after every reply preceding
            // DA1 has updated the capability set.
            core.native_images = vx.caps.kitty_graphics;
            vx.queueRefresh();
        }

        // ---- render: surface -> vaxis, cell for cell ----
        _ = frame_arena.reset(.retain_capacity);
        const tz_core = tracy.zone(@src(), "core.render");
        const surface = try core.render(frame_arena.allocator());
        tz_core.end();
        const tz_cells = tracy.zone(@src(), "surface->vaxis");
        const win = vx.window();
        win.clear();
        var y: u16 = 0;
        while (y < surface.rows) : (y += 1) {
            var x: u16 = 0;
            while (x < surface.cols) : (x += 1) {
                const cell = surface.at(x, y);
                if (cell.default) continue;
                win.writeCell(x, y, .{
                    .char = .{ .grapheme = cell.grapheme() },
                    .style = vaxisStyle(cell.style),
                });
            }
        }
        tz_cells.end();
        // Pixel attachments (kitty graphics): transmit once per pixel
        // generation, then re-place every frame (placements aren't
        // persistent). The map is keyed by pane lifetime + PDF page + pixel
        // revision, so any number of short visible pages can coexist without
        // aliasing a fixed terminal cache slot.
        for (surface.images[0..surface.nimages]) |maybe| {
            const place = maybe orelse continue;
            if (comptime pardes.pdf_enabled) {
                if (!kittyImageRepresentable(place)) continue;
            }
            const key = place.cacheKey();
            if (!kitty_handles.contains(key) and vx.caps.kitty_graphics) {
                const enc = std.base64.standard.Encoder;
                if (gpa.alloc(u8, enc.calcSize(place.rgba.len))) |b64| {
                    defer gpa.free(b64);
                    _ = enc.encode(b64, place.rgba);
                    if (vx.transmitPreEncodedImage(tty.writer(), b64, @intCast(place.iw), @intCast(place.ih), .rgba) catch null) |handle|
                        kitty_handles.put(key, handle) catch vx.freeImage(tty.writer(), handle.id);
                } else |_| {}
            }
            if (kitty_handles.get(key)) |cached| {
                if (comptime !pardes.pdf_enabled) {
                    const child = win.child(.{ .x_off = place.x, .y_off = place.y, .width = place.w, .height = place.h });
                    cached.draw(child, .{ .scale = .contain }) catch {};
                } else {
                    if (place.native.fit == .contain) {
                        const child = win.child(.{ .x_off = place.x, .y_off = place.y, .width = place.w, .height = place.h });
                        cached.draw(child, .{ .scale = .contain }) catch {};
                    } else if (kittyPlacement(
                        place,
                        vx.screen.width,
                        vx.screen.height,
                        vx.screen.width_pix,
                        vx.screen.height_pix,
                    )) |placement| {
                        const child = win.child(.{
                            .x_off = @as(i17, place.x) + placement.cell_x,
                            .y_off = @as(i17, place.y) + placement.cell_y,
                            .width = placement.cell_cols,
                            .height = placement.cell_rows,
                        });
                        cached.draw(child, placement.options) catch {};
                    }
                }
            }
        }
        // Toggling PETSCII or closing a pane removes its attachment from the
        // Surface. Release the terminal-side image then, not merely when that
        // numeric pane slot happens to be reused.
        var stale: std.ArrayList(pardes.ImageCacheKey) = .empty;
        defer stale.deinit(gpa);
        var image_iterator = kitty_handles.iterator();
        while (image_iterator.next()) |entry|
            if (!surfaceHasKittyKey(surface, entry.key_ptr.*))
                stale.append(gpa, entry.key_ptr.*) catch {};
        for (stale.items) |key| if (kitty_handles.fetchRemove(key)) |removed|
            vx.freeImage(tty.writer(), removed.value.id);
        if (surface.cursor) |cur| {
            win.showCursor(cur.x, cur.y);
            // insert = beam, everything else = the terminal's default shape
            win.setCursorShape(if (cur.bar) .beam else .default);
        }
        const tz_render = tracy.zone(@src(), "vx.render");
        try vx.render(tty.writer());
        tz_render.end();
        tracy.frameMark();

        // A theme transition is the only reason this otherwise event-driven
        // frontend redraws on a clock. Sleep on the loop thread, then make the
        // next pass a tick; input and worker events can queue during the short
        // sleep and are drained in that pass. No timer worker can outlive the
        // loop, and at the exact endpoint we return to an indefinite wait.
        if (core.themeAnimationActive()) {
            std.Io.sleep(io, .fromMilliseconds(pardes.animation.frame_ms), .awake) catch {};
            pending = .tick;
        }
    }
}

fn drainEffects(
    core: *pardes.Pardes,
    ptys: *[pardes.MAX_PANES]?Pty,
    gens: *[pardes.MAX_PANES]u32,
    io: std.Io,
    gpa: std.mem.Allocator,
    loop: *Loop,
    vx: *vaxis.Vaxis,
    tty: *vaxis.Tty,
    lsp_task: *?std.Io.Future(anyerror!void),
    pipe_tasks: *std.ArrayList(PipeTask),
    inotify_fd: c_int,
    watches: *[pardes.MAX_PANES]?Watch,
    threads_ok: bool,
) void {
    while (core.nextEffect()) |effect| switch (effect) {
        .spawn => |sp| {
            // the core reuses pane ids and there is no close effect: a deleted
            // pane's shell lives in its slot until a respawn lands here — reap
            // it (cancel joins the reader; its late eof is ignored by gen)
            if (ptys[sp.pane]) |*old| {
                old.reader.cancel(io) catch {};
                _ = libc.close(old.file.handle);
                ptys[sp.pane] = null;
            }
            gens[sp.pane] +%= 1;
            const cwd = sp.cwd.slice();
            var cwd_buf: [256:0]u8 = undefined;
            var cwd_z: ?[*:0]const u8 = null;
            if (cwd.len > 0) {
                @memcpy(cwd_buf[0..cwd.len], cwd);
                cwd_buf[cwd.len] = 0;
                cwd_z = @ptrCast(&cwd_buf);
            }
            const child = forkShell(core.shellBin(), cwd_z, core.screen_h, core.screen_w);
            ptys[sp.pane] = .{ .file = child.file, .pid = child.pid, .reader = .{ .any_future = null, .result = {} } };
            // report the pane's starting directory back to the core (tags)
            var lbuf: [1024]u8 = undefined;
            if (look.shellCwd(child.pid, &lbuf)) |wd| core.setCwd(sp.pane, wd);
            if (threads_ok) {
                if (ptys[sp.pane]) |*pt| {
                    pt.reader = io.concurrent(readPty, .{ io, gpa, pt.file, @as(usize, sp.pane), gens[sp.pane], loop }) catch pt.reader;
                }
            }
        },
        .write => |w| {
            if (ptys[w.pane]) |pt| writeFd(pt.file.handle, w.bytes.slice());
        },
        .resize_pty => |rs| {
            if (ptys[rs.pane]) |pt| {
                const ws: posix.winsize = .{ .row = rs.rows, .col = rs.cols, .xpixel = 0, .ypixel = 0 };
                _ = posix.system.ioctl(pt.file.handle, TIOCSWINSZ, @intFromPtr(&ws));
            }
        },
        .open_link => |url| look.openLink(url.slice()), // desktop browser
        .save_file => |sf| {
            const pane = core.panes[sf.pane] orelse continue;
            const f = pane.file orelse continue;
            var pathbuf: [4096:0]u8 = undefined;
            if (f.path.len >= pathbuf.len) continue;
            @memcpy(pathbuf[0..f.path.len], f.path);
            pathbuf[f.path.len] = 0;
            const fd = libc.open(pathbuf[0..f.path.len :0], .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644));
            if (fd < 0) continue;
            writeFd(fd, f.content);
            _ = libc.close(fd);
            // our own write is about to come back as a watch event: restamp
            // from the bytes we just put there so it reads as "no change"
            if (watches[sf.pane]) |*w| w.hash = std.hash.Wyhash.hash(0, f.content);
            // ...and say so on the pane's message row. AFTER the write, not
            // beside it: every `continue` above is a save that did not happen
            // and must not be reported as one.
            var mbuf: [256]u8 = undefined;
            core.setMessage(sf.pane, message.stamp(&mbuf, "saved", f.path));
        },
        .new_file => |request| {
            var path_buf: [4096:0]u8 = undefined;
            const made = temp_file.create(&path_buf) orelse continue;
            if (core.openNewFile(request.pane, request.serial, made.path))
                made.adopt()
            else
                made.discard();
        },
        .write_dump => {
            const out = core.dump_out orelse continue;
            var pbuf: [1024:0]u8 = undefined;
            const path = pardes.dump.outPath(&pbuf) orelse continue;
            const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644));
            if (fd < 0) continue;
            writeFd(fd, out);
            _ = libc.close(fd);
            core.setLastDump(path);
        },
        .set_clipboard => {
            // mirror the core's yank register out via OSC 52
            if (core.yank) |y| vx.copyToSystemClipboard(tty.writer(), y, gpa) catch {};
        },
        .lsp => |q| {
            if (!threads_ok) continue; // pre-loop drain: nothing to answer to yet
            const pane = core.panes[q.pane] orelse continue;
            // a pane with no file still asks `status` (it is about the backend,
            // not the buffer): empty path and source, root from the pane's cwd
            const f = pane.file;
            const job = gpa.create(LspJob) catch continue;
            job.* = .{
                .id = q.id,
                .kind = q.kind,
                .offset = q.offset,
                .path = gpa.dupe(u8, if (f) |ff| ff.path else "") catch {
                    gpa.destroy(job);
                    continue;
                },
                .source = gpa.dupeZ(u8, if (f) |ff| ff.content else "") catch {
                    gpa.free(job.path);
                    gpa.destroy(job);
                    continue;
                },
                .arg = gpa.dupe(u8, q.arg.slice()) catch {
                    gpa.free(job.path);
                    gpa.free(job.source);
                    gpa.destroy(job);
                    continue;
                },
                .root = gpa.dupe(u8, if (f) |ff| (std.fs.path.dirname(ff.path) orelse "/") else pane.cwdSlice()) catch {
                    gpa.free(job.path);
                    gpa.free(job.source);
                    gpa.free(job.arg);
                    gpa.destroy(job);
                    continue;
                },
            };
            // ponytail: ONE query in flight, so one future slot. Replacing it
            // cancels-then-joins the previous worker, which for a backend that
            // ignores cancellation means waiting out a query the user already
            // abandoned. Queries are milliseconds; make this a real pool the
            // day a backend takes long enough to notice.
            if (lsp_task.*) |*old| {
                old.cancel(io) catch {};
                lsp_task.* = null;
            }
            lsp_task.* = io.concurrent(lspWorker, .{ gpa, job, loop }) catch {
                job.free(gpa);
                continue;
            };
        },
        .pipe => |request| {
            if (!threads_ok) continue;
            const view = core.pipeRequest(request.id) orelse continue;
            const job = selection_pipe.Job.copy(gpa, view) catch continue;
            pipe_tasks.ensureUnusedCapacity(gpa, 1) catch {
                job.deinit(gpa);
                continue;
            };
            const future = io.concurrent(pipeWorker, .{ io, gpa, job, loop }) catch {
                job.deinit(gpa);
                continue;
            };
            pipe_tasks.appendAssumeCapacity(.{ .id = request.id, .future = future });
        },
        .watch => |w| {
            // starting, the path and the on-disk bytes are read off the core
            // (same split as save_file); stopping, the pane is already gone
            var path: ?[]const u8 = null;
            var hash: u64 = 0;
            if (w.on) if (core.panes[w.pane]) |pane| if (pane.file) |f| {
                path = f.path;
                hash = std.hash.Wyhash.hash(0, f.content);
            };
            watchPane(inotify_fd, watches, w.pane, path, hash);
        },
        .quit => {},
    };
}

/// Answer a language query off the event loop and post the rows back. This is
/// the whole async execution model: the same shape as readPty — do the slow
/// thing on a worker, hand the result to the loop as an event, let the core
/// stay a state machine that never blocks.
fn lspWorker(gpa: std.mem.Allocator, job: *LspJob, loop: *Loop) anyerror!void {
    defer job.free(gpa);
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    // the shell owns the result buffer; the backend only ever writes to it
    var out: std.Io.Writer.Allocating = .init(gpa);
    defer out.deinit();
    pardes.lsp.query(gpa, arena.allocator(), .{
        .kind = job.kind,
        .path = job.path,
        .source = job.source,
        .offset = job.offset,
        .arg = job.arg,
        .root = job.root,
    }, &out.writer);
    const rows = gpa.dupe(u8, out.written()) catch return;
    loop.postEvent(.{ .lsp_done = .{ .id = job.id, .rows = rows } }) catch gpa.free(rows);
    return;
}

fn pipeWorker(
    io: std.Io,
    gpa: std.mem.Allocator,
    job: *selection_pipe.Job,
    loop: *Loop,
) anyerror!void {
    defer job.deinit(gpa);
    var response = selection_pipe.runJob(gpa, io, job);
    loop.postEvent(.{ .pipe_done = response }) catch response.deinit(gpa);
}

/// Mark or unmark one pane's file (`path` null = unmark). Linux only: on any
/// other OS this returns silently, the core never receives a file_changed
/// event, and the feature is simply off — a state the core has to tolerate
/// regardless, since the browser shell has no filesystem at all.
/// ponytail: darwin wants the FSEvents half of std.Build.Watch here.
fn watchPane(fd: c_int, watches: *[pardes.MAX_PANES]?Watch, id: u8, path: ?[]const u8, hash: u64) void {
    if (comptime builtin.os.tag != .linux) return;
    if (fd < 0) return;
    if (watches[id]) |old| {
        // inotify hands out ONE descriptor per directory, so two panes on
        // files in the same directory share it: drop the mark only when the
        // last of them lets go, or closing one blinds the other.
        var shared = false;
        for (watches, 0..) |other, i| {
            const o = other orelse continue;
            if (i != id and o.wd == old.wd) shared = true;
        }
        if (!shared) _ = libc.inotify_rm_watch(fd, old.wd);
        watches[id] = null;
    }
    const p = path orelse return;
    const dir = std.fs.path.dirname(p) orelse ".";
    var dbuf: [4096:0]u8 = undefined;
    if (dir.len >= dbuf.len) return;
    @memcpy(dbuf[0..dir.len], dir);
    dbuf[dir.len] = 0;
    // CLOSE_WRITE, not MODIFY: one event when a writer is DONE rather than one
    // per write(2), which is most of the debounce for free. MOVED_TO and
    // CREATE catch the rename-over and the delete-then-recreate that are how
    // files are actually replaced (see Watch).
    const mask = linux.IN.CLOSE_WRITE | linux.IN.MOVED_TO | linux.IN.CREATE | linux.IN.ONLYDIR;
    const wd = libc.inotify_add_watch(fd, dbuf[0..dir.len :0], mask);
    if (wd < 0) return;
    watches[id] = .{ .wd = wd, .hash = hash };
}

/// Block on the inotify fd and wake the loop. Deliberately does NOT parse the
/// events: the loop re-reads every watched pane anyway, so the only thing an
/// event carries that we need is THAT something happened, and parsing would
/// mean sharing the watch table with the thread that mutates it. Same shape as
/// readPty — block off the loop, hand the loop an event, keep the core a state
/// machine that never blocks. Going through std.Io.File rather than a raw
/// read(2) is what lets the teardown `cancel` interrupt it.
///
/// ponytail: churn in a watched directory that never touches the watched file
/// still costs a wake and a re-read per event. The ceiling is one directory
/// per open file pane; filter by basename here if it ever shows up in a
/// profile.
fn watchFiles(io: std.Io, fd: c_int, loop: *Loop) anyerror!void {
    const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } };
    var read_buf: [4096]u8 = undefined;
    var reader = file.readerStreaming(io, &read_buf);
    while (true) {
        var buf: [4096]u8 = undefined;
        var vec = [_][]u8{&buf};
        const n = reader.interface.readVec(&vec) catch break;
        if (n == 0) break;
        loop.postEvent(.files_changed) catch break;
    }
}

/// Block on the nested-instance socket and hand the loop each command line a
/// pardes started inside this one sends. Same shape as winchWatch: a plain
/// detached thread around a call that never returns, posting into the vaxis
/// loop from ordinary thread context.
///
/// Nothing here is woken by teardown — close(2) does NOT release a thread
/// parked in accept4 on linux — so this dies with the process, exactly as
/// winchWatch dies inside sigwait. The window that leaves is one connection
/// accepted between the last drain and process exit posting into a queue whose
/// owner has returned; same shape and same bound as every other detached
/// worker here, and a self-pipe to close it would be more machinery than the
/// window is worth.
fn lookServer(gpa: std.mem.Allocator, fd: c_int, loop: *Loop) void {
    var buf: [nested.max_line]u8 = undefined;
    while (nested.acceptLine(fd, &buf)) |line| {
        const owned = gpa.dupe(u8, line) catch continue;
        loop.postEvent(.{ .command = owned }) catch {
            gpa.free(owned);
            break;
        };
    }
}

/// Consume SIGWINCH synchronously (it is blocked in every thread) and post
/// the new size as a winsize event from normal thread context — the one place
/// vaxis's Io-backed queue is safe to touch on a resize.
fn winchWatch(loop: *Loop, vx: *vaxis.Vaxis, tty: *vaxis.Tty) void {
    var set = posix.sigemptyset();
    posix.sigaddset(&set, posix.SIG.WINCH);
    while (true) {
        var sig: c_int = 0;
        if (libc.sigwait(&set, &sig) != 0) continue;
        if (vx.state.in_band_resize) continue; // terminal reports via CSI 48
        const ws = tty.getWinsize() catch continue;
        loop.postEvent(.{ .winsize = ws }) catch {};
    }
}

fn forkShell(bin: []const u8, cwd: ?[*:0]const u8, rows: u16, cols: u16) struct { file: std.Io.File, pid: posix.pid_t } {
    var master: c_int = undefined;
    // resolved BEFORE the fork, into this frame, which the child inherits:
    // nothing between fork and exec may allocate, and a PATH search would
    var path_buf: [std.fs.max_path_bytes]u8 = undefined;
    const spawn = shell_bin.resolve(bin, &path_buf);
    const ws = posix.winsize{ .row = rows, .col = cols, .xpixel = 0, .ypixel = 0 };
    const pid = forkpty(&master, null, null, &ws);
    if (pid == 0) {
        // the blocked-SIGWINCH mask survives fork AND exec — unblock it or
        // bash/vim in the pane would never see resizes (sigprocmask is
        // async-signal-safe)
        var set = posix.sigemptyset();
        posix.sigaddset(&set, posix.SIG.WINCH);
        posix.sigprocmask(posix.SIG.UNBLOCK, &set, null);
        if (cwd) |c| _ = chdir(c);
        _ = execv(spawn.path, &spawn.argv);
        _exit(127);
    }
    return .{ .file = .{ .handle = master, .flags = .{ .nonblocking = false } }, .pid = pid };
}

fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: u32, loop: *Loop) anyerror!void {
    var read_buf: [0x10000]u8 = undefined;
    var reader = pty.readerStreaming(io, &read_buf);
    while (true) {
        var buf: [0x10000]u8 = undefined;
        var vec = [_][]u8{&buf};
        const n = reader.interface.readVec(&vec) catch break;
        if (n == 0) break;
        const bytes = try gpa.dupe(u8, buf[0..n]);
        loop.postEvent(.{ .pty_read = .{ .id = id, .bytes = bytes } }) catch {
            gpa.free(bytes);
            break;
        };
    }
    // non-blocking: a teardown cancel only unblocks one wait, so a blocking
    // post into a full queue here could hang the exit
    _ = loop.tryPostEvent(.{ .pty_eof = .{ .id = id, .gen = gen } }) catch {};
}

/// The effective codepoint the way vaxis Key.matches sees it: a single-char
/// text wins (shift resolved by the terminal), else the shifted codepoint.
fn effCp(key: vaxis.Key) u21 {
    if (key.text) |t| {
        const view = std.unicode.Utf8View.init(t) catch return key.codepoint;
        var it = view.iterator();
        if (it.nextCodepoint()) |c| {
            if (it.nextCodepoint() == null) return c;
        }
    }
    return key.shifted_codepoint orelse key.codepoint;
}

/// vaxis functional-key codepoints -> core Key constants (ASCII ones already
/// coincide: enter/tab/escape/backspace pass through).
fn mapKey(cp: u21) u21 {
    return switch (cp) {
        vaxis.Key.up => pardes.Key.up,
        vaxis.Key.down => pardes.Key.down,
        vaxis.Key.left => pardes.Key.left,
        vaxis.Key.right => pardes.Key.right,
        vaxis.Key.home => pardes.Key.home,
        vaxis.Key.end => pardes.Key.end,
        vaxis.Key.page_up => pardes.Key.page_up,
        vaxis.Key.page_down => pardes.Key.page_down,
        vaxis.Key.delete => pardes.Key.delete,
        else => cp,
    };
}

fn vaxisStyle(s: pardes.CellStyle) vaxis.Style {
    return .{
        .fg = vaxisColor(s.fg),
        .bg = vaxisColor(s.bg),
        .bold = s.bold,
        .dim = s.dim,
        .italic = s.italic,
        .blink = s.blink,
        .reverse = s.reverse,
        .invisible = s.invisible,
        .strikethrough = s.strikethrough,
        .ul_style = switch (s.ul) {
            .off => .off,
            .single => .single,
            .double => .double,
            .curly => .curly,
            .dotted => .dotted,
            .dashed => .dashed,
        },
    };
}

fn vaxisColor(c: pardes.Color) vaxis.Color {
    return switch (c) {
        .default => .default,
        .index => |i| .{ .index = i },
        .rgb => |rgb| .{ .rgb = rgb },
    };
}

fn writeFile(path: [*:0]const u8, data: []const u8) void {
    const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644));
    if (fd < 0) return;
    defer _ = libc.close(fd);
    writeFd(fd, data);
}

fn writeFd(fd: c_int, data: []const u8) void {
    var off: usize = 0;
    while (off < data.len) {
        const n = libc.write(fd, data[off..].ptr, data.len - off);
        if (n < 0) {
            if (libc.errno(n) == .INTR) continue;
            return;
        }
        off += @intCast(n);
    }
}