summaryrefslogtreecommitdiff
path: root/src/ninep/pty.zig
blob: c7a32fbf7cfa2c1f354491033c37cb5147c210ef (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
//! A terminal pane's pty/: ctl (winsize, sig, exec), status and the raw data stream.
const std = @import("std");
const pardes = @import("../pardes.zig");
const tree = @import("tree.zig");
const pane_files = @import("pane.zig");

const Pardes = pardes.Pardes;
const Pane = pardes.Pane;
const Req = tree.Req;
const Reply = tree.Reply;
const E = tree.E;
const PaneFile = tree.PaneFile;

pub fn fileNamed(name: []const u8) ?PaneFile {
    if (std.mem.eql(u8, name, "ctl")) return .pty_ctl;
    if (std.mem.eql(u8, name, "status")) return .pty_status;
    if (std.mem.eql(u8, name, "data")) return .pty_data;
    if (std.mem.eql(u8, name, "run")) return .pty_run;
    return null;
}

const Verb = enum { winsize, sig, exec };

fn dimension(word: []const u8) ?u16 {
    if (word.len == 0 or word.len > 5) return null;
    for (word) |c| if (c < '0' or c > '9') return null;
    const n = std.fmt.parseInt(u16, word, 10) catch return null;
    return if (n == 0) null else n;
}

fn signalNamed(word: []const u8) ?pardes.PtySignal {
    if (std.mem.eql(u8, word, "INT")) return .int;
    if (std.mem.eql(u8, word, "TERM")) return .term;
    if (std.mem.eql(u8, word, "HUP")) return .hup;
    if (std.mem.eql(u8, word, "QUIT")) return .quit;
    if (std.mem.eql(u8, word, "KILL")) return .kill;
    return null;
}

pub fn writeCtl(p: *Pardes, req: Req, id: usize) Reply {
    for ([2]bool{ false, true }) |apply| {
        var it = std.mem.splitScalar(u8, req.data, '\n');
        while (it.next()) |raw| {
            const line = std.mem.trim(u8, raw, " \t\r");
            if (line.len == 0) continue;
            if (!verb(p, id, line, apply)) return tree.failText(req.tag, E.INVAL, tree.e_bad_ctl);
        }
    }
    return .{ .tag = req.tag, .written = @intCast(req.data.len) };
}

fn verb(p: *Pardes, id: usize, line: []const u8, apply: bool) bool {
    const pane = p.panes[id] orelse return false;
    var words = std.mem.tokenizeAny(u8, line, " \t");
    const v = std.meta.stringToEnum(Verb, words.next() orelse return false) orelse return false;
    switch (v) {
        .winsize => {
            const cols = dimension(words.next() orelse return false) orelse return false;
            const rows = dimension(words.next() orelse return false) orelse return false;
            if (words.next() != null) return false;
            if (!apply) return true;
            p.emit(.{ .resize_pty = .{ .pane = @intCast(id), .cols = cols, .rows = rows } });
        },
        .sig => {
            const which = signalNamed(words.next() orelse return false) orelse return false;
            if (words.next() != null) return false;
            if (!apply) return true;
            p.emit(.{ .signal_pty = .{ .pane = @intCast(id), .sig = which } });
        },
        .exec => {
            if (words.next() != null) return false;
            if (pane.cwdSlice().len > pardes.effect_path_cap) return false;
            if (!apply) return true;
            p.emit(.{ .spawn = .{ .pane = @intCast(id), .cwd = .from(pane.cwdSlice()) } });
        },
    }
    return true;
}

/// ctl reads back its state in the words it takes, as a Plan 9 ctl does.
pub fn readCtl(p: *Pardes, req: Req, pane: *Pane) Reply {
    p.fs.stage(p.gpa).print(p.gpa, "winsize {d} {d}\n", .{ pane.cols, pane.rows }) catch
        return Reply.fail(req.tag, E.NOMEM);
    return tree.stagedReply(p, req);
}

pub fn ctlLen(pane: *const Pane) u64 {
    var buf: [32]u8 = undefined;
    return (std.fmt.bufPrint(&buf, "winsize {d} {d}\n", .{ pane.cols, pane.rows }) catch unreachable).len;
}

/// Three right-aligned fields: cols, rows and whether the host holds the tty.
pub const status_len: u64 = 36;

pub fn readStatus(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply {
    const out = p.fs.stage(p.gpa);
    out.print(p.gpa, "{d:>11} {d:>11} {d:>11} ", .{
        pane.cols,
        pane.rows,
        @intFromBool(p.hostTtyTaken(id)),
    }) catch {};
    return tree.stagedReply(p, req);
}

// ---- run: one command line in, how it ended out ----
//
// factotum's rpc shape (factotum(4)): write a request on an open, read the
// answer on that same open, so the open is what ties a result to its
// command. The shell's own OSC 133 marks say when the command started (C)
// and ended (D, with its status); pardes injects them into bash and fish.

pub const run_slots = 8;

pub const Run = struct {
    /// 0 is a free slot.
    node: u64 = 0,
    phase: enum { idle, sent, done } = .idle,
    /// The shell's command count its C must reach for the end to be ours.
    want: u32 = 0,
    /// The shell's prompt count when the line went: a newer prompt with no
    /// C for it means the shell never ran the line.
    prompts: u32 = 0,
    /// The refused line was taken back off the prompt.
    cleared: bool = false,
    answer: [48]u8 = undefined,
    len: u8 = 0,
};

fn runOf(p: *Pardes, req: Req) ?*Run {
    if (req.handle == 0 or req.handle > run_slots) return null;
    const slot = &p.fs.runs[req.handle - 1];
    return if (slot.node == req.node) slot else null;
}

pub fn openRun(p: *Pardes, req: Req, serial: u32) Reply {
    _ = serial;
    for (&p.fs.runs, 0..) |*slot, i| {
        if (slot.node != 0) continue;
        slot.* = .{ .node = req.node };
        return .{ .tag = req.tag, .handle = @intCast(i + 1) };
    }
    return Reply.fail(req.tag, E.NFILE);
}

fn answer(slot: *Run, comptime fmt: []const u8, args: anytype) void {
    slot.len = @intCast((std.fmt.bufPrint(&slot.answer, fmt ++ "\n", args) catch unreachable).len);
    slot.phase = .done;
    pardes.turn.parked = true; // wake the read waiting on it
}

pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply {
    const slot = runOf(p, req) orelse return Reply.fail(req.tag, E.INVAL);
    if (slot.phase == .sent) return tree.failText(req.tag, 16, tree.e_in_use);
    const line = std.mem.trimEnd(u8, req.data, "\r\n");
    if (line.len == 0) return tree.failText(req.tag, E.INVAL, e_bad_line);
    for (line) |c| if (c < ' ' and c != '\t') return tree.failText(req.tag, E.INVAL, e_bad_line);
    const pf = &p.fs.panes[id];
    const state = pane.terminal orelse return tree.failText(req.tag, E.INVAL, e_bad_line);
    const marks = &state.stream.handler;
    if (pf.unmarked) {
        answer(slot, "error no prompt marks", .{});
    } else if (pf.run != null or !pardes.panes.Terminal.promptInputEmpty(pane) or p.hostTtyTaken(id)) {
        // Something is running, someone has typed at the prompt, or the
        // shell has not drawn its first one yet: sending now would type into
        // the middle of it.
        answer(slot, "busy", .{});
    } else {
        slot.want = marks.started +% 1;
        slot.prompts = marks.prompts;
        p.emitWrite(id, line);
        p.emitWrite(id, "\r");
        slot.phase = .sent;
        pf.run = @intCast(slot - &p.fs.runs[0]);
    }
    return .{ .tag = req.tag, .written = @intCast(req.data.len) };
}

pub fn readRun(p: *Pardes, req: Req) Reply {
    const slot = runOf(p, req) orelse return Reply.fail(req.tag, E.INVAL);
    switch (slot.phase) {
        .idle => return .{ .tag = req.tag, .payload = .{ .staged = 0 } },
        .sent => return .{ .tag = req.tag, .status = .again },
        .done => {},
    }
    const text = slot.answer[0..slot.len];
    const off = @min(req.off, text.len);
    const n = @min(text.len - off, req.size);
    p.fs.stage(p.gpa).appendSlice(p.gpa, text[off..][0..n]) catch return Reply.fail(req.tag, E.NOMEM);
    return .{ .tag = req.tag, .payload = .{ .staged = @intCast(n) } };
}

pub fn releaseRun(p: *Pardes, req: Req) Reply {
    const slot = runOf(p, req) orelse return .{ .tag = req.tag };
    const idx: u8 = @intCast(slot - &p.fs.runs[0]);
    // The command runs on in the shell; nobody is waiting for it any more.
    for (&p.fs.panes) |*pf| if (pf.run == idx) {
        pf.run = null;
    };
    slot.* = .{};
    return .{ .tag = req.tag };
}

/// After each chunk of a terminal's output: once the command the run sent
/// has ended and the shell is back at a prompt, the run answers how. Waiting
/// for the prompt means whoever reads the answer can send the next command
/// at once instead of finding the shell still drawing it.
pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void {
    if (comptime !pardes.panes.Terminal.enabled) return;
    const state = pane.terminal orelse return;
    const pf = &p.fs.panes[id];
    const slot = &p.fs.runs[pf.run orelse return];
    const marks = &state.stream.handler;
    if (marks.phase != .input) return;
    // ponytail: a prompt redrawn before the command starts (a resize in that
    // instant) reads as not run; a per-command id in the marks would tell.
    if (marks.started != slot.want and marks.prompts != slot.prompts) {
        // fish keeps a refused line on the prompt for editing; it is the one
        // this run typed into an empty prompt, so take it back (Ctrl-U), and
        // answer once it is gone so the next line finds the prompt clear.
        if (!pardes.panes.Terminal.promptInputEmpty(pane)) {
            if (!slot.cleared) p.emitWrite(id, "\x15");
            slot.cleared = true;
            return;
        }
        answer(slot, "error not run", .{});
        pf.run = null;
        return;
    }
    const done = marks.finished orelse return;
    if (done.seq != slot.want) return;
    if (done.status) |status| answer(slot, "exit {d}", .{status}) else answer(slot, "exit", .{});
    pf.run = null;
}

/// The pane closed or its shell was replaced: the command's end will never
/// be reported, so the run says so instead of waiting forever.
pub fn shellGone(p: *Pardes, id: usize) void {
    const pf = &p.fs.panes[id];
    const idx = pf.run orelse return;
    answer(&p.fs.runs[idx], "error shell gone", .{});
    pf.run = null;
}

const e_bad_line = "bad command line";

pub fn readData(p: *Pardes, req: Req, pf: *pane_files.State) Reply {
    if (pf.pty_out.empty()) return .{ .tag = req.tag, .status = .again };
    const out = p.fs.stage(p.gpa);
    while (out.items.len < req.size) {
        const chunk = pf.pty_out.peek() orelse break;
        const n = @min(chunk.len, req.size - out.items.len);
        out.appendSlice(p.gpa, chunk[0..n]) catch break;
        pf.pty_out.popFront(n);
    }
    return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } };
}

