summaryrefslogtreecommitdiff
path: root/core/jj.zig
blob: a381443cf39cf7a3465b941216218403f2e4f033 (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
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
//! A file at a revision, as jj shows it (PARDES.md "Changes on the source
//! view"): the address `path@rev`, with a place `path@rev:line`, which a
//! Look resolves anywhere, and `At <rev>` in a file's pane.
//!
//! What jj says is the session machine's: it is run out of the turn as a
//! site of the step's tape (`Site.jj`), its answer recorded; a replica
//! replays the answer and never runs jj. A revision's pane is an output
//! (`Output.Origin.revision`, its argument the revision), named
//! `path@rev`, coloured as its file (File.langPath), read-only (File.edit
//! refuses its text a change; a bare Save says why).
const std = @import("std");
const pardes = @import("root.zig");
const Pardes = pardes.Pardes;
const Pane = pardes.Pane;
const File = pardes.panes.File;
const Output = pardes.panes.Output;
const look = @import("look.zig");
const layout = @import("layout.zig");
const diff = @import("diff.zig");

/// What jj answered: why not, in its own words (its first line, without
/// `Error: `), or the file's bytes. The caller's, in the allocator the site
/// was given.
pub const Shown = union(enum) { refused: []u8, bytes: []u8 };

/// The longest text a revision's pane takes.
const bytes_max = 256 << 20;

/// `text`, not a file of its own, read as `path@rev`: the text before its
/// first `@` the path, the rest the revision (`main`, `@-`, `main@origin`).
pub fn split(text: []const u8) ?struct { path: []const u8, rev: []const u8 } {
    const at = std.mem.indexOfScalar(u8, text, '@') orelse return null;
    if (at == 0 or at + 1 == text.len or text[at - 1] == '/') return null;
    return .{ .path = text[0..at], .rev = text[at + 1 ..] };
}

/// The file at `path` (absolute) at revision `rev`, as jj shows it.
pub fn show(p: *Pardes, path: []const u8, rev: []const u8) Shown {
    const set = fileset(p.scratch.allocator(), path) catch return refusal(p.gpa, "out of memory");
    return p.tape.site(.jj, p.gpa, runHost, .{ p.gpa, dirOf(path), @as([]const []const u8, &.{ "file", "show", "-r", rev, "--", set }) });
}

fn dirOf(path: []const u8) []const u8 {
    return std.Io.Dir.path.dirname(path) orelse "/";
}

/// The name of `path` as a fileset of that one file in its directory,
/// taken literally whatever it is called.
fn fileset(arena: std.mem.Allocator, path: []const u8) ![]u8 {
    var set: std.ArrayList(u8) = .empty;
    try set.appendSlice(arena, "file:\"");
    for (std.Io.Dir.path.basename(path)) |c| {
        if (c == '"' or c == '\\') try set.append(arena, '\\');
        try set.append(arena, c);
    }
    try set.append(arena, '"');
    return set.toOwnedSlice(arena);
}

/// jj with `args`, run in `dir`: what it printed, or its refusal. The
/// working copy is left alone (`--ignore-working-copy`): an editor's read
/// makes no operation, and `@` is the working copy as jj last saw it.
fn runHost(gpa: std.mem.Allocator, dir: []const u8, args: []const []const u8) Shown {
    // The tape's io spawns nothing (its allocator fails, its environment is
    // empty): one of its own, with this process's environment.
    var threaded: std.Io.Threaded = .init_single_threaded;
    threaded.allocator = gpa;
    threaded.environ = .{ .process_environ = .{ .block = .{ .slice = std.mem.span(std.c.environ) } } };
    threaded.environ_initialized = false;
    const io = threaded.io();
    var argv: std.ArrayList([]const u8) = .empty;
    defer argv.deinit(gpa);
    argv.appendSlice(gpa, &.{ "jj", "--ignore-working-copy", "--color=never", "--no-pager" }) catch return refusal(gpa, "out of memory");
    argv.appendSlice(gpa, args) catch return refusal(gpa, "out of memory");
    // As Stream's children: this thread's mask is the child's.
    const none = std.posix.sigemptyset();
    var kept: std.posix.sigset_t = undefined;
    std.posix.sigprocmask(std.posix.SIG.SETMASK, &none, &kept);
    var child = std.process.spawn(io, .{ .argv = argv.items, .cwd = .{ .path = dir }, .stdin = .ignore, .stdout = .pipe, .stderr = .pipe }) catch |err| {
        std.posix.sigprocmask(std.posix.SIG.SETMASK, &kept, null);
        return refusal(gpa, if (err == error.FileNotFound) "no jj" else @errorName(err));
    };
    std.posix.sigprocmask(std.posix.SIG.SETMASK, &kept, null);
    defer child.kill(io);
    // One after the other, on an io with no thread to read both at once:
    // jj says a refusal in a line and nothing on stdout.
    var out: std.ArrayList(u8) = .empty;
    defer out.deinit(gpa);
    var err: std.ArrayList(u8) = .empty;
    defer err.deinit(gpa);
    for ([_]std.Io.File{ child.stdout.?, child.stderr.? }, [_]*std.ArrayList(u8){ &out, &err }, [_]usize{ bytes_max, 64 << 10 }) |from, to, cap| {
        var chunk: [64 * 1024]u8 = undefined;
        while (to.items.len <= cap) {
            const n = from.readStreaming(io, &.{&chunk}) catch break;
            if (n == 0) break;
            to.appendSlice(gpa, chunk[0..n]) catch return refusal(gpa, "out of memory");
        }
    }
    const term = child.wait(io) catch |e| return refusal(gpa, @errorName(e));
    if (out.items.len > bytes_max) return refusal(gpa, "too much to show");
    if (term == .exited and term.exited == 0) return .{ .bytes = out.toOwnedSlice(gpa) catch return refusal(gpa, "out of memory") };
    var first = std.mem.trim(u8, err.items[0 .. std.mem.indexOfScalar(u8, err.items, '\n') orelse err.items.len], " \t\r");
    if (std.mem.startsWith(u8, first, "Error: ")) first = first["Error: ".len..];
    return refusal(gpa, if (first.len > 0) first else "jj failed");
}

fn refusal(gpa: std.mem.Allocator, why: []const u8) Shown {
    return .{ .refused = gpa.dupe(u8, why) catch &.{} };
}

/// A revision's pane: the file it is of (its name without `@rev`) and the
/// revision. Null for any other pane.
pub fn of(f: *const File.State) ?struct { path: []const u8, rev: []const u8 } {
    // The pane's own, not a copy: the revision is a slice of it.
    const o = if (f.output) |*o| o else return null;
    if (o.from != .revision) return null;
    return .{ .path = f.path[0 .. f.path.len - o.arg().len - 1], .rev = o.arg() };
}

/// `path` (absolute) at `rev` in a pane: the one showing it focused, else
/// one made beside pane `near` (or, with `replace`, in its place: it goes),
/// wearing `near`'s layers; its cursor on line `line` (0: the first). Said
/// at `near` when jj refuses. The pane's id.
pub fn open(p: *Pardes, near: usize, path: []const u8, rev: []const u8, at: look.Spot, replace: bool) ?usize {
    const name = std.fmt.allocPrint(p.scratch.allocator(), "{s}@{s}", .{ path, rev }) catch return null;
    for (p.panes, 0..) |slot, i| if (slot) |shown| if (shown.file) |*f| if (of(f) != null and std.mem.eql(u8, f.path, name)) {
        look.focusPaneLine(p, i, at, .center);
        return i;
    };
    if (rev.len > Output.max_arg) return refused(p, near, "a revision that long");
    const free = p.freeSlot() orelse {
        p.reportError(.at(near), "At", error.NoPaneSlots);
        return null;
    };
    const bytes = switch (show(p, path, rev)) {
        .refused => |why| {
            defer p.gpa.free(why);
            return refused(p, near, why);
        },
        .bytes => |b| b,
    };
    const pane = Output.open(p, free, std.Io.Dir.path.dirname(path) orelse "/", .revision, rev, bytes) catch |err| {
        p.gpa.free(bytes);
        p.reportError(.at(near), "At", err);
        return null;
    };
    const f = &pane.file.?;
    const owned = p.gpa.dupe(u8, name) catch {
        p.removePane(free, near) catch {};
        return null;
    };
    p.gpa.free(f.path);
    f.path = owned;
    if (p.panes[near]) |from| pane.layers = from.layers;
    layout.placeNew(p, near, near, free, .doc);
    if (replace) p.removePane(near, free) catch |err| p.reportError(.at(free), "At", err);
    layout.compute(p);
    // Sized for its place before it is centred there.
    p.sync();
    look.focusPaneLine(p, free, at, .center);
    return free;
}

fn refused(p: *Pardes, id: usize, why: []const u8) ?usize {
    var line: pardes.Kind.Buf(512) = .{};
    p.reportFailure(id, line.print("At: {s}", .{why[0..@min(why.len, 480)]}));
    return null;
}

/// The `At` word (builtins.zig registers it): in a file's pane, that file
/// at revision `rev` beside it; in a revision's pane, the same file at
/// `rev` in its place, its cursor's line kept; bare there, the file.
pub fn word(c: pardes.builtins.Ctx) void {
    const p = c.p;
    const f = if (c.pane.file) |*file| file else return p.reportFailure(c.id, "At: only a file's pane takes it");
    const rev = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
    const at: look.Spot = .{ .line = @intCast(@max(0, c.pane.body.cur_row) + 1) };
    if (of(f)) |r| {
        if (rev.len == 0) return look.lookAt(p, c.id, r.path);
        const path = p.scratch.allocator().dupe(u8, r.path) catch return;
        _ = open(p, c.id, path, rev, at, true);
        return;
    }
    if (f.output != null or pardes.filesystem.localPath(f.path) == null) return p.reportFailure(c.id, "At: only a file's pane takes it");
    if (rev.len == 0) return p.reportFailure(c.id, "At: which revision?");
    _ = open(p, c.id, f.path, rev, at, false);
}

/// A Look at `text` (a path relative to `dir`, then `@rev`) that names no
/// file: a file at a revision, if the path is a file. False when it is not
/// one, for the look to go on.
pub fn looked(p: *Pardes, id: usize, dir: []const u8, text: []const u8, at: look.Spot) bool {
    const r = split(text) orelse return false;
    const path = std.Io.Dir.path.resolvePosix(p.scratch.allocator(), &.{ dir, r.path }) catch return false;
    if (pardes.filesystem.localPath(path) == null or pardes.exec.kindOf(p.tape, path) != .file) return false;
    _ = open(p, id, path, r.rev, at, false);
    return true;
}

// ---- `Changes [revset]` (PARDES.md: pinned changes as lanes): what jj
// answers for it, kept as flat arrays, the session's ----

/// What jj answered for a pane's `Changes`: replicated state, the
/// session's (`Pardes.changes`, by the pane's serial: a client never runs
/// jj; one that joins late has it in the dump), its revset with it, drawn
/// by each view that shows them (File.Layers.lanes: a view holds that, not
/// the revset; one set a pane, so a view's `Changes other` replaces what
/// every view shows). From two jj runs off the loop (`Ask`): the changes
/// with their diffs of the file (`jj log -p --git`, the diffs read with
/// diff.zig's walk), and who wrote each line of the shown revision (`jj
/// file annotate`).
pub const Changes = struct {
    pub const replica = .{ .len = .{.{ "revset", "revset_len" }} };
    /// The pane's (its serial).
    serial: u32,
    revset: [revset_max]u8 = undefined,
    revset_len: u8 = 0,
    /// The revset's changes that touch the file, oldest first.
    pins: []Pin = &.{},
    /// A value a line of the shown revision.
    lines: []Line = &.{},
    /// Each pin's hunks in the file, a pin's together, each in place order.
    hunks: []Hunk = &.{},
    /// The lines the hunks took away, hunk after hunk, each with its `\n`.
    removed: []u8 = &.{},

    pub fn deinit(c: *Changes, gpa: std.mem.Allocator) void {
        gpa.free(c.pins);
        gpa.free(c.lines);
        gpa.free(c.hunks);
        gpa.free(c.removed);
        c.* = .{ .serial = c.serial };
    }

    pub fn pinned(c: *const Changes) []const u8 {
        return c.revset[0..c.revset_len];
    }

    pub const revset_max = 64;
};

/// What jj answered for pane `serial`'s `Changes` (`Pardes.changes`), if anything.
pub fn answered(p: *Pardes, serial: u32) ?*Changes {
    for (p.changes.items) |*c| if (c.serial == serial) return c;
    return null;
}

/// Pane `serial`'s answers let go (the pane's end).
pub fn forget(p: *Pardes, serial: u32) void {
    for (p.changes.items, 0..) |*c, i| if (c.serial == serial) {
        c.deinit(p.gpa);
        _ = p.changes.swapRemove(i);
        return;
    };
}

/// A pinned change, as `jj log` says it.
pub const Pin = struct {
    pub const replica = .{ .len = .{ .{ "author", "author_len" }, .{ "title", "title_len" } } };
    id: [8]u8,
    /// Its author's time, in seconds since the epoch.
    time: i64,
    author: [32]u8 = undefined,
    author_len: u8 = 0,
    /// Its description's first line, cut to fit.
    title: [96]u8 = undefined,
    title_len: u8 = 0,
};

/// A line of the shown revision: which pin wrote it (its place in
/// `Changes.pins`) or none, and whether that pin added it whole (no line
/// it took away stood in its place) or changed one.
pub const Line = struct {
    pin: PinIndex,
    whole: bool = false,
    /// The pins whose lanes run down it, outermost (oldest) first (`nest`).
    lanes: [levels]PinIndex = @splat(.none),
};

/// The lanes a row shows at most: the ruled gutter fits three.
pub const levels = 3;

pub const PinIndex = enum(u16) {
    none = std.math.maxInt(u16),
    _,
};

/// The changes a `Changes` takes at most.
pub const pins_max = 64;

/// A run of lines a pin took away and wrote in their place, in its own
/// revisions' numbers (from 1; `old_len` 0: it only wrote, after old line
/// `old_start`).
pub const Hunk = struct {
    pin: u16,
    old_start: u32,
    old_len: u32,
    new_start: u32,
    new_len: u32,
    /// Its removed lines' text: `Changes.removed[removed..][0..removed_len]`.
    removed: u32,
    removed_len: u32,
};

/// The `Changes` word (builtins.zig registers it): in a file's pane (or a
/// revision's), the changes `revset` names pinned on the pane and shown in
/// this view; another revset replaces them (in every view that shows
/// them). Bare: shown in this view or not, the pane's pinned ones (none
/// yet: `@`, the change against its parent). What jj refuses is said in
/// its words.
pub fn changesWord(c: pardes.builtins.Ctx) void {
    const p = c.p;
    const pane = c.pane;
    const f = if (pane.file) |*file| file else return p.reportFailure(c.id, "Changes: only a file's pane takes it");
    const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
    if (arg.len == 0 and pane.layers.lanes > 0) {
        pane.layers.lanes = 0;
        return;
    }
    const cells: u8 = if (p.view().frontend.windowed) 2 else levels;
    if (arg.len == 0 and answered(p, pane.serial) != null) {
        pane.layers.lanes = cells;
        return;
    }
    const revset = if (arg.len == 0) "@" else arg;
    if (revset.len > Changes.revset_max) return p.reportFailure(c.id, "Changes: a revset that long");
    const shown: struct { path: []const u8, rev: []const u8 } = if (of(f)) |r|
        .{ .path = r.path, .rev = r.rev }
    else if (f.output == null and pardes.filesystem.localPath(f.path) != null)
        .{ .path = f.path, .rev = "@" }
    else
        return p.reportFailure(c.id, "Changes: only a file's pane takes it");
    pane.layers.lanes = cells;
    ask(p, c.id, pane.serial, shown.path, shown.rev, revset);
}

// ---- jj off the loop (Stream.zig's model) ----

/// A `Changes` asked of jj: the pane (by serial), the file it shows and the
/// revision whose lines are annotated, the revset. Its two runs go on a
/// worker where the host has one (the `search` effect: Stream.start), their
/// raw answers back as one input (`Event.search`, its `jj` set) stamped
/// with its generation, which the step takes (`receive`): a replica replays
/// that input and never runs jj. With no worker (a test), on the loop, each
/// run a site of the step's tape.
pub const Ask = struct {
    gpa: std.mem.Allocator,
    /// What its answer is made with: the shell's, which frees a batch.
    out: std.mem.Allocator,
    gen: u32,
    serial: u32,
    path: []u8,
    rev: []u8,
    revset: []u8,

    fn make(gpa: std.mem.Allocator, gen: u32, serial: u32, path: []const u8, rev: []const u8, revset: []const u8) error{OutOfMemory}!*Ask {
        const a = try gpa.create(Ask);
        errdefer gpa.destroy(a);
        const owned = try std.mem.concat(gpa, u8, &.{ path, rev, revset });
        a.* = .{ .gpa = gpa, .out = gpa, .gen = gen, .serial = serial, .path = owned[0..path.len], .rev = owned[path.len..][0..rev.len], .revset = owned[path.len + rev.len ..] };
        return a;
    }

    pub fn deinit(a: *Ask) void {
        a.gpa.free(a.path.ptr[0 .. a.path.len + a.rev.len + a.revset.len]);
        a.gpa.destroy(a);
    }
};

/// The `Changes` asked and its worker (`Stream.changes`), one at a time:
/// one asked while it runs waits (`Stream.changes_next`), and only the last
/// asked is pinned.
pub const Task = struct {
    // The worker the host started for it, live: a replica has none.
    pub const replica = .{ .authority = .{ "future", "io" } };
    ask: *Ask,
    future: ?std.Io.Future(void) = null,
    io: ?std.Io = null,
};

/// A `Changes` generation has this bit (a search's and a parse's count
/// from 0; a paint's has the top one).
pub const gen_bit: u32 = 1 << 29;

fn liveGen(s: *const pardes.Stream) u32 {
    return gen_bit | (s.changes_count & (gen_bit - 1));
}

/// Ask jj of `revset` for pane `serial` (said at pane `id` while it runs):
/// what the pane shows stays until the answer lands.
fn ask(p: *Pardes, id: usize, serial: u32, path: []const u8, rev: []const u8, revset: []const u8) void {
    const s = &p.stream;
    s.changes_count +%= 1;
    const a = Ask.make(p.gpa, liveGen(s), serial, path, rev, revset) catch return p.reportFailure(id, "Changes: out of memory");
    p.setStatus(.at(id), "Changes: jj\u{2026}");
    if (s.changes != null) {
        if (s.changes_next) |old| old.deinit();
        s.changes_next = a;
        return;
    }
    go(p, a);
}

fn go(p: *Pardes, a: *Ask) void {
    p.stream.changes = .{ .ask = a };
    if (p.tape.has(p, .search)) return p.emit(.{ .search = .{ .gen = a.gen } });
    runHere(p, a.gen, false);
}

/// The host's `search` effect for a `Changes` generation (Stream.start):
/// its runs on a worker that sends to `sink`.
pub fn start(io: std.Io, gpa: std.mem.Allocator, p: *Pardes, gen: u32, ctx: ?*anyopaque, sink: pardes.Stream.Sink) void {
    const t = if (p.stream.changes) |*t| t else return;
    if (t.ask.gen != gen or t.future != null) return;
    t.ask.out = gpa;
    // No worker to be had: here, its answer an input.
    t.future = io.concurrent(work, .{ t.ask, ctx, sink }) catch return runHere(p, gen, true);
    t.io = io;
}

fn work(a: *Ask, ctx: ?*anyopaque, sink: pardes.Stream.Sink) void {
    const b = answer(null, a.out, a);
    if (!sink(ctx, b)) b.deinit(a.out);
}

/// With no worker: the runs here, each a site (a replica replays them).
/// `in_call`: in the host's `search` entry, the answer handed in as an
/// input, as a worker's is.
pub fn runHere(p: *Pardes, gen: u32, comptime in_call: bool) void {
    const t = p.stream.changes orelse return;
    if (t.ask.gen != gen or t.future != null) return;
    const b = answer(p, p.gpa, t.ask);
    defer b.deinit(p.gpa);
    if (in_call) p.update(.{ .search = b }) else receive(p, &b, t.ask.serial);
}

/// jj's two answers for `a`, raw, in `gpa`: through `p`'s tape when given
/// (on the loop), else run here (a worker).
fn answer(p: ?*Pardes, gpa: std.mem.Allocator, a: *const Ask) pardes.Stream.Batch {
    const failed = struct {
        fn f(g: std.mem.Allocator, at: *const Ask, why: []u8) pardes.Stream.Batch {
            _ = g;
            return .{ .gen = at.gen, .jj = at.serial, .rows = why, .end = .failed };
        }
    }.f;
    const set = fileset(gpa, a.path) catch return failed(gpa, a, refusal(gpa, "out of memory").refused);
    defer gpa.free(set);
    // The changes, oldest first, each with its diff of the file: one run.
    const query = std.fmt.allocPrint(gpa, "({s}) & files({s})", .{ a.revset, set }) catch return failed(gpa, a, refusal(gpa, "out of memory").refused);
    defer gpa.free(query);
    const log_args = [_][]const u8{ "log", "--no-graph", "--reversed", "-r", query, "-T", log_template, "--git", "--context=0", "--", set };
    const logged = switch (runJj(p, gpa, dirOf(a.path), &log_args)) {
        .refused => |why| return failed(gpa, a, why),
        .bytes => |bytes| bytes,
    };
    var it = std.mem.splitScalar(u8, logged, '\n');
    const any = while (it.next()) |l| {
        if (pinOf(l) != null) break true;
    } else false;
    if (!any) return .{ .gen = a.gen, .jj = a.serial, .rows = logged, .end = .done };
    // Who wrote each line: a path, not a fileset (annotate takes one file
    // as it is named).
    const annotate_args = [_][]const u8{ "file", "annotate", "-r", a.rev, "-T", "commit.change_id().short(8) ++ \"\\t\" ++ content", "--", std.Io.Dir.path.basename(a.path) };
    return switch (runJj(p, gpa, dirOf(a.path), &annotate_args)) {
        .refused => |why| {
            gpa.free(logged);
            return failed(gpa, a, why);
        },
        .bytes => |annotated| .{ .gen = a.gen, .jj = a.serial, .rows = logged, .styles = annotated, .end = .done },
    };
}

fn runJj(p: ?*Pardes, gpa: std.mem.Allocator, dir: []const u8, args: []const []const u8) Shown {
    return if (p) |q| q.tape.site(.jj, gpa, runHost, .{ gpa, dir, args }) else runHost(gpa, dir, args);
}

/// A `Changes` answer (`Event.search`, its `jj` set), borrowed: the last
/// asked's is parsed and pinned on its pane; an earlier one's, or a gone
/// pane's, dropped. Then the one asked meanwhile goes.
pub fn receive(p: *Pardes, b: *const pardes.Stream.Batch, serial: u32) void {
    const s = &p.stream;
    var revset: [Changes.revset_max]u8 = undefined;
    var revset_len: usize = 0;
    if (s.changes) |t| if (t.ask.gen == b.gen) {
        s.changes = null;
        if (t.future) |f| pardes.Stream.join(f, t.io.?, .wait);
        revset_len = t.ask.revset.len;
        @memcpy(revset[0..revset_len], t.ask.revset);
        t.ask.deinit();
    };
    defer if (s.changes == null) if (s.changes_next) |next| {
        s.changes_next = null;
        go(p, next);
    };
    if (b.gen != liveGen(s) or revset_len == 0) return;
    const id = p.paneBySerial(serial) orelse return;
    pinAnswer(p, id, b, revset[0..revset_len]);
}

/// A splice of `f`'s text, before its bytes go in (File.edit, the one
/// place a text changes, an undo's too): each pane showing it that has
/// pins keeps a value for each of its lines, so the values ride with the
/// lines, never asking jj again: the lines a splice takes out take their
/// values with them, and a line it puts in is nobody's.
pub fn edited(p: *Pardes, f: *const File.State, off: usize, len: usize, bytes: []const u8) void {
    var i = p.changes.items.len;
    while (i > 0) {
        i -= 1;
        const c = &p.changes.items[i];
        const id = p.paneBySerial(c.serial) orelse continue;
        const shown = if (p.panes[id].?.file) |*shown| shown else continue;
        if (shown.content.ptr != f.content.ptr) continue;
        splice(p.gpa, c, f.content, off, len, bytes) catch {
            // No room for it: its values would lie, so it goes.
            c.deinit(p.gpa);
            _ = p.changes.swapRemove(i);
        };
    }
}

/// `c`'s values spliced as `text`'s lines are by the splice of `len` bytes
/// at `off` for `bytes`. A splice that starts in a line's leading blanks
/// (at its start, or after its indent, as `o` puts a line in) leaves that
/// line's text after what it puts in: the lines it takes and puts come
/// before it. Else the line it starts in keeps its value, and the lines
/// taken and put come after it.
fn splice(gpa: std.mem.Allocator, c: *Changes, text: []const u8, off: usize, len: usize, bytes: []const u8) error{OutOfMemory}!void {
    const taken = std.mem.count(u8, text[off..][0..len], "\n");
    const put = std.mem.count(u8, bytes, "\n");
    if (taken == 0 and put == 0) return;
    const line_start = if (std.mem.lastIndexOfScalar(u8, text[0..off], '\n')) |nl| nl + 1 else 0;
    const in_lead = std.mem.trimStart(u8, text[line_start..off], " \t").len == 0;
    const from = std.mem.count(u8, text[0..line_start], "\n") + @intFromBool(!in_lead);
    if (from > c.lines.len) return;
    const take = @min(taken, c.lines.len - from);
    const next = try gpa.alloc(Line, c.lines.len - take + put);
    @memcpy(next[0..from], c.lines[0..from]);
    @memset(next[from..][0..put], .{ .pin = .none });
    @memcpy(next[from + put ..], c.lines[from + take ..]);
    gpa.free(c.lines);
    c.lines = next;
}

/// The session's end: the worker canceled, the asks let go.
pub fn cancel(s: *pardes.Stream) void {
    if (s.changes) |t| {
        s.changes = null;
        if (t.future) |f| pardes.Stream.join(f, t.io.?, .cancel);
        t.ask.deinit();
    }
    if (s.changes_next) |a| {
        s.changes_next = null;
        a.deinit();
    }
}

/// jj's answer `b` for `revset` parsed and pinned on pane `id`, or its
/// refusal said there.
fn pinAnswer(p: *Pardes, id: usize, b: *const pardes.Stream.Batch, revset: []const u8) void {
    const pane = p.panes[id].?;
    var line: pardes.Kind.Buf(512) = .{};
    const f = if (pane.file) |*file| file else return;
    // Nothing pinned yet: no gutter for it.
    defer if (answered(p, pane.serial) == null) {
        pane.layers.lanes = 0;
    };
    if (b.end == .failed) return p.reportFailure(id, line.print("Changes: {s}", .{b.rows[0..@min(b.rows.len, 480)]}));
    var got = parse(p.gpa, p.scratch.allocator(), b.rows, b.styles, f.content) catch |err| return p.reportFailure(id, line.print("Changes: {s}", .{@errorName(err)}));
    switch (got) {
        .refused => |why| {
            defer p.gpa.free(why);
            return p.reportFailure(id, line.print("Changes: {s}", .{why[0..@min(why.len, 480)]}));
        },
        .read => |*changes| {
            if (changes.pins.len == 0) {
                changes.deinit(p.gpa);
                const shown = if (of(f)) |r| r.path else f.path;
                return p.reportFailure(id, line.print("Changes: no change of `{s}` touches {s}", .{ revset, std.Io.Dir.path.basename(shown) }));
            }
            @memcpy(changes.revset[0..revset.len], revset);
            changes.revset_len = @intCast(revset.len);
            changes.serial = pane.serial;
            if (answered(p, pane.serial)) |kept| {
                kept.deinit(p.gpa);
                kept.* = changes.*;
            } else p.changes.append(p.gpa, changes.*) catch {
                changes.deinit(p.gpa);
                return p.reportFailure(id, "Changes: out of memory");
            };
            p.setStatus(.at(id), "");
        },
    }
}

const Read = union(enum) { refused: []u8, read: Changes };

/// jj's answers parsed: `logged` (the pins, each with its diff of the
/// file) and `annotated` (who wrote each line of `text`, what the pane
/// shows: a line is matched to the line its change added by its text).
fn parse(gpa: std.mem.Allocator, arena: std.mem.Allocator, logged: []const u8, annotated: []const u8, text: []const u8) error{OutOfMemory}!Read {
    var out: Changes = .{ .serial = 0 };
    var kept = false;
    defer if (!kept) out.deinit(gpa);
    var pins: std.ArrayList(Pin) = .empty;
    defer pins.deinit(gpa);
    // Where each pin's diff starts in `logged`, and the end.
    var diffs: std.ArrayList(usize) = .empty;
    var it = std.mem.splitScalar(u8, logged, '\n');
    while (it.next()) |l| if (pinOf(l)) |pin| {
        if (pins.items.len == pins_max) return .{ .refused = try std.fmt.allocPrint(gpa, "more than {d} changes touch it", .{pins_max}) };
        try pins.append(gpa, pin);
        try diffs.append(arena, it.index orelse logged.len);
    };
    try diffs.append(arena, logged.len);
    out.pins = try pins.toOwnedSlice(gpa);
    if (out.pins.len == 0) {
        kept = true;
        return .{ .read = out };
    }
    out.lines = try provenance(gpa, arena, annotated, out.pins, text);
    // Each change's hunks, and which of its lines it added whole.
    var hunks: std.ArrayList(Hunk) = .empty;
    defer hunks.deinit(gpa);
    var removed: std.ArrayList(u8) = .empty;
    defer removed.deinit(gpa);
    for (0..out.pins.len) |k| try hunksOf(gpa, arena, @intCast(k), logged[diffs.items[k]..diffs.items[k + 1]], text, out.lines, &hunks, &removed);
    out.hunks = try hunks.toOwnedSlice(gpa);
    out.removed = try removed.toOwnedSlice(gpa);
    nest(out.lines, out.pins.len);
    kept = true;
    return .{ .read = out };
}

/// `jj log`'s line a change, before its diff: its id, its author's time,
/// its author, its description's first line, a tab between.
const log_template = "change_id.short(8) ++ \"\\t\" ++ author.timestamp().utc().format(\"%s\") ++ \"\\t\" ++ author.name() ++ \"\\t\" ++ description.first_line() ++ \"\\n\"";

/// A `log_template` line, or null for a line of a diff (which starts with
/// a blank, a sign, `@`, `\\` or a word and a blank: never eight of jj's
/// id letters, k to z, and a tab).
fn pinOf(l: []const u8) ?Pin {
    if (l.len < 9 or l[8] != '\t') return null;
    for (l[0..8]) |c| if (c < 'k' or c > 'z') return null;
    var cols = std.mem.splitScalar(u8, l[9..], '\t');
    var pin: Pin = .{ .id = l[0..8].*, .time = std.fmt.parseInt(i64, cols.next() orelse "", 10) catch 0 };
    const author = cols.next() orelse "";
    pin.author_len = @intCast(@min(author.len, pin.author.len));
    @memcpy(pin.author[0..pin.author_len], author[0..pin.author_len]);
    const title = cols.rest();
    pin.title_len = @intCast(@min(title.len, pin.title.len));
    @memcpy(pin.title[0..pin.title_len], title[0..pin.title_len]);
    return pin;
}

/// Which pin wrote each line of `text` (what the pane shows: `whole` is the
/// hunks' to say), a value a line, the caller's in `gpa`, from `annotated`
/// (`jj file annotate`'s answer: an id, a tab and the line, a line each, of
/// the revision it annotated, which is jj's last snapshot of a file and
/// not the keys typed since): the two texts lined up by what they agree on
/// at either end (`File.spanOf`, the editor's differ: a line inside both
/// ends keeps its owner, a line only the pane has is nobody's).
pub fn provenance(gpa: std.mem.Allocator, arena: std.mem.Allocator, annotated: []const u8, pins: []const Pin, text: []const u8) error{OutOfMemory}![]Line {
    var owners: std.ArrayList(PinIndex) = .empty;
    var was: std.ArrayList(u8) = .empty;
    var rows = std.mem.splitScalar(u8, annotated, '\n');
    while (rows.next()) |row| {
        // The empty text after the last newline is no line.
        if (row.len == 0 and rows.peek() == null) break;
        const tab = std.mem.indexOfScalar(u8, row, '\t') orelse row.len;
        try owners.append(arena, for (pins, 0..) |pin, i| {
            if (std.mem.eql(u8, &pin.id, row[0..tab])) break @enumFromInt(i);
        } else .none);
        try was.appendSlice(arena, row[@min(tab + 1, row.len)..]);
        try was.append(arena, '\n');
    }
    if (!std.mem.endsWith(u8, annotated, "\n") and was.items.len > 0) was.items.len -= 1;
    const out = try gpa.alloc(Line, lineCount(text));
    @memset(out, .{ .pin = .none });
    if (std.mem.eql(u8, was.items, text)) {
        for (out[0..@min(out.len, owners.items.len)], owners.items[0..@min(out.len, owners.items.len)]) |*l, pin| l.pin = pin;
        return out;
    }
    const span = File.spanOf(was.items, text);
    const head = @min(std.mem.count(u8, was.items[0..span.head], "\n"), out.len, owners.items.len);
    for (out[0..head], owners.items[0..head]) |*l, pin| l.pin = pin;
    var tail = @min(tailLines(was.items, span.tail), out.len - head, owners.items.len - head);
    // The line the two ends meet inside (an insertion before it shares its
    // indent with the line above) is the same line when its bytes are.
    if (head + tail < @min(out.len, owners.items.len) and std.mem.eql(u8, lineFromEnd(was.items, tail), lineFromEnd(text, tail))) tail += 1;
    for (out[out.len - tail ..], owners.items[owners.items.len - tail ..]) |*l, pin| l.pin = pin;
    return out;
}

/// `text`'s line `k` from its end (0: its last).
fn lineFromEnd(text: []const u8, k: usize) []const u8 {
    var end = text.len - @intFromBool(std.mem.endsWith(u8, text, "\n"));
    for (0..k) |_| end = (std.mem.lastIndexOfScalar(u8, text[0..end], '\n') orelse return "");
    const from = if (std.mem.lastIndexOfScalar(u8, text[0..end], '\n')) |nl| nl + 1 else 0;
    return text[from..end];
}

/// The lines of `text`: one after each newline but a last one, as the
/// annotation numbers them.
fn lineCount(text: []const u8) usize {
    return std.mem.count(u8, text, "\n") + @intFromBool(text.len > 0 and text[text.len - 1] != '\n');
}

/// How many of `text`'s lines lie whole in its last `tail` bytes.
fn tailLines(text: []const u8, tail: usize) usize {
    if (tail == 0) return 0;
    const from = text.len - tail;
    // A line starts at `from`, and after each newline in the tail but the
    // text's last byte.
    const starts = if (from == 0) 1 else @intFromBool(text[from - 1] == '\n');
    return starts + std.mem.count(u8, text[from .. text.len - 1], "\n");
}

/// Pin `k`'s hunks in `diffed` (its diff of the file, `--git --context=0`) onto
/// `hunks`, their removed lines onto `removed`; and each line of `text`
/// pin `k` wrote (`lines`) marked `whole` when the line it is, matched in
/// order by its text, was one the change added whole: in a run of lines
/// taken away and written, the first as many written as were taken away
/// are changed, the rest added whole.
fn hunksOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, k: u16, diffed: []const u8, text: []const u8, lines: []Line, hunks: *std.ArrayList(Hunk), removed: *std.ArrayList(u8)) error{OutOfMemory}!void {
    const Added = struct { text: []const u8, whole: bool };
    var added: std.ArrayList(Added) = .empty;
    var walk: diff.Walk = .{};
    var taken: u32 = 0;
    var it = std.mem.splitScalar(u8, diffed, '\n');
    while (it.next()) |raw| {
        const l = walk.step(raw);
        switch (l.kind) {
            .hunk => {
                const h = diff.parseHunk(std.mem.trimEnd(u8, raw, "\r")).?;
                try hunks.append(gpa, .{ .pin = k, .old_start = @intCast(h.old_start), .old_len = @intCast(h.old_count), .new_start = @intCast(h.new_start), .new_len = @intCast(h.new_count), .removed = @intCast(removed.items.len), .removed_len = 0 });
                taken = 0;
            },
            .removed => {
                const body = std.mem.trimEnd(u8, raw, "\r")[1..];
                try removed.appendSlice(gpa, body);
                try removed.append(gpa, '\n');
                hunks.items[hunks.items.len - 1].removed_len += @intCast(body.len + 1);
                taken += 1;
            },
            .added => {
                try added.append(arena, .{ .text = std.mem.trimEnd(u8, raw, "\r")[1..], .whole = taken == 0 });
                taken -|= 1;
            },
            else => {},
        }
    }
    var next: usize = 0;
    var rows = std.mem.splitScalar(u8, text, '\n');
    for (lines) |*line| {
        const row = rows.next() orelse break;
        if (@intFromEnum(line.pin) != k) continue;
        const from = next;
        while (next < added.items.len and !std.mem.eql(u8, added.items[next].text, std.mem.trimEnd(u8, row, "\r"))) next += 1;
        if (next == added.items.len) {
            next = from;
            continue;
        }
        line.whole = added.items[next].whole;
        next += 1;
    }
}

/// Each line's lanes: the blocks of the pins that span it, oldest first.
/// A pin's block runs from a line it wrote on to each next line it wrote
/// while every line between was written by a newer pin: its lane unbroken
/// down what it wrote, through what later pins rewrote inside it. An older
/// pin's line (or one no pin wrote) ends a newer pin's block, so blocks
/// nest, the older outside, and a block keeps its level down all its rows:
/// the spine keeps its place, a nested change steps to the right on its
/// rows only. Past `levels`, the innermost are not drawn.
fn nest(lines: []Line, npins: usize) void {
    for (0..npins) |k| {
        var i: usize = 0;
        while (i < lines.len) {
            if (@intFromEnum(lines[i].pin) != k) {
                i += 1;
                continue;
            }
            var last = i;
            for (lines[i + 1 ..], i + 1..) |l, j| {
                const q = @intFromEnum(l.pin);
                if (q == k) last = j else if (l.pin == .none or q < k) break;
            }
            for (lines[i .. last + 1]) |*l| for (&l.lanes) |*lane| if (lane.* == .none) {
                lane.* = @enumFromInt(k);
                break;
            };
            i = last + 1;
        }
    }
}

/// The lanes' colours, a pin's the `pin % len`th, oldest first: the
/// theme's accents but the two that mean written and taken away (its green
/// and red), in hue order from the top, each a hue `hue_apart` or more from
/// the one kept before it (doom one: magenta, blue, yellow; cyan and
/// orange go). Distinct colours, never one between two.
pub fn laneColours(th: *const pardes.Theme, buf: *[8][3]u8) []const [3]u8 {
    const pal = th.palette;
    const grounds = [2][3]u8{ if (pal) |c| c[1] else .{ 0xcf, 0x22, 0x2e }, if (pal) |c| c[2] else .{ 0x2e, 0xa0, 0x43 } };
    const accents: [6][3]u8 = if (pal) |c| .{ c[3], c[4], c[5], c[6], th.num, th.kw } else .{ th.kw, th.num, th.str, th.box, th.column_box orelse th.box, th.comment };
    var sorted: [6][3]u8 = undefined;
    var n: usize = 0;
    for (accents) |c| {
        // A grey is no accent; one near written or taken away means that.
        if (chroma(c) < 48 or hueApart(c, grounds[0]) < hue_apart or hueApart(c, grounds[1]) < hue_apart) continue;
        sorted[n] = c;
        n += 1;
    }
    std.sort.insertion([3]u8, sorted[0..n], {}, struct {
        fn above(_: void, a: [3]u8, b: [3]u8) bool {
            return hue(a) > hue(b);
        }
    }.above);
    var kept: usize = 0;
    for (sorted[0..n]) |c| {
        if (kept > 0 and hueApart(c, buf[kept - 1]) < hue_apart) continue;
        buf[kept] = c;
        kept += 1;
    }
    return buf[0..kept];
}