pub fn writeData(p: *Pardes, req: Req, id: usize) Reply {
    if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 };
    const take = pane_files.wholeUtf8(req.data);
    p.emitWrite(id, req.data[0..take]);
    return .{ .tag = req.tag, .written = @intCast(take) };
}

// ---- tests ----

const testing = std.testing;
const th = @import("testing.zig");
const events = @import("events.zig");
const call = th.call;
const rd = th.rd;
const wr = th.wr;
const rdir = th.rdir;
const look_up = th.look_up;
const withFile = th.withFile;
const withTerm = th.withTerm;
const serialOf = th.serialOf;
const Node = tree.Node;
const Status = tree.Status;

test "a pane that is not a terminal has no pty/ at all" {
    const gpa = testing.allocator;
    const p = try withFile(gpa, "hello\n");
    defer p.deinit();
    const serial = serialOf(p);
    const dir = Node.of(serial, .dir);

    try testing.expectEqual(E.NOENT, look_up(p, dir, "pty").errno());
    try testing.expectEqual(E.NOENT, call(p, .{
        .tag = 1,
        .op = .getattr,
        .node = Node.of(serial, .pty),
    }).errno());
    try testing.expectEqual(E.NOENT, rd(p, Node.of(serial, .pty_status), 0, 256).errno());
    try testing.expectEqual(E.NOENT, wr(p, Node.of(serial, .pty_ctl), "winsize 80 24\n").errno());
    try testing.expectEqual(E.NOENT, rdir(p, Node.of(serial, .pty), 0).errno());
    try testing.expectEqual(E.NOENT, call(p, .{
        .tag = 2,
        .op = .open,
        .node = Node.of(serial, .pty_data),
    }).errno());
    try testing.expectEqual(@as(u16, 0), p.fs.panes[0].pty_readers);

    var buf: [32]th.Dirent = undefined;
    const files = th.dirents(rdir(p, dir, 0).bytes, &buf);
    try testing.expectEqual(@as(usize, 17), files.len);
    try testing.expect(th.nameAt(files, "pty") == null);

    try testing.expectEqual(E.NOENT, look_up(p, dir, "pty_ctl").errno());
    try testing.expectEqual(E.NOENT, look_up(p, dir, "status").errno());
}

test "a terminal pane's pty/ holds exactly ctl, status and data" {
    const gpa = testing.allocator;
    const p = try withTerm(gpa);
    defer p.deinit();
    const serial = serialOf(p);
    const dir = Node.of(serial, .dir);

    const pty = look_up(p, dir, "pty");
    try testing.expectEqual(Node.of(serial, .pty), pty.reply.attr.node);
    try testing.expect(pty.reply.attr.dir);
    try testing.expectEqual(@as(u16, 0o755), pty.reply.attr.mode);

    var buf: [32]th.Dirent = undefined;
    const files = th.dirents(rdir(p, dir, 0).bytes, &buf);
    try testing.expectEqual(@as(usize, 18), files.len);
    try testing.expect(th.nameAt(files, "pty").?.dir);

    const inside = th.dirents(rdir(p, Node.of(serial, .pty), 0).bytes, &buf);
    try testing.expectEqual(@as(usize, 4), inside.len);
    try testing.expectEqualStrings("ctl", inside[0].name);
    try testing.expectEqualStrings("status", inside[1].name);
    try testing.expectEqualStrings("data", inside[2].name);
    try testing.expectEqualStrings("run", inside[3].name);
    for (inside) |d| try testing.expect(!d.dir);
    try testing.expectEqual(Node.of(serial, .pty_data), inside[2].node);

    const ctl = look_up(p, Node.of(serial, .pty), "ctl");
    try testing.expectEqual(Node.of(serial, .pty_ctl), ctl.reply.attr.node);
    try testing.expectEqual(@as(u16, 0o666), ctl.reply.attr.mode);
    try testing.expectEqual(@as(u16, 0o444), look_up(p, Node.of(serial, .pty), "status").reply.attr.mode);
    try testing.expectEqual(E.NOENT, look_up(p, Node.of(serial, .pty), "body").errno());
    try testing.expectEqual(E.NOENT, look_up(p, Node.of(serial, .pty), "pty").errno());

    try testing.expectEqual(E.NOTDIR, look_up(p, Node.of(serial, .pty_ctl), "x").errno());
    try testing.expectEqual(E.NOTDIR, rdir(p, Node.of(serial, .pty_ctl), 0).errno());
    try testing.expectEqual(E.PERM, rd(p, Node.of(serial, .pty), 0, 16).errno());
    try testing.expect(std.mem.startsWith(u8, rd(p, Node.of(serial, .pty_ctl), 0, 64).bytes, "winsize "));
    try testing.expectEqual(E.PERM, wr(p, Node.of(serial, .pty_status), "x").errno());
}