/// Two hues closer than this are one colour to a lane (doom one's cyan is
/// 12 degrees from its blue, its orange 11 from its yellow).
const hue_apart = 15;

fn chroma(c: [3]u8) u8 {
    return @max(c[0], c[1], c[2]) - @min(c[0], c[1], c[2]);
}

/// HSV's hue, in degrees.
fn hue(c: [3]u8) f32 {
    const r: f32 = @floatFromInt(c[0]);
    const g: f32 = @floatFromInt(c[1]);
    const b: f32 = @floatFromInt(c[2]);
    const hi = @max(r, g, b);
    const d = hi - @min(r, g, b);
    if (d == 0) return 0;
    const h = if (hi == r) @mod((g - b) / d, 6) else if (hi == g) (b - r) / d + 2 else (r - g) / d + 4;
    return 60 * h;
}

fn hueApart(a: [3]u8, b: [3]u8) f32 {
    const d = @abs(hue(a) - hue(b));
    return @min(d, 360 - d);
}

/// The pane's pinned changes as a view shows them, on its body's rows (body_layer.zig, while
/// File.Layers.lanes is set): in the gutter's lane cells after the number a
/// lane each pin whose block runs down the row, at its level, a glyph in a
/// terminal, a strip of pixels in a window (Surface.lanes); and a line a
/// pin added whole green across it, as a diff's added line. Not yet: the
/// ghost rows (what the shown revision has not: removed lines, each pin's
/// description), a changed line's words.
pub fn paint(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void {
    const ch = answered(p, pane.serial) orelse return;
    if (ch.lines.len == 0) return;
    var buf: [8][3]u8 = undefined;
    const colours = laneColours(p.theme(), &buf);
    if (colours.len == 0) return;
    const gutter = File.gutterWidth(pane);
    const cells = File.laneCells(pane);
    if (gutter >= tw or cells == 0) return;
    const first = tx + gutter - cells;
    const windowed = p.view().frontend.windowed;
    const ground = pardes.colors.Grounds.of(p.theme()).add.row;
    const body_y = p.bodyTop(pane, r);
    const scroll = pane.scroll();
    var vr: u16 = pane.context_rows;
    while (vr < body_h) : (vr += 1) {
        const row: i32 = if (pane.wrap_n == 0) scroll + @as(i32, vr) else if (vr < pane.wrap_n) pane.wrap_line[vr] else break;
        if (row < 0 or row >= ch.lines.len) continue;
        const line = ch.lines[@intCast(row)];
        const y = body_y + vr;
        if (line.whole and line.pin != .none) s.tint(tx + gutter, y, tw - gutter, ground, null);
        for (line.lanes, 0..) |lane, level| {
            if (lane == .none) break;
            const rgb = colours[@intFromEnum(lane) % colours.len];
            if (windowed) {
                // A body a pixel shell draws as a layer is painted on a
                // temporary surface first: its lanes are not drawn yet.
                if (s == &p.surface) s.lanes.append(p.gpa, .{ .x = first, .y = y, .level = @intCast(level), .rgb = rgb }) catch {};
            } else if (level < cells) {
                var style = s.at(first + @as(u16, @intCast(level)), y).style;
                style.fg = .{ .rgb = rgb };
                s.set(first + @as(u16, @intCast(level)), y, "\u{258e}", style);
            }
        }
    }
}

// ---- tests ----

const testing = std.testing;

test "path@rev splits at its first @: a path before it, a revision after" {
    const cases = [_]struct { []const u8, []const u8, []const u8 }{
        .{ "a.zig@main", "a.zig", "main" },
        .{ "core/File.zig@@-", "core/File.zig", "@-" },
        .{ "x.zig@main@origin", "x.zig", "main@origin" },
    };
    for (cases) |c| {
        const got = split(c[0]).?;
        try testing.expectEqualStrings(c[1], got.path);
        try testing.expectEqualStrings(c[2], got.rev);
    }
    for ([_][]const u8{ "@p12", "a.zig@", "a.zig", "dir/@x" }) |text| try testing.expect(split(text) == null);
}

/// A jj repository in a test's directory: `a.zig` committed as `one`, then
/// as `two`, and `three` in its working copy, never snapshotted. Null with
/// no jj to run.
const Repo = struct {
    tmp: testing.TmpDir,
    dir: []const u8,
    file: []const u8,

    const one = "const one = 1;\nconst x = 2;\n";
    const two = "const two = 2;\nconst x = 2;\nconst y = 3;\n";
    const three = "const three = 3;\n";

    fn init(gpa: std.mem.Allocator) !?Repo {
        return with(gpa, &.{ .{ one, "one" }, .{ two, "two" } }, three);
    }

    /// `a.zig` committed as each text with its message, in order; then
    /// `working` in the working copy, never snapshotted.
    fn with(gpa: std.mem.Allocator, commits: []const [2][]const u8, working: ?[]const u8) !?Repo {
        var tmp = testing.tmpDir(.{});
        errdefer tmp.cleanup();
        var buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
        const dir = try gpa.dupe(u8, buf[0..try tmp.dir.realPath(testing.io, &buf)]);
        errdefer gpa.free(dir);
        if (!try run(gpa, dir, &.{ "git", "init" })) return null;
        for (commits) |c| {
            try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = c[0] });
            if (!try run(gpa, dir, &.{ "commit", "-m", c[1] })) return null;
        }
        if (working) |text| try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = text });
        return .{ .tmp = tmp, .dir = dir, .file = try std.fmt.allocPrint(gpa, "{s}/a.zig", .{dir}) };
    }

    fn run(gpa: std.mem.Allocator, dir: []const u8, args: []const []const u8) !bool {
        var argv: std.ArrayList([]const u8) = .empty;
        defer argv.deinit(gpa);
        try argv.appendSlice(gpa, &.{ "jj", "--config=user.name=t", "--config=user.email=t@t", "--quiet" });
        try argv.appendSlice(gpa, args);
        const r = std.process.run(gpa, testing.io, .{ .argv = argv.items, .cwd = .{ .path = dir } }) catch return false;
        gpa.free(r.stdout);
        gpa.free(r.stderr);
        return r.term == .exited and r.term.exited == 0;
    }

    fn deinit(r: *Repo, gpa: std.mem.Allocator) void {
        gpa.free(r.file);
        gpa.free(r.dir);
        r.tmp.cleanup();
    }
};