test "every pty/ctl verb, and every refusal" {
    const gpa = testing.allocator;
    const p = try withTerm(gpa);
    defer p.deinit();
    const ctl = Node.of(serialOf(p), .pty_ctl);

    const pane = p.panes[0].?;
    const cols = pane.cols;
    const rows = pane.rows;
    var said: [32]u8 = undefined;
    try testing.expectEqualStrings(try std.fmt.bufPrint(&said, "winsize {d} {d}\n", .{ cols, rows }), rd(p, ctl, 0, 64).bytes);
    const ws = wr(p, ctl, "winsize 132 44\n");
    try testing.expectEqual(@as(u32, "winsize 132 44\n".len), ws.reply.written);
    try testing.expectEqual(@as(u16, 132), ws.winsize.?.cols);
    try testing.expectEqual(@as(u16, 44), ws.winsize.?.rows);
    try testing.expectEqual(cols, pane.cols);
    try testing.expectEqual(rows, pane.rows);

    for ([_]struct { line: []const u8, want: pardes.PtySignal }{
        .{ .line = "sig INT", .want = .int },
        .{ .line = "sig TERM", .want = .term },
        .{ .line = "sig HUP", .want = .hup },
        .{ .line = "sig QUIT", .want = .quit },
        .{ .line = "sig KILL", .want = .kill },
    }) |c| {
        const a = wr(p, ctl, c.line);
        try testing.expectEqual(Status.ok, a.reply.status);
        try testing.expectEqual(c.want, a.signal.?);
    }

    const ex = wr(p, ctl, "exec\n");
    try testing.expectEqual(Status.ok, ex.reply.status);
    try testing.expect(ex.spawned);

    const both = wr(p, ctl, "winsize 100 30\nsig TERM");
    try testing.expectEqual(@as(u16, 100), both.winsize.?.cols);
    try testing.expectEqual(pardes.PtySignal.term, both.signal.?);

    for ([_][]const u8{
        "winsize", // no arguments
        "winsize 80", // one argument
        "winsize 80 24 extra", // three
        "winsize 0 24", // zero is "unknown", never a width
        "winsize 80 0",
        "winsize -1 24", // not a decimal
        "winsize 999999 24", // wider than a u16
        "sig", // no name
        "sig INT TERM", // two
        "sig SIGINT",
        "sig int", // lower case
        "sig 9", // a number is one platform's number
        "sig USR1", // a real signal, deliberately not offered
        "exec /bin/sh", // the effect carries no argv; refused, never ignored
        "raw",
        "cooked",
        "winsize 80 24\nbogus", // a good verb beside a bad one
        "bogus\nwinsize 80 24",
        "look x", // a pane command; pty/ctl shares none of that vocabulary
        "exec Del",
    }) |bad| {
        const a = wr(p, ctl, bad);
        try testing.expectEqual(E.INVAL, a.errno());
        try testing.expect(a.winsize == null);
        try testing.expect(a.signal == null);
        try testing.expect(!a.spawned);
    }

    const spaced = wr(p, ctl, "\n  winsize 90 20  \n\n");
    try testing.expectEqual(Status.ok, spaced.reply.status);
    try testing.expectEqual(@as(u16, 90), spaced.winsize.?.cols);
    try testing.expectEqual(Status.ok, wr(p, ctl, "").reply.status);
}

test "owned cwd pty exec rejects long paths before applying its batch" {
    const p = try withTerm(testing.allocator);
    defer p.deinit();
    const pane = p.panes[0].?;
    const ctl = Node.of(pane.serial, .pty_ctl);
    var path: [1025]u8 = @splat('d');
    path[0] = '/';
    p.setCwd(0, &path);
    for ([_][]const u8{ "exec\n", "winsize 100 30\nexec\n", "sig TERM\nexec\n" }) |command| {
        const result = wr(p, ctl, command);
        try testing.expectEqual(E.INVAL, result.errno());
        try testing.expect(!result.spawned);
        try testing.expect(result.signal == null and result.winsize == null);
    }
    try testing.expectEqualStrings(&path, pane.cwdSlice());
    p.setCwd(0, path[0..pardes.effect_path_cap]);
    const accepted = wr(p, ctl, "exec\n");
    try testing.expectEqual(Status.ok, accepted.reply.status);
    try testing.expect(accepted.spawned);
}

test "pty/status reports the grid and who holds the tty" {
    const gpa = testing.allocator;
    const p = try withTerm(gpa);
    defer p.deinit();
    const pane = p.panes[0].?;
    const status = Node.of(pane.serial, .pty_status);

    const a = rd(p, status, 0, 256);
    try testing.expectEqual(Status.ok, a.reply.status);
    var want: [64]u8 = undefined;
    const whole = try std.fmt.bufPrint(&want, "{d:>11} {d:>11} {d:>11} ", .{ pane.cols, pane.rows, 0 });
    try testing.expectEqualStrings(whole, a.bytes);
    try testing.expectEqual(@as(usize, 3 * 12), a.bytes.len);
    try testing.expectEqualStrings(whole[12..], rd(p, status, 12, 256).bytes);

    var probe: th.FakeTty = .{ .taken = true };
    p.host = .{ .ctx = &probe, .vtable = &th.FakeTty.vtable };
    const held = rd(p, status, 0, 256);
    try testing.expectEqualStrings(
        try std.fmt.bufPrint(&want, "{d:>11} {d:>11} {d:>11} ", .{ pane.cols, pane.rows, 1 }),
        held.bytes,
    );
}