fn told(p: *Pardes, id: usize) []const u8 {
    const pane = p.panes[id].?;
    return pane.msg[0..pane.msg_len];
}

test "At shows a file at a revision beside it, read-only, coloured as its file; a Look at path@rev:line goes to it; At in it turns it in place; jj's refusals are said" {
    const gpa = testing.allocator;
    var repo = try Repo.init(gpa) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 40 });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
    const file = p.view().active;
    try testing.expectEqualStrings(Repo.three, p.panes[file].?.file.?.content);
    p.update(.{ .command = "At @-" });
    const shown = p.view().active;
    try testing.expect(shown != file);
    const pane = p.panes[shown].?;
    try testing.expectEqualStrings(Repo.two, pane.file.?.content);
    const name = try std.fmt.allocPrint(gpa, "{s}@@-", .{repo.file});
    defer gpa.free(name);
    try testing.expectEqualStrings(name, try pardes.tagline.tagPrefix(p, pane));
    try testing.expectEqualStrings(repo.file, File.langPath(&pane.file.?));
    try testing.expect(pane.colorAlgo() == .source);
    // Read-only: a key's edit and a whole-text edit (dd) change nothing, and a bare Save says so.
    for ("iz") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
    p.update(.{ .key = .{ .cp = pardes.Key.escape } });
    for ("dd") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
    try testing.expectEqualStrings(Repo.two, pane.file.?.content);
    p.update(.{ .command = "Save" });
    try testing.expect(std.mem.indexOf(u8, told(p, shown), "is a revision, read-only") != null);
    // From the file's pane, a Look at the address with a line goes there.
    p.view().active = file;
    p.update(.{ .command = "Look a.zig@@-:3" });
    try testing.expectEqual(shown, p.view().active);
    try testing.expectEqual(@as(i32, 2), pane.body.cur_row);
    // Turned to another revision in its place: one pane, the older text.
    p.update(.{ .command = "At @--" });
    const turned = p.view().active;
    try testing.expect(p.panes[shown] == null);
    try testing.expectEqualStrings(Repo.one, p.panes[turned].?.file.?.content);
    var n: usize = 0;
    for (p.panes) |slot| if (slot) |s| if (s.file) |*f| {
        n += @intFromBool(of(f) != null);
    };
    try testing.expectEqual(@as(usize, 1), n);
    // jj's refusals, in its words.
    p.update(.{ .command = "At nosuch" });
    try testing.expect(std.mem.indexOf(u8, told(p, turned), "At: Revision `nosuch` doesn't exist") != null);
    p.view().active = file;
    p.update(.{ .command = "At" });
    try testing.expect(std.mem.indexOf(u8, told(p, file), "At: which revision?") != null);
    // Bare in a revision's pane: the file.
    p.view().active = turned;
    p.update(.{ .command = "At" });
    try testing.expectEqual(file, p.view().active);
}