test "pty/data writes at the shell and reads the raw stream" {
    const gpa = testing.allocator;
    const p = try withTerm(gpa);
    defer p.deinit();
    const serial = serialOf(p);
    const data = Node.of(serial, .pty_data);

    const w = call(p, .{ .tag = 2, .op = .write, .node = data, .off = 999, .data = "ls -l\r" });
    try testing.expectEqual(@as(u32, 6), w.reply.written);
    try testing.expectEqualStrings("ls -l\r", w.pty());
    try testing.expectEqual(@as(u32, 1), wr(p, data, "a\xC3").reply.written);
    try testing.expectEqual(@as(u32, 0), wr(p, data, "").reply.written);

    try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status);

    p.update(.{ .output = .{ .pane = 0, .bytes = "unwatched" } });
    while (p.nextEffect()) |_| {}
    try testing.expectEqual(@as(usize, 0), p.fs.panes[0].pty_out.buf.items.len);
    try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status);

    // An open that only writes is not a reader: nothing queues for it.
    const writer = call(p, .{ .tag = 4, .op = .open, .node = data, .omode = 1 });
    try testing.expectEqual(@as(u16, 0), p.fs.panes[0].pty_readers);
    _ = call(p, .{ .tag = 4, .op = .release, .node = data, .handle = writer.reply.handle });

    const reader = call(p, .{ .tag = 5, .op = .open, .node = data });
    try testing.expectEqual(@as(u16, 1), p.fs.panes[0].pty_readers);
    try testing.expectEqual(@as(u16, 0), p.fs.listeners);
    try testing.expect(!p.fs.scripted(0));

    p.update(.{ .output = .{ .pane = 0, .bytes = "hello" } });
    while (p.nextEffect()) |_| {}
    try testing.expectEqualStrings("hello", rd(p, data, 0, 64).bytes);
    try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status);

    p.update(.{ .output = .{ .pane = 0, .bytes = "abcdef" } });
    while (p.nextEffect()) |_| {}
    try testing.expectEqualStrings("ab", rd(p, data, 0, 2).bytes);
    try testing.expectEqualStrings("cd", rd(p, data, 0, 2).bytes);
    p.update(.{ .output = .{ .pane = 0, .bytes = "ghi" } });
    while (p.nextEffect()) |_| {}
    try testing.expectEqualStrings("efghi", rd(p, data, 0, 64).bytes);

    p.update(.{ .output = .{ .pane = 0, .bytes = "orphan" } });
    while (p.nextEffect()) |_| {}
    _ = call(p, .{ .tag = 6, .op = .release, .node = data, .handle = reader.reply.handle });
    try testing.expectEqual(@as(u16, 0), p.fs.panes[0].pty_readers);
    try testing.expectEqual(@as(usize, 0), p.fs.panes[0].pty_out.buf.capacity);
    try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status);

    // A second reader would take half the stream from the first: refused.
    _ = call(p, .{ .tag = 7, .op = .open, .node = data });
    const second = call(p, .{ .tag = 8, .op = .open, .node = data, .omode = 2 });
    try testing.expectEqual(Status.err, second.reply.status);
    try testing.expectEqualStrings(tree.e_in_use, second.reply.ename);
    try testing.expectEqual(@as(u16, 1), p.fs.panes[0].pty_readers);
    p.update(.{ .output = .{ .pane = 0, .bytes = "still" } });
    while (p.nextEffect()) |_| {}
    try testing.expectEqualStrings("still", rd(p, data, 0, 64).bytes);
}