test "a client replays the open of a file at a revision and ends equal" {
    const gpa = testing.allocator;
    var repo = try Repo.init(gpa) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const R = pardes.replica;
    const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{}, false);
    defer a.deinit();
    const r = try R.Replica.init(gpa, 1, try a.unit(0, 0), false);
    defer r.deinit();
    var line: [4200]u8 = undefined;
    r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-:2", .{repo.file}) }));
    r.settle();
    try testing.expect(r.diverged == null);
    const id = a.core.view().active;
    try testing.expectEqualStrings(Repo.two, a.core.panes[id].?.file.?.content);
    try testing.expectEqualStrings(Repo.two, r.core().panes[id].?.file.?.content);
    try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core()));
}

test "Changes pins a revset's changes on the pane, shown in this view: who wrote each line, which it added whole, each one's hunks and what they took away; bare hides and shows them; jj's refusals are said" {
    const gpa = testing.allocator;
    var repo = try Repo.init(gpa) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30, .windowed = false });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) });
    const id = p.view().active;
    const pane = p.panes[id].?;
    try testing.expectEqualStrings(Repo.two, pane.file.?.content);
    p.update(.{ .command = "Changes @--::@-" });
    try testing.expectEqual(levels, pane.layers.lanes);
    const ch = answered(p, pane.serial).?;
    try testing.expectEqualStrings("@--::@-", ch.pinned());
    try testing.expectEqual(@as(usize, 2), ch.pins.len);
    for (ch.pins, [_][]const u8{ "one", "two" }) |pin, title| {
        try testing.expectEqualStrings(title, pin.title[0..pin.title_len]);
        try testing.expectEqualStrings("t", pin.author[0..pin.author_len]);
        try testing.expect(pin.time > 0);
    }
    // `two` changed line 1 (`one`'s first) and added line 3 whole; line 2 is `one`'s, added whole.
    const one: PinIndex = @enumFromInt(0);
    const two: PinIndex = @enumFromInt(1);
    const want = [_]Line{
        .{ .pin = two, .whole = false, .lanes = .{ two, .none, .none } },
        .{ .pin = one, .whole = true, .lanes = .{ one, .none, .none } },
        .{ .pin = two, .whole = true, .lanes = .{ two, .none, .none } },
    };
    try testing.expectEqualSlices(Line, &want, ch.lines);
    const hunks = [_]Hunk{
        .{ .pin = 0, .old_start = 0, .old_len = 0, .new_start = 1, .new_len = 2, .removed = 0, .removed_len = 0 },
        .{ .pin = 1, .old_start = 1, .old_len = 1, .new_start = 1, .new_len = 1, .removed = 0, .removed_len = 15 },
        .{ .pin = 1, .old_start = 2, .old_len = 0, .new_start = 3, .new_len = 1, .removed = 15, .removed_len = 0 },
    };
    try testing.expectEqualSlices(Hunk, &hunks, ch.hunks);
    try testing.expectEqualStrings("const one = 1;\n", ch.removed);
    // Bare: not shown in this view; what jj said is kept on the pane.
    p.update(.{ .command = "Changes" });
    try testing.expectEqual(0, pane.layers.lanes);
    try testing.expectEqual(@as(usize, 2), ch.pins.len);
    // Bare again: the pane's, shown again (jj not asked).
    p.update(.{ .command = "Changes" });
    try testing.expectEqual(levels, pane.layers.lanes);
    try testing.expectEqual(ch, answered(p, pane.serial).?);
    // jj's refusal, in its words; what was shown stays.
    p.update(.{ .command = "Changes nosuch" });
    try testing.expect(std.mem.indexOf(u8, told(p, id), "Changes: Revision `nosuch` doesn't exist") != null);
    try testing.expectEqualStrings("@--::@-", answered(p, pane.serial).?.pinned());
    // `@`, the working copy's change, which (never snapshotted) touches nothing.
    p.update(.{ .command = "Changes @" });
    try testing.expect(std.mem.indexOf(u8, told(p, id), "Changes: no change of `@` touches a.zig") != null);
}

test "the pinned changes are the pane's, shown in a view by its own bit: another view's Changes shows its set in both, and its bare Changes hides them there alone" {
    const gpa = testing.allocator;
    var repo = try Repo.init(gpa) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30, .windowed = false });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) });
    const pane = p.panes[p.view().active].?;
    const before = File.gutterWidth(pane);
    const other = p.openView().?;
    p.update(.{ .command = "Changes @--::@-" });
    try testing.expectEqual(before + levels, File.gutterWidth(pane));
    // A view of its own: nothing shown there until it asks.
    p.toView(other);
    try testing.expectEqual(0, pane.layers.lanes);
    try testing.expectEqual(before, File.gutterWidth(pane));
    p.update(.{ .command = "Changes @-" });
    try testing.expectEqualStrings("@-", answered(p, pane.serial).?.pinned());
    try testing.expectEqual(@as(usize, 1), answered(p, pane.serial).?.pins.len);
    // The first view shows the new set, not nothing.
    p.toView(.at(0));
    try testing.expectEqual(levels, pane.layers.lanes);
    // Hidden in the other view alone.
    p.toView(other);
    p.update(.{ .command = "Changes" });
    try testing.expectEqual(0, pane.layers.lanes);
    p.toView(.at(0));
    try testing.expectEqual(levels, pane.layers.lanes);
    try testing.expectEqual(before + levels, File.gutterWidth(pane));
}