test "run answers how its command ended once the shell is back at a prompt" {
    const gpa = testing.allocator;
    const p = try withTerm(gpa);
    defer p.deinit();
    const node = Node.of(serialOf(p), .pty_run);
    const out = struct {
        fn put(pp: *Pardes, bytes: []const u8) void {
            pp.update(.{ .output = .{ .pane = 0, .bytes = bytes } });
            while (pp.nextEffect()) |_| {}
        }
    };
    const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";

    // Before its first prompt the shell cannot take a line: busy, at once.
    const early = call(p, .{ .tag = 1, .op = .open, .node = node });
    _ = call(p, .{ .tag = 2, .op = .write, .node = node, .handle = early.reply.handle, .data = "true\n" });
    try testing.expectEqualStrings("busy\n", call(p, .{ .tag = 3, .op = .read, .node = node, .handle = early.reply.handle, .size = 64 }).bytes);
    _ = call(p, .{ .tag = 4, .op = .release, .node = node, .handle = early.reply.handle });

    out.put(p, prompt);
    const r = call(p, .{ .tag = 5, .op = .open, .node = node });
    const h = r.reply.handle;
    const sent = call(p, .{ .tag = 6, .op = .write, .node = node, .handle = h, .data = "make\n" });
    try testing.expectEqualStrings("make\r", sent.pty());
    try testing.expectEqual(Status.again, call(p, .{ .tag = 7, .op = .read, .node = node, .handle = h, .size = 64 }).reply.status);
    // A second line on the same open while the first runs is refused.
    try testing.expectEqual(Status.err, call(p, .{ .tag = 8, .op = .write, .node = node, .handle = h, .data = "ls\n" }).reply.status);

    // Untagged marks (fish's own, a nested shell's, a file being printed)
    // and bash's C from its PROMPT_COMMAND trap change nothing.
    out.put(p, "\x1b]133;D;9\x07\x1b]133;C;aid=pardes\x07building\r\n");
    out.put(p, "\x1b]133;C;aid=pardes\x07\x1b]133;D;2;aid=pardes\x07");
    try testing.expectEqual(Status.again, call(p, .{ .tag = 9, .op = .read, .node = node, .handle = h, .size = 64 }).reply.status);
    out.put(p, prompt);
    try testing.expectEqualStrings("exit 2\n", call(p, .{ .tag = 10, .op = .read, .node = node, .handle = h, .size = 64 }).bytes);
    // The answer stays for a re-read until the open closes.
    try testing.expectEqualStrings("exit 2\n", call(p, .{ .tag = 11, .op = .read, .node = node, .handle = h, .size = 64 }).bytes);
    _ = call(p, .{ .tag = 12, .op = .release, .node = node, .handle = h });

    // Typed text on the prompt line: busy, rather than typing into it.
    out.put(p, "ls -");
    const typed = call(p, .{ .tag = 13, .op = .open, .node = node });
    _ = call(p, .{ .tag = 14, .op = .write, .node = node, .handle = typed.reply.handle, .data = "true\n" });
    try testing.expectEqualStrings("busy\n", call(p, .{ .tag = 15, .op = .read, .node = node, .handle = typed.reply.handle, .size = 64 }).bytes);
    _ = call(p, .{ .tag = 16, .op = .release, .node = node, .handle = typed.reply.handle });
    out.put(p, "\x08\x08\x08\x08\x1b[K");

    // A line the shell refuses without running it (fish on a syntax error):
    // a fresh prompt and no C. Waiting for a D would wait forever.
    const refused = call(p, .{ .tag = 21, .op = .open, .node = node });
    _ = call(p, .{ .tag = 22, .op = .write, .node = node, .handle = refused.reply.handle, .data = "(exit 7)\n" });
    out.put(p, "\r\nfish: command substitutions not allowed\r\n" ++ prompt);
    try testing.expectEqualStrings("error not run\n", call(p, .{ .tag = 23, .op = .read, .node = node, .handle = refused.reply.handle, .size = 64 }).bytes);
    _ = call(p, .{ .tag = 24, .op = .release, .node = node, .handle = refused.reply.handle });

    // The pane going away while a command runs ends the wait.
    out.put(p, "\r\n" ++ prompt);
    const gone = call(p, .{ .tag = 17, .op = .open, .node = node });
    _ = call(p, .{ .tag = 18, .op = .write, .node = node, .handle = gone.reply.handle, .data = "sleep 9\n" });
    try p.removePane(0, null);
    try testing.expectEqualStrings("error shell gone\n", call(p, .{ .tag = 19, .op = .read, .node = node, .handle = gone.reply.handle, .size = 64 }).bytes);
    _ = call(p, .{ .tag = 20, .op = .release, .node = node, .handle = gone.reply.handle });
    for (p.fs.runs) |slot| try testing.expect(slot.node == 0);
}

test "the pty queue drops the oldest at its cap" {
    const gpa = testing.allocator;
    const p = try withTerm(gpa);
    defer p.deinit();
    const data = Node.of(serialOf(p), .pty_data);
    _ = call(p, .{ .tag = 5, .op = .open, .node = data });

    const oldest: [4096]u8 = @splat('A');
    const rest: [4096]u8 = @splat('B');
    events.notePtyOutput(p, 0, &oldest);
    for (0..events.queue_cap / rest.len + 4) |_| events.notePtyOutput(p, 0, &rest);
    const q = &p.fs.panes[0].pty_out;
    try testing.expect(q.buf.items.len - q.head <= events.queue_cap);

    var seen: usize = 0;
    while (true) {
        const a = rd(p, data, 0, 1 << 16);
        if (a.reply.status == .again) break;
        try testing.expect(std.mem.indexOfScalar(u8, a.bytes, 'A') == null);
        if (a.bytes.len == 0) break;
        seen += a.bytes.len;
    }
    try testing.expect(seen > 0 and seen <= events.queue_cap);
}