test "a client replays Changes from what the session's jj answered and ends equal" {
    const gpa = testing.allocator;
    var repo = try Repo.init(gpa) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const R = pardes.replica;
    const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{}, false);
    defer a.deinit();
    const r = try R.Replica.init(gpa, 1, try a.unit(0, 0), false);
    defer r.deinit();
    var line: [4200]u8 = undefined;
    r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) }));
    r.confirm(try a.local(.{ .command = "Changes @--::@-" }));
    r.settle();
    try testing.expect(r.diverged == null);
    const id = a.core.view().active;
    try testing.expectEqual(@as(usize, 2), answered(a.core, a.core.panes[id].?.serial).?.pins.len);
    try testing.expectEqualSlices(Line, answered(a.core, a.core.panes[id].?.serial).?.lines, answered(r.core(), r.core().panes[id].?.serial).?.lines);
    try testing.expectEqualStrings("@--::@-", answered(r.core(), r.core().panes[id].?.serial).?.pinned());
    try testing.expect(r.core().panes[id].?.layers.lanes > 0);
    try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core()));
}

/// A session whose `Changes` runs on a worker (Stream.start), as a shell's
/// does, its answer posted to an inbox, with a client of it.
const WorkerJj = struct {
    const Inbox = @import("dev").host_io.Inbox;
    const R = pardes.replica;
    /// The host's: where its worker posts, and the core it starts for.
    const Shell = struct { q: Inbox, core: ?*Pardes = null };
    shell: *Shell,
    a: *R.Authority,
    r: *R.Replica,
    /// The revision `@-` of the repository's `a.zig`, open.
    id: usize,
    serial: u32,

    fn search(ctx: ?*anyopaque, gen: u32) void {
        const shell: *Shell = @ptrCast(@alignCast(ctx.?));
        pardes.Stream.start(testing.io, testing.allocator, shell.core.?, gen, &shell.q, Inbox.pushSearch);
    }
    const vtable: pardes.Host.VTable = .{ .search = search };

    fn init(repo: *const Repo) !WorkerJj {
        const shell = try testing.allocator.create(Shell);
        shell.* = .{ .q = .{ .gpa = testing.allocator, .lsp_allocator = testing.allocator, .io = testing.io } };
        const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{ .vtable = &vtable, .ctx = shell }, false);
        errdefer a.deinit();
        shell.core = a.core;
        const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0), false);
        var line: [4200]u8 = undefined;
        r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) }));
        const id = a.core.view().active;
        return .{ .shell = shell, .a = a, .r = r, .id = id, .serial = a.core.panes[id].?.serial };
    }

    fn deinit(w: *WorkerJj) void {
        w.r.deinit();
        w.a.deinit();
        w.shell.q.deinit();
        testing.allocator.destroy(w.shell);
    }

    fn word(w: *WorkerJj, text: []const u8) !void {
        w.r.confirm(try w.a.local(.{ .command = text }));
        w.r.settle();
    }

    /// Until no `Changes` is asked or running (five seconds at most): each
    /// answer the session's input, as its loop hands it, and the client's.
    fn land(w: *WorkerJj) !void {
        var waited: u32 = 0;
        while (w.a.core.stream.changes != null or w.a.core.stream.changes_next != null) : (waited += 1) {
            if (waited == 5000) return error.Timeout;
            var batch: Inbox.Batch = .{};
            w.shell.q.takeInto(&batch);
            for (batch.slice()) |m| switch (m) {
                .search => |b| {
                    defer b.deinit(testing.allocator);
                    w.r.confirm(try w.a.local(.{ .search = b }));
                    w.r.settle();
                },
                else => m.deinit(testing.allocator, testing.allocator),
            };
            testing.io.sleep(.fromMilliseconds(1), .awake) catch {};
        }
        try testing.expect(w.r.diverged == null);
        try testing.expectEqual(pardes.tape.digestOf(w.a.core), pardes.tape.digestOf(w.r.core()));
    }
};

test "Changes asks jj on a worker: the word says so and returns, its answer lands as one input and pins; a client replays that input and ends equal" {
    var repo = try Repo.init(testing.allocator) orelse return error.SkipZigTest;
    defer repo.deinit(testing.allocator);
    var w = try WorkerJj.init(&repo);
    defer w.deinit();
    try w.word("Changes @--::@-");
    // Asked, not answered: the word did not wait for jj.
    try testing.expect(answered(w.a.core, w.serial) == null);
    try testing.expect(std.mem.indexOf(u8, told(w.a.core, w.id), "Changes: jj") != null);
    try w.land();
    try testing.expectEqual(@as(usize, 2), answered(w.a.core, w.serial).?.pins.len);
    try testing.expectEqualSlices(Line, answered(w.a.core, w.serial).?.lines, answered(w.r.core(), w.serial).?.lines);
}

test "a second Changes before the first's answer: only the second's pins" {
    var repo = try Repo.init(testing.allocator) orelse return error.SkipZigTest;
    defer repo.deinit(testing.allocator);
    var w = try WorkerJj.init(&repo);
    defer w.deinit();
    try w.word("Changes @--::@-");
    try w.word("Changes @-");
    try w.land();
    const ch = answered(w.a.core, w.serial).?;
    try testing.expectEqualStrings("@-", ch.pinned());
    try testing.expectEqual(@as(usize, 1), ch.pins.len);
}

test "the pane closed before its Changes answer: nothing pinned, nothing kept" {
    var repo = try Repo.init(testing.allocator) orelse return error.SkipZigTest;
    defer repo.deinit(testing.allocator);
    var w = try WorkerJj.init(&repo);
    defer w.deinit();
    try w.word("Changes @--::@-");
    try w.word("Del");
    try testing.expect(w.a.core.panes[w.id] == null or w.a.core.panes[w.id].?.serial != w.serial);
    try w.land();
    try testing.expectEqual(@as(usize, 0), w.a.core.changes.items.len);
}

test "Changes draws a lane a pinned change after the line number, nested ones a level to the right on their rows only, and a line one added whole green across it; bare again, the gutter as it was" {
    const gpa = testing.allocator;
    // `fn` wrote the function; `mid` rewrote its lines 3-4 as 3-6 (two
    // changed, two added whole); `shift` rewrote line 4 again.
    const fn_text = "fn f() void {\n    a();\n    b();\n    c();\n    g();\n    h();\n    i();\n}\n";
    const mid_text = "fn f() void {\n    a();\n    b2();\n    c2();\n    x();\n    y();\n    g();\n    h();\n    i();\n}\n";
    const shift_text = "fn f() void {\n    a();\n    b2();\n    c3();\n    x();\n    y();\n    g();\n    h();\n    i();\n}\n";
    var repo = try Repo.with(gpa, &.{ .{ fn_text, "fn" }, .{ mid_text, "mid" }, .{ shift_text, "shift" } }, null) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    for ([_]bool{ false, true }) |windowed| {
        const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = windowed });
        defer p.deinit();
        var line: [4200]u8 = undefined;
        p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
        const id = p.view().active;
        const pane = p.panes[id].?;
        const before = File.gutterWidth(pane);
        p.update(.{ .command = "Changes ::@" });
        try testing.expectEqual(@as(usize, 3), answered(p, pane.serial).?.pins.len);
        const cells: u16 = if (windowed) 2 else levels;
        try testing.expectEqual(before + cells, File.gutterWidth(pane));
        p.sync();
        var arena: std.heap.ArenaAllocator = .init(gpa);
        defer arena.deinit();
        const s = try p.render(arena.allocator());
        const body = s.region(.body, id).?.rect;
        const first = body.x + before;
        var buf: [8][3]u8 = undefined;
        const colours = laneColours(p.theme(), &buf);
        try testing.expect(colours.len >= 3);
        const ground = pardes.colors.Grounds.of(p.theme()).add.row;
        // Rows 1-10: `fn`'s spine on all; `mid` on 3-6; `shift` on 4.
        const want = [_][]const u8{ "0", "0", "01", "012", "01", "01", "0", "0", "0", "0" };
        for (want, 0..) |lanes, row| {
            const y = body.y + @as(u16, @intCast(row));
            if (windowed) {
                var n: usize = 0;
                for (s.lanes.items) |lane| if (lane.y == y) {
                    try testing.expectEqual(first, lane.x);
                    try testing.expectEqual(lanes[lane.level] - '0', lane.level);
                    try testing.expectEqual(colours[lane.level], lane.rgb);
                    n += 1;
                };
                try testing.expectEqual(lanes.len, n);
            } else for (0..levels) |level| {
                const cell = s.at(first + @as(u16, @intCast(level)), y);
                if (level < lanes.len) {
                    try testing.expectEqualStrings("\u{258e}", cell.grapheme());
                    try testing.expectEqual(pardes.Color{ .rgb = colours[level] }, cell.style.fg);
                } else if (!cell.default and !std.mem.eql(u8, cell.grapheme(), " ")) {
                    std.debug.print("row {d} level {d}: [{s}] {any}\n", .{ row, level, cell.grapheme(), cell.style });
                    return error.TestUnexpectedResult;
                }
            }
            // `fn`'s lines it still has (1, 2, 7-10) and `mid`'s x() and
            // y() (5, 6) were added whole; b2 (3) and c3 (4) changed one.
            const whole = row != 2 and row != 3;
            const text_cell = s.at(body.x + File.gutterWidth(pane) + 1, y);
            try testing.expectEqual(whole, std.meta.eql(text_cell.style.bg, pardes.Color{ .rgb = ground }));
        }
        if (!windowed) try testing.expectEqual(@as(usize, 0), s.lanes.items.len);
        p.update(.{ .command = "Changes" });
        try testing.expectEqual(before, File.gutterWidth(pane));
    }
}

/// A function three changes wrote: `fn` all of it, `mid` its lines 3-6
/// (rewriting two, adding two), `shift` line 4 again.
const Stack = struct {
    const fn_text = "fn f() void {\n    a();\n    b();\n    c();\n    g();\n    h();\n    i();\n}\n";
    const mid_text = "fn f() void {\n    a();\n    b2();\n    c2();\n    x();\n    y();\n    g();\n    h();\n    i();\n}\n";
    const shift_text = "fn f() void {\n    a();\n    b2();\n    c3();\n    x();\n    y();\n    g();\n    h();\n    i();\n}\n";
    /// Who wrote each of shift_text's lines: fn 0, mid 1, shift 2.
    const pins = [_]u16{ 0, 0, 1, 2, 1, 1, 0, 0, 0, 0 };

    fn repo(working: ?[]const u8) !?Repo {
        return Repo.with(testing.allocator, &.{ .{ fn_text, "fn" }, .{ mid_text, "mid" }, .{ shift_text, "shift" } }, working);
    }
};

fn pinsOf(ch: *const Changes, out: []u16) []u16 {
    for (ch.lines, out[0..ch.lines.len]) |l, *o| o.* = @intFromEnum(l.pin);
    return out[0..ch.lines.len];
}

test "Changes lines jj's annotation up with the pane's text: a line jj has not seen (typed, not snapshotted) is nobody's, the lines after it keep their changes" {
    // The file on disk has a line more than jj's last snapshot of it.
    const working = "fn f() void {\n    a();\n    b2();\n    c3();\n    x();\n    new();\n    y();\n    g();\n    h();\n    i();\n}\n";
    var repo = try Stack.repo(working) orelse return error.SkipZigTest;
    defer repo.deinit(testing.allocator);
    const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = false });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
    const pane = p.panes[p.view().active].?;
    try testing.expectEqualStrings(working, pane.file.?.content);
    p.update(.{ .command = "Changes ::@" });
    const none = @intFromEnum(PinIndex.none);
    var got: [16]u16 = undefined;
    try testing.expectEqualSlices(u16, &.{ 0, 0, 1, 2, 1, none, 1, 0, 0, 0, 0 }, pinsOf(answered(p, pane.serial).?, &got));
}

test "the lanes ride with the text: a line typed in a nested block is nobody's, its undo puts the values back, a deleted line takes its value; a client replays it equal" {
    var repo = try Stack.repo(null) orelse return error.SkipZigTest;
    defer repo.deinit(testing.allocator);
    const R = pardes.replica;
    const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{}, false);
    defer a.deinit();
    const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0), false);
    defer r.deinit();
    const Keys = struct {
        fn send(au: *R.Authority, re: *R.Replica, keys: []const u8) !void {
            for (keys) |k| {
                const ev: pardes.Event = if (k == 27) .{ .key = .{ .cp = pardes.Key.escape } } else .{ .key = .{ .cp = k, .text = &[_]u8{k} } };
                re.confirm(try au.local(ev));
            }
            re.settle();
        }
    };
    var line: [4200]u8 = undefined;
    r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }));
    r.confirm(try a.local(.{ .command = "Changes ::@" }));
    r.settle();
    const serial = a.core.panes[a.core.view().active].?.serial;
    const ch = answered(a.core, serial).?;
    var got: [16]u16 = undefined;
    try testing.expectEqualSlices(u16, &Stack.pins, pinsOf(ch, &got));
    const before = try testing.allocator.dupe(Line, ch.lines);
    defer testing.allocator.free(before);
    const none = @intFromEnum(PinIndex.none);
    // A line opened below `c3();` (line 4, inside mid's block): nobody's;
    // the rows around keep their lanes.
    r.confirm(try a.local(.{ .command = "Look a.zig:4" }));
    try Keys.send(a, r, "oz\x1b");
    try testing.expectEqualSlices(u16, &.{ 0, 0, 1, 2, none, 1, 1, 0, 0, 0, 0 }, pinsOf(answered(a.core, serial).?, &got));
    try testing.expectEqual(before[3].lanes, answered(a.core, serial).?.lines[3].lanes);
    try testing.expectEqual(before[4].lanes, answered(a.core, serial).?.lines[5].lanes);
    // Undone: the values as they were.
    try Keys.send(a, r, "u");
    try testing.expectEqualSlices(Line, before, answered(a.core, serial).?.lines);
    // `x();` (line 5, mid's) deleted: its value goes with it.
    r.confirm(try a.local(.{ .command = "Look a.zig:5" }));
    try Keys.send(a, r, ";xd");
    try testing.expectEqualStrings(Stack.shift_text[0..41] ++ Stack.shift_text[50..], a.core.panes[a.core.view().active].?.file.?.content);
    try testing.expectEqualSlices(u16, &.{ 0, 0, 1, 2, 1, 0, 0, 0, 0 }, pinsOf(answered(a.core, serial).?, &got));
    try testing.expectEqual(before[5].lanes, answered(a.core, serial).?.lines[4].lanes);
    try testing.expect(r.diverged == null);
    try testing.expectEqualSlices(Line, answered(a.core, serial).?.lines, answered(r.core(), serial).?.lines);
    try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core()));
}

test "a B3 click on path@rev:line in running text opens the file at that revision there" {
    const gpa = testing.allocator;
    var repo = try Repo.init(gpa) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    try repo.tmp.dir.writeFile(testing.io, .{ .sub_path = "notes.txt", .data = "see a.zig@@-:2 here\n" });
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/notes.txt", .{repo.dir}) });
    const notes = p.view().active;
    p.sync();
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    const s = try p.render(arena.allocator());
    const body = s.region(.body, notes).?.rect;
    // On the `@` of the address, the body's first row.
    const x: u16 = body.x + File.gutterWidth(p.panes[notes].?) + @as(u16, "see a.zig".len);
    p.update(.{ .mouse = .{ .button = .right, .kind = .press, .col = x, .row = body.y } });
    p.update(.{ .mouse = .{ .button = .right, .kind = .release, .col = x, .row = body.y } });
    const shown = p.view().active;
    try testing.expect(shown != notes);
    const f = &p.panes[shown].?.file.?;
    try testing.expect(of(f) != null);
    try testing.expectEqualStrings(Repo.two, f.content);
    try testing.expectEqual(@as(i32, 1), p.panes[shown].?.body.cur_row);
}

test "a revision's text is read-only over 9P too: an open to write it is refused in words" {
    const gpa = testing.allocator;
    var repo = try Repo.init(gpa) orelse return error.SkipZigTest;
    defer repo.deinit(gpa);
    const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 });
    defer p.deinit();
    var line: [4200]u8 = undefined;
    p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) });
    const pane = p.panes[p.view().active].?;
    try testing.expect(of(&pane.file.?) != null);
    const th = @import("ninep/harness.zig");
    const tree = @import("ninep/tree.zig");
    for ([_]tree.PaneFile{ .body, .data, .xdata, .sel }) |file| {
        const got = th.call(p, .{ .tag = 1, .op = .open, .node = tree.Node.of(pane.serial, file), .omode = 1 });
        try testing.expectEqual(@as(u16, 30), got.errno());
        try testing.expectEqual(@as(u16, 30), @import("cloud9").fs.enameErrno(got.reply.ename));
    }
    // Reading it is as any text's.
    try testing.expectEqual(@as(u16, 0), th.call(p, .{ .tag = 1, .op = .open, .node = tree.Node.of(pane.serial, .body), .omode = 0 }).errno());
    try testing.expectEqualStrings(Repo.two, pane.file.?.content);
}