From 40094a08394fc0ecba2876e4e934e2158b17bdab Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 22 Nov 2026 02:45:04 -0300 Subject: soak: ONE soak, the pty's bytes' (the old road's deletion, piece 1 of 8, the user's ruling of 2026-11-22): test/replicas.zig loses its screen-state mode and `--bytes` stops being a flag (its clients' terminals are always their own emulators fed the units' bytes, the session's Peers.bytes set): gone are the screen_down/screen_up messages, the `deltas wrong` check (screens_checked/screens_wrong/resets and the session's version-to-screen record, `flushed`, `versions`), the delta and fill counters (deltas, delta and filled bytes, rows fetched, encode and apply times: the terminals' table is now a peer's unit bytes a second under the flood), `flushAll` and the delta half of `sendUnit` (the old in-process rig), and the `--screen-state ` encoder soak (`screenState`, `encodeBench`, `floods`); kept on the one road: the quiescence check that every client's terminal is the session's cell for cell and its kitty images pixel for pixel, the witness (it never held screen messages), the image and kitty-answer checks (unconditional now), the join in the middle of the flood (client 4 at the flood's start + 100 ms, always), and `--echo`, rewired to the bytes road (Authority and Replica of the bytes kind, the echo armed by hand as a joined client's is; a key's echo seen when the client has fed the authority's unit after the one before its echo: `unit_before`, `fed`), its gates the same (diverged, unequal, secret frames, vim predicted, drawn wrong) less `screens-wrong`; the diff, plumb and corpus cases made on the bytes road too; the one soak is `zig build replicas -Dplatform=tui ... -- --clients 5`; checked: `--echo --seeds 1 --rtt 80` (rc 0, 0 diverged 0 unequal, 7.3 ms p50 with prediction against 105 ms without) and `--seeds 1 --steps 30 --clients 3 --rtt 80` (rc 0, diverged 0, unequal 0, unlisted 0, corpus 22 scenes, diff and plumb the same); core-test and shell-test do not build this file (the base's 911/1075 and 1117/1120); -424 +71 lines Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- test/replicas.zig | 495 ++++++++---------------------------------------------- 1 file changed, 71 insertions(+), 424 deletions(-) diff --git a/test/replicas.zig b/test/replicas.zig index 48eaa857..f1d5c478 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -12,32 +12,27 @@ //! and joins again for its view, and those past the views a session has //! are refused until one is let go. //! -//! Terminals cross as screen state (core/term/screen_state.zig): the session's -//! shell pane runs a full-screen program and then a flood (`--flood` MB of -//! `yes`, then as much of a `cat` of source text) while the clients type, its output stepped by the authority -//! and sent to each replica as deltas, once a frame and before any input -//! the authority steps, each replica acknowledging them over its link and -//! asking for the rows it scrolls back into and does not hold. +//! Terminals cross as the pty's bytes in the session's units: the +//! session's shell pane runs a full-screen program and then a flood +//! (`--flood` MB of `yes`, then as much of a `cat` of source text) while the +//! clients type, and each client feeds its own emulators what its units +//! carry, in the tape's order. //! //! zig build replicas -Dplatform=tui -- [--seeds N] [--steps M] [--clients C] [--rtt 30,80,207] [--first K] [--flood MB] //! zig build replicas -Dplatform=tui -- --echo [--seeds N] [--rtt 30,80,207] [--first K] -//! zig build replicas -Dplatform=tui -Doptimize=ReleaseFast -- --screen-state //! //! `--echo` types a corpus into a shell instead, with and without the //! predicted echo (core/term/echo.zig), and gates what it draws: below, at -//! "predicted echo". `--screen-state` runs recorded pty streams through -//! screen_state's soak and measures its encoder: below, at screenState. +//! "predicted echo". //! //! Gates, per seed and RTT: no replica diverges (every confirmed unit's //! digests agree as it is replayed), and at quiescence every replica's -//! digest and every file's text are the authority's; every delta a replica applies leaves its -//! terminal what the authority's was at that version, and at quiescence it -//! is the authority's, cell for cell. Reported per RTT: how inputs went +//! digest and every file's text are the authority's, and every terminal +//! the authority's, cell for cell. Reported per RTT: how inputs went //! (applied at once, stopped at a host call, left to the authority), how //! units were taken (fast path, rollback for a misprediction or another's //! input), what a speculative apply, a copy and a rollback cost against a -//! frame, and the terminals': deltas a second, wire bytes a second under -//! the flood, encode a frame (every peer), apply a delta. +//! frame, and a peer's unit bytes a second under the flood. const std = @import("std"); const libc = std.c; const pardes = @import("pardes"); @@ -53,10 +48,6 @@ const gpa = std.heap.c_allocator; pub const std_options: std.Options = .{ .log_level = .warn }; extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; var trace = false; -/// `--bytes`: its clients are replicas of the bytes kind, each terminal fed -/// the pty's bytes its units carry into an emulator of its own, joined from -/// a dump with every emulator whole (core/replica.zig `Peers.bytes`). -var bytes_kind = false; /// `--witness`: the witness judged at every run's end, not only after a /// divergence (`Witness`). var witness_always = false; @@ -157,8 +148,6 @@ const Kind = enum { echo, frame, output, - screen_down, - screen_up, client_frame, /// The session's own frontend's input, in its own view. own, @@ -247,25 +236,12 @@ const Totals = struct { copy_ns: std.ArrayListUnmanaged(u64) = .empty, rollback_ns: std.ArrayListUnmanaged(u64) = .empty, // Terminals. - apply_ns: std.ArrayListUnmanaged(u64) = .empty, - frame_ns: std.ArrayListUnmanaged(u64) = .empty, - deltas: u64 = 0, - delta_bytes: u64 = 0, unit_bytes: u64 = 0, - /// Deltas the replicas applied while the flood ran. - flood_deltas: u64 = 0, flood_us: u64 = 0, /// Kitty images a client held at quiescence, the session's pixels /// (`--bytes`, `images`). images_equal: u64 = 0, - flood_delta_bytes: u64 = 0, flood_unit_bytes: u64 = 0, - fetched: u64 = 0, - /// Bytes of rows sent before a step's unit, the step having read them. - filled_bytes: u64 = 0, - resets: u64 = 0, - screens_wrong: u64 = 0, - screens_checked: u64 = 0, /// Joins from a dump, refused, again after a divergence put on it /// (PARDES_TEST_DIVERGE's), and clients that left; quiet checks. joins: u64 = 0, @@ -322,7 +298,6 @@ const Totals = struct { try t.spec_ns.appendSlice(gpa, s.spec_ns.items); try t.copy_ns.appendSlice(gpa, s.copy_ns.items); try t.rollback_ns.appendSlice(gpa, s.rollback_ns.items); - try t.apply_ns.appendSlice(gpa, s.apply_ns.items); } }; @@ -464,17 +439,7 @@ fn writeText(path: [:0]const u8, text: []const u8) !void { const Run = struct { seed: u64, rtt_ms: u64, steps: usize, clients: u16, flood_mb: u64 }; -/// The terminal pane's screen as a hash of screen_state's dump of it. -/// The module's own replica behind the core's handle (Replica.screens). -fn replicaOf(r: *pardes.Term.Replica) *screen_state.Replica { - return @ptrCast(@alignCast(r)); -} - -/// The module's own track behind the core's handle (Screens.tracks). -fn trackOf(t: *pardes.Term.Track) *screen_state.Track { - return @ptrCast(@alignCast(t)); -} - +/// The terminal pane's screen as a hash of a dump of its cells. fn screenHash(t: *screen_state.Terminal) u64 { var buf: [8192]u8 = undefined; var h: std.Io.Writer.Hashing(std.hash.Wyhash) = .initHasher(.init(0), &buf); @@ -1019,10 +984,8 @@ const Witness = struct { // No client's id: every unit is another's. const rp = try replica.Replica.initDump(gpa, std.math.maxInt(u16), d.view, d.bytes, .{ .cols = d.cols, .rows = d.rows, .distrusted = &distrusted }); rp.guess = false; - if (bytes_kind) { - rp.t.screen_state = false; - rp.core().echo = null; - } + rp.t.screen_state = false; + rp.core().echo = null; rp.t.local_files = true; return rp; } @@ -1225,19 +1188,12 @@ const Soak = struct { frames_left: u32 = 0, flood_end: u64 = 0, program: struct { bytes: []const u8 = &.{}, at: usize = 0 } = .{}, - /// The session's version of each terminal, as its screen showed then. - versions: std.AutoHashMapUnmanaged(u64, u64) = .empty, - flood_deltas: [8]u64 = @splat(0), kinds_seen: u32 = 0, /// Each client's link made (its first join), and its replica's. has_link: [8]bool = @splat(false), /// An input of its own frontend's held for the next wait, a pty's /// output taken in this one (tui.zig `split`). held: ?Msg = null, - /// The step boundary after a frame's wake under the flood: what its - /// encoding cost. - framed: bool = false, - encode_ns: u64 = 0, /// The session's pty told the answers to the program's kitty query and /// its four images (`questions`, `images`, `kitty_oks`): each once, whatever the /// clients. @@ -1340,8 +1296,7 @@ const Soak = struct { pub fn open(s: *Soak, l: *SessionLoop) !pardes.Host { s.l = l; l.peers.threads = false; - l.peers.bytes = bytes_kind; - l.peers.flushed = .{ .ctx = s, .f = flushed }; + l.peers.bytes = true; const host: pardes.Host = .{ .ctx = s, .vtable = &vtable }; l.core.host = host; return host; @@ -1368,7 +1323,6 @@ const Soak = struct { if (s.held) |m| if (m.bytes.len > 0) gpa.free(m.bytes); for (s.echo.items) |e| gpa.free(e.bytes); s.echo.deinit(gpa); - s.versions.deinit(gpa); } /// The tty's own boot (a raw shell, a text pane under it), then three @@ -1409,7 +1363,7 @@ const Soak = struct { 2 => 1_200_000, // One joins in the middle of the flood, its emulators loaded // whole and every other side's reloaded. - 3 => if (bytes_kind) flood_at + 100_000 else 2_300_000, + 3 => flood_at + 100_000, else => 2_000_000 + c * 100_000, }; try net.send(.{ .at = at, .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); @@ -1511,7 +1465,7 @@ const Soak = struct { cl.view = welcome.view.index(); cl.digest = welcome.digest; s.totals.joins += 1; - if (bytes_kind) Witness.joined(c, cl, try gpa.dupe(u8, whole.items), cl.join_seq); // never given the screen deltas, it checks no screen-state run + Witness.joined(c, cl, try gpa.dupe(u8, whole.items), cl.join_seq); try net.toClient(c, now, .dump, cl.gen, try whole.toOwnedSlice(gpa)); }; // A Detach typed in a client's view, or one cut off for its lag: its @@ -1542,10 +1496,6 @@ const Soak = struct { }; for (s.echo.items) |e| try net.send(.{ .at = now + 2_000, .n = 0, .kind = .echo, .who = e.pane, .bytes = e.bytes }); s.echo.clearRetainingCapacity(); - if (s.framed) { - s.framed = false; - if (now >= flood_at and (s.flood_end == 0 or now <= s.flood_end)) try s.totals.frame_ns.append(gpa, ps.screens.encode_ns - s.encode_ns); - } } /// The units the session queued for client `cl` since, their heads @@ -1610,14 +1560,6 @@ const Soak = struct { if (flooding) s.totals.flood_unit_bytes += f.payload.len; try net.toClient(c, now, .to_replica, cl.gen, try gpa.dupe(u8, f.payload)); }, - .screen => { - if (f.payload[5] == 1) { - s.totals.deltas += 1; - s.totals.delta_bytes += f.payload.len; - if (flooding) s.totals.flood_delta_bytes += f.payload.len; - } else s.totals.filled_bytes += f.payload.len; - try net.toClient(c, now, .screen_down, cl.gen, try gpa.dupe(u8, f.payload)); - }, .check => { const d = try gpa.alloc(u8, 8); std.mem.writeInt(u64, d[0..8], (try pardes.wire.decodeServer(f.tag, f.payload)).check, .little); @@ -1644,20 +1586,6 @@ const Soak = struct { try s.net.toClient(c, s.now, .gone, cl.gen, &.{}); } - /// Each terminal at its version as the session's screen shows it now - /// (after a flush: `Peers.flushed`). - fn flushed(ctx: *anyopaque, core: *pardes.Pardes, screens: *replica.Screens) void { - const s: *Soak = @ptrCast(@alignCast(ctx)); - for (&screens.tracks, 0..) |*slot, id| if (slot.*) |*tr| { - const key = @as(u64, tr.serial) << 32 | trackOf(tr.track).version; - if (trackOf(tr.track).version == 0 or s.versions.contains(key)) continue; - _ = core.panes[id] orelse continue; - s.versions.put(gpa, key, screenHash(&pardes.Term.emulatorOf(tr.state).vt)) catch |err| { - s.err = err; - }; - }; - } - pub fn upgradeAsked(_: *Soak) void {} pub fn restoring(_: *Soak, _: *pardes.Pardes) void {} pub fn restored(_: *Soak, _: *SessionLoop) void {} @@ -1672,8 +1600,8 @@ const Soak = struct { fn wait(s: *Soak, timeout_ms: u32) !bool { const core = s.l.core; const net = s.net; - // An input of its own held while a pty's output was taken: the step - // after reads the terminal as the clients' deltas bring it. + // An input of its own held while a pty's output was taken: its step + // comes after that output's. if (s.held) |m| { s.held = null; try s.own(m); @@ -1713,7 +1641,7 @@ const Soak = struct { // tape is stepped in it between its steps (tape.enter's check), // and no rollback epoch's trees are held. const in_client = switch (m.kind) { - .refused, .dump, .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone, .word => true, + .refused, .dump, .input, .to_replica, .checked, .blob, .wake, .quit, .gone, .word => true, .draw => Draws.jobs.items.len > 0 and Draws.jobs.items[0].draw != null and Draws.jobs.items[0].draw != @as(?*const pardes.Pardes, core), else => false, }; @@ -1777,11 +1705,7 @@ const Soak = struct { const busy = s.typing > 0 or s.flood_end == 0; s.frames_left = if (busy) 120 else s.frames_left -| 1; if (s.frames_left > 0) try net.send(.{ .at = m.at + frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} }); - if (took_output or core.needs_frame or (core.nextWake() orelse std.math.maxInt(u64)) <= s.now_ns) { - s.framed = true; - s.encode_ns = s.l.peers.screens.encode_ns; - return false; - } + if (took_output or core.needs_frame or (core.nextWake() orelse std.math.maxInt(u64)) <= s.now_ns) return false; }, // Room in the far link: its Peer's writer goes on. .drain => { @@ -1812,8 +1736,6 @@ const Soak = struct { if (m.gen != cl.gen or cl.read_done or cl.shut) continue; const f = (try pardes.wire.framed(m.bytes)) orelse return error.BadFrame; if (ending and f.tag == @backingInt(pardes.wire.ClientTag.check)) continue; - if (f.tag == @backingInt(pardes.wire.ClientTag.screen_ack) and f.payload.len >= 22 and f.payload[5] == 2) - s.totals.fetched += std.mem.readInt(u64, f.payload[14..22], .little) - std.mem.readInt(u64, f.payload[6..14], .little); if (!peer.take(f.tag, f.payload)) { cl.read_done = true; s.l.peers.post(.{ .gone = peer }); @@ -1884,7 +1806,7 @@ const Soak = struct { } }, .dump => try s.joined(cl, c, m), - .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone, .word => { + .input, .to_replica, .checked, .blob, .wake, .quit, .gone, .word => { if (m.kind == .input and cl.left == 0) continue; const rp = cl.r orelse if (m.kind == .input and cl.dialling) { try net.send(.{ .at = m.at + 50_000, .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }); @@ -1931,26 +1853,6 @@ const Soak = struct { }, .word => cl.loop.take(.{ .refused = try std.heap.c_allocator.dupe(u8, m.bytes) }), .blob => cl.loop.take(.{ .blob = try std.heap.c_allocator.dupe(u8, m.bytes) }), - .screen_down => { - const pane = m.bytes[0]; - const was = if (rp.screens[pane]) |sc| replicaOf(sc.rep).seq else 0; - cl.loop.take(.{ .screen = try std.heap.c_allocator.dupe(u8, m.bytes) }); - if (m.bytes[5] == 1) if (rp.screens[pane]) |sc| { - const now_seq = replicaOf(sc.rep).seq; - if (now_seq == was) s.totals.resets += 1 else { - // Applied: the screen is the session's at that version. - s.totals.screens_checked += 1; - const want = s.versions.get(@as(u64, sc.serial) << 32 | now_seq); - const vt = &pardes.Term.emulatorOf(rp.core().panes[pane].?.terminal.?).vt; - if (want == null or want.? != screenHash(vt)) { - s.totals.screens_wrong += 1; - std.debug.print("seed {d} rtt {d} ms: client {d}'s terminal {d} at version {d} is not the session's\n", .{ s.r.seed, s.r.rtt_ms, m.who, pane, now_seq }); - } - // Deltas while the flood runs (an RTT/2 behind it). - if (m.at >= flood_at + net.one_way and (s.flood_end == 0 or m.at <= s.flood_end + net.one_way)) s.flood_deltas[c] += 1; - } - }; - }, .checked => cl.loop.take(.{ .checked = std.mem.readInt(u64, m.bytes[0..8], .little) }), .wake => { // One the next replaced is no wake. @@ -1967,7 +1869,7 @@ const Soak = struct { try woke(cl, c, net, m.at, s.totals, s.r); if (cl.loop.link.quit) try ended(cl, c, net, m.at, s.totals, s.r, &s.typing); }, - .to_authority, .screen_up, .client_frame, .check_up, .bye_up => unreachable, + .to_authority, .client_frame, .check_up, .bye_up => unreachable, } } } @@ -2049,10 +1951,8 @@ const Soak = struct { } } // Its terminals its own emulators, fed what the units carry. - if (bytes_kind) { - rp.t.screen_state = false; - rp.core().echo = null; - } + rp.t.screen_state = false; + rp.core().echo = null; rp.stats.samples = true; rp.t.local_files = true; rp.echo.now = m.at * 1000; @@ -2089,21 +1989,20 @@ const Soak = struct { const totals = s.totals; const core = s.l.core; totals.flood_us += s.flood_end -| flood_at; - for (s.flood_deltas[0..s.clients.len]) |d| totals.flood_deltas += d; const want = pardes.tape.digestOf(core); totals.cut += s.l.peers.cut; - if (bytes_kind) std.debug.print("seed {d} rtt {d} ms: a join's step at worst {d} us (the session's reloads and its dump), the last dump {d} KB ({d} KB of state)\n", .{ s.r.seed, s.r.rtt_ms, s.join_worst / 1000, s.l.peers.dump_bytes >> 10, s.l.peers.state_bytes >> 10 }); + std.debug.print("seed {d} rtt {d} ms: a join's step at worst {d} us (the session's reloads and its dump), the last dump {d} KB ({d} KB of state)\n", .{ s.r.seed, s.r.rtt_ms, s.join_worst / 1000, s.l.peers.dump_bytes >> 10, s.l.peers.state_bytes >> 10 }); if (s.net.throttled) |c| if (!s.far_final) std.debug.print("seed {d} rtt {d} ms: the far client never showed the screen after the flood ({s})\n", .{ s.r.seed, s.r.rtt_ms, if (s.clients[c].r == null) "it left" else "it is joined" }); - if (bytes_kind) for (kitty_oks, s.kitty_answers) |ok, n| if (n != 1) { + for (kitty_oks, s.kitty_answers) |ok, n| if (n != 1) { totals.unequal += 1; std.debug.print("seed {d} rtt {d} ms: the program's kitty {f} was answered {d} times on the session's pty\n", .{ s.r.seed, s.r.rtt_ms, std.ascii.hexEscape(ok, .lower), n }); }; - if (bytes_kind) for (&s.media.temp, &s.media.object) |*temp, *object| { + for (&s.media.temp, &s.media.object) |*temp, *object| { for ([_][:0]const u8{ temp, object }, [_]bool{ libc.access(temp, libc.F_OK) == 0, shm.shm_open(object, @bitCast(libc.O{ .ACCMODE = .RDONLY }), 0) >= 0 }) |name, left| if (left) { totals.unequal += 1; std.debug.print("seed {d} rtt {d} ms: {s}, an image's medium, is still there\n", .{ s.r.seed, s.r.rtt_ms, name }); }; - }; + } for (s.clients, 1..) |*cl, id| { totals.resizes += cl.resizes; totals.wakes += cl.wakes; @@ -2231,17 +2130,17 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { defer gpa.free(tui); const session_only = try screen_state.shellStream(gpa); defer gpa.free(session_only); - const shell_session = try std.mem.concat(gpa, u8, &.{ session_only, if (bytes_kind) questions else "" }); + const shell_session = try std.mem.concat(gpa, u8, &.{ session_only, questions }); defer gpa.free(shell_session); var media: Media = undefined; - const shown = if (bytes_kind) try images(dir, r.seed, &media) else ""; - defer if (bytes_kind) { + const shown = try images(dir, r.seed, &media); + defer { gpa.free(shown); for (&media.temp, &media.object) |*temp, *object| { _ = libc.unlink(temp); _ = shm.shm_unlink(object); } - }; + } const yes_only = try screen_state.yesStream(gpa, @intCast(r.flood_mb * (1 << 20) / 3)); defer gpa.free(yes_only); const yes = try std.mem.concat(gpa, u8, &.{ yes_only, shown }); @@ -2426,11 +2325,11 @@ fn diffCase(dir: []const u8) !bool { const look = try std.fmt.bufPrint(&lbuf, "Look {s}", .{patch}); var ok = true; for ([_]bool{ false, true }) |own| { - const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, host.host(), true); + const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, host.host(), false); defer a.deinit(); const first = try gpa.dupe(u8, try a.unit(0, 0)); defer gpa.free(first); - const rp = try replica.Replica.init(gpa, 1, first, true); + const rp = try replica.Replica.init(gpa, 1, first, false); defer rp.deinit(); if (own) { const msg = try gpa.dupe(u8, try rp.input(.{ .command = look })); @@ -2491,11 +2390,11 @@ fn plumbCase(dir: []const u8) !bool { const open = try std.fmt.bufPrint(&obuf, "Look {s}", .{notes}); var ok = true; for ([_][]const u8{ "Look https://ziglang.org", "Look 3f2a9c1" }) |look| for ([_]bool{ false, true }) |own| { - const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, host.host(), true); + const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, host.host(), false); defer a.deinit(); const first = try gpa.dupe(u8, try a.unit(0, 0)); defer gpa.free(first); - const rp = try replica.Replica.init(gpa, 1, first, true); + const rp = try replica.Replica.init(gpa, 1, first, false); defer rp.deinit(); rp.confirm(try a.local(.{ .command = open })); rp.settle(); @@ -2543,11 +2442,11 @@ fn plumbCase(dir: []const u8) !bool { // The rule from the session's plumbing file, read at boot. var pbuf: [256]u8 = undefined; try writeText(try std.fmt.bufPrintSentinel(&pbuf, "{s}/plumbing", .{dir}, 0), "type is text\ndata matches 'https://letters/.*'\nplumb to seemail\n\ninclude basic\n"); - const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty, .config_dir = dir }, host.host(), true); + const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty, .config_dir = dir }, host.host(), false); defer a.deinit(); const first = try gpa.dupe(u8, try a.unit(0, 0)); defer gpa.free(first); - const rp = try replica.Replica.init(gpa, 1, first, true); + const rp = try replica.Replica.init(gpa, 1, first, false); defer rp.deinit(); rp.confirm(try a.local(.{ .command = open })); rp.settle(); @@ -2590,48 +2489,8 @@ fn push(q: *std.PriorityQueue(Msg, void, Msg.order), nn: *u64, m: Msg) !void { try q.push(gpa, mm); } -/// What each peer is owed of the terminals, onto its link (before the -/// authority steps an input, and once a frame); each version as the -/// authority's screen showed it. -fn flushAll(sc: *replica.Screens, core: *pardes.Pardes, ps: []const u16, list: *std.ArrayListUnmanaged([]u8), q: *std.PriorityQueue(Msg, void, Msg.order), nn: *u64, now: u64, dl: []Link, rnd: std.Random, ow: u64, jt: u64, vs: *std.AutoHashMapUnmanaged(u64, u64), tot: *Totals) !void { - for (ps, 0..) |peer, c| { - list.clearRetainingCapacity(); - // Terminals alone cross: the view is not read. - try sc.flush(core, peer, list); - for (list.items) |bytes| { - tot.deltas += 1; - tot.delta_bytes += bytes.len; - try push(q, nn, .{ .at = dl[c].arrive(rnd, now, ow, jt), .n = 0, .kind = .screen_down, .who = @intCast(c + 1), .bytes = bytes }); - } - } - // Each version as the authority's screen showed it. - for (&sc.tracks, 0..) |*slot, id| if (slot.*) |*tr| { - const key = @as(u64, tr.serial) << 32 | trackOf(tr.track).version; - if (trackOf(tr.track).version == 0 or vs.contains(key)) continue; - _ = core.panes[id] orelse continue; - try vs.put(gpa, key, screenHash(&pardes.Term.emulatorOf(tr.state).vt)); - }; -} - -/// A unit of the authority's to every replica, down its link: first the -/// rows of its terminals its step read that a replica holds as holes. -fn sendUnit(q: *std.PriorityQueue(Msg, void, Msg.order), n: *u64, unit: []const u8, now: u64, down: []Link, random: std.Random, one_way: u64, jitter: u64, totals: *Totals, flooding: bool, screens: *replica.Screens, core: *pardes.Pardes, peers: []const u16) !void { - var rows: std.ArrayListUnmanaged([]u8) = .empty; - defer rows.deinit(gpa); - for (down, peers, 1..) |*l, peer, who| { - rows.clearRetainingCapacity(); - try screens.fill(core, peer, &rows); - for (rows.items) |bytes| { - totals.filled_bytes += bytes.len; - try q.push(gpa, .{ .at = l.arrive(random, now, one_way, jitter), .n = n.*, .kind = .screen_down, .who = @intCast(who), .bytes = bytes }); - n.* += 1; - } - } - screens.filled(core); - // The sizes its steps gave terminals, after their rows (Peers.unit). - pardes.panes.resizeDeferred(core); - totals.unit_bytes += unit.len * down.len; - if (flooding) totals.flood_unit_bytes += unit.len * down.len; +/// A unit of the authority's to every replica, down its link. +fn sendUnit(q: *std.PriorityQueue(Msg, void, Msg.order), n: *u64, unit: []const u8, now: u64, down: []Link, random: std.Random, one_way: u64, jitter: u64) !void { for (down, 1..) |*l, who| { try q.push(gpa, .{ .at = l.arrive(random, now, one_way, jitter), .n = n.*, .kind = .to_replica, .who = @intCast(who), .bytes = try gpa.dupe(u8, unit) }); n.* += 1; @@ -2647,8 +2506,8 @@ fn sendUnit(q: *std.PriorityQueue(Msg, void, Msg.order), n: *u64, unit: []const // plain echo, no marks). Each key's echo comes back 2 ms after the authority // writes it, as a shell's. The client types at a typist's pace and in bursts; // each of its frames (60 Hz, a phase of its own) is what its screen shows: -// the predicted echo where it is drawn (core/term/echo.zig), the screen state -// under it. Per key the shell echoed at a prompt or in cat: the time from +// the predicted echo where it is drawn (core/term/echo.zig), its own +// emulator under it, fed the units' bytes. Per key the shell echoed at a prompt or in cat: the time from // the key to its character on that screen, with prediction and without. Per // key predicted: whether the authority's screen, right after its echo, // shows what was predicted where it was. Per key drawn wrong: its frames. @@ -2961,10 +2820,10 @@ const Typed = struct { pred: ?struct { x: u16, y: u16, cp: u21 } = null, pcur: ?struct { x: u16, y: u16 } = null, /// The shell's mode as it took the key; whether it printed anything for - /// it; the authority's version of the screen before that. + /// it; the authority's last unit before that (its echo is in a later one). mode: ?FakeShell.Mode = null, echoed: bool = false, - version_before: u32 = 0, + unit_before: u32 = 0, /// The authority's screen right after its echo: its cursor and the /// cursor's row; whether that is what was predicted. after: ?struct { x: u16, y: u16, row: [128]u21 } = null, @@ -2972,7 +2831,7 @@ const Typed = struct { /// Its prediction drawn: first, and in how many frames. first_visible: ?u64 = null, visible_frames: u32 = 0, - /// The screen state showing its echo, first. + /// The client's emulator showing its echo, first. seen: ?u64 = null, }; @@ -2994,7 +2853,6 @@ const EchoTotals = struct { alt_predicted: u64 = 0, divergences: u64 = 0, unequal: u64 = 0, - screens_wrong: u64 = 0, /// The replica's frame drawn while it shows a prediction (its core's /// render, the tty's and the GUI's), and the overlay's part of it (ns); /// cells drawn otherwise than predicted. @@ -3043,14 +2901,11 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { } var sh: FakeShell = .{}; defer sh.out.deinit(gpa); - const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty_shell }, host.host(), true); + const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty_shell }, host.host(), false); defer a.deinit(); - var screens: replica.Screens = .init(gpa); - defer screens.deinit(a.core); - const peer = try screens.addPeer(); - const peers = [_]u16{peer}; - const rp = try replica.Replica.init(gpa, 1, try a.unit(0, 0), true); + const rp = try replica.Replica.init(gpa, 1, try a.unit(0, 0), false); defer rp.deinit(); + rp.core().echo = &rp.echo; rp.echo.on = on; const shell: u8 = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break @intCast(id); @@ -3065,11 +2920,7 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { t.spec_ns.deinit(gpa); t.copy_ns.deinit(gpa); t.rollback_ns.deinit(gpa); - t.apply_ns.deinit(gpa); - t.frame_ns.deinit(gpa); } - var versions: std.AutoHashMapUnmanaged(u64, u64) = .empty; - defer versions.deinit(gpa); var queue: std.PriorityQueue(Msg, void, Msg.order) = .empty; defer { while (queue.pop()) |m| if (m.bytes.len > 0) gpa.free(m.bytes); @@ -3080,8 +2931,8 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { const jitter = one_way / 10; var up: [1]Link = @splat(.{}); var down: [1]Link = @splat(.{}); - var owed: std.ArrayListUnmanaged([]u8) = .empty; - defer owed.deinit(gpa); + // The last of the authority's own units the replica fed its emulator. + var fed: u32 = 0; // The shell's first prompt. sh.put(prompt_bytes); @@ -3131,12 +2982,11 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { if (next_step < corpus.steps.items.len) try push(&queue, &n, .{ .at = m.at + corpus.steps.items[next_step].gap, .n = 0, .kind = .input, .who = 1, .bytes = &.{} }); }, .to_authority => { - if (try a.pending()) |batch| try sendUnit(&queue, &n, batch, m.at, &down, random, one_way, jitter, &t, false, &screens, a.core, &peers); - try flushAll(&screens, a.core, &peers, &owed, &queue, &n, m.at, &down, random, one_way, jitter, &versions, &t); + if (try a.pending()) |batch| try sendUnit(&queue, &n, batch, m.at, &down, random, one_way, jitter); host.current = (replica.parseInput(m.bytes) orelse return error.BadInput).seq; const unit = try a.take(m.bytes); host.current = 0; - try sendUnit(&queue, &n, unit, m.at, &down, random, one_way, jitter, &t, false, &screens, a.core, &peers); + try sendUnit(&queue, &n, unit, m.at, &down, random, one_way, jitter); for (host.writes.items) |w| try push(&queue, &n, .{ .at = m.at + 2_000, .n = 0, .kind = .echo, .who = shell, .bytes = w.bytes, .seq = w.seq }); host.writes.clearRetainingCapacity(); }, @@ -3145,7 +2995,7 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { const state = a.core.panes[shell].?.terminal.?; if (ty) |k| { k.mode = sh.mode; - k.version_before = if (screens.tracks[shell]) |*tr| trackOf(tr.track).version else 0; + k.unit_before = a.seq; } sh.key(m.bytes); if (sh.out.items.len > 0) { @@ -3161,8 +3011,7 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { } }, .frame => { - if (try a.pending()) |batch| try sendUnit(&queue, &n, batch, m.at, &down, random, one_way, jitter, &t, false, &screens, a.core, &peers); - try flushAll(&screens, a.core, &peers, &owed, &queue, &n, m.at, &down, random, one_way, jitter, &versions, &t); + if (try a.pending()) |batch| try sendUnit(&queue, &n, batch, m.at, &down, random, one_way, jitter); const busy = next_step < corpus.steps.items.len or queue.count() + 1 > periodic; left[0] = if (busy) 60 else left[0] -| 1; if (left[0] > 0) try push(&queue, &n, .{ .at = m.at + frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} }) else periodic -= 1; @@ -3200,8 +3049,7 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { } } }; - const applied = if (rp.screens[shell]) |sc| replicaOf(sc.rep).seq else 0; - for (typed.items) |*k| if (k.echoed and k.seen == null and applied > k.version_before) { + for (typed.items) |*k| if (k.echoed and k.seen == null and fed > k.unit_before) { k.seen = m.at; }; const busy = next_step < corpus.steps.items.len or queue.count() + 1 > periodic; @@ -3211,22 +3059,9 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { .to_replica => { rp.confirm(m.bytes); rp.settle(); - }, - .screen_down => { - if (rp.screen(m.bytes)) |reply| { - const pane = m.bytes[0]; - if (reply[5] == 1) { - const sc = rp.screens[pane].?; - if (versions.get(@as(u64, sc.serial) << 32 | replicaOf(sc.rep).seq)) |want| { - if (want != screenHash(&pardes.Term.emulatorOf(rp.core().panes[pane].?.terminal.?).vt)) t.screens_wrong += 1; - } else t.screens_wrong += 1; - } - try push(&queue, &n, .{ .at = up[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_up, .who = 1, .bytes = try gpa.dupe(u8, reply) }); - } - if (rp.screenRequest()) |req| try push(&queue, &n, .{ .at = up[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_up, .who = 1, .bytes = try gpa.dupe(u8, req) }); - }, - .screen_up => { - if (try screens.take(a.core, peer, m.bytes)) |answer| try push(&queue, &n, .{ .at = down[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_down, .who = 1, .bytes = answer }); + if (replica.parseUnit(m.bytes)) |u| if (u.origin == 0) { + fed = u.seq; + }; }, .output, .own, .dial, .dump, .refused, .check_up, .checked, .bye_up, .wake, .quit, .gone, .draw, .up, .blob, .word, .drain => {}, } @@ -3237,7 +3072,6 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { et.confirmed += s.confirmed; et.mispredicted += s.mispredicted; et.cursor_missed += s.cursor_missed; - et.screens_wrong += t.screens_wrong; for (typed.items) |k| { et.keys += 1; const sec = &et.sec[k.section]; @@ -3288,7 +3122,7 @@ fn echoMain(seeds: u64, first: u64, rtts: []const u64) !bool { var draw_lines: std.ArrayList(u8) = .empty; defer draw_lines.deinit(gpa); std.debug.print("predicted echo: one client typing the corpus into a shell, {d} seeds a cell; from a key to its character on the client's screen (ms, frames at 60 Hz)\n", .{seeds}); - std.debug.print(" rtt echo keys echoed p50 p90 max predicted unpredicted right/wrong confirmed mispredicted cursor-missed drawn-wrong keys/frames/max secret-frames vim-predicted diverged unequal screens-wrong\n", .{}); + std.debug.print(" rtt echo keys echoed p50 p90 max predicted unpredicted right/wrong confirmed mispredicted cursor-missed drawn-wrong keys/frames/max secret-frames vim-predicted diverged unequal\n", .{}); var by_section: std.ArrayList(u8) = .empty; defer by_section.deinit(gpa); var off: [sections.len][2]u64 = undefined; @@ -3301,13 +3135,13 @@ fn echoMain(seeds: u64, first: u64, rtts: []const u64) !bool { return @as(f64, @floatFromInt(us)) / 1000; } }.f; - std.debug.print("{d:>4} {s:>4} {d:>4} {d:>6} {d:>5.1} {d:>5.1} {d:>5.1} {d:>9} {d:>11} {d:>5}/{d:<5} {d:>9} {d:>12} {d:>13} {d:>5}/{d:>5}/{d:<5} {d:>13} {d:>13} {d:>8} {d:>7} {d:>13}\n", .{ + std.debug.print("{d:>4} {s:>4} {d:>4} {d:>6} {d:>5.1} {d:>5.1} {d:>5.1} {d:>9} {d:>11} {d:>5}/{d:<5} {d:>9} {d:>12} {d:>13} {d:>5}/{d:>5}/{d:<5} {d:>13} {d:>13} {d:>8} {d:>7}\n", .{ rtt, if (on) "on" else "off", et.keys, et.echo_keys, ms(pct(et.latency.items, 50)), ms(pct(et.latency.items, 90)), ms(pct(et.latency.items, 100)), et.predicted, et.unpredicted, et.right, et.wrong, et.confirmed, et.mispredicted, et.cursor_missed, et.wrong_shown, et.wrong_frames, et.wrong_max, et.secret_frames, et.alt_predicted, et.divergences, - et.unequal, et.screens_wrong, + et.unequal, }); for (&et.sec, &off, sections) |*x, *o, name| { const p50 = pct(x.latency.items, 50) / 1000; @@ -3319,7 +3153,7 @@ fn echoMain(seeds: u64, first: u64, rtts: []const u64) !bool { try by_section.print(gpa, "{d:>4} {s:<14} {d:>5} {d:>9} {d:>7} {d:>4} -> {d:<4} {d:>4} -> {d:<4} {d:>12}\n", .{ rtt, name, x.keys, x.predicted, x.latency.items.len, o[0], p50, o[1], p90, x.wrong_frames }); } if (on) try draw_lines.print(gpa, "{d:>4} {d:>12} {d:>6}/{d:<6} {d:>5}/{d:<5} {d:>10}\n", .{ rtt, et.drawn_frames, pct(et.render_ns.items, 50) / 1000, pct(et.render_ns.items, 99) / 1000, pct(et.paint_ns.items, 50), pct(et.paint_ns.items, 99), et.paint_wrong }); - if (et.divergences > 0 or et.unequal > 0 or et.screens_wrong > 0 or et.secret_frames > 0 or et.alt_predicted > 0 or et.paint_wrong > 0) failed = true; + if (et.divergences > 0 or et.unequal > 0 or et.secret_frames > 0 or et.alt_predicted > 0 or et.paint_wrong > 0) failed = true; }; std.debug.print("by part of the corpus (all seeds): keys typed, predicted, echoed (the latency sample); key to its character on the screen, ms, without -> with; frames a wrong prediction was drawn\n rtt part keys predicted echoed p50 off/on p90 off/on drawn-wrong\n{s}", .{by_section.items}); std.debug.print("the client's frames drawn with a prediction shown: its render (us) and the overlay's part (ns); cells drawn otherwise than predicted\n rtt frames-drawn render p50/p99 paint p50/p99 drawn-wrong\n{s}", .{draw_lines.items}); @@ -3341,174 +3175,6 @@ fn pct(samples: []u64, p: usize) u64 { return samples[@min(samples.len - 1, samples.len * p / 100)]; } -/// `--screen-state `: every recorded pty stream in `dir` (a -/// `-x` in its name sizes it, 80x24 otherwise) through -/// screen_state's soak at three seeds, then the encode's cost and the bytes -/// floods put on the wire (numbers from a ReleaseFast build). -fn screenState(io: std.Io, dir_path: []const u8, w: *std.Io.Writer) !void { - var dir = try std.Io.Dir.cwd().openDir(io, dir_path, .{ .iterate = true }); - defer dir.close(io); - var it = dir.iterate(); - var files: usize = 0; - var failed: usize = 0; - while (try it.next(io)) |entry| { - if (entry.kind != .file) continue; - const bytes = try dir.readFileAlloc(io, entry.name, gpa, .unlimited); - defer gpa.free(bytes); - var cols: u16 = 80; - var rows: u16 = 24; - if (std.mem.lastIndexOfScalar(u8, entry.name, '-')) |dash| { - const size = std.mem.sliceTo(entry.name[dash + 1 ..], '.'); - if (std.mem.indexOfScalar(u8, size, 'x')) |x| { - cols = std.fmt.parseInt(u16, size[0..x], 10) catch cols; - rows = std.fmt.parseInt(u16, size[x + 1 ..], 10) catch rows; - } - } - files += 1; - for (0..3) |seed| { - const st = screen_state.soak(gpa, io, bytes, cols, rows, 128 * 1024, seed, seed != 0) catch |err| { - try w.print("screen-state {s} seed {d}: {s}\n", .{ entry.name, seed, @errorName(err) }); - failed += 1; - continue; - }; - if (seed == 0) try w.print("screen-state {s} {d}x{d}: {d} bytes, {d} deltas ({d} lost, {d} refused, {d} in flight at most), {d} wire bytes, {d} history rows checked, {d} fetched\n", .{ entry.name, cols, rows, bytes.len, st.deltas, st.lost, st.refused, st.most_in_flight, st.bytes, st.history_checked, st.fetched }); - } - } - try w.print("screen-state corpus: {d} streams x 3 seeds, {d} failed\n", .{ files, failed }); - try w.flush(); - try encodeBench(io, w); -} - -fn encodeBench(io: std.Io, w: *std.Io.Writer) !void { - const t = try gpa.create(screen_state.Terminal); - defer gpa.destroy(t); - t.* = try screen_state.Terminal.init(io, gpa, .{ .cols = 200, .rows = 60, .max_scrollback_bytes = 16 << 20 }); - defer t.deinit(gpa); - var stream = t.vtStream(); - defer stream.deinit(); - var enc: screen_state.Encoder = .init(gpa); - defer enc.deinit(); - var out: std.Io.Writer.Allocating = .init(gpa); - defer out.deinit(); - var line: [1024]u8 = undefined; - // A full 200x60 screen, every row new to the peer: each a blob. - var full: [200]u64 = undefined; - var same: [200]u64 = undefined; - var full_bytes: usize = 0; - var same_bytes: usize = 0; - var changes: u32 = 0; - for (&full, &same, 0..) |*f, *u, rep| { - for (0..60) |y| { - var lw: std.Io.Writer = .fixed(&line); - try lw.print("\x1b[{d};1H\x1b[0;3{d};4{d}m{d} {d} ", .{ y + 1, rep % 8, y % 8, rep, y }); - while (lw.end < 190) try lw.writeAll("\x1b[1mbold\x1b[22m text "); - stream.nextSlice(lw.buffered()); - } - changes += 1; - var tr: screen_state.Track = .init(gpa); - defer tr.deinit(gpa, t); - var peer: screen_state.Peer = .{}; - defer peer.deinit(gpa); - out.clearRetainingCapacity(); - var t0 = std.Io.Clock.awake.now(io).nanoseconds; - _ = try screen_state.encode(&enc, &tr, &peer, t, changes, "", &out.writer); - f.* = @intCast(std.Io.Clock.awake.now(io).nanoseconds - t0); - full_bytes = out.written().len; - // The same screen again as a new version: every row held. - out.clearRetainingCapacity(); - t0 = std.Io.Clock.awake.now(io).nanoseconds; - _ = try screen_state.encode(&enc, &tr, &peer, t, changes + 1, "", &out.writer); - u.* = @intCast(std.Io.Clock.awake.now(io).nanoseconds - t0); - same_bytes = out.written().len; - } - std.mem.sort(u64, &full, {}, std.sort.asc(u64)); - std.mem.sort(u64, &same, {}, std.sort.asc(u64)); - try w.print("screen-state encode 200x60, every row new: p50 {d} us p99 {d} us, {d} bytes\n", .{ full[100] / 1000, full[198] / 1000, full_bytes }); - try w.print("screen-state encode 200x60, nothing new: p50 {d} us p99 {d} us, {d} bytes\n", .{ same[100] / 1000, same[198] / 1000, same_bytes }); - try w.flush(); - - // Floods: a second of output as fast as ghostty takes it, a frame every - // 16 ms: one version, a delta for each peer (the same bytes for peers - // at the same base), each replica applying its own at once. Under the C - // allocator, as a replica's. - try floods(io, w); -} - -fn floods(io: std.Io, w: *std.Io.Writer) !void { - var enc: screen_state.Encoder = .init(gpa); - defer enc.deinit(); - var out: std.Io.Writer.Allocating = .init(gpa); - defer out.deinit(); - const yes = try screen_state.yesStream(gpa, 1 << 16); - defer gpa.free(yes); - const shell = try screen_state.shellStream(gpa); - defer gpa.free(shell); - for ([_]struct { name: []const u8, bytes: []const u8 }{ .{ .name = "yes", .bytes = yes }, .{ .name = "varied text", .bytes = shell } }) |flood| for ([_]usize{ 1, 3 }) |npeers| { - const a = try gpa.create(screen_state.Terminal); - defer gpa.destroy(a); - a.* = try screen_state.Terminal.init(io, gpa, .{ .cols = 200, .rows = 60, .max_scrollback_bytes = 16 << 20 }); - defer a.deinit(gpa); - var as = a.vtStream(); - defer as.deinit(); - var tr: screen_state.Track = .init(gpa); - defer tr.deinit(gpa, a); - var peers: [3]screen_state.Peer = @splat(.{}); - var reps: [3]screen_state.Replica = @splat(.{}); - var bs: [3]screen_state.Terminal = undefined; - for (bs[0..npeers]) |*b| b.* = try screen_state.Terminal.init(io, gpa, .{ .cols = 2, .rows = 2, .max_scrollback_bytes = 32 << 20 }); - defer for (bs[0..npeers], reps[0..npeers], peers[0..npeers]) |*b, *r, *peer| { - b.deinit(gpa); - r.deinit(gpa); - peer.deinit(gpa); - }; - var applies: std.ArrayList(u64) = .empty; - defer applies.deinit(gpa); - var frames: std.ArrayList(u64) = .empty; - defer frames.deinit(gpa); - const start = std.Io.Clock.awake.now(io).nanoseconds; - var next = start; - var fed: u64 = 0; - var deltas: u64 = 0; - var wire: u64 = 0; - var version: u32 = 0; - while (true) { - const now = std.Io.Clock.awake.now(io).nanoseconds; - if (now - start >= std.time.ns_per_s) break; - as.nextSlice(flood.bytes); - version += 1; - fed += flood.bytes.len; - if (now < next) continue; - next += 16 * std.time.ns_per_ms; - var frame_ns: u64 = 0; - for (peers[0..npeers], reps[0..npeers], bs[0..npeers]) |*peer, *rep, *b| { - out.clearRetainingCapacity(); - const e0 = std.Io.Clock.awake.now(io).nanoseconds; - if (!try screen_state.encode(&enc, &tr, peer, a, version, "", &out.writer)) continue; - frame_ns += @intCast(std.Io.Clock.awake.now(io).nanoseconds - e0); - const a0 = std.Io.Clock.awake.now(io).nanoseconds; - peer.ack((try rep.apply(gpa, io, b, out.written())).seq); - try applies.append(gpa, @intCast(std.Io.Clock.awake.now(io).nanoseconds - a0)); - deltas += 1; - wire += out.written().len; - } - try frames.append(gpa, frame_ns); - } - std.mem.sort(u64, applies.items, {}, std.sort.asc(u64)); - std.mem.sort(u64, frames.items, {}, std.sort.asc(u64)); - const p = struct { - fn at(s: []const u64, q: usize) u64 { - return if (s.len == 0) 0 else s[@min(s.len - 1, s.len * q / 100)] / 1000; - } - }.at; - try w.print("screen-state flood of {s}, {d} peer(s): {d} MB/s of output, {d} deltas/s a peer, {d} wire bytes/s a peer ({d} a delta); encode a frame, all peers: p50 {d} us p99 {d} us; apply a delta p50 {d} us p99 {d} us\n", .{ - flood.name, npeers, fed / 1_000_000, deltas / npeers, wire / npeers, - wire / @max(1, deltas), p(frames.items, 50), p(frames.items, 99), p(applies.items, 50), - p(applies.items, 99), - }); - }; - try w.flush(); -} - pub fn main(init: std.process.Init) !void { const args = try init.minimal.args.toSlice(init.arena.allocator()); // A loop that does not end names itself (`Watchdog`): its gdb, a child, @@ -3522,7 +3188,6 @@ pub fn main(init: std.process.Init) !void { var rtts: []const u64 = &.{ 30, 80, 207 }; var echo_mode = false; var flood_mb: u64 = 8; - var screen_dir: ?[]const u8 = null; var rtt_buf: [8]u64 = undefined; var addons: std.ArrayListUnmanaged([]const u8) = .empty; defer addons.deinit(gpa); @@ -3533,10 +3198,6 @@ pub fn main(init: std.process.Init) !void { echo_mode = true; continue; } - if (std.mem.eql(u8, name, "--bytes")) { - bytes_kind = true; - continue; - } if (std.mem.eql(u8, name, "--witness")) { witness_always = true; continue; @@ -3544,7 +3205,7 @@ pub fn main(init: std.process.Init) !void { if (i + 1 >= args.len) return error.MissingValue; i += 1; const value = args[i]; - if (std.mem.eql(u8, name, "--seeds")) seeds = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--first")) first = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--steps")) steps = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, name, "--clients")) clients = @min(8, try std.fmt.parseInt(u16, value, 10)) else if (std.mem.eql(u8, name, "--flood")) flood_mb = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--screen-state")) screen_dir = value else if (std.mem.eql(u8, name, "--addon")) try addons.append(gpa, value) else if (std.mem.eql(u8, name, "--pdf")) { + if (std.mem.eql(u8, name, "--seeds")) seeds = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--first")) first = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--steps")) steps = try std.fmt.parseInt(usize, value, 10) else if (std.mem.eql(u8, name, "--clients")) clients = @min(8, try std.fmt.parseInt(u16, value, 10)) else if (std.mem.eql(u8, name, "--flood")) flood_mb = try std.fmt.parseInt(u64, value, 10) else if (std.mem.eql(u8, name, "--addon")) try addons.append(gpa, value) else if (std.mem.eql(u8, name, "--pdf")) { var whole: [libc.PATH_MAX]u8 = undefined; pdf_path = try init.arena.allocator().dupe(u8, std.mem.span(libc.realpath(try init.arena.allocator().dupeSentinel(u8, value, 0), &whole) orelse return error.NoPdf)); } else if (std.mem.eql(u8, name, "--rtt")) { @@ -3554,11 +3215,6 @@ pub fn main(init: std.process.Init) !void { rtts = rtt_buf[0..k]; } else return error.UnknownOption; } - if (screen_dir) |d| { - var buf: [4096]u8 = undefined; - var out = std.Io.File.stderr().writer(init.io, &buf); - return screenState(init.io, d, &out.interface); - } trace = libc.getenv("PARDES_REPLICA_TRACE") != null; if (libc.getenv("PARDES_REPLICA_FILL")) |b| pardes.rollback.Epoch.fill = std.fmt.parseInt(u8, std.mem.span(b), 0) catch 0xff; var dir_buf: [256]u8 = undefined; @@ -3610,7 +3266,7 @@ pub fn main(init: std.process.Init) !void { var t: Totals = .{}; pardes.Term.reloads = .{}; for (first..first + seeds) |seed| try run(init, .{ .seed = seed, .rtt_ms = rtt, .steps = steps, .clients = clients, .flood_mb = flood_mb }, dir, &t); - if (bytes_kind) std.debug.print("rtt {d}: {d} reloads of a terminal at joins, every side (the session's own too), {d} us each, {d} us at worst; {d} kitty images in clients at quiescence, each the session's pixels\n", .{ rtt, pardes.Term.reloads.n, pardes.Term.reloads.ns / @max(1, pardes.Term.reloads.n) / 1000, pardes.Term.reloads.worst_ns / 1000, t.images_equal }); + std.debug.print("rtt {d}: {d} reloads of a terminal at joins, every side (the session's own too), {d} us each, {d} us at worst; {d} kitty images in clients at quiescence, each the session's pixels\n", .{ rtt, pardes.Term.reloads.n, pardes.Term.reloads.ns / @max(1, pardes.Term.reloads.n) / 1000, pardes.Term.reloads.worst_ns / 1000, t.images_equal }); const rollbacks = t.mispredicted + t.foreign; std.debug.print("{d:>4} {d:>6} {d:>7} {d:>7} {d:>6} {d:>6} {d:>6} ({d}+{d}) {d:>5.1}% {d:>6} {d:>5}/{d:<6} {d:>5}/{d:<5} ({d}) {d:>7}/{d:<7} {d:>8} {d:>7}\n", .{ rtt, t.inputs, t.speculated, @@ -3623,20 +3279,10 @@ pub fn main(init: std.process.Init) !void { }); const flood_s = @as(f64, @floatFromInt(@max(1, t.flood_us))) / 1e6; - try term_lines.print(gpa, "{d:>4} {d:>7.1} {d:>9.0} {d:>9.0} {d:>5}/{d:<5} {d:>5}/{d:<5} {d:>7} {d:>9} {d:>6} {d:>6}/{d:<6}\n", .{ + try term_lines.print(gpa, "{d:>4} {d:>9.0} {d:>9}\n", .{ rtt, - @as(f64, @floatFromInt(t.flood_deltas)) / flood_s / @as(f64, @floatFromInt(clients)), - @as(f64, @floatFromInt(t.flood_delta_bytes)) / flood_s / @as(f64, @floatFromInt(clients)), @as(f64, @floatFromInt(t.flood_unit_bytes)) / flood_s / @as(f64, @floatFromInt(clients)), - pct(t.frame_ns.items, 50) / 1000, - pct(t.frame_ns.items, 99) / 1000, - pct(t.apply_ns.items, 50) / 1000, - pct(t.apply_ns.items, 99) / 1000, - t.fetched, - t.filled_bytes / 1024, - t.resets, - t.screens_checked, - t.screens_wrong, + t.unit_bytes >> 10, }); try stop_lines.print(gpa, "{d:>4} {d:>8} {d:>6} {d:>6} {d:>3}/{d}/{d} ", .{ rtt, t.unlisted, t.wakes, t.draws, t.asked[0], t.asked[1], t.asked[2] }); for (t.stops) |st| if (st.n > 0) try stop_lines.print(gpa, "{s}:{d} ", .{ st.name, st.n }); @@ -3656,10 +3302,10 @@ pub fn main(init: std.process.Init) !void { // The far client shows the final screen in every run, and the near // ones never fall behind with it. if ((t.far_final.items.len < seeds and clients >= 3) or t.near_lags > 0) failed = true; - if (t.divergences > 0 or t.unequal > 0 or t.screens_wrong > 0 or t.differ > 0 or t.unlisted > 0) failed = true; + if (t.divergences > 0 or t.unequal > 0 or t.differ > 0 or t.unlisted > 0) failed = true; } - std.debug.print("terminals: deltas a replica applied a second under the flood; a peer's bytes a second under the flood (deltas, units); encode a frame of the flood for every peer, apply a delta (us); rows fetched, KB of rows sent before the step that read them; resets; deltas checked/wrong\n", .{}); - std.debug.print(" rtt deltas/s delta B/s unit B/s encode p50/p99 apply p50/p99 fetched filled KB resets checked/wrong\n{s}", .{term_lines.items}); + std.debug.print("terminals: a peer's unit bytes a second under the flood (the pty's bytes ride in them); KB of units sent to the peers in all\n", .{}); + std.debug.print(" rtt unit B/s units KB\n{s}", .{term_lines.items}); std.debug.print("clients: joins from a dump, refused (every view taken), joined again after a divergence put on them, left (of them by a Detach); quiet checks of the session's digest agreed/differed; the digests the clients compared (units and quiet), of the units they took; resizes the windows posted; the kinds' panes the session opened (image/life/pdf)\n", .{}); std.debug.print(" rtt joins refused rejoined detached detach agree/differ checks/units resizes kinds\n{s}", .{join_lines.items}); std.debug.print("stops: the wakes the clients' loops asked, the frames they drew, the yanks, pastes and links their frontends did (y/p/l), and what stopped their inputs (a stop counted again as its input is applied again), by name; those at a name replica.may_wait does not list fail the run\n", .{}); @@ -3828,9 +3474,9 @@ fn corpusCase(dir: []const u8) !bool { defer own_host.shown.deinit(); var noop: Host = .{}; const options: pardes.Options = .{ .cols = 100, .rows = 22, .file = shapes }; - const a = try replica.Authority.init(gpa, options, own_host.host(), true); + const a = try replica.Authority.init(gpa, options, own_host.host(), false); defer a.deinit(); - const b = try replica.Authority.init(gpa, options, noop.host(), true); + const b = try replica.Authority.init(gpa, options, noop.host(), false); defer b.deinit(); noop.core = b.core; _ = try b.unit(0, 0); @@ -3838,6 +3484,7 @@ fn corpusCase(dir: []const u8) !bool { defer gpa.free(j.dump); const rp = try replica.Replica.initDump(gpa, 1, j.view, j.dump, .{ .cols = 100, .rows = 22 }); defer rp.deinit(); + rp.t.screen_state = false; var fds: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; defer for (fds) |fd| { -- cgit v1.3 From 02099b716e5320cbee7f829d93fd53717fd2a57d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 22 Nov 2026 02:46:48 -0300 Subject: daemon.py: the way back's word gone from the harnesses, and far_flood says what a far client does under a flood on the one road (the old road's deletion, piece 2 of 8): test/daemon.py's `KEEP` (PARDES_TERM_SCREEN passed to every session it starts) and test/process.zig's twin go, so the caller's PARDES_* is dropped as before the flip; far_flood's words were the old road's ("it pulls its terminal's screen (screen state), so the flood does not queue for it"): on the one road the flood queues for a far client, it falls behind past replica.behind_max_ms, its link is let go (`Link.lags`) and it joins again from a dump, its notice saying "joined again: N s behind" until a key (round 7's table: a 1 MiB `cat` through 1 Mbit, one rejoin of 2.2 s); the case now asserts that shape and no time: a link of the client ended under the flood (its PARDES_REPLICA_STATS line, one a link), its notice, then as before its agreement once `yes` ends and its keys after; kitty_image's docstring loses "(screen state)"; no build reads these files' change but process-test's runner (core-test and shell-test: the base's) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- test/daemon.py | 88 +++++++++++++++++++++++++++++--------------------------- test/process.zig | 5 ++-- 2 files changed, 47 insertions(+), 46 deletions(-) diff --git a/test/daemon.py b/test/daemon.py index 2e666ad1..e10b3c1f 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -69,12 +69,6 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from ninep import Client # noqa: E402 -# The caller's PARDES_* is dropped (a session of the user's), these kept: a -# road for every session the run starts (PARDES_TERM_SCREEN: its terminals to -# its clients as screen state, the way back). -KEEP = ('PARDES_TERM_SCREEN',) - - def wait_for(what, check, timeout=10): deadline = time.monotonic() + timeout while True: @@ -441,7 +435,7 @@ def clients(binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rc-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -583,7 +577,7 @@ def launch(binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rl-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -651,7 +645,7 @@ def pair(binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rp-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -725,7 +719,7 @@ def pair_rows(binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rq-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -915,7 +909,7 @@ def attach_upgrading(binary, rounds=6, dump=True): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='ru-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -1006,7 +1000,7 @@ def kept_views(binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rk-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -1064,7 +1058,7 @@ def pair_upgrade_views(binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rv-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -1170,7 +1164,7 @@ def pair_exec_reaps(old, new): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rpx-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -1234,7 +1228,7 @@ def far_exec(old, new): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rfx-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -1300,7 +1294,7 @@ def pair_window_geometry(gui_binary, new_gui): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rgg-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_DAEMON='on', TERM='xterm-256color', PARDES_PAIR='1', SDL_VIDEO_DRIVER='offscreen') @@ -1372,7 +1366,7 @@ def manage(binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rm-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -1476,7 +1470,7 @@ def relink(binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rr-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -1582,7 +1576,7 @@ def answer_late(binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='ra-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -1700,7 +1694,7 @@ def pdf_window(binary, gui_binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='pdfw-', dir=os.environ.get('TMPDIR') or scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') env.pop('XDG_DATA_HOME', None) @@ -1766,7 +1760,7 @@ def window_clients(binary, gui_binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='wc-', dir=os.environ.get('TMPDIR') or scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -1988,7 +1982,7 @@ def far(binary): scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rf-', dir=scratch)) cache = root / 'cache' - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_CACHE_HOME=str(cache), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_REPLICA_FAR='1') @@ -2147,15 +2141,18 @@ def far(binary): def far_flood(binary): """A far client (PARDES_REPLICA_FAR) across a slow link (delay_relay.py: - 200 ms each way, 20 KB/s) while the session's shell runs `yes`: once - `yes` ends it agrees with the session, and its keys after go in. It - pulls its terminal's screen (screen state), so the flood does not - queue for it: it keeps up without joining again (two runs, 2026-11-20), - and replica.behind_max_ms is not reached this way.""" + 200 ms each way, 20 KB/s) while the session's shell runs `yes`. Its + terminal is the pty's bytes in the session's units, so the flood queues + for it: it falls behind, past replica.behind_max_ms its link is let go + (`Link.lags`), and it joins again from a dump, saying so on its notice + line ("joined again: N s behind") until a key. Once `yes` ends it agrees + with the session, and its keys after go in. The shape is asserted, not + the times: a link ended before its last (a line of + PARDES_REPLICA_STATS a link), the notice, the agreement.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='fl-', dir=os.environ.get('TMPDIR') or scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_CACHE_HOME=str(root / 'cache'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') @@ -2184,16 +2181,21 @@ def far_flood(binary): started.append(relay.pid) wait_for('the relay', (root / 'relay.sock').exists) check = root / 'f.check' + stats = root / 'f.stats' t = Term(30, 100) terms.append(t) c = t.spawn([binary, f'--attach={root / "relay.sock"}:files'], - dict(env, PARDES_REPLICA_FAR='1', PARDES_REPLICA_CHECK=str(check))) + dict(env, PARDES_REPLICA_FAR='1', PARDES_REPLICA_CHECK=str(check), PARDES_REPLICA_STATS=str(stats))) started.append(c.pid) wait_for('the far client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=60) nine.write(f'/pane/{shell}/pty/data', b'timeout 20 yes; echo yes-done\r') wait_for('yes ended', lambda: b'yes-done' in nine.read(f'/pane/{shell}/body').replace(b'\r', b''), timeout=60) seen = len(checks(check)) wait_for('the far client agrees once yes ended', lambda: agreed(check, seen), timeout=120) + # Queued behind the flood, let go for its lag, joined again from a + # dump: a link of its ended (its stats line), and its notice says why. + assert joins(stats), ('no link of the far client ended under the flood', checks(stats)) + wait_for('the far client\'s notice of its join again', lambda: b'joined again: ' in t.text() and b' s behind' in t.text(), timeout=30) os.write(t.master, b'echo from-far\r') wait_for('the far client\'s keys in the shell', lambda: b'from-far' in nine.read(f'/pane/{shell}/body'), timeout=30) seen = len(checks(check)) @@ -2201,8 +2203,8 @@ def far_flood(binary): # Its keys go to the shell: its terminal hangs up instead. c.send_signal(signal.SIGHUP) c.wait(timeout=10) - print(f'daemon: a far client across 20 KB/s and 200 ms each way under `yes` agreed once it ended ' - f'({len(checks(check))} checks) and its keys went in') + print(f'daemon: a far client across 20 KB/s and 200 ms each way under `yes` was let go for its lag and ' + f'joined again ({len(joins(stats))} links), agreed once it ended ({len(checks(check))} checks) and its keys went in') relay.kill() relay.wait() exit_session(nine, pane) @@ -2230,7 +2232,7 @@ def by_hash(binary): scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rh-', dir=scratch)) cache = root / 'cache' - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_CACHE_HOME=str(cache), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -2316,7 +2318,7 @@ def games(binary, libs, secs=10): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rg-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -2427,7 +2429,7 @@ def far_find(binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rq-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_REPLICA_FAR='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -2494,7 +2496,7 @@ def restore_client(binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rr-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -2621,14 +2623,14 @@ def cpu_ticks(pid): def kitty_image(binary, secs=5): - """A plain attach (screen state) watching a terminal in which a program + """A plain attach watching a terminal in which a program shows a kitty image (the corpus's scene 10's: 8x8 RGB, 10x4 cells): it agrees with its session and does not join again (it joined again ~3.3 times a second: the tag said ` petscii:on` on the session's side only).""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='ri-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -2689,7 +2691,7 @@ def main(binary, cycles): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rt-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -2923,7 +2925,7 @@ def gui(binary, cycles): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rtg-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} (root / 'caps').mkdir() env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_TEST='1', PARDES_TEST_CAPTURE_DIR=str(root / 'caps'), @@ -3018,7 +3020,7 @@ def gui_pair(gui_binary): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rgp-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_DAEMON='on', TERM='xterm-256color', PARDES_PAIR='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -3189,7 +3191,7 @@ def upgrades(old, new): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rtu-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -3498,7 +3500,7 @@ def upgrade_clients(old, new): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='ruc-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') (root / 'config' / 'pardes').mkdir(parents=True) @@ -3600,7 +3602,7 @@ def gui_upgrades(old, new): another build.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' root = Path(tempfile.mkdtemp(prefix='rtgu-', dir=scratch)) - env = {k: v for k, v in os.environ.items() if (not k.startswith('PARDES_') or k in KEEP) and 'PAGER' not in k} + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} display = Path(os.environ.get('WAYLAND_DISPLAY', 'wayland-0')) if not display.is_absolute(): display = Path(os.environ.get('XDG_RUNTIME_DIR', f'/run/user/{os.getuid()}')) / display diff --git a/test/process.zig b/test/process.zig index a1647ff1..791a5b8e 100644 --- a/test/process.zig +++ b/test/process.zig @@ -945,9 +945,8 @@ pub const Child = struct { while (environ[i]) |kv| { const entry = std.mem.span(kv); const eq = std.mem.indexOfScalar(u8, entry, '=') orelse entry.len; - // PARDES_PAIR kept: the suite run as pairs (main.zig `pair`); - // PARDES_TERM_SCREEN, their terminals as screen state. - if ((std.mem.startsWith(u8, entry, "PARDES_") and !std.mem.startsWith(u8, entry, "PARDES_PAIR=") and !std.mem.startsWith(u8, entry, "PARDES_TERM_SCREEN=")) or std.mem.indexOf(u8, entry[0..eq], "PAGER") != null) { + // PARDES_PAIR kept: the suite run as pairs (main.zig `pair`). + if ((std.mem.startsWith(u8, entry, "PARDES_") and !std.mem.startsWith(u8, entry, "PARDES_PAIR=")) or std.mem.indexOf(u8, entry[0..eq], "PAGER") != null) { var name: [256]u8 = undefined; const n = std.fmt.bufPrintSentinel(&name, "{s}", .{entry[0..@min(eq, 255)]}, 0) catch _exit(126); _ = unsetenv(n); -- cgit v1.3 From d56973aa92d0de6d84446dff73eba9d5654fe6f4 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 22 Nov 2026 03:00:12 -0300 Subject: replica: the delta protocol deleted, with the wire's screen messages (the old road's deletion, piece 3 of 8): core/replica.zig loses the screen-state section (the screen message's head, `Screens`: tracks, peers, flush, fill, filled, take), `Peers.screens`/`msgs`/`flushed`/`screensOut`/`screensTo`, the `.screen` note and its arm in `boundary`, `Peers.input`'s flushes and fills, a joiner's `addPeer` and a leaver's `dropPeer`, `Peer.sid` and its `screen_ack` arm, `Replica.screen`/`screenRequest`/`screenMessage`/`overTerminals`, `Replica.screens`/`screen_out`/`ScreenOf`, `Stats.apply_ns`, `Said.screen` (and its arms in dev/tui/tui.zig and dev/gui/gui.zig: a delta no longer counts as an echo there, nor is its latency noted), the Link's `.screen` arm and `drawn`'s row requests, `sendScreen`, and the `screens` argument of `Authority.init` and `Replica.init` (every caller: core/jj.zig 10, core/tape.zig 2, core/echo.zig 2, test/panes.zig 15, test/perf.zig 2, runtime/client.zig 1, test/rollback_bench.zig 1, test/replicas.zig 10, core/replica.zig 98); a replica's own `made` no longer starts on screen state, and `confirm` and `applyPending` keep only their one-road branches; abi/wire.zig retires the replica's `screen_ack` (0x04) and the session's `screen` (0x06) as gaps (the version moves once, in piece 4); test/daemon.py's round trip passes over units alone; the tests that were the old road's alone go: a delta under a speculation, a terminal sized again by a client's key (screen state's deferred size), pardes's own keys over a terminal's history and a delta while they wait, a unit kept over a copy and a delta after it, a step's rows sent as a new client's holes, the screen-state twin of the 9P pty/run test, and the 9P open over a copy taken ahead (on the one road a unit that feeds a terminal lets the copy go: `Term.writes`, so no copy is held across the run's output: its premise was the old road's); the others that ran on screen state now run on the bytes road (a kitty image: the client's emulator has it as the session's does; prompt marks and Kill; the far client's may_wait walk, its click into a focus-reporting shell, its backed-up queue; a view that sized a terminal closing; a closed terminal brought back; a leave's queued resize before a join); FOUND AND FIXED on the way (those tests on the one road failed: the far click `expected 0, found 1` stopped, and may_wait named `Del`, `DelAbove`, `Up`, `C-w a`, `click shell`, `Look` stopped at `pty_write`): a client's own step that moved the focus in a session whose shell asked for focus events wrote the report (CSI I/O) through pty_write, which a speculation stops at (`keeps_stopping`), so the key or click waited a round trip, and the session's write was on the tape; on screen state both were skipped (core/Core.zig `reportFocus` skipped the write only `speculating and screen_state`, core/tape.zig `hostCall` kept pty_write off the tape only under screen state): both now on every road (a user on the flip's build could hit it: a far client's click, pane switch or Del beside vim or tmux waited a round trip); core/root.zig `machine_lines` for replica.zig 76 -> 74 (Authority.init's getenv and a joiner's `addPeer` failure's shutdown gone); core-test 911/1068 (157 skipped: 7 tests gone, each one skipped there for want of a shell), shell-test 1110/1113 (the 7 gone) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- abi/wire.zig | 22 +- core/Core.zig | 5 +- core/echo.zig | 4 +- core/jj.zig | 20 +- core/replica.zig | 1314 +++++------------------------------------------ core/root.zig | 2 +- core/tape.zig | 13 +- dev/gui/gui.zig | 4 +- dev/tui/tui.zig | 11 +- runtime/client.zig | 2 +- test/daemon.py | 6 +- test/panes.zig | 30 +- test/perf.zig | 4 +- test/replicas.zig | 20 +- test/rollback_bench.zig | 2 +- 15 files changed, 202 insertions(+), 1257 deletions(-) diff --git a/abi/wire.zig b/abi/wire.zig index f87131bf..ab974e35 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -113,9 +113,6 @@ pub const ClientTag = enum(u8) { hello = 0x01, bye = 0x02, ping = 0x03, - /// A replica's word about a terminal's state (core/term/screen_state.zig): the - /// delta it holds, or rows it asks for. Opaque here. - screen_ack = 0x04, /// What is the session's digest, in stream order (a replica checks /// itself against it once quiet). check = 0x05, @@ -201,9 +198,6 @@ pub const ServerTag = enum(u8) { /// A unit of the authority's stream (core/replica.zig): its origin, seq, /// clocks and tape. unit = 0x05, - /// A terminal's delta, or rows asked for (core/term/screen_state.zig), applied - /// before the next unit. Opaque here. - screen = 0x06, /// The session's digest (u64le), after every unit before it. check = 0x07, /// Part of the join's list of blobs, to a far client: each one's place @@ -232,7 +226,6 @@ pub const ServerMsg = union(ServerTag) { pong: u64, dump: []const u8, unit: []const u8, - screen: []const u8, check: u64, blobs: []const u8, zstd: []const u8, @@ -270,7 +263,6 @@ pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg { .pong => .{ .pong = try r.takeInt(u64, .little) }, .dump => return .{ .dump = payload }, .unit => return .{ .unit = payload }, - .screen => return .{ .screen = payload }, .check => .{ .check = try r.takeInt(u64, .little) }, .blobs => return .{ .blobs = payload }, .zstd => return .{ .zstd = payload }, @@ -300,7 +292,7 @@ pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { }, .refused => |words| try putSlice16(&w, words), .pong => |v| try w.writeInt(u64, v, .little), - .dump, .unit, .screen, .blobs, .zstd, .blob => |bytes| try w.writeAll(bytes), + .dump, .unit, .blobs, .zstd, .blob => |bytes| try w.writeAll(bytes), .check => |v| try w.writeInt(u64, v, .little), .ended => |code| try w.writeByte(code), .left => |name| try putSlice16(&w, name), @@ -327,7 +319,6 @@ pub const ClientMsg = union(enum) { bye: struct { again: bool = false, close: bool = false }, /// A round trip's probe, answered `pong` with the same value. ping: u64, - screen_ack: []const u8, check, far: bool, want: []const u8, @@ -545,7 +536,7 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { // 0 it leaves, 1 it joins again, 2 its window was closed. .bye => |b| try w.writeByte(if (b.close) 2 else @intFromBool(b.again)), .ping, .boot => |v| try w.writeInt(u64, v, .little), - .screen_ack, .want => |bytes| try w.writeAll(bytes), + .want => |bytes| try w.writeAll(bytes), .check => {}, .far => |far| try w.writeByte(@intFromBool(far)), .stamp => |s| for (s) |v| try w.writeInt(i64, v, .little), @@ -620,7 +611,6 @@ pub fn decodeClient(tag: u8, payload: []const u8) Error!ClientMsg { else => return error.BadValue, } }, .ping => .{ .ping = try r.takeInt(u64, .little) }, - .screen_ack => return .{ .screen_ack = payload }, .check => .check, .far => .{ .far = try getBool(&r) }, .want => return .{ .want = payload }, @@ -683,7 +673,7 @@ pub fn clientBound(msg: ClientMsg) usize { return msg_slack + switch (msg) { .hello => |h| h.session.len, .bye, .ping, .check, .far, .stamp, .boot => 0, - .screen_ack, .want => |bytes| bytes.len, + .want => |bytes| bytes.len, .event => |ev| switch (ev) { // Its hits' places (14 bytes each) past the slack. .mouse => 32, @@ -804,10 +794,8 @@ test "detached wire: a session is never told to do a frontend's remembering" { // them, and the machine that reports them is the one already holding the // core. const allowed = [_][]const u8{ - // Who this connection is, its round trip, and that it is finished, - // and which terminal state its replica holds (a protocol's word, - // as a ping is). - "hello", "bye", "ping", "screen_ack", "check", + // Who this connection is, its round trip, and that it is finished. + "hello", "bye", "ping", "check", // ...and how far it is, and which of the join's blobs it lacks. "far", "want", // ...and the digest of the core it made itself (a pair's). diff --git a/core/Core.zig b/core/Core.zig index 72e92212..4c8c98dd 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -949,8 +949,9 @@ fn reportFocus(p: *Pardes) void { // A client's own step records what it told and writes nothing: the // session's step makes the write, off the tape on both sides // (tape.hostCall's pty_write), so the switch shows at once and the - // program hears of it a round trip later. - if (p.tape.speculating and p.tape.screen_state) return; + // program hears of it a round trip later (a write there would stop the + // speculation: pty_write is `keeps_stopping`'s). + if (p.tape.speculating) return; if (v.focus_told) |old| if (p.panes[old.id]) |pane| { if (pane.serial == old.serial and pardes.Term.modes(pane.terminal).focus) p.emitWrite(old.id, "\x1b[O"); }; diff --git a/core/echo.zig b/core/echo.zig index 95127f55..e2a6521c 100644 --- a/core/echo.zig +++ b/core/echo.zig @@ -588,8 +588,8 @@ const Rig = struct { g.now = 1_000 * ms; // The one road: the shell's bytes in the units, fed to the // replica's own emulator. - g.a = try replica.Authority.init(gpa, .{ .cols = 60, .rows = 16, .boot = .tty_shell }, .{ .ctx = g, .vtable = &vtable }, false); - g.r = try replica.Replica.init(gpa, 1, try g.a.unit(0, 0), false); + g.a = try replica.Authority.init(gpa, .{ .cols = 60, .rows = 16, .boot = .tty_shell }, .{ .ctx = g, .vtable = &vtable }); + g.r = try replica.Replica.init(gpa, 1, try g.a.unit(0, 0)); g.r.core().echo = &g.r.echo; g.shell = for (g.a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break @intCast(id); diff --git a/core/jj.zig b/core/jj.zig index dd54dfc5..6a7d7da4 100644 --- a/core/jj.zig +++ b/core/jj.zig @@ -1528,9 +1528,9 @@ test "a client replays the open of a file at a revision and ends equal" { 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); + const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{}); defer a.deinit(); - const r = try R.Replica.init(gpa, 1, try a.unit(0, 0), false); + const r = try R.Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); var line: [4200]u8 = undefined; r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-:2", .{repo.file}) })); @@ -1636,9 +1636,9 @@ test "a client replays Changes from what the session's jj answered and ends equa 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); + const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{}); defer a.deinit(); - const r = try R.Replica.init(gpa, 1, try a.unit(0, 0), false); + const r = try R.Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); var line: [4200]u8 = undefined; r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) })); @@ -1676,10 +1676,10 @@ const WorkerJj = struct { fn init(repo: *const Repo, at: []const u8) !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); + const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{ .vtable = &vtable, .ctx = shell }); errdefer a.deinit(); shell.core = a.core; - const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0), false); + const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0)); var line: [4200]u8 = undefined; r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}{s}", .{ repo.file, at }) })); const id = a.core.view().active; @@ -2011,9 +2011,9 @@ test "ghost rows ride with the text: a line deleted above moves them up, a line var repo = try Ghosts.repo() 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); + const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{}); defer a.deinit(); - const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0), false); + const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0)); defer r.deinit(); var line: [4200]u8 = undefined; r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) })); @@ -2193,9 +2193,9 @@ test "the lanes ride with the text: a line typed in a nested block is nobody's, 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); + const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{}); defer a.deinit(); - const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0), false); + const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0)); defer r.deinit(); const Keys = struct { fn send(au: *R.Authority, re: *R.Replica, keys: []const u8) !void { diff --git a/core/replica.zig b/core/replica.zig index 993d9e2c..3f897044 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -164,9 +164,7 @@ pub const Authority = struct { /// A session booted with `opts`; `unit` is its first, which a replica /// is made from. - /// `screens`: its terminals cross as screen state (`Screens`), not as - /// their pty's bytes. - pub fn init(gpa: Allocator, options: pardes.Options, host: pardes.Host, screens: bool) !*Authority { + pub fn init(gpa: Allocator, options: pardes.Options, host: pardes.Host) !*Authority { // A replay gives its core every allocator (tape.zig), and a digest // tells an allocator from none. var opts = options; @@ -177,9 +175,6 @@ pub const Authority = struct { errdefer gpa.destroy(a); a.* = .{ .gpa = gpa, .t = tape.memory(gpa), .core = undefined, .host = host }; errdefer tape.release(&a.t); - a.t.screen_state = screens; - // One word a digest: every pty read is a unit. - a.t.whole_digest = screens and std.c.getenv("PARDES_REPLICA_TRACE") == null; // A digest at a unit's end, as the session's (Peers.unit). a.t.no_digest = true; opts.tape = &a.t; @@ -355,208 +350,6 @@ pub const Authority = struct { } }; -// ---- terminals as screen state (core/term/screen_state.zig) ---- -// -// A message of either side is u8 pane, u32 the pane's serial (a slot's -// next pane is another), u8 kind, and the kind's bytes: -// to a replica: kind 1, a delta; kind 2, rows (encodeRows): asked for, -// or a step read them; -// to the authority: kind 1, an acknowledgement (u32 seq); kind 2, a -// request for rows (u64 lo, u64 hi, absolute); kind 3, a -// delta refused: start this terminal afresh. -// In the authority's stream to a peer, before it steps any input but a -// pty's output, and once a frame: its own steps since the last unit, as one -// (`Authority.pending`), then what the peer is owed of the terminals -// (`Screens.flush`). After a step, before its unit: the rows it read that -// the peer holds as holes (`Screens.fill`, then `filled`). A replica takes -// them in that order between units (`Replica.screen`), so a step it replays -// reads the terminal its authority's step read. - -const kind_delta = 1; -const kind_rows = 2; -const kind_ack = 1; -const kind_reset = 3; - -const ScreenMsg = struct { pane: u8, serial: u32, kind: u8, payload: []const u8 }; - -fn parseScreen(msg: []const u8) ?ScreenMsg { - if (msg.len < 6) return null; - return .{ .pane = msg[0], .serial = std.mem.readInt(u32, msg[1..5], .little), .kind = msg[5], .payload = msg[6..] }; -} - -fn writeScreenHead(out: *std.ArrayListUnmanaged(u8), gpa: Allocator, pane: u8, serial: u32, kind: u8) !void { - var head: [6]u8 = undefined; - head[0] = pane; - std.mem.writeInt(u32, head[1..5], serial, .little); - head[5] = kind; - try out.appendSlice(gpa, &head); -} - -/// The authority's side of its replicas' terminals: a track each terminal -/// pane, and what each peer was sent of it. -pub const Screens = struct { - gpa: Allocator, - /// Made the first time a terminal is encoded (`encoder`). - enc: ?*Term.Encoder = null, - tracks: [pardes.MAX_PANES]?Tracked = @splat(null), - peers: std.ArrayListUnmanaged(*[pardes.MAX_PANES]PeerOf) = .empty, - free_peers: std.ArrayListUnmanaged(u16) = .empty, - out: std.ArrayListUnmanaged(u8) = .empty, - /// Nanoseconds: what each flush spent encoding, for every peer. - encode_ns: u64 = 0, - - const Tracked = struct { serial: u32, state: *Term.State, track: *Term.Track }; - const PeerOf = struct { serial: u32 = 0, peer: Term.Peer = .{} }; - - pub fn init(gpa: Allocator) Screens { - return .{ .gpa = gpa }; - } - - /// `core` is the session's, its terminals still there. - pub fn deinit(s: *Screens, core: *Pardes) void { - for (&s.tracks, 0..) |*slot, id| if (slot.*) |*tr| Term.untrack(tr.track, s.gpa, if (s.live(core, id, tr)) tr.state else null); - for (s.peers.items) |p| { - for (p) |*pp| pp.peer.deinit(s.gpa); - s.gpa.destroy(p); - } - s.peers.deinit(s.gpa); - s.free_peers.deinit(s.gpa); - s.out.deinit(s.gpa); - if (s.enc) |e| Term.encoderFree(e); - } - - fn live(_: *const Screens, core: *Pardes, id: usize, tr: *const Tracked) bool { - const pane = core.panes[id] orelse return false; - return pane.serial == tr.serial and pane.terminal == tr.state; - } - - /// A new peer, with nothing yet: its first delta of each terminal - /// starts it afresh. - pub fn addPeer(s: *Screens) !u16 { - if (s.free_peers.pop()) |again| return again; - const p = try s.gpa.create([pardes.MAX_PANES]PeerOf); - p.* = @splat(.{}); - try s.peers.append(s.gpa, p); - return @intCast(s.peers.items.len - 1); - } - - /// Peer `peer` gone: what it was sent forgotten, its number free for - /// the next `addPeer` (a socket's clients come and go). - pub fn dropPeer(s: *Screens, peer: u16) void { - for (s.peers.items[peer]) |*pp| pp.peer.deinit(s.gpa); - s.peers.items[peer].* = @splat(.{}); - s.free_peers.append(s.gpa, peer) catch {}; - } - - /// What `peer` is owed of every terminal, each a message onto `out` - /// (owned): nothing for one it has as it is, or with `bound` in flight. - pub fn flush(s: *Screens, core: *Pardes, peer: u16, out: *std.ArrayListUnmanaged([]u8)) !void { - const t0 = nowNs(); - defer s.encode_ns += nowNs() - t0; - for (core.panes, 0..) |slot, id| { - const pane = slot orelse continue; - const state = pane.terminal orelse continue; - const tr = try s.track(core, id); - const pp = &s.peers.items[peer][id]; - if (pp.serial != pane.serial) { - pp.peer.reset(); - pp.serial = pane.serial; - } - s.out.clearRetainingCapacity(); - try writeScreenHead(&s.out, s.gpa, @intCast(id), pane.serial, kind_delta); - var w: std.Io.Writer.Allocating = .fromArrayList(s.gpa, &s.out); - defer s.out = w.toArrayList(); - if (!try Term.encode(state, try s.encoder(), tr.track, &pp.peer, &w.writer)) continue; - try out.append(s.gpa, try s.gpa.dupe(u8, w.written())); - } - } - - /// Rows a peer holds as holes of every terminal a step read (its rows, - /// history and all: text mode over a shell), each a rows message onto - /// `out` (owned): sent after the step and before its unit, so the - /// replica's replay reads what the authority's step read. A history row - /// never changes, so each goes once. Then `filled`. - // ponytail: a step that reads a terminal's rows reads all of them (its - // motion surface), so the first after a flood sends its whole history. - pub fn fill(s: *Screens, core: *Pardes, peer: u16, out: *std.ArrayListUnmanaged([]u8)) !void { - for (core.panes, 0..) |slot, id| { - const pane = slot orelse continue; - const state = pane.terminal orelse continue; - if (!Term.wasRead(state)) continue; - const pp = &s.peers.items[peer][id]; - if (pp.serial != pane.serial or pp.peer.holes.items.len == 0) continue; - const tr = try s.track(core, id); - for (pp.peer.holes.items) |hole| { - var lo = hole[0]; - while (lo < hole[1]) { - const hi = @min(hole[1], lo + 512); - s.out.clearRetainingCapacity(); - try writeScreenHead(&s.out, s.gpa, @intCast(id), pane.serial, kind_rows); - var w: std.Io.Writer.Allocating = .fromArrayList(s.gpa, &s.out); - defer s.out = w.toArrayList(); - try Term.encodeRows(state, try s.encoder(), tr.track, lo, hi, &w.writer); - try out.append(s.gpa, try s.gpa.dupe(u8, w.written())); - lo = hi; - } - } - pp.peer.holes.clearRetainingCapacity(); - } - } - - /// Every peer is filled: the steps' reads are forgotten. - pub fn filled(_: *Screens, core: *Pardes) void { - for (core.panes) |slot| if (slot) |pane| if (pane.terminal) |state| { - Term.clearRead(state); - }; - } - - fn track(s: *Screens, core: *Pardes, id: usize) !*Tracked { - const pane = core.panes[id].?; - if (s.tracks[id]) |*tr| { - if (s.live(core, id, tr)) return tr; - // Its pane closed (its emulator, the pin with it, gone). - Term.untrack(tr.track, s.gpa, null); - s.tracks[id] = null; - } - s.tracks[id] = .{ .serial = pane.serial, .state = pane.terminal.?, .track = try Term.track(s.gpa) }; - return &s.tracks[id].?; - } - - /// The encoder, made the first time a terminal is encoded. - fn encoder(s: *Screens) !*Term.Encoder { - if (s.enc) |e| return e; - s.enc = try Term.encoder(s.gpa); - return s.enc.?; - } - - /// A peer's message (`Replica.screen`'s, `Replica.screenRequest`'s): - /// an answer for it (owned), or null. - pub fn take(s: *Screens, core: *Pardes, peer: u16, msg: []const u8) !?[]u8 { - const m = parseScreen(msg) orelse return null; - const pane = core.panes[m.pane] orelse return null; - if (pane.serial != m.serial) return null; - const state = pane.terminal orelse return null; - const pp = &s.peers.items[peer][m.pane]; - if (pp.serial != m.serial) return null; - switch (m.kind) { - kind_ack => if (m.payload.len == 4) pp.peer.ack(std.mem.readInt(u32, m.payload[0..4], .little)), - kind_reset => pp.peer.reset(), - kind_rows => { - if (m.payload.len != 16) return null; - const tr = try s.track(core, m.pane); - s.out.clearRetainingCapacity(); - try writeScreenHead(&s.out, s.gpa, m.pane, m.serial, kind_rows); - var w: std.Io.Writer.Allocating = .fromArrayList(s.gpa, &s.out); - defer s.out = w.toArrayList(); - try Term.encodeRows(state, try s.encoder(), tr.track, std.mem.readInt(u64, m.payload[0..8], .little), std.mem.readInt(u64, m.payload[8..16], .little), &w.writer); - return try s.gpa.dupe(u8, w.written()); - }, - else => {}, - } - return null; - } -}; - // ---- a replica ---- pub const Stats = struct { @@ -588,8 +381,6 @@ pub const Stats = struct { rollback_ns: std.ArrayListUnmanaged(u64) = .empty, copy_bytes: u64 = 0, copies: u32 = 0, - /// Nanoseconds: a terminal's delta applied. - apply_ns: std.ArrayListUnmanaged(u64) = .empty, /// What stopped them (`Tape.poisoned_by`), a count a name. stops: [16]Stop = @splat(.{}), @@ -619,7 +410,6 @@ pub const Stats = struct { s.spec_ns.deinit(gpa); s.copy_ns.deinit(gpa); s.rollback_ns.deinit(gpa); - s.apply_ns.deinit(gpa); } }; @@ -689,17 +479,14 @@ pub const Replica = struct { rtt_ns: u64 = 0, gmtoff: i32 = 0, - /// Its terminals' screen state, as the authority's deltas made it. - screens: [pardes.MAX_PANES]?ScreenOf = @splat(null), - /// Each terminal's view (`Term.grid`'s view) as the copy was taken, or - /// as the last delta since set it: the copy holds no emulator, and a - /// speculation may move a view, so a rollback puts these back. + /// Each terminal's view (`Term.grid`'s view) as the copy was taken: the + /// copy holds no emulator, and a speculation may move a view, so a + /// rollback puts these back. views: [pardes.MAX_PANES]?usize = @splat(null), /// Its panes' serials as the copy was taken, and whether one was being /// torn down then (`panesMoved`). serials: [pardes.MAX_PANES]u32 = @splat(0), retiring: bool = false, - screen_out: std.ArrayListUnmanaged(u8) = .empty, /// A record's bytes by hash coming in pieces (`blobPiece`), and how /// many of them came. incoming: ?tape.Big = null, @@ -709,26 +496,16 @@ pub const Replica = struct { cache: ?Cache = null, io: std.Io = undefined, /// Its predicted echo (core/term/echo.zig), drawn over its core's terminals: - /// fed by its keys, its units and its deltas here, and by `echoFrame`. + /// fed by its keys and its units here, and by `echoFrame`. echo: Echo = .{}, - const ScreenOf = struct { - serial: u32, - rep: *Term.Replica, - /// A delta was refused, and a reset asked for: those in flight - /// before it are refused unasked. - refused: bool = false, - /// The rows asked for and not yet answered. - asked: ?[2]u64 = null, - }; - - /// A replica of the session whose first unit is `first`; `screens` - /// as the authority's (its terminals fed by `screen`). In process, its - /// timing samples kept for the harness that reads them. - pub fn init(gpa: Allocator, id: u16, first: []const u8, screens: bool) !*Replica { + /// A replica of the session whose first unit is `first`, its terminals + /// fed the pty's bytes the units carry. In process, its timing samples + /// kept for the harness that reads them; no predicted echo (a joined + /// client's has one: `made`). + pub fn init(gpa: Allocator, id: u16, first: []const u8) !*Replica { const r = try gpa.create(Replica); r.* = .{ .gpa = gpa, .id = id, .t = tape.memory(gpa), .stats = .{ .samples = true } }; - r.t.screen_state = screens; r.t.core_gpa = r.epoch.allocator(); r.t.checks = false; r.confirm(first); @@ -736,7 +513,6 @@ pub const Replica = struct { r.deinit(); return error.NoCore; } - if (screens) r.core().echo = &r.echo; return r; } @@ -769,8 +545,6 @@ pub const Replica = struct { r.* = .{ .gpa = gpa, .id = id, .view = view orelse 0, .t = tape.memory(gpa), .guess = true }; r.t.skips_render = true; r.t.checks = false; - // Its terminals are the session's deltas (Peers sends them). - r.t.screen_state = true; errdefer { tape.release(&r.t); r.epoch.deinit(); @@ -834,7 +608,6 @@ pub const Replica = struct { } pub fn deinit(r: *Replica) void { - for (&r.screens) |*slot| if (slot.*) |*sc| Term.replicaFree(sc.rep, pardes.panes.emulator_gpa); if (r.t.core) |c| { const was = Stepping.begin(&r.t, &r.epoch); // The state it ends on is whole as it is: the copy let go, its @@ -854,7 +627,6 @@ pub const Replica = struct { for (r.since.items) |u| r.gpa.free(u); r.since.deinit(r.gpa); r.out.deinit(r.gpa); - r.screen_out.deinit(r.gpa); r.last_digest.deinit(r.gpa); r.stats.deinit(r.gpa); tape.release(&r.t); @@ -923,8 +695,8 @@ pub const Replica = struct { r.since_check +|= 1; if (u.origin == r.id) if (r.t.core) |c| r.echo.confirmed(c, u.seq); // The pty's bytes fed its emulators: its predicted echo judged - // against them, as a screen-state delta judges it (`screen`). - defer if (!r.t.screen_state and r.diverged == null and tape.feedsTerminal(u.tape)) if (r.t.core) |c| if (c.echo != null) r.echo.fed(c); + // against them. + defer if (r.diverged == null and tape.feedsTerminal(u.tape)) if (r.t.core) |c| if (c.echo != null) r.echo.fed(c); // A copy taken ahead (`ready`), nothing on top: it stays the point a // rollback goes back to, the unit replayed on it and kept in `since`, // not let go and taken again (a megabyte walked) for each unit of @@ -948,11 +720,12 @@ pub const Replica = struct { // nothing ends on again (`neutral`); none, not known. r.last_digest.clearRetainingCapacity(); if (lastDigest(u.tape)) |d| r.last_digest.appendSlice(r.gpa, d) catch {}; - if (r.pending.items[0].terminal and (r.applied > 1 or !r.t.screen_state)) { - // Right, but what it did read a terminal: replayed later (a - // rollback's `since`) it would read the deltas that came - // after it. So it is taken now, over the emulator its step - // read, and the ones on top applied again over it. + if (r.pending.items[0].terminal) { + // Right, but what it did wrote an emulator (or owes one a + // write: a grid's size): replayed later (a rollback's + // `since`) it would write it again. So it is taken now, over + // the emulator its step read, and the ones on top applied + // again over it. r.toConfirmed(); if (tape.replayUnit(&r.t, u.tape)) |why| return r.fail(why); r.freePending(r.pending.orderedRemove(0)); @@ -1007,7 +780,7 @@ pub const Replica = struct { // place, and much of it no digest covers (a colour set, a mode, the // pages a reload remakes). if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items) and - (r.t.screen_state or !tape.feedsTerminal(u.tape))) + !tape.feedsTerminal(u.tape)) { // Nothing a digest covers moved: what was applied on top is // what the session will apply on top of it. Replayed when the @@ -1076,7 +849,7 @@ pub const Replica = struct { const c = r.core(); for (c.retired_panes.current, c.retired_panes.previous) |x, y| retiring = retiring or x != null or y != null; for (c.panes, serials) |slot, n| retiring = retiring or (if (slot) |pane| pane.serial else 0) != n; - if (retiring or (!r.t.screen_state and Term.writes != writes)) { + if (retiring or Term.writes != writes) { r.copy.release(); rollback.Epoch.select(null); return r.clearSince(); @@ -1189,18 +962,14 @@ pub const Replica = struct { c.toView(.at(r.view)); // Input into a terminal: what reaches its program (a key in tty // mode, a paste, a mouse report) is a pty write, the authority's, - // and stops here (phase 6 predicts its echo). The rest (pardes's - // own keys over it, the wheel) reads its emulator, here the last - // delta's and there what the pty has said since: it is applied, - // and applied again over each delta while it waits (`screen`), so - // what the authority's unit confirms read the emulator its step - // read (the deltas come before it). - const keyboard = if (c.panes[c.view().active]) |pane| pane.terminal != null else false; + // and stops here (core/echo.zig predicts its echo). The rest + // (pardes's own keys over it, the wheel) reads its emulator, fed + // the same bytes in the same order as the session's: it is applied. c.update(in.event); c.step(); - // Under bytes: it owes an emulator a write it skipped (a grid's - // size), replayed when confirmed. - p.terminal = if (r.t.screen_state) keyboard or r.t.touched else r.t.touched; + // It owes an emulator a write it skipped (a grid's size): replayed + // when confirmed. + p.terminal = r.t.touched; const clean = tape.endSpeculation(&r.t); const dt = nowNs() - t0; // Where a blob was written, should one be: the input that did. @@ -1315,134 +1084,6 @@ pub const Replica = struct { return pardes.views.drawOne(c, r.view, present) catch true; } - /// One of the authority's terminal messages (`Screens.flush`, or an - /// answer to `screenRequests`), taken between units in stream order: a - /// delta written into its pane's emulator, or fetched rows. The - /// message for the authority (an acknowledgement, or a request to start - /// afresh), valid until the next call, or null. - pub fn screen(r: *Replica, msg: []const u8) ?[]const u8 { - const m = parseScreen(msg) orelse return null; - const c = r.t.core orelse return null; - const pane = c.panes[m.pane] orelse return null; - if (pane.serial != m.serial) return null; // a pane gone: its slot's next is another - const state = pane.terminal orelse return null; - const slot = &r.screens[m.pane]; - if (slot.* == null or slot.*.?.serial != m.serial) { - if (slot.*) |*old| Term.replicaFree(old.rep, pardes.panes.emulator_gpa); - slot.* = null; - const rep = Term.replica(pardes.panes.emulator_gpa) catch { - r.fail("no memory for a terminal's replica"); - return null; - }; - slot.* = .{ .serial = m.serial, .rep = rep }; - } - const sc = &slot.*.?; - // The emulator is the authority's: on the C heap, outside the - // rollback epoch, so a copy held now never saves or puts back any - // of what this writes (State.gpa). - switch (m.kind) { - kind_delta => { - // A unit kept to replay (`since`) read the emulator as it is - // now, and its step may have read it (a key over a shell's - // text reads its rows, an output its prompt): replayed over - // this delta it would read another (the soak, a copy taken - // ahead, three clients: another's key that read the rows, - // replayed by a rollback after the full-screen program - // redrew them, came to another state). So the units since go - // before it: let go with the copy when nothing is on top (the - // state is the confirmed one), else replayed now. - if (r.copy.held and r.since.items.len > 0) { - const was = Stepping.begin(&r.t, &r.epoch); - defer was.end(); - if (r.applied == 0) { - r.copy.release(); - rollback.Epoch.select(null); - r.clearSince(); - } else { - r.toConfirmed(); - r.dirty = true; - } - } - const t0 = nowNs(); - const applied = Term.apply(state, sc.rep, m.payload) catch |err| { - if (err != error.BaseMismatch) r.fail("a terminal's delta did not apply"); - if (sc.refused) return null; - sc.refused = true; - return r.screenMessage(m.pane, m.serial, kind_reset, &.{}); - }; - if (r.stats.samples) r.stats.apply_ns.append(r.gpa, nowNs() - t0) catch {}; - sc.refused = false; - r.echo.delta(c, m.pane, Term.replicaTop(sc.rep)); - // Its rows as the core keeps them read are another grid's. - c.shell_rows.markStale(pane); - // Its view is the authority's now: a rollback puts it back - // here, and what was applied over a terminal goes on top. - if (r.copy.held) r.views[m.pane] = pardes.Term.grid(state).view; - r.overTerminals(); - var seq: [4]u8 = undefined; - std.mem.writeInt(u32, &seq, applied.seq, .little); - return r.screenMessage(m.pane, m.serial, kind_ack, &seq); - }, - kind_rows => { - sc.asked = null; - Term.applyRows(state, sc.rep, m.payload) catch r.fail("a terminal's rows did not apply"); - c.shell_rows.markStale(pane); - r.overTerminals(); - return null; - }, - else => return null, - } - } - - /// A terminal was written (a delta, rows): what is applied over the - /// emulator (`Pending.terminal`) read the one before it, and the - /// authority's step reads this one (it comes before that step's unit). - /// Back to the confirmed position, to be applied again over it. - fn overTerminals(r: *Replica) void { - const any = for (r.pending.items[0..r.applied]) |p| { - if (p.terminal) break true; - } else false; - if (!any) return; - const was = Stepping.begin(&r.t, &r.epoch); - defer was.end(); - r.toConfirmed(); - r.dirty = true; - } - - /// A request for the rows a terminal shows here and does not hold (its - /// holes in view, after a scroll back), one a terminal at a time; null - /// when none is owed. Until the answer, a hole shows blank. - pub fn screenRequest(r: *Replica) ?[]const u8 { - const c = r.t.core orelse return null; - for (&r.screens, 0..) |*slot, id| { - const sc: *ScreenOf = if (slot.*) |*x| x else continue; - if (sc.asked != null) continue; - const pane = c.panes[id] orelse continue; - if (pane.serial != sc.serial) continue; - const state = pane.terminal orelse continue; - const shown = Term.shown(state, sc.rep); - var holes: std.ArrayList([2]u64) = .empty; - defer holes.deinit(r.gpa); - Term.missing(sc.rep, shown[0], shown[1], &holes, r.gpa) catch return null; - if (holes.items.len == 0) continue; - const want: [2]u64 = .{ holes.items[0][0], holes.items[holes.items.len - 1][1] }; - Term.blank(state, sc.rep, want[0], want[1]); - sc.asked = want; - var range: [16]u8 = undefined; - std.mem.writeInt(u64, range[0..8], want[0], .little); - std.mem.writeInt(u64, range[8..16], want[1], .little); - return r.screenMessage(@intCast(id), sc.serial, kind_rows, &range); - } - return null; - } - - fn screenMessage(r: *Replica, pane: u8, serial: u32, kind: u8, payload: []const u8) ?[]const u8 { - r.screen_out.clearRetainingCapacity(); - writeScreenHead(&r.screen_out, r.gpa, pane, serial, kind) catch return null; - r.screen_out.appendSlice(r.gpa, payload) catch return null; - return r.screen_out.items; - } - /// A piece of a record's bytes by hash (Peer.blob): whole and checked /// against its hash, kept for the unit that names it (tape.keepFile), /// and a file's, a far client's, on disk (`cache`) for its next join. @@ -1720,8 +1361,6 @@ pub const Peer = struct { again: bool = false, /// ...or that its window was closed (Peers.closed). close: bool = false, - /// Its number in the session's `Screens`. - sid: u16 = 0, /// Inputs read (each one's seq, as the client numbered them). seq: u32 = 0, /// The `stamp` frame its next input came with (its reader's). @@ -2010,13 +1649,6 @@ pub const Peer = struct { peer.send(&.{pong}); return true; }, - // Its word about a terminal (an ack, rows asked, a reset), to - // the session's Screens at the next boundary. - .screen_ack => { - const msg = peer.peers.gpa.dupe(u8, payload) catch return false; - peer.peers.post(.{ .screen = .{ .peer = peer, .msg = msg } }); - return true; - }, .check => { peer.peers.post(.{ .check = peer }); return true; @@ -2152,25 +1784,18 @@ pub const Peers = struct { boundary_ns: std.ArrayListUnmanaged(u64) = .empty, cut: u32 = 0, head: [unit_head]u8 = undefined, - /// Its clients' terminals as screen state (core/term/screen_state.zig), while - /// it records: what each was sent. - screens: Screens = undefined, - msgs: std.ArrayListUnmanaged([]u8) = .empty, /// False: its clients' links are in this process's memory, a thread /// for none of them (the soak's, test/replicas.zig): what a client's /// writer would write (its join, then `out`) and its reader read /// (`Peer.take`, then `.gone` posted) are its driver's to do. threads: bool = true, - /// After each flush of a client's terminals, told: the soak's record - /// of each terminal as each version left it (test/replicas.zig). - flushed: ?struct { ctx: *anyopaque, f: *const fn (*anyopaque, *Pardes, *Screens) void } = null, /// Its clients' terminals cross as the pty's bytes in its units, each /// client's emulator its own (P29, P32), not as screen state: every /// session's (runtime/session.zig) but under PARDES_TERM_SCREEN, the /// soak's `--bytes`; its welcome says so to each client. bytes: bool = false, - pub const Note = union(enum) { join: Joining, input: Msg, screen: Msg, gone: *Peer, check: *Peer, joined: *Peer }; + pub const Note = union(enum) { join: Joining, input: Msg, gone: *Peer, check: *Peer, joined: *Peer }; /// A connection to join, and the view it joins again for, if it does. pub const Joining = daemon.Joining; pub const Msg = struct { peer: *Peer, msg: []u8 }; @@ -2191,13 +1816,13 @@ pub const Peers = struct { ps.lock.unlock(ps.io); switch (note) { .join => |j| _ = libc.close(j.fd), - .input, .screen => |in| ps.gpa.free(in.msg), + .input => |in| ps.gpa.free(in.msg), .gone, .check, .joined => {}, } return; }; ps.mail.store(true, .release); - if (note != .screen) ps.urgent.store(true, .release); + ps.urgent.store(true, .release); ps.lock.unlock(ps.io); if (ps.wake) |w| w(ps.wake_ctx); } @@ -2227,8 +1852,6 @@ pub const Peers = struct { const head = wire.header(@backingInt(wire.ServerTag.unit), unit_head + bytes.len); for (ps.list) |slot| if (slot) |peer| peer.send(&.{ &head, &ps.head, bytes }); ps.t.buf.clearRetainingCapacity(); - // The sizes its steps gave terminals, now: the next flush says so. - if (ps.t.core) |core| pardes.panes.resizeDeferred(core); } /// After each of the session's pumps: its unit sent, the clients that @@ -2239,12 +1862,8 @@ pub const Peers = struct { const t0 = nowNs(); defer if (ps.recording and ps.samples) ps.boundary_ns.append(ps.gpa, nowNs() - t0) catch {}; if (ps.recording) { - // The rows the pump's steps read, then its unit, then what the - // terminals came to (the next steps read that). - ps.screensOut(core, .fill); ps.seq += 1; ps.unit(0, ps.seq); - ps.screensOut(core, .flush); } if (!ps.mail.load(.acquire)) return; ps.lock.lockUncancelable(ps.io); @@ -2257,20 +1876,6 @@ pub const Peers = struct { ps.input(core, in.peer, in.msg); ps.gpa.free(in.msg); }, - .screen => |in| { - defer ps.gpa.free(in.msg); - // An acknowledgement (or a reset): room again in its flight - // for what its terminals came to since. Its flush at this - // boundary came before it, and at the bound sent nothing: - // with no step after it, that client kept an old screen. - const reply = (ps.screens.take(core, in.peer.sid, in.msg) catch null) orelse { - ps.screensTo(core, in.peer, .flush); - continue; - }; - defer ps.gpa.free(reply); - const head = wire.header(@backingInt(wire.ServerTag.screen), reply.len); - in.peer.send(&.{ &head, reply }); - }, .gone => |peer| ps.leave(core, peer), .joined => |peer| released(peer), .check => |peer| { @@ -2285,20 +1890,12 @@ pub const Peers = struct { const in = parseInput(msg) orelse return; const t0 = nowNs(); defer if (ps.samples) ps.input_ns.append(ps.gpa, nowNs() - t0) catch {}; - // The terminals as this step reads them, then the step, the rows - // it read, its unit (part B terminal notes' order). - ps.screensOut(core, .flush); core.toView(peer.view); ps.t.stamp = stampOf(in); core.update(in.event); core.step(); ps.t.stamp = null; - ps.screensOut(core, .fill); ps.unit(peer.id, in.seq); - // What the step made of a kind's pane (the tick after a key or a - // click into it: another layout) goes now, not at the next pump's: - // one may not come before the client looks. - ps.screensOut(core, .flush); } /// What its steps recorded passed a unit's bound (`tape.unit_max`): a @@ -2309,33 +1906,6 @@ pub const Peers = struct { ps.unit(0, ps.seq); } - const ScreensOut = enum { flush, fill }; - - /// What each client is owed of the terminals (`Screens.flush`), or the - /// rows a step read that it lacks (`Screens.fill`, then `filled`), each - /// a screen message queued for it. - fn screensOut(ps: *Peers, core: *Pardes, comptime what: ScreensOut) void { - for (ps.list) |slot| if (slot) |peer| ps.screensTo(core, peer, what); - if (what == .fill) ps.screens.filled(core); - } - - fn screensTo(ps: *Peers, core: *Pardes, peer: *Peer, comptime what: ScreensOut) void { - if (ps.bytes) return; - defer { - for (ps.msgs.items) |m| ps.gpa.free(m); - ps.msgs.clearRetainingCapacity(); - } - (switch (what) { - .flush => ps.screens.flush(core, peer.sid, &ps.msgs), - .fill => ps.screens.fill(core, peer.sid, &ps.msgs), - }) catch return; - if (what == .flush) if (ps.flushed) |h| h.f(h.ctx, core, &ps.screens); - for (ps.msgs.items) |m| { - const head = wire.header(@backingInt(wire.ServerTag.screen), m.len); - peer.send(&.{ &head, m }); - } - } - /// A client on `joining.fd` joined: a dump of the session now, its /// threads started. At a step boundary (`boundary`), or a session's /// first client before its first effects (runtime/session.zig). @@ -2355,12 +1925,9 @@ pub const Peers = struct { if (tape.on != null) return daemon.refuseReplica(fd, "that session records a tape of its own (PARDES_RECORD)"); ps.t = tape.memory(ps.gpa); ps.t.unit_digests = true; - // Terminals cross as screen state: a unit carries no pty bytes, - // and its digest is a word (PARDES_REPLICA_TRACE: one a field). - ps.t.screen_state = !ps.bytes; + // A unit's digest is a word (PARDES_REPLICA_TRACE: one a field). ps.t.whole_digest = std.c.getenv("PARDES_REPLICA_TRACE") == null; ps.t.cut = .{ .ctx = ps, .f = cutUnit }; - ps.screens = .init(ps.gpa); tape.on = &ps.t; core.tape = &ps.t; ps.recording = true; @@ -2438,11 +2005,6 @@ pub const Peers = struct { slot.* = peer; peer.pid = peerPid(fd); ps.tellClients(); - // Its terminals afresh, after its dump and before any unit. - if (ps.screens.addPeer()) |sid| { - peer.sid = sid; - ps.screensTo(core, peer, .flush); - } else |_| _ = libc.shutdown(fd, 2); log.info("client {d} joined '{s}' as view {d}: a {d} KB dump ({d} KB of state) in {d} us", .{ peer.id, ps.name, k, whole >> 10, bytes.len >> 10, (nowNs() - t0) / 1000 }); if (std.c.getenv("PARDES_REPLICA_TRACE") != null) std.debug.print("session: client {d} joined after unit {d}\n", .{ peer.id, ps.seq }); } @@ -2492,7 +2054,6 @@ pub const Peers = struct { }; log.info("client {d} left '{s}'", .{ peer.id, ps.name }); ps.tellClients(); - ps.screens.dropPeer(peer.sid); core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view.index())); // Cut off, it joins again after the words why (`send`); its reader // has ended and no other thread sets `cut` now. @@ -2535,7 +2096,7 @@ pub const Peers = struct { var i: usize = 0; while (i < ps.inbox.items.len) { const mine = switch (ps.inbox.items[i]) { - .input, .screen => |in| in.peer == peer, + .input => |in| in.peer == peer, .gone, .check, .joined => |p| p == peer, .join => false, }; @@ -2544,7 +2105,7 @@ pub const Peers = struct { continue; } switch (ps.inbox.items[i]) { - .input, .screen => |in| ps.gpa.free(in.msg), + .input => |in| ps.gpa.free(in.msg), else => {}, } _ = ps.inbox.orderedRemove(i); @@ -2662,8 +2223,6 @@ pub const Peers = struct { fn stop(ps: *Peers, core: *Pardes) void { if (!ps.recording) return; - pardes.panes.resizeDeferred(core); - ps.screens.deinit(core); tape.on = null; core.tape = core.opts.tape orelse &tape.none; tape.release(&ps.t); @@ -2682,7 +2241,6 @@ pub const Peers = struct { slot.* = null; core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view.index())); ps.closeViewOf(core, peer, again); - ps.screens.dropPeer(peer.sid); ps.letGo(peer); }; ps.tellClients(); @@ -2690,7 +2248,7 @@ pub const Peers = struct { ps.lock.lockUncancelable(ps.io); for (ps.inbox.items) |note| switch (note) { .join => |j| _ = libc.close(j.fd), - .input, .screen => |in| ps.gpa.free(in.msg), + .input => |in| ps.gpa.free(in.msg), .gone, .check, .joined => {}, }; ps.inbox.clearRetainingCapacity(); @@ -2704,7 +2262,6 @@ pub const Peers = struct { ps.taken.deinit(ps.gpa); ps.input_ns.deinit(ps.gpa); ps.boundary_ns.deinit(ps.gpa); - ps.msgs.deinit(ps.gpa); ps.each_join.deinit(ps.gpa); } @@ -3110,18 +2667,6 @@ pub fn sendInput(fd: c_int, msg: []const u8) bool { return writeAll(fd, msg[head_len..]); } -/// A message `Replica.screen` or `screenRequest` made, to the session. -pub fn sendScreen(fd: c_int, msg: []const u8) bool { - var buf: [64]u8 = undefined; - if (wire.header_len + msg.len > buf.len) { - const head = wire.header(@backingInt(wire.ClientTag.screen_ack), msg.len); - return writeAll(fd, &head) and writeAll(fd, msg); - } - buf[0..wire.header_len].* = wire.header(@backingInt(wire.ClientTag.screen_ack), msg.len); - @memcpy(buf[wire.header_len..][0..msg.len], msg); - return writeAll(fd, buf[0 .. wire.header_len + msg.len]); -} - /// Asks the session's digest, answered in stream order. pub fn askCheck(fd: c_int) bool { var out: [16]u8 = undefined; @@ -3136,9 +2681,9 @@ pub fn bye(fd: c_int, how: @FieldType(wire.ClientMsg, "bye")) void { } /// What the session streams a client after its dump, as its frontend's loop -/// takes it: a unit's and a terminal message's bytes and a refusal's words -/// on the C heap, the loop's to free. -pub const Said = union(enum) { unit: []u8, screen: []u8, checked: u64, refused: []u8, blob: []u8, ended: u8, left }; +/// takes it: a unit's bytes and a refusal's words on the C heap, the loop's +/// to free. +pub const Said = union(enum) { unit: []u8, checked: u64, refused: []u8, blob: []u8, ended: u8, left }; /// The session's stream off `fd`, each message handed to `post` until the /// link ends (a refusal ends it too); `post` says whether it took it (one @@ -3149,7 +2694,6 @@ pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime const t = std.enums.fromInt(wire.ServerTag, tag) orelse return false; const msg: Said = switch (t) { .unit => .{ .unit = std.heap.c_allocator.dupe(u8, payload) catch return false }, - .screen => .{ .screen = std.heap.c_allocator.dupe(u8, payload) catch return false }, .blob => .{ .blob = std.heap.c_allocator.dupe(u8, payload) catch return false }, .check => .{ .checked = (wire.decodeServer(tag, payload) catch return false).check }, .refused => .{ .refused = std.heap.c_allocator.dupe(u8, (wire.decodeServer(tag, payload) catch return false).refused) catch return false }, @@ -3158,11 +2702,11 @@ pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime .pong, .welcome, .dump, .blobs, .zstd => return true, }; if (!post(x, msg)) switch (msg) { - .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b), + .unit, .refused, .blob => |b| std.heap.c_allocator.free(b), .checked, .ended, .left => {}, }; // A last word ends the stream. - return msg == .unit or msg == .screen or msg == .checked or msg == .blob; + return msg == .unit or msg == .checked or msg == .blob; } }; rest.run(gpa, fd, ctx, Take.take); @@ -3576,11 +3120,6 @@ pub const Link = struct { // after it in the stream and its digest covers it. if (!c.asked) c.changed = true; }, - .screen => |bytes| { - defer std.heap.c_allocator.free(bytes); - if (c.r.screen(bytes)) |reply| if (!sendScreen(c.fd, reply)) c.cut(); - c.dirty = true; - }, .blob => |bytes| { defer std.heap.c_allocator.free(bytes); c.r.blobPiece(bytes); @@ -3604,9 +3143,7 @@ pub const Link = struct { } /// Its own view drawn, by the frontend (`drew` is whether anything was - /// written to it): a rollback it may have shown counted, and the - /// history rows it shows and does not hold (a scroll back) asked for, - /// blank until they come. + /// written to it): a rollback it may have shown counted. pub fn drawn(c: *Link, drew: bool) void { if (c.r.stats.mispredicted > c.mispredicted) { c.mispredicted = c.r.stats.mispredicted; @@ -3617,10 +3154,6 @@ pub const Link = struct { // What moved before this frame is in it: not drawn again at the // next unit (a stopped input's rollback, under its own frame). c.r.moved = false; - while (c.r.screenRequest()) |req| if (!sendScreen(c.fd, req)) { - c.cut(); - break; - }; } /// The session's unit `bytes`, taken now: how far behind it is. Past @@ -3817,29 +3350,6 @@ fn key(r: *Replica, cp: u21, sent: *std.ArrayListUnmanaged([]u8)) !void { try sent.append(std.testing.allocator, try std.testing.allocator.dupe(u8, msg)); } -/// What the session sends a peer: its terminals' changes (`.flush`), or, -/// around a step's unit (Peers.input), the rows the step read that the -/// peer lacks (`.fill`), after which the caller gives terminals the sizes -/// the step gave them (`panes.resizeDeferred`), then the unit. -fn deliver(a: *Authority, screens: *Screens, peer: u16, r: *Replica, comptime what: enum { flush, fill }) !void { - const gpa = std.testing.allocator; - var msgs: std.ArrayListUnmanaged([]u8) = .empty; - defer { - for (msgs.items) |m| gpa.free(m); - msgs.deinit(gpa); - } - switch (what) { - .flush => try screens.flush(a.core, peer, &msgs), - .fill => { - try screens.fill(a.core, peer, &msgs); - screens.filled(a.core); - }, - } - for (msgs.items) |m| if (r.screen(m)) |reply| { - _ = try screens.take(a.core, peer, reply); - }; -} - /// The blob cache of a test, in its own directory (never the user's). fn testCache(tmp: *std.testing.TmpDir, buf: *[4200]u8, cap: u64) !Cache { var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; @@ -3935,34 +3445,21 @@ fn inputOf(buf: []u8, client: u16, seq: u32, ev: pardes.Event) ![]const u8 { } /// An input of a replica's in the session's order, as `Peers.input` takes -/// it: the terminals flushed to every peer, the step, the rows it read that -/// each peer holds as holes (`fill`), then its unit to every replica. -fn takeAll(a: *Authority, screens: *Screens, rs: []const *Replica, ps: []const u16, msg: []const u8) !void { +/// it: the step, then its unit to every replica. +fn takeAll(a: *Authority, rs: []const *Replica, msg: []const u8) !void { const gpa = std.testing.allocator; - for (rs, ps) |r, peer| try deliver(a, screens, peer, r, .flush); const u = try gpa.dupe(u8, try a.take(msg)); defer gpa.free(u); - var rows: std.ArrayListUnmanaged([]u8) = .empty; - defer rows.deinit(gpa); - for (rs, ps) |r, peer| { - rows.clearRetainingCapacity(); - try screens.fill(a.core, peer, &rows); - for (rows.items) |m| { - _ = r.screen(m); - gpa.free(m); - } - } - screens.filled(a.core); for (rs) |r| { r.confirm(u); r.settle(); } } -fn sendAs(r: *Replica, a: *Authority, screens: *Screens, rs: []const *Replica, ps: []const u16, ev: pardes.Event) !void { +fn sendAs(r: *Replica, a: *Authority, rs: []const *Replica, ev: pardes.Event) !void { const msg = try std.testing.allocator.dupe(u8, try r.input(ev)); defer std.testing.allocator.free(msg); - try takeAll(a, screens, rs, ps, msg); + try takeAll(a, rs, msg); } fn shows(p: *Pardes, text: []const u8) !bool { @@ -4044,9 +3541,9 @@ test "an Upgrade tells a client handed to the session and not joined yet that it test "a replica's own keys apply at once, confirm on the fast path, and end at the authority's digest" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); try std.testing.expectEqual(digestOf(a), r.digest()); var sent: std.ArrayListUnmanaged([]u8) = .empty; @@ -4071,9 +3568,9 @@ test "a replica's own keys apply at once, confirm on the fast path, and end at t test "an input's time is its client's: an edit's second confirms on the fast path though the authority takes it in the next" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); var sent: std.ArrayListUnmanaged([]u8) = .empty; defer { @@ -4108,13 +3605,13 @@ test "an input's time is its client's: an edit's second confirms on the fast pat test "another client's input first: a replica rolls back, replays it and applies its own again" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const first = try gpa.dupe(u8, try a.unit(0, 0)); defer gpa.free(first); - const r1 = try Replica.init(gpa, 1, first, false); + const r1 = try Replica.init(gpa, 1, first); defer r1.deinit(); - const r2 = try Replica.init(gpa, 2, first, false); + const r2 = try Replica.init(gpa, 2, first); defer r2.deinit(); var s1: std.ArrayListUnmanaged([]u8) = .empty; var s2: std.ArrayListUnmanaged([]u8) = .empty; @@ -4149,11 +3646,11 @@ test "another client's input first: a replica rolls back, replays it and applies test "the copy taken for an input of its own stays once the input is confirmed: the next takes none, and a rollback replays the first over it" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const first = try gpa.dupe(u8, try a.unit(0, 0)); defer gpa.free(first); - const r = try Replica.init(gpa, 1, first, false); + const r = try Replica.init(gpa, 1, first); defer r.deinit(); var sent: std.ArrayListUnmanaged([]u8) = .empty; defer { @@ -4182,7 +3679,7 @@ test "a client marks its view moved for a unit of the session's whose steps aske // clock, or a ctl write's close, draws nothing; a client presented it // again (the corpus's pet: one picture twice). const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); // A client as a dial joins it: it draws none of its replay. const r = try joinedNow(a, 1, 0); @@ -4207,9 +3704,9 @@ test "the session's pump units that moved nothing, kept under a key applied on t // of them is the bound's is the arrivals' parity, and a pump's unit // while idle turns it. const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); var sent: std.ArrayListUnmanaged([]u8) = .empty; defer { @@ -4255,11 +3752,11 @@ test "a rollback over a Tab it applied measures tabs as its core has them again" // a Tab undone left it, and the next replayed step measured the files' // tabs otherwise (the soak, five clients). const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const first = try gpa.dupe(u8, try a.unit(0, 0)); defer gpa.free(first); - const r = try Replica.init(gpa, 1, first, false); + const r = try Replica.init(gpa, 1, first); defer r.deinit(); const was = r.core().settings.tab; const msg = try gpa.dupe(u8, try r.input(.{ .command = "Tab 2" })); @@ -4275,101 +3772,12 @@ test "a rollback over a Tab it applied measures tabs as its core has them again" try agrees(a, r); } -test "a delta applied under a speculation outlives its rollback: the terminal stays the authority's newest" { - if (pardes.Term.ops == null) return error.SkipZigTest; // a shell - const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true); - defer a.deinit(); - var screens: Screens = .init(gpa); - defer screens.deinit(a.core); - const peer = try screens.addPeer(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), true); - defer r.deinit(); - const shell: u8 = for (a.core.panes, 0..) |slot, id| { - if (slot) |pane| if (pane.isTerminal()) break @intCast(id); - } else return error.NoShell; - // Typing goes to the text pane under the shell (the host's write of - // `active`, taped). - a.core.view().active = for (a.core.panes, 0..) |slot, id| { - if (slot) |pane| if (pane.file != null) break id; - } else return error.NoTextPane; - r.confirm(try a.local(.{ .focus = true })); - try deliver(a, &screens, peer, r, .flush); - var sent: std.ArrayListUnmanaged([]u8) = .empty; - defer { - for (sent.items) |m| gpa.free(m); - sent.deinit(gpa); - } - // Typed into the file, at once: a copy is held. - try key(r, 'o', &sent); - try std.testing.expect(r.copy.held); - var line: [64]u8 = undefined; - for (0..3) |round| { - // The shell prints: its unit rolls the replica back and applies the - // key again; then its delta lands, under the new copy. - for (0..40) |i| a.output(.{ .output = .{ .pane = .at(shell), .bytes = try std.fmt.bufPrint(&line, "round {d} line {d}\r\n", .{ round, i }) } }); - r.confirm((try a.pending()).?); - r.settle(); - try std.testing.expect(r.copy.held); - try deliver(a, &screens, peer, r, .flush); - // The rows the core keeps, read once under the copy. - _ = try pardes.edit.shellRows(r.core(), r.core().panes[shell].?); - } - for (sent.items) |m| { - r.confirm(try a.take(m)); - r.settle(); - gpa.free(m); - } - sent.clearRetainingCapacity(); - try deliver(a, &screens, peer, r, .flush); - // Drawn (its rows read, between steps), then typed into: the copy keeps - // those rows. The shell prints, its delta lands under the copy, and then - // another's unit puts the copy back: the rows it kept are of an older - // grid and must not be read. - r.confirm(try a.local(.{ .focus = false })); - _ = try pardes.edit.shellRows(r.core(), r.core().panes[shell].?); - try key(r, 'x', &sent); - for (0..40) |i| a.output(.{ .output = .{ .pane = .at(shell), .bytes = try std.fmt.bufPrint(&line, "last line {d}\r\n", .{i}) } }); - r.confirm((try a.pending()).?); - r.settle(); - try deliver(a, &screens, peer, r, .flush); - r.confirm(try a.local(.{ .focus = true })); - r.settle(); - const n = a.core.panes[shell].?.rows; - const back = try pardes.edit.shellRows(r.core(), r.core().panes[shell].?); - const now = try pardes.edit.shellRows(a.core, a.core.panes[shell].?); - for (now[now.len - n ..], back[back.len - n ..]) |x, y| try std.testing.expectEqualStrings(x, y); - for (sent.items) |m| { - r.confirm(try a.take(m)); - r.settle(); - } - try deliver(a, &screens, peer, r, .flush); - if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); - try std.testing.expect(r.diverged == null and r.quiet()); - try std.testing.expectEqual(digestOf(a), r.digest()); - var dump_a: std.Io.Writer.Allocating = .init(gpa); - defer dump_a.deinit(); - var dump_r: std.Io.Writer.Allocating = .init(gpa); - defer dump_r.deinit(); - try Term.dumpScreen(a.core.panes[shell].?.terminal.?, &dump_a.writer); - try Term.dumpScreen(r.core().panes[shell].?.terminal.?, &dump_r.writer); - try std.testing.expectEqualStrings(dump_a.written(), dump_r.written()); - const rows_a = try pardes.edit.shellRows(a.core, a.core.panes[shell].?); - const rows_r = try pardes.edit.shellRows(r.core(), r.core().panes[shell].?); - // As many rows (the history is the authority's to the row), the screen's - // the same; above it, rows scrolled past more than a screen at once are - // holes until fetched. - try std.testing.expectEqual(rows_a.len, rows_r.len); - const shown = a.core.panes[shell].?.rows; - for (rows_a[rows_a.len - shown ..], rows_r[rows_r.len - shown ..]) |x, y| try std.testing.expectEqualStrings(x, y); -} - test "a closed terminal brought back on a screen-state replica: its emulator on the C heap, never the rollback epoch's" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host()); defer a.deinit(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), true); + const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); const shell: u8 = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break @intCast(id); @@ -4392,13 +3800,13 @@ test "a closed terminal brought back on a screen-state replica: its emulator on test "a view that sized a terminal closing leaves nothing queued: the others' replicas copy, type and agree" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, TestHost.host(), true); + const a = try Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, TestHost.host()); defer a.deinit(); const first = try gpa.dupe(u8, try a.unit(0, 0)); defer gpa.free(first); - const r1 = try Replica.init(gpa, 1, first, true); + const r1 = try Replica.init(gpa, 1, first); defer r1.deinit(); - const r2 = try Replica.init(gpa, 2, first, true); + const r2 = try Replica.init(gpa, 2, first); defer r2.deinit(); a.core.view().active = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break id; @@ -4436,244 +3844,12 @@ test "a view that sized a terminal closing leaves nothing queued: the others' re try std.testing.expectEqual(digestOf(a), r1.digest()); } -test "a terminal sized again by a client's key: the step reads the grid it had, on both sides" { - if (pardes.Term.ops == null) return error.SkipZigTest; // a shell - const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 50, .rows = 20, .boot = .tty }, TestHost.host(), true); - defer a.deinit(); - var screens: Screens = .init(gpa); - defer screens.deinit(a.core); - const peer = try screens.addPeer(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), true); - defer r.deinit(); - const shell: u8 = for (a.core.panes, 0..) |slot, id| { - if (slot) |pane| if (pane.isTerminal()) break @intCast(id); - } else return error.NoShell; - a.core.view().active = shell; - // History the replica holds as holes, of lines a narrow grid wraps in - // two, which a wider one unwraps. - var line: [96]u8 = undefined; - for (0..60) |i| a.output(.{ .output = .{ .pane = .at(shell), .bytes = try std.fmt.bufPrint(&line, "{d:0>4} xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n", .{i}) } }); - r.confirm((try a.pending()).?); - // Out of terminal mode in the session's view, which sizes it; then a - // client's own view (a copy of it), wider: its first key sizes the - // terminal again, in that key's step (the soak's tty and window at two - // sizes, 2026-10-30: the client's replay read holes the session's step - // had read as text, and the fill came in the new grid's numbers). - r.confirm(try a.local(.{ .key = .{ .cp = 'b', .ctrl = true } })); - for ([_]u21{ 'g', 'g' }) |cp| r.confirm(try a.local(.{ .key = .{ .cp = cp, .text = &.{@intCast(cp)} } })); - const opened = try a.openView(1); - r.view = opened.view; - r.confirm(opened.unit); - try deliver(a, &screens, peer, r, .flush); - var sent: std.ArrayListUnmanaged([]u8) = .empty; - defer { - for (sent.items) |m| gpa.free(m); - sent.deinit(gpa); - } - const Step = struct { - fn take(au: *Authority, sc: *Screens, pe: u16, rr: *Replica, msg: []const u8) !void { - try deliver(au, sc, pe, rr, .flush); - const u = try std.testing.allocator.dupe(u8, try au.take(msg)); - defer std.testing.allocator.free(u); - try deliver(au, sc, pe, rr, .fill); - pardes.panes.resizeDeferred(au.core); - rr.confirm(u); - rr.settle(); - } - }; - try sent.append(gpa, try gpa.dupe(u8, try r.input(.{ .resize = .{ .cols = 120, .rows = 30 } }))); - try key(r, 'g', &sent); - try key(r, 'g', &sent); - for (sent.items) |m| try Step.take(a, &screens, peer, r, m); - for (sent.items) |m| gpa.free(m); - sent.clearRetainingCapacity(); - // The session's view types into it, which sizes it back (the client's - // copy of its history all holes again, a new numbering); then the - // client's key that reads all of it, and sizes it again. - try deliver(a, &screens, peer, r, .flush); - { - const was = Stepping.begin(&a.t, null); - a.core.toView(.at(0)); - a.core.update(.{ .key = .{ .cp = 'k', .text = "k" } }); - a.core.step(); - was.end(); - } - a.seq += 1; - const back = try gpa.dupe(u8, try a.unit(0, a.seq)); - defer gpa.free(back); - try deliver(a, &screens, peer, r, .fill); - pardes.panes.resizeDeferred(a.core); - r.confirm(back); - r.settle(); - try deliver(a, &screens, peer, r, .flush); - try key(r, 'w', &sent); - try key(r, 'w', &sent); - for (sent.items) |m| try Step.take(a, &screens, peer, r, m); - try deliver(a, &screens, peer, r, .flush); - if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); - try std.testing.expect(r.diverged == null and r.quiet()); - try std.testing.expectEqual(digestOf(a), r.digest()); -} - -test "pardes's own keys over a terminal's history apply at once: its view moves here, a delta while they wait puts them on top again, the authority's ends the same" { - if (pardes.Term.ops == null) return error.SkipZigTest; // a shell - const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true); - defer a.deinit(); - var screens: Screens = .init(gpa); - defer screens.deinit(a.core); - const peer = try screens.addPeer(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), true); - defer r.deinit(); - const shell: u8 = for (a.core.panes, 0..) |slot, id| { - if (slot) |pane| if (pane.isTerminal()) break @intCast(id); - } else return error.NoShell; - a.core.view().active = shell; - r.confirm(try a.local(.{ .focus = true })); - var line: [64]u8 = undefined; - for (0..200) |i| a.output(.{ .output = .{ .pane = .at(shell), .bytes = try std.fmt.bufPrint(&line, "history line {d}\r\n", .{i}) } }); - r.confirm((try a.pending()).?); - try deliver(a, &screens, peer, r, .flush); - r.settle(); - var sent: std.ArrayListUnmanaged([]u8) = .empty; - defer { - for (sent.items) |m| gpa.free(m); - sent.deinit(gpa); - } - // Normal mode in the shell, up a few rows, then half a screen and more: - // the cursor leaves the view, and the view follows it back. - const keys = [_]pardes.Key{ - .{ .cp = a.core.opts.tty_toggle, .ctrl = true }, .{ .cp = 'k', .text = "k" }, .{ .cp = 'k', .text = "k" }, - .{ .cp = 'u', .ctrl = true }, .{ .cp = 'u', .ctrl = true }, .{ .cp = 'k', .text = "k" }, - }; - for (keys) |k| try sent.append(gpa, try gpa.dupe(u8, try r.input(.{ .key = k }))); - try std.testing.expectEqual(@as(u32, 0), r.stats.stopped); - try std.testing.expectEqual(sent.items.len, r.applied); - const here = r.core().panes[shell].?; - try std.testing.expect(pardes.Term.grid(here.terminal).view != null); - // The shell prints while they wait: its unit, then its delta, which - // sets the view the authority's (at the bottom still): what was applied - // goes on top of it again. - for (0..5) |i| a.output(.{ .output = .{ .pane = .at(shell), .bytes = try std.fmt.bufPrint(&line, "late line {d}\r\n", .{i}) } }); - r.confirm((try a.pending()).?); - r.settle(); - try deliver(a, &screens, peer, r, .flush); - r.settle(); - try std.testing.expectEqual(sent.items.len, r.applied); - try std.testing.expect(pardes.Term.grid(r.core().panes[shell].?.terminal).view != null); - // The authority takes them in order, the terminal sent before each and - // the rows its step read after, as the session's loop does. - for (sent.items) |m| { - try deliver(a, &screens, peer, r, .flush); - r.settle(); - const u = try gpa.dupe(u8, try a.take(m)); - defer gpa.free(u); - try deliver(a, &screens, peer, r, .fill); - r.confirm(u); - r.settle(); - } - try deliver(a, &screens, peer, r, .flush); - r.settle(); - if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); - try std.testing.expect(r.diverged == null and r.quiet()); - try std.testing.expectEqual(@as(u32, 0), r.stats.mispredicted); - try std.testing.expectEqual(digestOf(a), r.digest()); - try std.testing.expect(pardes.Term.grid(a.core.panes[shell].?.terminal).view != null); - try std.testing.expectEqual(pardes.Term.grid(a.core.panes[shell].?.terminal).view, pardes.Term.grid(r.core().panes[shell].?.terminal).view); - // A rollback with nothing confirmed on top puts the view back: one more - // key up, and another's unit first. - try sent.append(gpa, try gpa.dupe(u8, try r.input(.{ .key = .{ .cp = 'u', .ctrl = true } }))); - const before = pardes.Term.grid(a.core.panes[shell].?.terminal).view; - try std.testing.expect(pardes.Term.grid(r.core().panes[shell].?.terminal).view.? < before.?); - r.confirm(try a.local(.{ .focus = false })); - r.settle(); - const last = try gpa.dupe(u8, try a.take(sent.items[sent.items.len - 1])); - defer gpa.free(last); - r.toConfirmed(); - try std.testing.expectEqual(before, pardes.Term.grid(r.core().panes[shell].?.terminal).view); - r.dirty = true; - r.settle(); - try deliver(a, &screens, peer, r, .fill); - r.confirm(last); - r.settle(); - try deliver(a, &screens, peer, r, .flush); - r.settle(); - if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); - try std.testing.expect(r.diverged == null and r.quiet()); - try std.testing.expectEqual(digestOf(a), r.digest()); - try std.testing.expectEqual(pardes.Term.grid(a.core.panes[shell].?.terminal).view, pardes.Term.grid(r.core().panes[shell].?.terminal).view); -} - -test "a unit kept over a copy taken ahead is never replayed over a delta that came after it: the session's key read a shell's rows, the program redrew them" { - if (pardes.Term.ops == null) return error.SkipZigTest; // a shell - const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true); - defer a.deinit(); - var screens: Screens = .init(gpa); - defer screens.deinit(a.core); - const peer = try screens.addPeer(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), true); - defer r.deinit(); - const shell: u8 = for (a.core.panes, 0..) |slot, id| { - if (slot) |pane| if (pane.isTerminal()) break @intCast(id); - } else return error.NoShell; - a.core.view().active = shell; - r.confirm(try a.local(.{ .focus = true })); - var line: [96]u8 = undefined; - for (0..30) |i| a.output(.{ .output = .{ .pane = .at(shell), .bytes = try std.fmt.bufPrint(&line, "line {d} {s}\r\n", .{ i, "words of a length its own"[0 .. i % 20 + 4] }) } }); - r.confirm((try a.pending()).?); - try deliver(a, &screens, peer, r, .flush); - // Out of the shell's tty mode, in the session's view: keys over its text. - r.confirm(try a.local(.{ .key = .{ .cp = a.core.opts.tty_toggle, .ctrl = true } })); - r.settle(); - // The client idle: a copy taken ahead. The session's keys read the rows - // (up, to the line's end): replayed here over the copy, and kept. - r.ready(); - try std.testing.expect(r.copy.held); - for ([_]u21{ 'k', 'k', '$' }) |cp| { - const u = try gpa.dupe(u8, try a.local(.{ .key = .{ .cp = cp, .text = &.{@intCast(cp)} } })); - defer gpa.free(u); - try deliver(a, &screens, peer, r, .fill); - r.confirm(u); - r.settle(); - } - // The program redraws the screen: other rows where those keys read. - a.output(.{ .output = .{ .pane = .at(shell), .bytes = "\x1b[H\x1b[2J" } }); - for (0..30) |i| a.output(.{ .output = .{ .pane = .at(shell), .bytes = try std.fmt.bufPrint(&line, "{d}\r\n", .{i}) } }); - r.confirm((try a.pending()).?); - r.settle(); - try deliver(a, &screens, peer, r, .flush); - // The client types, and the session's key comes first: a rollback, which - // must not replay the keys that read the rows over the redrawn ones. - var sent: std.ArrayListUnmanaged([]u8) = .empty; - defer { - for (sent.items) |m| gpa.free(m); - sent.deinit(gpa); - } - try key(r, 'h', &sent); - try std.testing.expectEqual(@as(usize, 1), r.applied); - { - const u = try gpa.dupe(u8, try a.local(.{ .key = .{ .cp = '0', .text = "0" } })); - defer gpa.free(u); - try deliver(a, &screens, peer, r, .fill); - r.confirm(u); - r.settle(); - } - try deliver(a, &screens, peer, r, .flush); - r.confirm(try a.take(sent.items[0])); - r.settle(); - if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); - try std.testing.expect(r.diverged == null and r.quiet()); - try std.testing.expectEqual(digestOf(a), r.digest()); -} - test "a unit that closes or tears down a terminal is never kept over a copy taken ahead: a rollback would close its emulator again" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host()); defer a.deinit(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), true); + const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); const text = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.file != null) break id; @@ -4738,9 +3914,9 @@ const BytesPair = struct { fn init() !BytesPair { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host()); errdefer a.deinit(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + const r = try Replica.init(gpa, 1, try a.unit(0, 0)); var shell: ?pardes.Pane.Id = null; for (a.core.panes, 0..) |slot, id| if (slot) |pane| { if (pane.isTerminal()) shell = .at(id) else if (pane.file != null) a.core.view().active = @intCast(id); @@ -4958,7 +4134,7 @@ test "a Restore tells its clients so before it lets them go (each joins again, s fn post(l: *@This(), msg: Said) bool { switch (msg) { .refused => |w| l.words = w, - .unit, .screen, .blob => |b| std.heap.c_allocator.free(b), + .unit, .blob => |b| std.heap.c_allocator.free(b), .checked, .ended, .left => {}, } return true; @@ -5073,7 +4249,7 @@ fn firstOnPair(bytes: bool) !void { const core = try Pardes.init(gpa, opts); defer core.deinit(); core.host = .{ .ctx = &spawns, .vtable = &Spawns.vtable }; - var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .name = "pair", .bytes = bytes, .detached = true }; + var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .name = "pair", .bytes = true, .detached = true }; defer ps.deinit(); defer live_peers = null; defer ps.dropAll(core); @@ -5123,7 +4299,7 @@ fn firstOnPair(bytes: bool) !void { } else return error.NoShell; core.update(.{ .output = .{ .pane = .at(shell), .bytes = "first$ " } }); ps.boundary(core); - // Its check, answered after every unit and terminal message before it. + // Its check, answered after every unit before it. try std.testing.expect(askCheck(j.fd)); while (!ps.mail.load(.acquire)) std.Thread.yield() catch {}; ps.boundary(core); @@ -5134,9 +4310,6 @@ fn firstOnPair(bytes: bool) !void { fn take(t: *@This(), tag: u8, payload: []const u8) bool { switch (std.enums.fromInt(wire.ServerTag, tag) orelse return false) { .unit => t.r.confirm(payload), - .screen => if (t.r.screen(payload)) |reply| { - _ = sendScreen(t.fd, reply); - }, .check => { t.digest = (wire.decodeServer(tag, payload) catch return false).check; return false; @@ -5357,7 +4530,7 @@ test "bytes: a kitty image shown by a file, a temporary file or shared memory is test "a replica joined from the session's dump replays the units after it" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); _ = try a.local(.{ .key = .{ .cp = 'j', .text = "j" } }); const was = Stepping.begin(&a.t, null); @@ -5393,7 +4566,7 @@ test "a replica joined from a dump replays a step that opens a file's pane and s // No rows for a second pane: the Look's pane of a kind is made, the // placement says it has no room (a message in the step that made the // pane, which was not in /log yet), and the pane goes. - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 5, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 5, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); var words: [64]pardes.Kind.LoadedWord = undefined; const zon = pardes.Kind.loadedOf(&Zon.ops, "/x/zon.so", @splat(9), &words); @@ -5427,7 +4600,7 @@ const Zon = struct { test "a replica joined from a themed dump paints its taglines in the restored theme" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host()); defer a.deinit(); _ = try a.local(.{ .command = "Theme rose_pine_moon" }); const was = Stepping.begin(&a.t, null); @@ -5460,7 +4633,7 @@ test "a host's Adopt and a terminal reader's failure are inputs: a replica makes if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, opened by a key const gpa = std.testing.allocator; // Its terminals as screen state, as a session's for its clients are. - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), true); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const was = Stepping.begin(&a.t, null); const bytes = try pardes.dump.dumpBytes(a.core); @@ -5486,7 +4659,7 @@ test "a host's Adopt and a terminal reader's failure are inputs: a replica makes test "a join's dump, its blobs put back where they go, is the session's dump" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const text = try gpa.alloc(u8, 20000); defer gpa.free(text); @@ -5612,7 +4785,7 @@ test "a far join is sent each blob once: joined again with them on disk or in th const io = std.testing.io; zstd.gpa = gpa; defer zstd.gpa = std.heap.c_allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const text = try gpa.alloc(u8, 30000); defer gpa.free(text); @@ -5707,7 +4880,7 @@ test "a far join is sent each blob once: joined again with them on disk or in th test "a replica joined after a pane closed: the session's jump to it, its Panes and Recent rows, asked by either" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); // A file looked at and closed: a jump to it, Recent's, a closed pane. var cwd: [std.Io.Dir.max_path_bytes]u8 = undefined; @@ -5759,7 +4932,7 @@ test "a replica joined after a pane closed: the session's jump to it, its Panes test "a replica's Del of a file its session's Recent knows asks the host what the session asked" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); var cwd: [std.Io.Dir.max_path_bytes]u8 = undefined; var line: [std.Io.Dir.max_path_bytes + 32]u8 = undefined; @@ -5778,11 +4951,11 @@ test "a replica's Del of a file its session's Recent knows asks the host what th test "a client leaves, and one joins: what the leave queued (a terminal's resize) is done in its unit, on every side, before the join's dump" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, PtyHost.host(), true); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, PtyHost.host()); defer a.deinit(); const first = try gpa.dupe(u8, try a.unit(0, 0)); defer gpa.free(first); - const old = try Replica.init(gpa, 1, first, true); + const old = try Replica.init(gpa, 1, first); defer old.deinit(); // A second client, bigger, types into the terminal: it sizes it. const opened = try a.openView(2); @@ -5817,11 +4990,11 @@ test "a client leaves, and one joins: what the leave queued (a terminal's resize test "a client that diverged joins again for its view: kept for it meanwhile, its pane in it again; the other client agrees" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const first = try gpa.dupe(u8, try a.unit(0, 0)); defer gpa.free(first); - const old = try Replica.init(gpa, 1, first, false); + const old = try Replica.init(gpa, 1, first); defer old.deinit(); const opened = try a.openView(2); old.confirm(opened.unit); @@ -5961,9 +5134,9 @@ test "a client cut off for what it left unread is told why and joins again for i test "a client whose session's units come more than two seconds later than its quickest lets its link go, says so once, and joins again; its first unit after a join learns the clocks again" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + const r = try Replica.init(gpa, 1, try a.unit(0, 0)); var fds: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; defer for (fds) |fd| { @@ -6061,7 +5234,7 @@ test "a client's writer, the client cut off while it waits on the socket, writes test "a client joined from a dump moves through another view's pane as the session does, its lines not wrapped" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host()); defer a.deinit(); // The first client's Wrap off (SPC t w), and its cursor down into the // file's long lines, near the bottom of its view. @@ -6090,7 +5263,7 @@ test "a client joined from a dump moves through another view's pane as the sessi test "a client joined from a dump makes a `/` query's rows as the session does, though only the session has drawn its owner" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host()); defer a.deinit(); // The session draws: its owner's colours painted for the view (File.refreshHighlights). { @@ -6126,7 +5299,7 @@ test "a client joined from a dump asks a worker for a `/` query's colours as the }; const gpa = std.testing.allocator; // A view as tall as the text: the frame paints every line of it. - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 500, .file = "build.zig" }, .{ .vtable = &Paints.vtable }, false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 500, .file = "build.zig" }, .{ .vtable = &Paints.vtable }); defer a.deinit(); { const was = Stepping.begin(&a.t, null); @@ -6156,7 +5329,7 @@ test "a client joined from a dump asks a worker for a `/` query's colours as the const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .search = search }; }; const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, .{ .vtable = &Paints.vtable }, false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, .{ .vtable = &Paints.vtable }); defer a.deinit(); { const p = a.core; @@ -6177,49 +5350,11 @@ test "a client joined from a dump asks a worker for a `/` query's colours as the } } -test "a step that reads a terminal's rows as the core keeps them sends a new client the ones it holds as holes" { - if (pardes.Term.ops == null) return error.SkipZigTest; // a shell - const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, PtyHost.host(), true); - defer a.deinit(); - var screens: Screens = .init(gpa); - defer screens.deinit(a.core); - const first = try gpa.dupe(u8, try a.unit(0, 0)); - defer gpa.free(first); - const r1 = try Replica.init(gpa, 1, first, true); - defer r1.deinit(); - const r2 = try Replica.init(gpa, 2, first, true); - defer r2.deinit(); - const shell: u8 = for (a.core.panes, 0..) |slot, id| { - if (slot) |pane| if (pane.isTerminal()) break @intCast(id); - } else return error.NoShell; - a.core.view().active = shell; - var line: [64]u8 = undefined; - for (0..60) |i| a.output(.{ .output = .{ .pane = .at(shell), .bytes = try std.fmt.bufPrint(&line, "line {d} of the shell's history\r\n", .{i}) } }); - const out = try gpa.dupe(u8, (try a.pending()).?); - defer gpa.free(out); - for ([_]*Replica{ r1, r2 }) |r| r.confirm(out); - // The first client alone has the terminal; it reads all of its rows - // (its text, the cursor on the first): the core keeps them. - const p1 = [_]u16{try screens.addPeer()}; - for ([_]pardes.Event{ .{ .key = .{ .cp = 'b', .ctrl = true } }, .{ .key = .{ .cp = 'g', .text = "g" } }, .{ .key = .{ .cp = 'g', .text = "g" } } }) |ev| { - const msg = try gpa.dupe(u8, try r1.input(ev)); - defer gpa.free(msg); - try takeAll(a, &screens, &.{r1}, &p1, msg); - r2.confirm(a.out.items); - } - // A second comes: its history all holes. The first reads the rows the - // core kept, nothing written since. - const ps = [_]u16{ p1[0], try screens.addPeer() }; - try sendAs(r1, a, &screens, &.{ r1, r2 }, &ps, .{ .key = .{ .cp = 'O', .text = "O" } }); - for ([_]*Replica{ r1, r2 }) |r| try agrees(a, r); -} - test "a replica with no code for a kind whose state is not plain shows its pane as a line saying so, and its keys go to the authority" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); // What the host read off the library, as the `addon` event: the // replica's core takes the kind's words, never its code. @@ -6277,9 +5412,9 @@ const Placed = struct { test "a kind's place moved in a step of another view's: a replica's key that reads it guesses the authority's" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); var words: [64]pardes.Kind.LoadedWord = undefined; const placed = pardes.Kind.loadedOf(&Placed.ops, "/x/placed.so", @splat(7), &words); @@ -6333,7 +5468,7 @@ const Jobber = struct { test "a client joined from a dump numbers a kind's next job as the session does" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); var words: [64]pardes.Kind.LoadedWord = undefined; const jobber = pardes.Kind.loadedOf(&Jobber.ops, "/x/jobber.so", @splat(7), &words); @@ -6350,9 +5485,9 @@ test "a client joined from a dump numbers a kind's next job as the session does" test "a replica's word that opens a kind's pane with no file waits for the authority's open: never mispredicted" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); var words: [64]pardes.Kind.LoadedWord = undefined; const placed = pardes.Kind.loadedOf(&Placed.ops, "/x/placed.so", @splat(7), &words); @@ -6371,7 +5506,7 @@ test "a replica's word that opens a kind's pane with no file waits for the autho test "a client joined from a dump tells a kind each view's facts as the session does, the live one's and another's" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); var words: [64]pardes.Kind.LoadedWord = undefined; const placed = pardes.Kind.loadedOf(&Placed.ops, "/x/placed.so", @splat(7), &words); @@ -6441,10 +5576,10 @@ const BusyHost = struct { test "a kind's job answered at once inside its host's call (no worker free) is taken by a client as the session took it" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &BusyHost.vtable }, false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &BusyHost.vtable }); defer a.deinit(); BusyHost.core = a.core; - const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); var words: [64]pardes.Kind.LoadedWord = undefined; const asker = pardes.Kind.loadedOf(&Asker.ops, "/x/asker.so", @splat(7), &words); @@ -6465,9 +5600,9 @@ test "a kind's job answered at once inside its host's call (no worker free) is t test "a closed terminal with a kitty image brought back on a client: its image drawn under a speculation, rolled back by another's unit, is drawn again from what the emulator holds" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host()); defer a.deinit(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), true); + const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); const shell: u8 = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break @intCast(id); @@ -6539,40 +5674,35 @@ fn partsApart(a: *Authority, r: *Replica, arena: std.mem.Allocator) ![]const u8 return if (std.mem.eql(u64, w, g)) "" else tape.partsDiffer(g, w, arena); } -test "a terminal's program shows a kitty image under screen state: the client's emulator never has it, and its tag says what the session's does" { +test "a terminal's program shows a kitty image: the client's emulator has it as the session's does, and its tag says what the session's does" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host()); defer a.deinit(); - var screens: Screens = .init(gpa); - defer screens.deinit(a.core); - const peer = try screens.addPeer(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), true); + const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); const shell: u8 = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break @intCast(id); } else return error.NoShell; - try deliver(a, &screens, peer, r, .flush); try std.testing.expectEqualStrings("", try partsApart(a, r, arena.allocator())); - // In the session's order: the pump's unit, then what its terminals came - // to; then a step after both, on every side. + // In the session's order: the pump's unit, its bytes fed on every side; + // then a step after it. a.output(.{ .output = .{ .pane = .at(shell), .bytes = "\x1b_Ga=T,i=7,f=24,s=2,v=2;ESIzESIzESIzESIz\x1b\\" } }); r.confirm((try a.pending()).?); r.settle(); - try deliver(a, &screens, peer, r, .flush); r.confirm(try a.local(.{ .focus = true })); r.settle(); try std.testing.expect(pardes.Term.hasImages(a.core.panes[shell].?.terminal)); - try std.testing.expect(!pardes.Term.hasImages(r.core().panes[shell].?.terminal)); + try std.testing.expect(pardes.Term.hasImages(r.core().panes[shell].?.terminal)); try std.testing.expectEqualStrings("", try partsApart(a, r, arena.allocator())); try agrees(a, r); const prefix = try pardes.tagline.prefixIn(r.core(), arena.allocator(), r.core().panes[shell].?); try std.testing.expect(std.mem.indexOf(u8, prefix, " petscii:") != null); } -test "a command typed into a shell with prompt marks under screen state: every side notes it as the session's emulator numbers it, and Kill finds it" { +test "a command typed into a shell with prompt marks: every side notes it as its own emulator, fed the same bytes, numbers it, and Kill finds it" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; var arena: std.heap.ArenaAllocator = .init(gpa); @@ -6584,12 +5714,9 @@ test "a command typed into a shell with prompt marks under screen state: every s fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {} const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write }; }; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &ShellHost.vtable }, true); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &ShellHost.vtable }); defer a.deinit(); - var screens: Screens = .init(gpa); - defer screens.deinit(a.core); - const peer = try screens.addPeer(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), true); + const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); const shell: u8 = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break @intCast(id); @@ -6599,7 +5726,6 @@ test "a command typed into a shell with prompt marks under screen state: every s a.output(.{ .output = .{ .pane = .at(shell), .bytes = prompt ++ "ls\r\n\x1b]133;C;aid=pardes\x07a b\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt } }); r.confirm((try a.pending()).?); r.settle(); - try deliver(a, &screens, peer, r, .flush); a.core.view().active = shell; r.confirm(try a.local(.{ .focus = true })); r.settle(); @@ -6607,7 +5733,7 @@ test "a command typed into a shell with prompt marks under screen state: every s // Exec'd in the shell: typed at its prompt, the command noted. r.confirm(try a.local(.{ .command = "Exec sleep 9" })); r.settle(); - // Its marks cross with the cells (Term.marksOf): numbered alike. + // Its marks are its bytes' on every side: numbered alike. try std.testing.expectEqual(@as(u32, 2), a.core.panes[shell].?.sent_command.?.seq); try std.testing.expectEqual(@as(u32, 2), r.core().panes[shell].?.sent_command.?.seq); try std.testing.expectEqualStrings("", try partsApart(a, r, arena.allocator())); @@ -6615,7 +5741,6 @@ test "a command typed into a shell with prompt marks under screen state: every s a.output(.{ .output = .{ .pane = .at(shell), .bytes = "sleep 9\r\n\x1b]133;C;aid=pardes\x07" } }); r.confirm((try a.pending()).?); r.settle(); - try deliver(a, &screens, peer, r, .flush); r.confirm(try a.local(.{ .command = "Kill" })); r.settle(); try std.testing.expectEqualStrings("", try partsApart(a, r, arena.allocator())); @@ -6680,7 +5805,6 @@ test "a step of the session's own that reads a terminal right after its output, var at: usize = 0; while (try wire.framed(from.out.items[at..])) |m| : (at += m.total) l.take(switch (std.enums.fromInt(wire.ServerTag, m.tag).?) { .unit => .{ .unit = try std.heap.c_allocator.dupe(u8, m.payload) }, - .screen => .{ .screen = try std.heap.c_allocator.dupe(u8, m.payload) }, else => return error.UnexpectedFrame, }); from.out.clearRetainingCapacity(); @@ -6711,7 +5835,7 @@ test "a step of the session's own that reads a terminal right after its output, test "a far client's own Del of a pane whose kind's state is not plain, rolled back by another's unit: the pane comes back whole, and is closed again with the session's order" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); var words: [64]pardes.Kind.LoadedWord = undefined; const counter = pardes.Kind.loadedOf(&Counter.ops, "/x/counter.so", @splat(7), &words); @@ -6792,7 +5916,7 @@ const SeenHost = struct { test "a client's step that asks the session's host for something that returns nothing goes on at once, and the session's unit confirms it: nothing rolled back" { const gpa = std.testing.allocator; var h: SeenHost = .{}; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host()); defer a.deinit(); h.core = a.core; const r = try joinedFresh(a); @@ -6812,7 +5936,7 @@ test "a client's step that asks the session's host for something that returns no test "a client's step whose session's host says something into the core during the call it made: its speculation rolled back, then the session's state" { const gpa = std.testing.allocator; var h: SeenHost = .{ .tell = true }; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host()); defer a.deinit(); h.core = a.core; const r = try joinedFresh(a); @@ -6835,7 +5959,7 @@ test "a client's ThemeFile waits for the session, whose host loads the file into const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; var line: [std.Io.Dir.max_path_bytes + 16]u8 = undefined; var h: SeenHost = .{}; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host()); defer a.deinit(); h.core = a.core; const r = try joinedFresh(a); @@ -6855,7 +5979,7 @@ test "a client's ThemeFile waits for the session, whose host loads the file into test "a client's yank and paste of the system clipboard are its own frontend's: its view counts them, at once and as the session does, and the session's host is asked neither" { const gpa = std.testing.allocator; var h: SeenHost = .{}; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host()); defer a.deinit(); h.core = a.core; _ = try a.unit(0, 0); @@ -6888,7 +6012,7 @@ test "a client's yank and paste of the system clipboard are its own frontend's: test "a client's own Zerox and Del of a file pane are instant: what Recent keeps of the file is what its open learned, not a question to the disk; Recent has its place as the session's always did" { const gpa = std.testing.allocator; var h: SeenHost = .{}; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host()); defer a.deinit(); h.core = a.core; var cwd: [std.Io.Dir.max_path_bytes]u8 = undefined; @@ -6931,7 +6055,7 @@ const Still = struct { test "a client's n in a kind's pane is a motion: it steps to the next place a result row holds at once, asking the disk nothing of words that might name files" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); var cwd: [std.Io.Dir.max_path_bytes]u8 = undefined; const dir = std.mem.span(@as([*:0]u8, @ptrCast(std.c.getcwd(&cwd, cwd.len) orelse return error.NoCwd))); @@ -7255,7 +6379,7 @@ const Walk = struct { test "a far client's every word and key, on a file's pane, a kind's and a shell's, and the gestures between them beside a shell that asked for focus events: what waits is in may_wait, with why, and nothing else waits" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 120, .rows = 40, .boot = .tty }, FullHost.host(), true); + const a = try Authority.init(gpa, .{ .cols = 120, .rows = 40, .boot = .tty }, FullHost.host()); defer a.deinit(); var cwd: [std.Io.Dir.max_path_bytes]u8 = undefined; var line: [std.Io.Dir.max_path_bytes + 32]u8 = undefined; @@ -7296,13 +6420,9 @@ test "a far client's every word and key, on a file's pane, a kind's and a shell' a.core.view().active = id; _ = a.local(.{ .key = .{ .cp = a.core.opts.tty_toggle, .ctrl = true } }) catch {}; }; - var screens: Screens = .init(gpa); - defer screens.deinit(a.core); - const peer = try screens.addPeer(); const r = try joinedFresh(a); defer r.deinit(); r.core().kinds.ops[r.core().kinds.byName("still").?] = &Still.ops; - try deliver(a, &screens, peer, r, .flush); r.settle(); try std.testing.expectEqual(id, r.core().view().active); if (on == .shell) try std.testing.expect(pardes.Term.modes(r.core().panes[id].?.terminal).focus); @@ -7384,7 +6504,7 @@ test "a far client's click into a shell whose program asked for focus events is const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .pty_write = write }; }; Told.len = 0; - const a = try Authority.init(gpa, .{ .cols = 120, .rows = 40, .boot = .tty }, .{ .vtable = &Told.vtable }, true); + const a = try Authority.init(gpa, .{ .cols = 120, .rows = 40, .boot = .tty }, .{ .vtable = &Told.vtable }); defer a.deinit(); const shell: u8 = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break @intCast(id); @@ -7392,12 +6512,8 @@ test "a far client's click into a shell whose program asked for focus events is a.output(.{ .output = .{ .pane = .at(shell), .bytes = "\x1b[?1004h$ " } }); _ = (try a.pending()).?; _ = try a.local(.{ .command = "New" }); - var screens: Screens = .init(gpa); - defer screens.deinit(a.core); - const peer = try screens.addPeer(); const r = try joinedFresh(a); defer r.deinit(); - try deliver(a, &screens, peer, r, .flush); r.settle(); Told.len = 0; const rect = r.core().view().rects[shell]; @@ -7411,10 +6527,8 @@ test "a far client's click into a shell whose program asked for focus events is try std.testing.expectEqual(@as(u32, 0), r.stats.stopped); try std.testing.expectEqual(@as(usize, shell), r.core().view().active); for (sent.items) |m| { - try deliver(a, &screens, peer, r, .flush); const u = try gpa.dupe(u8, try a.take(m)); defer gpa.free(u); - try deliver(a, &screens, peer, r, .fill); r.confirm(u); r.settle(); } @@ -7426,7 +6540,7 @@ test "a far client's click into a shell whose program asked for focus events is test "a far client's own Look of ~/x, bare Shell and a word that runs in the session's directory read the session's facts: its speculation asks its own machine's environment nothing" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const r = try joinedFresh(a); defer r.deinit(); @@ -7464,7 +6578,7 @@ test "a far client's replay of the session's DumpDir takes the session's answer // The session's machine: a directory it may not write in. if (std.c.mkdir(ro, 0o500) != 0) return error.NoDir; defer _ = std.c.chmod(ro, 0o700); - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const r = try joinedFresh(a); defer r.deinit(); @@ -7522,7 +6636,7 @@ test "a far client's replay of the session's Fonts and Font takes the session's if (fonts.list(arena.allocator(), null).len == session_faces and client_named.len > 0 and std.mem.eql(u8, client_named[0].path, session_first)) return error.SkipZigTest; _ = Shell.setenv("HOME", session_home, 1); // A window's view: the font words are a window's. - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .windowed = true }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .windowed = true }, TestHost.host()); defer a.deinit(); const r = try joinedFresh(a); defer r.deinit(); @@ -7545,7 +6659,7 @@ test "a far client's replay of the session's Fonts and Font takes the session's // cover; an answer let go (not quiet then) covers nothing. test "an idle client's check answered covers the units that came while it was asked: it asks no other until something changes" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host()); defer a.deinit(); const r = try joinedNow(a, 1, 0); defer r.deinit(); @@ -7594,7 +6708,7 @@ test "an idle client's check answered covers the units that came while it was as // to look at, at its own focus-in (upgrade.noticeNewer). test "a far client's window found again is instant: its refocus asks the session's host nothing, and the session's unit confirms it" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, FullHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, FullHost.host()); defer a.deinit(); const r = try joinedFresh(a); defer r.deinit(); @@ -7643,7 +6757,7 @@ const Pointed = struct { // client's speculation). test "a far client's drag in a kind's pane it grabbed, the pane since too short for a row of body: the kind is told its edge, at once and as on the session" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); var words: [64]pardes.Kind.LoadedWord = undefined; const pointed = pardes.Kind.loadedOf(&Pointed.ops, "/x/pointed.so", @splat(8), &words); @@ -7744,7 +6858,7 @@ test "a far client's frame drawn under a speculation that rolls back asks a pict } }; const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); var words: [64]pardes.Kind.LoadedWord = undefined; const drawn = pardes.Kind.loadedOf(&Drawn.ops, "/x/drawn.so", @splat(9), &words); @@ -7804,7 +6918,7 @@ test "a far client's click into a shell whose queue is backed up: the session's } const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .pty_write = write }; }; - const a = try Authority.init(gpa, .{ .cols = 120, .rows = 40, .boot = .tty }, .{ .vtable = &Told.vtable }, true); + const a = try Authority.init(gpa, .{ .cols = 120, .rows = 40, .boot = .tty }, .{ .vtable = &Told.vtable }); defer a.deinit(); const shell: u8 = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break @intCast(id); @@ -7812,12 +6926,8 @@ test "a far client's click into a shell whose queue is backed up: the session's a.output(.{ .output = .{ .pane = .at(shell), .bytes = "\x1b[?1004h$ " } }); _ = (try a.pending()).?; _ = try a.local(.{ .command = "New" }); - var screens: Screens = .init(gpa); - defer screens.deinit(a.core); - const peer = try screens.addPeer(); const r = try joinedFresh(a); defer r.deinit(); - try deliver(a, &screens, peer, r, .flush); r.settle(); // A 9P write into the shell, past the ring: the rest parked, on both. const big = try gpa.alloc(u8, pardes.memory.limits.effect_cap * pardes.effect_write_cap + 100); @@ -7848,10 +6958,8 @@ test "a far client's click into a shell whose queue is backed up: the session's try std.testing.expectEqual(@as(usize, 0), r.applied); for (r.stats.stops) |st| if (st.n > 0) try std.testing.expectEqualStrings("pty_write", st.name); for (sent.items) |m| { - try deliver(a, &screens, peer, r, .flush); const u = try gpa.dupe(u8, try a.take(m)); defer gpa.free(u); - try deliver(a, &screens, peer, r, .fill); r.confirm(u); r.settle(); } @@ -7912,7 +7020,7 @@ test "a client joined from a dump makes a `/` query's rows as the session does, } }; const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, .{ .vtable = &WorkerSearch.vtable }, false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, .{ .vtable = &WorkerSearch.vtable }); defer a.deinit(); WorkerSearch.init(a); defer WorkerSearch.q.deinit(); @@ -7939,7 +7047,7 @@ test "a client joined from a dump makes a `/` query's rows as the session does, // elsewhere on a core that drew than on one that did not. test "a client joined from a dump lands a click on a rail's tick as the session does, the session's ticks drawn before the places changed" { const gpa = std.testing.allocator; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host()); defer a.deinit(); _ = try a.local(.{ .command = "Search /pub" }); const owner: usize = 0; @@ -8006,7 +7114,7 @@ test "a far client's step that asks for a search goes on at once, and a session const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; var path_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined; const path = try std.fmt.bufPrint(&path_buf, "{s}/a.zig", .{dir}); - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = path }, .{ .vtable = &LoopSearch.vtable }, false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = path }, .{ .vtable = &LoopSearch.vtable }); defer a.deinit(); LoopSearch.core = a.core; const r = try joinedFresh(a); @@ -8053,7 +7161,7 @@ test "a far client's replay of a message its session's host stamped takes the se const was = if (std.c.getenv("PARDES_NOTIME")) |v| try gpa.dupeSentinel(u8, std.mem.span(v), 0) else null; defer if (was) |v| gpa.free(v); defer _ = if (was) |v| Shell.setenv("PARDES_NOTIME", v, 1) else @import("dev").host_io.testUnsetenv("PARDES_NOTIME"); - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &Stamping.vtable }, false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &Stamping.vtable }); defer a.deinit(); Stamping.core = a.core; const r = try joinedFresh(a); @@ -8082,9 +7190,9 @@ test "a client joined from a dump takes a 9P pty/run in a shell as the session d fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {} const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write }; }; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &RunHost.vtable }, false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &RunHost.vtable }); defer a.deinit(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); const shell: u8 = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break @intCast(id); @@ -8146,158 +7254,6 @@ test "a client joined from a dump takes a 9P pty/run in a shell as the session d try agrees(a, late); } -// The same run with the terminals crossing as screen state (a session's -// clients', until the switch to bytes): a replica's emulator is the -// deltas', its marks not the session's. -test "a client of screen-state terminals takes a 9P pty/run in a shell as the session does" { - if (pardes.Term.ops == null) return error.SkipZigTest; // a shell - const gpa = std.testing.allocator; - const RunHost = struct { - fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool { - return false; - } - fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {} - const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write }; - }; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &RunHost.vtable }, true); - defer a.deinit(); - var screens: Screens = .init(gpa); - defer screens.deinit(a.core); - const peer = try screens.addPeer(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), true); - defer r.deinit(); - const shell: u8 = for (a.core.panes, 0..) |slot, id| { - if (slot) |pane| if (pane.isTerminal()) break @intCast(id); - } else return error.NoShell; - const Step = struct { - var second: ?*Replica = null; - fn take(s: *Authority, sc: *Screens, p: u16, x: *Replica, u: []const u8) !void { - const gpa_ = std.testing.allocator; - const kept = try gpa_.dupe(u8, u); - defer gpa_.free(kept); - // The unit first, its screens at the frame after (Peers). - x.confirm(kept); - x.settle(); - if (second) |y| { - y.confirm(kept); - y.settle(); - } - try deliver(s, sc, p, x, .flush); - if (second) |y| try deliver(s, sc, p + 1, y, .flush); - } - fn serve(s: *Authority, sc: *Screens, p: u16, x: *Replica, req: pardes.ctlfs.Req) !pardes.ctlfs.Reply { - const was = Stepping.begin(&s.t, null); - const reply = s.core.serveFs(req); - s.core.pump(s.host) catch {}; - was.end(); - s.seq += 1; - try take(s, sc, p, x, try s.unit(0, s.seq)); - return reply; - } - fn output(s: *Authority, sc: *Screens, p: u16, x: *Replica, pane: u8, bytes: []const u8) !void { - s.output(.{ .output = .{ .pane = .at(pane), .bytes = bytes } }); - try take(s, sc, p, x, (try s.pending()).?); - } - }; - const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; - try Step.output(a, &screens, peer, r, shell, prompt ++ "ls\r\n\x1b]133;C;aid=pardes\x07a b\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt); - // A second client joins now, from the session's dump. - const joined = (try a.join(2, null)).?; - defer gpa.free(joined.dump); - try Step.take(a, &screens, peer, r, joined.unit); - const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); - defer late.deinit(); - const peer2 = try screens.addPeer(); - try deliver(a, &screens, peer2, late, .flush); - Step.second = late; - defer Step.second = null; - const node = pardes.ctlfs.Node.of(a.core.panes[shell].?.serial, .pty_run); - for (0..2) |_| { - const h = (try Step.serve(a, &screens, peer, r, .{ .tag = 1, .op = .open, .node = node, .omode = 2 })).handle; - _ = try Step.serve(a, &screens, peer, r, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "true\n" }); - try Step.output(a, &screens, peer, r, shell, "true\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;0;aid=pardes\x07" ++ prompt); - const answer = try Step.serve(a, &screens, peer, r, .{ .tag = 3, .op = .read, .node = node, .handle = h, .size = 64 }); - try std.testing.expectEqualStrings("exit 0\n", a.core.fsPayload(answer)); - _ = try Step.serve(a, &screens, peer, r, .{ .tag = 4, .op = .release, .node = node, .handle = h, .opened = true }); - } - try agrees(a, r); - try agrees(a, late); -} - -// daemon.py --clients' client C (2026-11-20): idle, a copy taken ahead; the -// session's script opens pty/run and its command prints, replayed over the -// copy and kept; the client types into the shell, its speculation stops at -// the pty write, and the rollback replays the open again over a record the -// copy never held (it holds the opens as far as `opens_len`), whose line -// and output the epoch had freed: freed again there, the client's C heap -// was corrupt. -test "a 9P open the session made over a copy taken ahead, replayed after a rollback: the record past the opens the copy holds is written over, never freed again" { - if (pardes.Term.ops == null) return error.SkipZigTest; // a shell - const gpa = std.testing.allocator; - const RunHost = struct { - fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool { - return false; - } - fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {} - const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write }; - }; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &RunHost.vtable }, true); - defer a.deinit(); - var screens: Screens = .init(gpa); - defer screens.deinit(a.core); - const peer = try screens.addPeer(); - const r = try Replica.init(gpa, 1, try a.unit(0, 0), true); - defer r.deinit(); - const shell: u8 = for (a.core.panes, 0..) |slot, id| { - if (slot) |pane| if (pane.isTerminal()) break @intCast(id); - } else return error.NoShell; - const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; - a.output(.{ .output = .{ .pane = .at(shell), .bytes = prompt } }); - r.confirm((try a.pending()).?); - try deliver(a, &screens, peer, r, .flush); - r.ready(); - try std.testing.expect(r.copy.held and r.core().fs.opens_len == 0); - const node = pardes.ctlfs.Node.of(a.core.panes[shell].?.serial, .pty_run); - const Serve = struct { - fn serve(s: *Authority, x: *Replica, req: pardes.ctlfs.Req) !pardes.ctlfs.Reply { - const was = Stepping.begin(&s.t, null); - const reply = s.core.serveFs(req); - s.core.pump(s.host) catch {}; - was.end(); - s.seq += 1; - const u = try std.testing.allocator.dupe(u8, try s.unit(0, s.seq)); - defer std.testing.allocator.free(u); - x.confirm(u); - x.settle(); - return reply; - } - }; - const h = (try Serve.serve(a, r, .{ .tag = 1, .op = .open, .node = node, .omode = 2 })).handle; - _ = try Serve.serve(a, r, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "echo x\n" }); - a.output(.{ .output = .{ .pane = .at(shell), .bytes = "echo x\r\n\x1b]133;C;aid=pardes\x07x\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt } }); - r.confirm((try a.pending()).?); - r.settle(); - // Kept over the copy: the record past its opens holds the run's output. - try std.testing.expect(r.copy.held and r.since.items.len > 0); - try std.testing.expectEqualStrings("x\n", r.core().fs.opens[h - 1].what.run.output); - var sent: std.ArrayListUnmanaged([]u8) = .empty; - defer { - for (sent.items) |m| gpa.free(m); - sent.deinit(gpa); - } - // A key into the shell: its speculation stops at the pty write, and - // the copy is put back, the units since replayed (the open again). - try key(r, 'e', &sent); - try std.testing.expect(r.applied == 0 and r.stats.stopped > 0); - r.confirm(try a.take(sent.items[0])); - r.settle(); - try deliver(a, &screens, peer, r, .flush); - _ = try Serve.serve(a, r, .{ .tag = 3, .op = .release, .node = node, .handle = h, .opened = true }); - if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); - try std.testing.expect(r.diverged == null and r.quiet()); - try agrees(a, r); -} - test "a script's half line held over a copy taken ahead, its next write run and its rest moved to the front in place, put back by a rollback: the line replayed is the session's" { var n = try NinepJoin.init("one\n", TestHost.host()); defer n.deinit(); @@ -8341,7 +7297,7 @@ test "a far client's Del with panes above and below is applied at once, and its } const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .now = now }; }; - const a = try Authority.init(gpa, .{ .cols = 80, .rows = 30, .file = "mise.toml" }, .{ .vtable = &Clocked.vtable }, false); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 30, .file = "mise.toml" }, .{ .vtable = &Clocked.vtable }); defer a.deinit(); _ = try a.local(.{ .command = "New" }); const mid = a.core.view().active; @@ -8393,7 +7349,7 @@ const NinepJoin = struct { serial: u32, fn init(text: []const u8, host: pardes.Host) !NinepJoin { - const a = try Authority.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, host, false); + const a = try Authority.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, host); errdefer a.deinit(); const was = Stepping.begin(&a.t, null); const pane = try a.core.setTestFile(text); @@ -8691,7 +7647,7 @@ const RunJoin = struct { /// The session at its shell's first prompt, and the shell's slot. fn init(n: *NinepJoin) !u8 { - const a = try Authority.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &vtable }, false); + const a = try Authority.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &vtable }); n.* = .{ .a = a, .serial = 0 }; _ = try a.unit(0, 0); const shell: u8 = for (a.core.panes, 0..) |slot, id| { diff --git a/core/root.zig b/core/root.zig index e29e70d8..66630b2d 100644 --- a/core/root.zig +++ b/core/root.zig @@ -632,7 +632,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{ .{ "jj.zig", 11, "jj run under tape.site(.jj) on an io of its own (the tape's spawns nothing) with this process's environment, the signal mask cleared as Stream's children's: the session's, a replica replays its answer; or on a worker for `Changes`, its answer an input, with the wall clock it was made at (tape.value(.clock) on the loop) for its descriptions' ages; a test's shell inbox (dev)" }, .{ "look.zig", 6, "openLink's fork (the host's: a view's frontend opens a link) and a remote's error name" }, .{ "memory.zig", 7, "the memory regions themselves (mmap, madvise, their locks)" }, - .{ "replica.zig", 76, "the client and session engines: sockets, threads, clocks, the blob cache, traces" }, + .{ "replica.zig", 74, "the client and session engines: sockets, threads, clocks, the blob cache, traces" }, .{ "rollback.zig", 1, "a test helper's directory" }, .{ "root.zig", 4, "dev's modules re-exported (host_io, file_watch, glide, fonts)" }, .{ "selection_pipe.zig", 14, "a pipe's child processes and their files: the host's `pipe` entry" }, diff --git a/core/tape.zig b/core/tape.zig index f231831d..5056f225 100644 --- a/core/tape.zig +++ b/core/tape.zig @@ -1153,7 +1153,8 @@ fn tagOf(comptime entry: anytype, comptime Made: type) [:0]const u8 { /// The entries that answer stop by nature: the answer is the session's. const keeps_stopping = [_]Host.Fn{ // A shell's input: a device by the user's line (a far shell may feel - // like ssh), and off the tape with screen-state terminals. + // like ssh; core/echo.zig predicts its echo), and off the tape outside + // a speculation. .pty_write, // Its host says into the core on every call that the shell started // and where (host_io.forkShell: acknowledgeShell, setCwd), and gives @@ -1197,8 +1198,10 @@ fn hostCall(t: *Tape, p: *const Pardes, comptime f: Host.Fn, args: Host.Args(f)) const R = Host.Ret(f); const name = @tagName(f); // A terminal's answers and what is typed at it from its output are the - // authority's to write, never a replica's: off the tape on both sides. - if (comptime std.mem.eql(u8, name, "pty_write")) if (t.screen_state and !t.speculating) { + // authority's to write, never a replica's: off the tape on both sides + // (a replica's replay of the step writes nothing, and checks nothing: + // a write returns nothing a step reads). + if (comptime std.mem.eql(u8, name, "pty_write")) if (!t.speculating) { if (!t.replay) _ = p.host.call(f, args); return; }; @@ -1832,11 +1835,11 @@ test "a core pumped twice with one host and once with another: which functions i const R = pardes.replica; var first: Pumped = .{ .ns = 0 }; var second: Pumped = .{ .ns = 1 << 40 }; - const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{ .ctx = &first, .vtable = &Pumped.one }, false); + const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{ .ctx = &first, .vtable = &Pumped.one }); defer a.deinit(); const boot = Pumped.said(a.t.buf.items); try std.testing.expectEqual(Host.mask(.{ .vtable = &Pumped.one }), boot.mask); - const r = try R.Replica.init(gpa, 1, try a.unit(0, 0), false); + const r = try R.Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); const hosts = [_]Host{ .{ .ctx = &first, .vtable = &Pumped.one }, .{ .ctx = &second, .vtable = &Pumped.more } }; for (hosts, [_]usize{ 0, 1 }, 1..) |h, sets, seq| { diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index bdbd7880..bfe658f9 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -1355,7 +1355,7 @@ const Client = struct { cl.lock.lockUncancelable(cl.io); defer cl.lock.unlock(cl.io); for (cl.inbox.items) |msg| switch (msg) { - .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b), + .unit, .refused, .blob => |b| std.heap.c_allocator.free(b), .checked, .ended, .left => {}, }; cl.inbox.clearRetainingCapacity(); @@ -1368,8 +1368,6 @@ const Client = struct { const link_ended = cl.link_ended; cl.lock.unlock(cl.io); for (cl.taken.items) |msg| { - // PARDES_TEST_LATENCY: when a terminal's delta came (an echo's). - if (msg == .screen) latencyNote("S {d}\n", .{monoNs()}); l.take(msg); // And after a unit, the first of its own inputs not confirmed. if (msg == .unit) { diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index 92ac6a0c..2f731e68 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -699,7 +699,7 @@ const Tty = struct { pub fn drop(t: *Tty) void { while (t.loop.tryEvent() catch null) |ev| switch (ev) { .said => |msg| switch (msg) { - .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b), + .unit, .refused, .blob => |b| std.heap.c_allocator.free(b), .checked, .ended, .left => {}, }, .paste => |b| t.sh.gpa.free(@constCast(b)), @@ -1585,12 +1585,11 @@ const Shell = struct { s.input_seen = true; }, .said => |said| if (s.client) |c| { - // The session's units and deltas are a client's output - // (waitInput paces it): a terminal's delta, or the unit - // that answers its own input, is its echo, drawn at once. + // The session's units are a client's output (waitInput + // paces it): the unit that answers its own input is its + // echo, drawn at once. s.output_seen = true; const echo = switch (said) { - .screen => true, .unit => |b| if (replica.parseUnit(b)) |u| u.origin == c.link.r.id else false, else => false, }; @@ -1598,7 +1597,7 @@ const Shell = struct { c.take(said); if (said == .refused or said == .ended or said == .left) return true; } else switch (said) { - .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b), + .unit, .refused, .blob => |b| std.heap.c_allocator.free(b), .checked, .ended, .left => {}, }, .link_gone => if (s.client) |c| { diff --git a/runtime/client.zig b/runtime/client.zig index 49ebbc6e..43fdf98d 100644 --- a/runtime/client.zig +++ b/runtime/client.zig @@ -442,7 +442,7 @@ const AskedHost = struct { test "a client's yank, paste and link reach its own frontend once each, through the loop, and the session's host is asked none of them" { const gpa = std.testing.allocator; var h: AskedHost = .{}; - const a = try replica.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host(), false); + const a = try replica.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host()); defer a.deinit(); _ = try a.unit(0, 0); const j = (try a.join(1, null)) orelse return error.NoView; diff --git a/test/daemon.py b/test/daemon.py index e10b3c1f..3a481c00 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -313,13 +313,13 @@ class Replica: return 'refused', why def ping(self, value): - """One round trip, in ms (the session's units and terminal - messages on the way are passed over).""" + """One round trip, in ms (the session's units on the way are + passed over).""" t = time.monotonic() self.send(0x03, struct.pack(' Date: Sun, 22 Nov 2026 03:03:25 -0300 Subject: replica: no road to choose, and the wire at 30 (the old road's deletion, piece 4 of 8; the coordinator's decision: the welcome's road byte goes, no dead field stays on the wire): `Peers.bytes` (set by runtime/session.zig unless PARDES_TERM_SCREEN), the welcome's `bytes` byte (abi/wire.zig: its encode, its decode, the round-trip test's byte), `Joined.bytes` and `joinOn`'s copy of it, `road` (fromDump's, ownBoot's, confirmBoot's, a test's: a replica's `made` arms its echo already, and no replica starts on screen state since piece 3), and ownBoot's read of PARDES_TERM_SCREEN; so PARDES_TERM_SCREEN and PARDES_TERM_BYTES name nothing in the tree; abi/wire.zig's version is 30, its history line saying both of this line's wire changes (the screen messages retired as gaps in piece 3, the welcome's byte here); test/daemon.py's `WIRE` 30; firstOnPair's argument is now what it chose, `by_dump` (a client joined by the session's dump, or one that makes its own core); core/root.zig `machine_lines` for replica.zig 74 -> 73; core-test 911/1068 (157 skipped), shell-test 1110/1113 Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- abi/wire.zig | 14 +++++++------- core/replica.zig | 53 ++++++++++++++--------------------------------------- core/root.zig | 2 +- runtime/session.zig | 6 +----- test/daemon.py | 2 +- test/replicas.zig | 1 - 6 files changed, 24 insertions(+), 54 deletions(-) diff --git a/abi/wire.zig b/abi/wire.zig index ab974e35..48b3ae51 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -10,6 +10,9 @@ const pardes = @import("core"); const config = @import("pardes_options"); const build_info = @import("build_info"); +/// 30: the terminals' one road: the screen-state messages are retired (a +/// replica's `screen_ack`, 0x04, and the session's `screen`, 0x06: gaps) +/// and a welcome says no road (its `bytes` byte gone); /// 29: a session's terminals reach its clients as the pty's bytes in its /// units, each client's emulator its own; a welcome says the road (`bytes`; /// screen state under PARDES_TERM_SCREEN), which the client loads its dump @@ -54,7 +57,7 @@ const build_info = @import("build_info"); /// part B); 14: the hello names a session and /// carries the semantics hash, and a ping is answered (phase 5's /// groundwork); 13: the frames went (phase 3). -pub const version: u16 = 29; +pub const version: u16 = 30; /// The terminal's build and the window's step alike (`semantics`). const family = switch (config.platform) { @@ -221,7 +224,7 @@ pub const ServerMsg = union(ServerTag) { /// dump that follows is, and the session's offset from UTC (a replica /// guesses the session's time of day). A far client is told how many /// blobs the dump holds (`blobs`). - welcome: struct { pid: u32, session: []const u8, client: u16 = 0, view: pardes.Pardes.View.Id = .at(0), dump_len: u64 = 0, gmtoff: i32 = 0, digest: u64 = 0, semantics: u64 = 0, bytes: bool = false, blobs: u32 = 0 }, + welcome: struct { pid: u32, session: []const u8, client: u16 = 0, view: pardes.Pardes.View.Id = .at(0), dump_len: u64 = 0, gmtoff: i32 = 0, digest: u64 = 0, semantics: u64 = 0, blobs: u32 = 0 }, refused: []const u8, pong: u64, dump: []const u8, @@ -256,7 +259,6 @@ pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg { .gmtoff = try r.takeInt(i32, .little), .digest = try r.takeInt(u64, .little), .semantics = try r.takeInt(u64, .little), - .bytes = try r.takeByte() != 0, .blobs = try r.takeInt(u32, .little), } }, .refused => .{ .refused = try r.take(try r.takeInt(u16, .little)) }, @@ -287,7 +289,6 @@ pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { try w.writeInt(i32, h.gmtoff, .little); try w.writeInt(u64, h.digest, .little); try w.writeInt(u64, h.semantics, .little); - try w.writeByte(@intFromBool(h.bytes)); try w.writeInt(u32, h.blobs, .little); }, .refused => |words| try putSlice16(&w, words), @@ -729,14 +730,13 @@ test "detached wire: every Event variant round-trips" { try testing.expectEqual(@as(u64, 0xfeed_beef_0000_0001), (try roundClient(&buf, .{ .ping = 0xfeed_beef_0000_0001 })).ping); { // The other way: framed the same, its tag the ServerTag's number. - const bytes = try encodeServer(&buf, .{ .welcome = .{ .pid = 42, .session = "work", .bytes = true } }); + const bytes = try encodeServer(&buf, .{ .welcome = .{ .pid = 42, .session = "work" } }); const f = (try framed(bytes)).?; try testing.expectEqual(@as(u8, 0x01), f.tag); - try testing.expectEqualSlices(u8, &.{ 42, 0, 0, 0, 4, 0, 'w', 'o', 'r', 'k', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 }, f.payload); + try testing.expectEqualSlices(u8, &.{ 42, 0, 0, 0, 4, 0, 'w', 'o', 'r', 'k', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, f.payload); const back = (try decodeServer(f.tag, f.payload)).welcome; try testing.expectEqualStrings("work", back.session); try testing.expectEqual(@as(u32, 42), back.pid); - try testing.expect(back.bytes); try testing.expectEqual(@as(u8, 0x03), (try framed(try encodeServer(&buf, .{ .pong = 7 }))).?.tag); } diff --git a/core/replica.zig b/core/replica.zig index 3f897044..55e7a1f7 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -1789,11 +1789,6 @@ pub const Peers = struct { /// writer would write (its join, then `out`) and its reader read /// (`Peer.take`, then `.gone` posted) are its driver's to do. threads: bool = true, - /// Its clients' terminals cross as the pty's bytes in its units, each - /// client's emulator its own (P29, P32), not as screen state: every - /// session's (runtime/session.zig) but under PARDES_TERM_SCREEN, the - /// soak's `--bytes`; its welcome says so to each client. - bytes: bool = false, pub const Note = union(enum) { join: Joining, input: Msg, gone: *Peer, check: *Peer, joined: *Peer }; /// A connection to join, and the view it joins again for, if it does. @@ -1992,7 +1987,7 @@ pub const Peers = struct { // (a pair's client, its own boot: `writeJoin`). const digest = tape.digestOf(core); peer.digest = digest; - peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = @intCast(libc.getpid()), .session = ps.name[0..@min(ps.name.len, wire.max_name)], .client = peer.id, .view = peer.view, .dump_len = whole, .gmtoff = gmtoff(), .digest = digest, .semantics = wire.semantics, .blobs = @intCast(blobs.items.len), .bytes = ps.bytes } }) catch unreachable).len; + peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = @intCast(libc.getpid()), .session = ps.name[0..@min(ps.name.len, wire.max_name)], .client = peer.id, .view = peer.view, .dump_len = whole, .gmtoff = gmtoff(), .digest = digest, .semantics = wire.semantics, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len; if (ps.threads) peer.writer = std.Thread.spawn(.{}, Peer.writeLoop, .{peer}) catch null; if (ps.threads) peer.reader = std.Thread.spawn(.{}, Peer.readLoop, .{peer}) catch null; if (ps.threads and (peer.writer == null or peer.reader == null)) { @@ -2316,9 +2311,6 @@ pub const Joined = struct { /// Its replica is its own boot, the welcome not read yet (`ownBoot`, /// `confirmBoot`). booted: bool = false, - /// Its session's terminals come as the pty's bytes, not screen state - /// (the welcome's word, Peers.bytes). - bytes: bool = false, }; /// A blob a far join was sent: where it is in the dump, and its hash. @@ -2399,7 +2391,6 @@ fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Ha r.j.gmtoff = w.gmtoff; r.j.digest = w.digest; r.j.semantics = w.semantics; - r.j.bytes = w.bytes; if (r.boot == w.digest) { r.done = true; return false; @@ -2803,16 +2794,14 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o return fromDump(gpa, j, o, have, why, t0); } -/// The replica of the dump `j` brought, on the road its welcome says, its -/// load checked by the session's digest, and what it takes of `j`; null, -/// and why in `why`, when it does not load as the session. +/// The replica of the dump `j` brought, its load checked by the session's +/// digest (its emulators' among it), and what it takes of `j`; null, and +/// why in `why`, when it does not load as the session. fn fromDump(gpa: Allocator, j: *Joined, o: pardes.Options, have: ?*Have, why: []u8, t0: u64) ?*Replica { const r = Replica.initDump(gpa, j.client, j.view, j.dump, o) catch |err| { _ = std.fmt.bufPrint(why, "the session's dump would not load: {t}\x00", .{err}) catch {}; return null; }; - // Before the check: on the bytes road the digest covers its emulators. - road(r, j.bytes); if (!r.loaded(j.digest)) { r.deinit(); _ = std.fmt.bufPrint(why, "the session's dump loaded as another session (a build's dump is not complete)\x00", .{}) catch {}; @@ -2822,14 +2811,6 @@ fn fromDump(gpa: Allocator, j: *Joined, o: pardes.Options, have: ?*Have, why: [] return r; } -/// Its terminals its own emulators, fed the pty's bytes its units carry -/// (`bytes`, its session's Peers.bytes), or the session's screen state; -/// its echo predicted on either (core/echo.zig). -fn road(r: *Replica, bytes: bool) void { - r.t.screen_state = !bytes; - r.core().echo = &r.echo; -} - /// What a replica joined by `j` takes of it, and of the environment. fn takeJoined(r: *Replica, j: *Joined, have: ?*Have, t0: u64) void { // PARDES_NO_ECHO: no predicted echo (the gates' baseline). @@ -2867,10 +2848,7 @@ fn ownBoot(gpa: Allocator, j: *Joined, fd: c_int, o: pardes.Options, why: *[600] _ = std.fmt.bufPrint(why, "the session hung up\x00", .{}) catch {}; return null; } - // Its session is this process's child, on the road this environment - // says (runtime/session.zig): the welcome says it again. - j.* = .{ .fd = fd, .pid = 0, .client = r.id, .view = r.view, .gmtoff = gmtoff(), .dump = &.{}, .digest = digest, .semantics = wire.semantics, .booted = true, .bytes = std.c.getenv("PARDES_TERM_SCREEN") == null }; - road(r, j.bytes); + j.* = .{ .fd = fd, .pid = 0, .client = r.id, .view = r.view, .gmtoff = gmtoff(), .dump = &.{}, .digest = digest, .semantics = wire.semantics, .booted = true }; takeJoined(r, j, null, t0); return r; } @@ -2889,7 +2867,6 @@ pub fn confirmBoot(gpa: Allocator, j: *Joined, r: *Replica, o: pardes.Options, w if (j.dump.len == 0) { r.id = j.client; r.view = j.view; - road(r, j.bytes); return r; } defer { @@ -4230,9 +4207,10 @@ fn ownBootAgainst(edited: bool) !void { /// A session's first client on a socket pair (runtime/session.zig's, then /// the client's first join on its end), the session's first effects after: /// its boot shell spawned, its first bytes output; the client quiet and -/// checked. Bytes: the client loaded as the soak's bytes clients are -/// (`replica.join` loads the screen-state kind until the switch). -fn firstOnPair(bytes: bool) !void { +/// checked. `by_dump`: the client joined by the session's dump, as any +/// client loads one (`fromDump`); else it makes its own core (Options.pair, +/// `confirmBoot`). +fn firstOnPair(by_dump: bool) !void { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const Spawns = struct { @@ -4249,7 +4227,7 @@ fn firstOnPair(bytes: bool) !void { const core = try Pardes.init(gpa, opts); defer core.deinit(); core.host = .{ .ctx = &spawns, .vtable = &Spawns.vtable }; - var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .name = "pair", .bytes = true, .detached = true }; + var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .name = "pair", .detached = true }; defer ps.deinit(); defer live_peers = null; defer ps.dropAll(core); @@ -4257,12 +4235,10 @@ fn firstOnPair(bytes: bool) !void { ps.join(core, .{ .fd = fds[0], .own = true }); var j: Joined = undefined; var why: [600]u8 = @splat(0); - const r = if (bytes) r: { - // Joined by its dump as any client loads one (`fromDump`): the - // welcome says the road, and its load is checked on it. + const r = if (by_dump) r: { + // Joined by its dump as any client loads one (`fromDump`). j = joinOn(gpa, fds[1], null, &why, null, null, null) orelse return error.JoinFailed; defer gpa.free(j.dump); - try std.testing.expect(j.bytes); break :r fromDump(gpa, &j, opts, null, &why, nowNs()) orelse { std.debug.print("the join: {s}\n", .{std.mem.sliceTo(&why, 0)}); return error.JoinFailed; @@ -4333,7 +4309,7 @@ fn firstOnPair(bytes: bool) !void { defer arena.deinit(); const rows = try pardes.Term.viewport(r.core().panes[shell].?.terminal.?, arena.allocator(), false); try std.testing.expect(std.mem.indexOf(u8, rows[0], "first$") != null); - if (!bytes) return; + if (!by_dump) return; // One that comes after the shell's bytes: every side reloads. var late: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &late) != 0) return error.NoSocket; @@ -5767,7 +5743,7 @@ test "a step of the session's own that reads a terminal right after its output, core.view().active = shell; // The session as runtime/session.zig runs it; the client's link in // memory. - var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .threads = false, .bytes = true }; + var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .threads = false }; defer ps.deinit(); defer ps.dropAll(core); var fds: [2]c_int = undefined; @@ -5795,7 +5771,6 @@ test "a step of the session's own that reads a terminal right after its output, try whole.appendSlice(gpa, peer.dump[pos..]); const r = try Replica.initDump(gpa, w.client, w.view.index(), whole.items, .{ .cols = 80, .rows = 24, .boot = .tty }); defer r.deinit(); - road(r, w.bytes); try std.testing.expect(r.loaded(w.digest)); var link: Link = .{ .r = r, .fd = fds[1] }; defer link.deinit(gpa); diff --git a/core/root.zig b/core/root.zig index 66630b2d..171bdfef 100644 --- a/core/root.zig +++ b/core/root.zig @@ -632,7 +632,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{ .{ "jj.zig", 11, "jj run under tape.site(.jj) on an io of its own (the tape's spawns nothing) with this process's environment, the signal mask cleared as Stream's children's: the session's, a replica replays its answer; or on a worker for `Changes`, its answer an input, with the wall clock it was made at (tape.value(.clock) on the loop) for its descriptions' ages; a test's shell inbox (dev)" }, .{ "look.zig", 6, "openLink's fork (the host's: a view's frontend opens a link) and a remote's error name" }, .{ "memory.zig", 7, "the memory regions themselves (mmap, madvise, their locks)" }, - .{ "replica.zig", 74, "the client and session engines: sockets, threads, clocks, the blob cache, traces" }, + .{ "replica.zig", 73, "the client and session engines: sockets, threads, clocks, the blob cache, traces" }, .{ "rollback.zig", 1, "a test helper's directory" }, .{ "root.zig", 4, "dev's modules re-exported (host_io, file_watch, glide, fonts)" }, .{ "selection_pipe.zig", 14, "a pipe's child processes and their files: the host's `pipe` entry" }, diff --git a/runtime/session.zig b/runtime/session.zig index 9499da9c..75e8efcc 100644 --- a/runtime/session.zig +++ b/runtime/session.zig @@ -86,11 +86,7 @@ pub fn Loop(comptime Frontend: type) type { defer l.prompt_rcs.deinit(); l.fs = ninep_io.start(l.io, l.gpa, l.core); defer if (l.fs) |f| f.deinit(l.gpa); - // Its clients' terminals by the pty's bytes (Peers.bytes), each - // client's emulator its own; PARDES_TERM_SCREEN (a working name, - // the way back until the screen state's road is deleted): as - // screen state. Its welcome tells each client which. - l.peers = .{ .gpa = l.gpa, .io = l.io, .name = daemon.name(), .bytes = std.c.getenv("PARDES_TERM_SCREEN") == null }; + l.peers = .{ .gpa = l.gpa, .io = l.io, .name = daemon.name() }; l.inbox = .{ .io = l.io, .gpa = l.gpa, .lsp_allocator = l.allocs.lsp }; defer l.inbox.deinit(); // A search's worker may be waiting on the queue for room. diff --git a/test/daemon.py b/test/daemon.py index 3a481c00..c5c39be3 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -257,7 +257,7 @@ class Replica: """A replica's connection (abi/wire.zig): length-prefixed messages, a tag byte and a little-endian u32 length. It is a near client: its first word after the hello says so.""" - WIRE = 29 + WIRE = 30 def __init__(self, path, timeout=10): self.path, self.timeout = path, timeout diff --git a/test/replicas.zig b/test/replicas.zig index 46eff641..aa10d4a9 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -1296,7 +1296,6 @@ const Soak = struct { pub fn open(s: *Soak, l: *SessionLoop) !pardes.Host { s.l = l; l.peers.threads = false; - l.peers.bytes = true; const host: pardes.Host = .{ .ctx = s, .vtable = &vtable }; l.core.host = host; return host; -- cgit v1.3 From 9158de5d50831e115e14e2ed502300ee8c1d9930 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 22 Nov 2026 03:03:55 -0300 Subject: term: screen_state.zig deleted, and the terminal module's side of the delta road (the old road's deletion, piece 5 of 8): core/term/screen_state.zig (1,213 lines: the encoder, tracks, peers' flights, a replica's apply and holes, its own soak and four tests) goes whole; core/term/terminal.zig loses `encode`/`encodeRows`/`encoder`/`encoderFree`/`track`/`untrack`/`replica`/`replicaFree`/`replicaTop`/`missing`/`apply`/`applyRows`/`shown`/`blank`, `takeMarks` (`marksOf` stays, private: the tests compare two terminals by it), the State's `changes` (a version's counter for the tracks), `read` with `markRead`/`wasRead`/`clearRead` (the rows a step read, for the fills), and `resize_to` with `resizeDeferred` and `resize`'s `later` (screen state's authority sized its terminals after a step's unit); abi/term.zig loses the `Encoder`/`Track`/`Replica` handles, `flight_bound`, `Peer`, `Applied` and those entries of `Ops` (and `dumpScreen`, which nothing in the core called); core/Term.zig its wrappers; core/term/term.zig its ops, its handle map and its `screen_state` export; core/panes.zig its `resizeDeferred` and resizes now (its later screen-state lines go in piece 6); core/edit.zig its `markRead`; the cell-for-cell dump the soak compares a client's terminal with its session's by moves to terminal.zig (`dumpScreen`, over the emulator), the soak's three streams (a shell's, a full-screen program's, `yes`) into test/replicas.zig, their one user; test/terminal.zig loses `a replica's terminal pane draws as its authority's does` (a delta's) and `a terminal made fresh has no size waiting` (`resize_to`'s); core-test 911/1068 (157 skipped), shell-test 1110/1113, term-test 15/15, pane-test 181/182 (again after the machines reboot, on a wiped cache), the soaks small run and `--echo` rc 0 Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- abi/term.zig | 86 +--- core/Term.zig | 102 +--- core/edit.zig | 3 - core/panes.zig | 12 +- core/term/screen_state.zig | 1213 -------------------------------------------- core/term/term.zig | 30 +- core/term/terminal.zig | 220 ++------ test/replicas.zig | 62 ++- test/terminal.zig | 95 +--- 9 files changed, 122 insertions(+), 1701 deletions(-) delete mode 100644 core/term/screen_state.zig diff --git a/abi/term.zig b/abi/term.zig index 187b99e5..a0636509 100644 --- a/abi/term.zig +++ b/abi/term.zig @@ -1,8 +1,8 @@ //! The terminal as the core sees it (docs/next-terminal.md, Phase 1): the //! entries (`Ops`) a terminal module gives the core, and the records they -//! take and give. A terminal's state, its replicas' encoder and tracks are -//! handles the core holds and never looks into; what it knows of them it is -//! told here, as numbers, bytes, text and cells. core/term/term.zig is the +//! take and give. A terminal's state is a handle the core holds and never +//! looks into; what it knows of it it is told here, as numbers, bytes, text +//! and cells. core/term/term.zig is the //! one implementation (ghostty-vt behind it); core/Term.zig is the core's //! side of it. const std = @import("std"); @@ -12,12 +12,6 @@ const CellStyle = plain.CellStyle; /// A terminal: its emulator, its parse and what is kept beside it. pub const State = opaque {}; -/// What a session's authority keeps to encode its terminals for its peers -/// (one for all of them), and what it keeps of one terminal for them. -pub const Encoder = opaque {}; -pub const Track = opaque {}; -/// A replica's side of one terminal: what it was sent. -pub const Replica = opaque {}; /// Where the view and the cursor are, in rows counted from the top of the /// history: `total` rows, the view's top at `offset`, `len` of them shown. @@ -35,7 +29,7 @@ pub const Grid = struct { /// The view's top row while it is scrolled to one, null while it /// follows the output. view: ?usize = null, - /// Its grid's width (a pane's may differ while a resize is deferred). + /// Its grid's width. cols: u16 = 0, }; @@ -240,50 +234,6 @@ pub const ImagesAt = struct { /// marked it input, and its style's identity. pub const EchoCell = struct { cp: u21, input: bool, style: u32 }; -// ---- its replicas ---- - -/// Deltas a peer may have in flight. At 207 ms and 60 frames a second about -/// 13 are; past the bound a peer gets nothing until an acknowledgement, and -/// then the newest state, the ones between skipped. -pub const flight_bound = 32; - -/// What the authority knows of one peer of one terminal. -pub const Peer = struct { - /// The version last sent, which the next delta is against; 0: none, so - /// the next starts the replica afresh. - sent: u32 = 0, - /// The versions in flight, oldest first. - flight: [flight_bound]u32 = undefined, - n: u8 = 0, - /// The history rows its replica holds as holes, absolute, as the - /// replica keeps them (Replica.apply's rule, from what it was sent): - /// what `fill` sends before a step reads them. - top: u64 = 0, - holes: std.ArrayListUnmanaged([2]u64) = .empty, - - pub fn deinit(peer: *Peer, gpa: std.mem.Allocator) void { - peer.holes.deinit(gpa); - } - - /// Every version up to `seq` has landed. - pub fn ack(peer: *Peer, seq: u32) void { - var i: u8 = 0; - while (i < peer.n and peer.flight[i] <= seq) i += 1; - std.mem.copyForwards(u32, peer.flight[0 .. peer.n - i], peer.flight[i..peer.n]); - peer.n -= i; - } - - /// Start the peer afresh: it lost its state, or never had one. - pub fn reset(peer: *Peer) void { - var holes = peer.holes; - holes.clearRetainingCapacity(); - peer.* = .{ .holes = holes }; - } -}; - -/// A delta applied: its version, and what its authority sent beside it. -pub const Applied = struct { seq: u32, extra: []const u8 }; - /// What the dump keeps of a terminal beside its emulator, by name as every /// dump is (core/walk.zig, through the core's `Term.State`). pub const Parts = struct { @@ -368,8 +318,7 @@ pub const Ops = struct { viewTo: *const fn (s: *State, at: ?usize) void, scroll: *const fn (s: *State, delta: i32) void, follow: *const fn (s: *State) void, - resize: *const fn (s: *State, cols: u16, rows: u16, later: bool) void, - resizeDeferred: *const fn (s: *State) bool, + resize: *const fn (s: *State, cols: u16, rows: u16) void, cellPixels: *const fn (s: *State, w: u32, h: u32) void, replies: *const fn (s: *State) []const u8, @@ -397,7 +346,6 @@ pub const Ops = struct { /// How much of its row `row` (from the top of its history) the prompt /// it starts with is; null for a row no prompt starts. promptCut: *const fn (s: *State, row: i32) ?PromptCut, - markRead: *const fn (s: *State) void, /// What a predicted echo reads of cell `x`, `y` of its active area. echoCell: *const fn (s: *const State, x: u16, y: u16) ?EchoCell, @@ -419,28 +367,4 @@ pub const Ops = struct { /// placeholder cells blanked in `frame` (`frame_cols` wide). images: *const fn (s: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.ArrayList(plain.Placement), frame: []plain.Cell, frame_cols: u16) void, hasImages: *const fn (s: ?*const State) bool, - - // ---- its replicas ---- - encoder: *const fn (gpa: std.mem.Allocator) error{OutOfMemory}!*Encoder, - encoderFree: *const fn (e: *Encoder) void, - track: *const fn (gpa: std.mem.Allocator) error{OutOfMemory}!*Track, - /// A peer's track of it let go (`s` null: it is gone). - untrack: *const fn (t: *Track, gpa: std.mem.Allocator, s: ?*State) void, - /// What a peer is owed of it, a delta against what the peer was sent. - encode: *const fn (s: *State, e: *Encoder, t: *Track, peer: *Peer, out: *std.Io.Writer) anyerror!bool, - /// Rows of it a replica holds as holes. - encodeRows: *const fn (s: *State, e: *Encoder, t: *Track, lo: u64, hi: u64, out: *std.Io.Writer) anyerror!void, - wasRead: *const fn (s: *const State) bool, - clearRead: *const fn (s: *State) void, - replica: *const fn (gpa: std.mem.Allocator) error{OutOfMemory}!*Replica, - replicaFree: *const fn (r: *Replica, gpa: std.mem.Allocator) void, - /// The absolute row its replica's active area begins at. - replicaTop: *const fn (r: *const Replica) u64, - /// History rows `lo..hi` it does not hold. - missing: *const fn (r: *const Replica, lo: u64, hi: u64, out: *std.ArrayList([2]u64), gpa: std.mem.Allocator) error{OutOfMemory}!void, - apply: *const fn (s: *State, r: *Replica, bytes: []const u8) anyerror!Applied, - applyRows: *const fn (s: *State, r: *Replica, bytes: []const u8) anyerror!void, - shown: *const fn (s: *State, r: *const Replica) [2]u64, - blank: *const fn (s: *State, r: *const Replica, lo: u64, hi: u64) void, - dumpScreen: *const fn (s: *State, w: *std.Io.Writer) error{WriteFailed}!void, }; diff --git a/core/Term.zig b/core/Term.zig index 6ef9b0a5..86c7518b 100644 --- a/core/Term.zig +++ b/core/Term.zig @@ -50,14 +50,9 @@ pub const Painted = iface.Painted; pub const PaintedRow = iface.PaintedRow; pub const ImagesAt = iface.ImagesAt; pub const EchoCell = iface.EchoCell; -pub const Peer = iface.Peer; -pub const Applied = iface.Applied; -pub const Encoder = iface.Encoder; -pub const Track = iface.Track; -pub const Replica = iface.Replica; fn the() *const iface.Ops { - return ops orelse unreachable; // no State, Encoder or Replica is made without it + return ops orelse unreachable; // no State is made without it } /// A terminal pane's terminal: the module's handle, and the walk's hooks @@ -236,16 +231,11 @@ pub fn follow(s: *State) void { the().follow(s.impl); } -/// Its grid reflowed, now or when `resizeDeferred` makes it. -pub fn resize(s: *State, cols: u16, rows: u16, later: bool) void { +/// Its grid reflowed. +pub fn resize(s: *State, cols: u16, rows: u16) void { writes +%= 1; s.written = true; - the().resize(s.impl, cols, rows, later); -} - -pub fn resizeDeferred(s: *State) bool { - writes +%= 1; - return the().resizeDeferred(s.impl); + the().resize(s.impl, cols, rows); } /// Its cells' size in pixels (kitty graphics, CSI 14/16 t). @@ -365,12 +355,6 @@ pub fn promptPrefix(tab: u16, s: ?*State, row: i32, raw: []const u8) usize { }; } -/// A step read its rows: its replicas must hold them for the step's -/// replay. -pub fn markRead(s: *State) void { - the().markRead(s.impl); -} - /// What a predicted echo reads of a cell of its active area. pub fn echoCell(s: *const State, x: u16, y: u16) ?EchoCell { return the().echoCell(s.impl, x, y); @@ -425,84 +409,6 @@ pub fn hasImages(s: ?*const State) bool { return o.hasImages(if (s) |state| state.impl else null); } -// ---- its replicas ---- - -pub fn encoder(gpa: std.mem.Allocator) !*Encoder { - return the().encoder(gpa); -} - -pub fn encoderFree(e: *Encoder) void { - the().encoderFree(e); -} - -pub fn track(gpa: std.mem.Allocator) !*Track { - return the().track(gpa); -} - -/// A peer's track of it let go (`s` null: it is gone). -pub fn untrack(t: *Track, gpa: std.mem.Allocator, s: ?*State) void { - the().untrack(t, gpa, if (s) |state| state.impl else null); -} - -/// What a peer is owed of it, a delta against what the peer was sent. -pub fn encode(s: *State, e: *Encoder, t: *Track, peer: *Peer, out: *std.Io.Writer) !bool { - return the().encode(s.impl, e, t, peer, out); -} - -/// Rows of it a replica holds as holes. -pub fn encodeRows(s: *State, e: *Encoder, t: *Track, lo: u64, hi: u64, out: *std.Io.Writer) !void { - return the().encodeRows(s.impl, e, t, lo, hi, out); -} - -/// Whether a step read its rows since `clearRead`. -pub fn wasRead(s: *const State) bool { - return the().wasRead(s.impl); -} - -pub fn clearRead(s: *State) void { - the().clearRead(s.impl); -} - -/// A replica's side of one terminal: made, freed, where its active area -/// begins, and the history rows it does not hold. -pub fn replica(gpa: std.mem.Allocator) !*Replica { - return the().replica(gpa); -} - -pub fn replicaFree(r: *Replica, gpa: std.mem.Allocator) void { - the().replicaFree(r, gpa); -} - -pub fn replicaTop(r: *const Replica) u64 { - return the().replicaTop(r); -} - -pub fn missing(r: *const Replica, lo: u64, hi: u64, out: *std.ArrayList([2]u64), gpa: std.mem.Allocator) !void { - return the().missing(r, lo, hi, out, gpa); -} - -/// A replica's side: a delta applied, rows applied, the rows its view -/// shows, rows blank until they come. -pub fn apply(s: *State, r: *Replica, bytes: []const u8) !Applied { - return the().apply(s.impl, r, bytes); -} - -pub fn applyRows(s: *State, r: *Replica, bytes: []const u8) !void { - return the().applyRows(s.impl, r, bytes); -} - -pub fn shown(s: *State, r: *const Replica) [2]u64 { - return the().shown(s.impl, r); -} - -pub fn blank(s: *State, r: *const Replica, lo: u64, hi: u64) void { - the().blank(s.impl, r, lo, hi); -} - -pub fn dumpScreen(s: *State, w: *std.Io.Writer) !void { - return the().dumpScreen(s.impl, w); -} - // ---- a core without a terminal (core-test's) ---- test "a core without a terminal boots to a scratch pane" { diff --git a/core/edit.zig b/core/edit.zig index 7a57fd09..a475fac2 100644 --- a/core/edit.zig +++ b/core/edit.zig @@ -471,9 +471,6 @@ const empty_grid = [1][]const u8{""}; pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { const state = pane.terminal orelse return &empty_grid; pardes.tape.touchTerminal(); - // A step's read whether the rows are kept or made: a client that came - // since holds them as holes, and is sent them (Screens.fill). - if (!drawing) panes.Term.markRead(state); const c = &p.shell_rows; if (!c.stale and c.pane == pane) return c.rows; // Another pane's rows, or a dropped pane's still waiting for the step's diff --git a/core/panes.zig b/core/panes.zig index 289de70f..d58bf30b 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -1001,10 +1001,7 @@ pub const Pane = struct { }; if (tape.screenReplica()) return; if (tape.speculating()) return tape.touchTerminal(); - // A client typing at another size than the last typist's read - // history rows its replay held as holes, and the rows came - // renumbered (2026-10-30): the authority's waits for the unit. - Term.resize(state, cols, rows, tape.screenAuthority()); + Term.resize(state, cols, rows); } /// The rows its terminal's top is passed over by in a view whose rect @@ -1176,13 +1173,6 @@ fn written(s: *Term.State) bool { return s.written; } -/// The sizes steps gave terminals (`Pane.resizeGrid`), made: between -/// units, on an authority with screen-state replicas (replica.Peers.unit). -pub fn resizeDeferred(p: *Pardes) void { - for (p.panes) |slot| if (slot) |pane| if (pane.terminal) |state| if (Term.resizeDeferred(state)) - p.shell_rows.markStale(pane); -} - /// A pane with nothing in it yet, `cols` by `rows`: what a file, a /// directory, a kind's pane or a terminal is made from. pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { diff --git a/core/term/screen_state.zig b/core/term/screen_state.zig deleted file mode 100644 index ec72a841..00000000 --- a/core/term/screen_state.zig +++ /dev/null @@ -1,1213 +0,0 @@ -//! Screen-state terminals (docs/next-daemon.md, "Terminals cross as -//! authoritative screen state", phase 5). A replica is sent a terminal's -//! state, never its pty's bytes, so a `cat` of a gigabyte costs it screens. -//! -//! The authority encodes a delta for one peer: a header (the cursor, the -//! active area's first row as an absolute row, the history's extent), the -//! content address of the terminal-wide state, the content address of each -//! row of the active area, and the blobs behind the addresses the peer does -//! not hold. Both kinds of blob are ghostty's own snapshot records, so they -//! cross exactly: the terminal-wide state is a TERMINAL record (modes, -//! colours, title, tab stops...), and a row is the PAGE record of a one-row -//! page (its styles, graphemes, hyperlinks, wide cells, wrap and prompt -//! marks). A row's address is a hash of what the row shows, not of its blob, -//! whose style ids are its source page's. An unchanged row costs 8 bytes. -//! -//! Each state the authority sends is a version of its terminal (`Track`), -//! made once whatever the number of peers. A peer's next delta is against -//! the version it was last sent: the stream is ordered and loses nothing, -//! so the peer has that one by the time it applies the next. Several are -//! in flight (`bound`); acknowledgements free their room, and a peer at the -//! bound gets nothing until one comes, then the newest version, the ones -//! between skipped. Peers at the same base are sent the same bytes. A -//! replica holds the blobs of the state it applied last and no others; a -//! delta against another (one lost) is refused, and the peer started afresh. -//! -//! The replica writes each delta into a ghostty Terminal, which a replica's -//! terminal pane draws as a local one (core/term/terminal.zig reads only that). -//! Rows that scroll off its active area go into its history, made what the -//! authority's are by the delta's tail (their addresses, up to a screen of -//! them). Older ones it never saw, or saw before they last changed, are -//! holes there, fetched by absolute row on demand (`encodeRows`, -//! `applyRows`). -const std = @import("std"); -const vt = @import("ghostty-vt"); -const plain = @import("plain"); -const snapshot = vt.snapshot; -pub const Terminal = vt.Terminal; -const Page = vt.page.Page; -const Row = vt.page.Row; -const Pin = vt.Pin; -const Screen = vt.Screen; - -// ponytail: 64 bits: two of a million distinct rows collide about once in -// 4*10^7 sessions; phase 6's cache, shared across sessions, wants 128. -pub const Hash = u64; - -/// What a row shows, hashed: its wrap and prompt flags, and each of its -/// first `cols` cells up to the last one that is not blank, with its style, -/// grapheme and hyperlink by value. Not the page's style or hyperlink ids, -/// nor its derived flags. Its width is in it: a blob is a row that wide. -/// (A page can be wider than its terminal: ghostty narrows them lazily.) -pub fn rowHash(page: *Page, row: *Row, cols: u16) Hash { - var h = std.hash.Wyhash.init(0); - h.update(&.{rowFlags(row)}); - h.update(std.mem.asBytes(&cols)); - const all = page.getCells(row); - const cells = all[0..@min(cols, all.len)]; - var n = cells.len; - while (n > 0 and @as(u64, @bitCast(cells[n - 1])) == 0) n -= 1; - for (cells[0..n]) |*c| { - var word = c.*; - word.style_id = 0; - h.update(std.mem.asBytes(&@as(u64, @bitCast(word)))); - if (c.style_id != 0) h.update(std.mem.asBytes(&page.styles.get(page.memory, c.style_id).hash())); - if (c.hasGrapheme()) h.update(std.mem.sliceAsBytes(page.lookupGrapheme(c).?)); - if (c.hyperlink) if (page.lookupHyperlink(c)) |id| - h.update(std.mem.asBytes(&page.hyperlink_set.get(page.memory, id).hash(page.memory))); - } - return h.final(); -} - -fn rowFlags(row: *const Row) u8 { - return @as(u8, @intFromBool(row.wrap)) | @as(u8, @intFromBool(row.wrap_continuation)) << 1 | - @as(u8, @backingInt(row.semantic_prompt)) << 2; -} - -/// The authority's absolute row numbers for one terminal: its primary -/// screen's active area starts at `top`, and a row `d` above it in its -/// history is `top - d`. Kept by a tracked pin at the last active top, so -/// it counts the rows scrolled since. A resize renumbers (`epoch`). -pub const Rows = struct { - pin: ?*Pin = null, - top: u64 = 0, - epoch: u32 = 0, - cols: u16 = 0, - rows: u16 = 0, - - pub fn update(n: *Rows, t: *Terminal) !void { - const pages = &t.screens.get(.primary).?.pages; - const top = pages.getTopLeft(.active); - const y = pages.pointFromPin(.screen, top).?.screen.y; - if (n.pin) |p| { - if (t.cols != n.cols or t.rows != n.rows) n.epoch +%= 1; - // The last top was pruned away: every row the peer has is - // older than the oldest row here. - const was: ?u32 = if (p.garbage) null else if (pages.pointFromPin(.screen, p.*)) |pt| pt.screen.y else null; - n.top += if (was) |w| y -| w else @as(u64, y) + t.rows; - // A reflow (a resize to fewer columns) puts more rows above the - // last top than ever scrolled past it: numbered from here, the - // history's oldest row is still row 0 or later. A resize - // renumbers anyway (`epoch`), so no peer holds the old numbers. - n.top = @max(n.top, y); - p.* = top; - } else { - n.pin = try pages.trackPin(top); - n.top = y; - } - n.cols = t.cols; - n.rows = t.rows; - } - - pub fn deinit(n: *Rows, t: *Terminal) void { - if (n.pin) |p| t.screens.get(.primary).?.pages.untrackPin(p); - n.* = .{}; - } - - /// The pin of absolute row `abs`, if the terminal still has it. - fn pinAt(n: *const Rows, t: *Terminal, abs: u64) ?Pin { - return pinOf(&t.screens.get(.primary).?.pages, n.top, abs); - } -}; - -fn pinOf(pages: *const vt.PageList, top: u64, abs: u64) ?Pin { - if (abs >= top) return pages.pin(.{ .active = .{ .y = std.math.cast(u32, abs - top) orelse return null } }); - const d = std.math.cast(usize, top - abs) orelse return null; - return pages.getTopLeft(.active).up(d); -} - -/// The authority's scratch: a one-row page each blob is copied into -/// (fresh, so the blob holds that row's styles alone) and encoded from. -pub const Encoder = struct { - gpa: std.mem.Allocator, - scratch: ?Page = null, - blob: std.Io.Writer.Allocating, - /// The rows a delta sends a blob for, and the addresses it lists once. - needed: std.ArrayList(struct { pin: Pin, hash: Hash }) = .empty, - listed: std.AutoHashMapUnmanaged(Hash, void) = .empty, - tail: std.ArrayList(Pin) = .empty, - - pub fn init(gpa: std.mem.Allocator) Encoder { - return .{ .gpa = gpa, .blob = .init(gpa) }; - } - - pub fn deinit(e: *Encoder) void { - if (e.scratch) |*s| s.deinit(); - e.blob.deinit(); - e.needed.deinit(e.gpa); - e.listed.deinit(e.gpa); - e.tail.deinit(e.gpa); - } - - /// The PAGE record of `row` alone, its first `cols` cells. - fn rowBlob(e: *Encoder, page: *Page, row: *Row, cols: u16, w: *std.Io.Writer) !void { - var cap: vt.page.Capacity = if (e.scratch) |s| s.capacity else .{ .cols = cols, .rows = 1, .styles = 64 }; - if (cap.cols != cols) cap = .{ .cols = cols, .rows = 1, .styles = 64 }; - for (0..16) |_| { - const s = try scratchPage(&e.scratch, cap); - s.cloneRowFrom(page, s.getRow(0), row) catch { - // Room for this row: everything doubled until it fits. - cap.styles *|= 2; - cap.grapheme_bytes *|= 2; - cap.hyperlink_bytes *|= 2; - cap.string_bytes *|= 2; - continue; - }; - break; - } else return error.RowTooBig; - var rw: snapshot.record.Writer = .init(e.gpa, w); - defer rw.deinit(); - try snapshot.page.encode(&e.scratch.?, &rw); - } -}; - -/// `slot`'s one-row scratch page, ready for `cap`: reused when it has that -/// capacity, else made again. -fn scratchPage(slot: *?Page, cap: vt.page.Capacity) !*Page { - if (slot.*) |*s| { - if (std.meta.eql(s.capacity, cap)) { - s.reinit(); - return s; - } - s.deinit(); - slot.* = null; - } - slot.* = try Page.init(cap); - return &slot.*.?; -} - -/// Holes older than a history's oldest row are gone with it. -fn clampHoles(holes: *std.ArrayList([2]u64), oldest: u64) void { - var i: usize = 0; - while (i < holes.items.len) { - const hole = &holes.items[i]; - hole[0] = @max(hole[0], oldest); - if (hole[0] >= hole[1]) _ = holes.orderedRemove(i) else i += 1; - } -} - -/// Deltas a peer may have in flight. At 207 ms and 60 frames a second about -/// 13 are; past the bound a peer gets nothing until an acknowledgement, and -/// then the newest state, the ones between skipped. -pub const bound = plain.term.flight_bound; - -/// What a peer holds once it has a version: the addresses of its active -/// rows and its meta. A delta against it sends no blob for these. -const Known = struct { - version: u32, - epoch: u32, - top: u64, - addrs: std.AutoHashMapUnmanaged(Hash, void) = .empty, -}; - -/// One terminal as the authority numbers it, for all of its peers: each -/// state it sends is a version, made once whatever the number of peers. -pub const Track = struct { - rows: Rows = .{}, - version: u32 = 0, - /// The emulator's change count the newest version was made at, and its - /// history's rows. - changes: u32 = 0, - history: u64 = 0, - /// The newest version: its active rows (pins, good while the emulator - /// is unchanged) and their addresses, and its meta. - pins: std.ArrayList(Pin) = .empty, - hashes: std.ArrayList(Hash) = .empty, - meta: std.Io.Writer.Allocating, - meta_hash: Hash = 0, - /// The newest versions, oldest first: the bases a peer's next delta may - /// have. A peer whose base has gone starts afresh. - known: std.ArrayList(Known) = .empty, - /// The last delta encoded, for the next peer at the same base. - cache: std.Io.Writer.Allocating, - cache_base: u32 = 0, - cache_version: u32 = 0, - - const kept = bound + 8; - - pub fn init(gpa: std.mem.Allocator) Track { - return .{ .meta = .init(gpa), .cache = .init(gpa) }; - } - - /// `t` is the terminal, or null when it is gone already (with its pins). - pub fn deinit(tr: *Track, gpa: std.mem.Allocator, t: ?*Terminal) void { - if (t) |term| tr.rows.deinit(term); - tr.pins.deinit(gpa); - tr.hashes.deinit(gpa); - tr.meta.deinit(); - for (tr.known.items) |*k| k.addrs.deinit(gpa); - tr.known.deinit(gpa); - tr.cache.deinit(); - } - - fn find(tr: *const Track, version: u32) ?*const Known { - if (version == 0) return null; - for (tr.known.items) |*k| if (k.version == version) return if (k.epoch == tr.rows.epoch) k else null; - return null; - } - - /// A version of `t` as it is now. - fn advance(tr: *Track, gpa: std.mem.Allocator, t: *Terminal, changes: u32) !void { - try tr.rows.update(t); - tr.version +%= 1; - if (tr.version == 0) tr.version = 1; - tr.changes = changes; - const primary = &t.screens.get(.primary).?.pages; - tr.history = primary.total_rows - primary.rows; - tr.meta.clearRetainingCapacity(); - { - var rw: snapshot.record.Writer = .init(gpa, &tr.meta.writer); - defer rw.deinit(); - try snapshot.terminal.encode(t, &rw); - } - tr.meta_hash = std.hash.Wyhash.hash(0, tr.meta.written()); - tr.pins.clearRetainingCapacity(); - tr.hashes.clearRetainingCapacity(); - var it = t.screens.active.pages.rowIterator(.right_down, .{ .active = .{} }, null); - while (it.next()) |p| { - try tr.pins.append(gpa, p); - try tr.hashes.append(gpa, rowHash(p.node.page(), p.rowAndCell().row, t.cols)); - } - if (tr.known.items.len == kept) { - tr.known.items[0].addrs.deinit(gpa); - _ = tr.known.orderedRemove(0); - } - var k: Known = .{ .version = tr.version, .epoch = tr.rows.epoch, .top = tr.rows.top }; - errdefer k.addrs.deinit(gpa); - try k.addrs.ensureTotalCapacity(gpa, @intCast(tr.hashes.items.len + 1)); - for (tr.hashes.items) |h| k.addrs.putAssumeCapacity(h, {}); - k.addrs.putAssumeCapacity(tr.meta_hash, {}); - try tr.known.append(gpa, k); - } -}; - -/// What the authority knows of one peer of one terminal: a plain record -/// both sides name (abi/term.zig), the core keeping one a peer. -pub const Peer = plain.term.Peer; - -/// Its replica's holes once it applies a delta to `tr`'s newest version -/// against `base`, as Replica.apply makes them. -fn noteSent(peer: *Peer, gpa: std.mem.Allocator, tr: *const Track, base: ?*const Known, rows: u16) !void { - const top = tr.rows.top; - const history = tr.history; - if (base) |b| { - if (top > peer.top) { - const tail = @min(top -| b.top, rows, history); - if (top - peer.top >= @as(u64, rows) + history) { - peer.holes.clearRetainingCapacity(); - if (history > tail) try peer.holes.append(gpa, .{ top - history, top - tail }); - } else if (top - tail > peer.top) try peer.holes.append(gpa, .{ peer.top, top - tail }); - } - } else { - peer.holes.clearRetainingCapacity(); - if (history > 0) try peer.holes.append(gpa, .{ top - history, top }); - } - peer.top = top; - clampHoles(&peer.holes, top -| history); -} - -/// The delta's fixed header: u32 seq, u32 base (0: none, the replica -/// starts afresh), u8 flags, u32 epoch, u64 meta, u16 cursor x and y, u8 -/// cursor style, u8 pending wrap, u8 the cursor's semantic content, the -/// kitty keyboard flags, u64 top, u64 history rows, u64 the viewport's top -/// as an absolute row (all ones: following the active area), u16 and the -/// caller's extra bytes; then u16 rows and a u64 per active row, u16 and a -/// u64 per row of the tail (those that scrolled off the active area since -/// the base, up to a screen of them, oldest first), and a u16 blob count -/// and each blob as u64 hash, u32 length, bytes. -const flag_reset: u8 = 1; -const KittyFlags = @FieldType(Screen, "kitty_keyboard"); -const following = std.math.maxInt(u64); - -/// The delta that takes `peer` from what it was last sent to `t` as it is, -/// onto `out`; false (nothing written) when it has that already, or has -/// `bound` in flight. `changes` counts the emulator's writes (a new count -/// is a new version); `extra` rides along (the caller's own state of the -/// terminal), the same for every peer of one version. A peer at the same -/// base as the last one encoded is sent the same bytes. -pub fn encode(e: *Encoder, tr: *Track, peer: *Peer, t: *Terminal, changes: u32, extra: []const u8, out: *std.Io.Writer) !bool { - if (tr.version == 0 or changes != tr.changes) try tr.advance(e.gpa, t, changes); - if (peer.sent == tr.version or peer.n == bound) return false; - const base = tr.find(peer.sent); - const base_version = if (base) |b| b.version else 0; - if (tr.cache_version != tr.version or tr.cache_base != base_version) { - tr.cache.clearRetainingCapacity(); - try write(e, tr, base, t, extra, &tr.cache.writer); - tr.cache_version = tr.version; - tr.cache_base = base_version; - } - try out.writeAll(tr.cache.written()); - try noteSent(peer, e.gpa, tr, base, t.rows); - peer.sent = tr.version; - peer.flight[peer.n] = tr.version; - peer.n += 1; - return true; -} - -fn write(e: *Encoder, tr: *Track, base: ?*const Known, t: *Terminal, extra: []const u8, out: *std.Io.Writer) !void { - const gpa = e.gpa; - const reset = base == null; - const screen = t.screens.active; - const pages = &t.screens.get(.primary).?.pages; - const history = pages.total_rows - pages.rows; - const top = tr.rows.top; - try out.writeInt(u32, tr.version, .little); - try out.writeInt(u32, if (base) |b| b.version else 0, .little); - try out.writeByte(if (reset) flag_reset else 0); - try out.writeInt(u32, tr.rows.epoch, .little); - try out.writeInt(u64, tr.meta_hash, .little); - try out.writeInt(u16, screen.cursor.x, .little); - try out.writeInt(u16, screen.cursor.y, .little); - try out.writeByte(@backingInt(screen.cursor.cursor_style)); - try out.writeByte(@intFromBool(screen.cursor.pending_wrap)); - try out.writeByte(@backingInt(screen.cursor.semantic_content)); - // ponytail: raw bytes, as the hello refuses a peer of another build. - try out.writeAll(std.mem.asBytes(&screen.kitty_keyboard)); - try out.writeInt(u64, top, .little); - try out.writeInt(u64, history, .little); - try out.writeInt(u64, if (pages.viewport == .active) following else top - history + pages.scrollbar().offset, .little); - try out.writeInt(u16, @intCast(extra.len), .little); - try out.writeAll(extra); - - // The active rows, then the tail: what scrolled off since the base, - // which may have changed after it was sent. - e.listed.clearRetainingCapacity(); - e.needed.clearRetainingCapacity(); - const tail: u16 = if (base) |b| @intCast(@min(top -| b.top, t.rows, history)) else 0; - e.tail.clearRetainingCapacity(); - for (0..tail) |j| try e.tail.append(gpa, pages.getTopLeft(.active).up(tail - j).?); - try out.writeInt(u16, @intCast(tr.pins.items.len), .little); - for (tr.pins.items, tr.hashes.items) |p, h| { - try out.writeInt(u64, h, .little); - try needBlob(e, base, p, h); - } - try out.writeInt(u16, tail, .little); - for (e.tail.items) |p| { - const h = rowHash(p.node.page(), p.rowAndCell().row, t.cols); - try out.writeInt(u64, h, .little); - try needBlob(e, base, p, h); - } - const meta_new = if (base) |b| !b.addrs.contains(tr.meta_hash) else true; - try out.writeInt(u16, @intCast(e.needed.items.len + @intFromBool(meta_new)), .little); - if (meta_new) { - try out.writeInt(u64, tr.meta_hash, .little); - try out.writeInt(u32, @intCast(tr.meta.written().len), .little); - try out.writeAll(tr.meta.written()); - } - for (e.needed.items) |need| { - e.blob.clearRetainingCapacity(); - try e.rowBlob(need.pin.node.page(), need.pin.rowAndCell().row, t.cols, &e.blob.writer); - try out.writeInt(u64, need.hash, .little); - try out.writeInt(u32, @intCast(e.blob.written().len), .little); - try out.writeAll(e.blob.written()); - } -} - -/// A blob goes for an address the base does not hold, once. -fn needBlob(e: *Encoder, base: ?*const Known, p: Pin, h: Hash) !void { - if ((try e.listed.getOrPut(e.gpa, h)).found_existing) return; - if (base) |b| if (b.addrs.contains(h)) return; - try e.needed.append(e.gpa, .{ .pin = p, .hash = h }); -} - -/// The primary screen's rows `[lo, hi)` the authority still has, for a -/// replica that holds them as holes: u32 epoch, u32 blobs, each u64 hash, -/// u32 length, bytes, then u32 rows, each u64 row and u64 hash. A blob goes -/// once a message (a flood's rows are one). -// ponytail: blobs once a message, not once a peer: phase 6's content cache. -pub fn encodeRows(e: *Encoder, tr: *Track, t: *Terminal, lo: u64, hi: u64, out: *std.Io.Writer) !void { - try tr.rows.update(t); - var blobs: std.Io.Writer.Allocating = .init(e.gpa); - defer blobs.deinit(); - var rows: std.Io.Writer.Allocating = .init(e.gpa); - defer rows.deinit(); - e.listed.clearRetainingCapacity(); - var nblobs: u32 = 0; - var nrows: u32 = 0; - var abs = lo; - // The active area is the deltas'. - while (abs < @min(hi, tr.rows.top)) : (abs += 1) { - const p = tr.rows.pinAt(t, abs) orelse continue; - const h = rowHash(p.node.page(), p.rowAndCell().row, t.cols); - try rows.writer.writeInt(u64, abs, .little); - try rows.writer.writeInt(u64, h, .little); - nrows += 1; - if ((try e.listed.getOrPut(e.gpa, h)).found_existing) continue; - e.blob.clearRetainingCapacity(); - try e.rowBlob(p.node.page(), p.rowAndCell().row, t.cols, &e.blob.writer); - try blobs.writer.writeInt(u64, h, .little); - try blobs.writer.writeInt(u32, @intCast(e.blob.written().len), .little); - try blobs.writer.writeAll(e.blob.written()); - nblobs += 1; - } - try out.writeInt(u32, tr.rows.epoch, .little); - try out.writeInt(u32, nblobs, .little); - try out.writeAll(blobs.written()); - try out.writeInt(u32, nrows, .little); - try out.writeAll(rows.written()); -} - -/// A replica's terminal: what it was sent, written into a ghostty Terminal. -pub const Replica = struct { - seq: u32 = 0, - epoch: u32 = 0, - meta: Hash = 0, - top: u64 = 0, - /// The address of each active row as the Terminal holds it, a list per - /// screen (primary, alternate). - held: [2]std.ArrayList(Hash) = .{ .empty, .empty }, - /// The blobs of the last state applied: what the authority takes it to - /// hold. Owned copies. - blobs: std.AutoHashMapUnmanaged(Hash, []u8) = .empty, - /// History rows it cannot vouch for (written blank, or seen before - /// they last changed), `[lo, hi)` absolute, oldest first. - holes: std.ArrayList([2]u64) = .empty, - /// The one-row page each row blob is decoded into. - scratch: ?Page = null, - - pub fn deinit(r: *Replica, gpa: std.mem.Allocator) void { - for (&r.held) |*h| h.deinit(gpa); - var it = r.blobs.valueIterator(); - while (it.next()) |b| gpa.free(b.*); - r.blobs.deinit(gpa); - r.holes.deinit(gpa); - if (r.scratch) |*s| s.deinit(); - } - - pub const Applied = plain.term.Applied; - - /// Write one delta into `t`: the seq to acknowledge, and the caller's - /// extra bytes (borrowed from `bytes`). error.BaseMismatch: the delta - /// is against a state this replica does not have (one was lost, or it - /// started afresh), so `t` is as it was and it must be sent a reset. - pub fn apply(r: *Replica, gpa: std.mem.Allocator, io: std.Io, t: *Terminal, bytes: []const u8) !Applied { - var in: std.Io.Reader = .fixed(bytes); - const seq = try in.takeInt(u32, .little); - const base = try in.takeInt(u32, .little); - const flags = try in.takeByte(); - const reset = flags & flag_reset != 0; - if (!reset and base != r.seq) return error.BaseMismatch; - const epoch = try in.takeInt(u32, .little); - const meta = try in.takeInt(u64, .little); - const cx = try in.takeInt(u16, .little); - const cy = try in.takeInt(u16, .little); - const style = try in.takeByte(); - const wrap = try in.takeByte(); - const semantic = try in.takeByte(); - var kitty: KittyFlags = undefined; - @memcpy(std.mem.asBytes(&kitty), try in.take(@sizeOf(KittyFlags))); - const top = try in.takeInt(u64, .little); - const history = try in.takeInt(u64, .little); - const viewport = try in.takeInt(u64, .little); - const extra = try in.take(try in.takeInt(u16, .little)); - const nrows = try in.takeInt(u16, .little); - const hashes = try in.take(@as(usize, nrows) * 8); - const tail = try in.takeInt(u16, .little); - const tails = try in.take(@as(usize, tail) * 8); - // The delta's blobs, borrowed from `bytes` while it applies. - var fresh: std.AutoHashMapUnmanaged(Hash, []const u8) = .empty; - defer fresh.deinit(gpa); - for (0..try in.takeInt(u16, .little)) |_| { - const h = try in.takeInt(u64, .little); - try fresh.put(gpa, h, try in.take(try in.takeInt(u32, .little))); - } - const blobOf = struct { - fn of(rr: *Replica, f: *const std.AutoHashMapUnmanaged(Hash, []const u8), h: Hash) ![]const u8 { - if (f.get(h)) |b| return b; - if (rr.blobs.get(h)) |b| return b; - return error.MissingBlob; - } - }.of; - - if (reset or meta != r.meta) { - var reader: std.Io.Reader = .fixed(try blobOf(r, &fresh, meta)); - var next = try snapshot.terminal.decode(&reader, try snapshot.record.nextHeader(&reader), io, gpa); - if (reset) { - std.mem.swap(Terminal, t, &next); - next.deinit(gpa); - for (&r.held) |*h| h.clearRetainingCapacity(); - r.holes.clearRetainingCapacity(); - r.top = top; - r.epoch = epoch; - // The authority's history, blank, to be fetched. Its own - // limit is the authority's row count (below), not bytes: - // its pages may pack rows otherwise. - const primary = t.screens.get(.primary).?; - primary.pages.setMaxBytes(null); - try scrollUp(primary, history); - if (history > 0) try r.holes.append(gpa, .{ top -| history, top }); - } else { - defer next.deinit(gpa); - try takeMeta(t, &next, io, gpa); - } - r.meta = meta; - } - if (epoch != r.epoch) return error.Renumbered; - - // The primary screen scrolled `top - r.top` rows since the last - // delta: as many go up into the history here (no more than its - // history holds and the screen), each beyond the tail a hole. - const primary = t.screens.get(.primary).?; - if (top > r.top) { - const k = top - r.top; - const held = &r.held[0]; - if (k >= @as(u64, t.rows) + history) { - // A flood: nothing held here is in this state. The rows stay - // where they are, renumbered: the active ones written below, - // the tail too, the rest holes (blanked when they come into - // view, `blank`), not grown and trimmed by the thousand. As - // many more as the history is longer there, grown blank. - const have = primary.pages.total_rows - primary.pages.rows; - if (have < history) try scrollUp(primary, history - have); - held.clearRetainingCapacity(); - try held.appendNTimes(gpa, unknown, t.rows); - r.holes.clearRetainingCapacity(); - if (history > tail) try r.holes.append(gpa, .{ top - history, top - tail }); - } else { - try scrollUp(primary, @min(k, @as(u64, t.rows) + history)); - if (k >= held.items.len) held.clearRetainingCapacity() else { - std.mem.copyForwards(Hash, held.items, held.items[@intCast(k)..]); - held.shrinkRetainingCapacity(held.items.len - @as(usize, @intCast(k))); - } - if (top - tail > r.top) try r.holes.append(gpa, .{ r.top, top - tail }); - } - r.top = top; - } - // The history as long as the authority's (it prunes a page at a - // time, and an ED 3 takes it all): row numbers and the scrollbar - // say the same on both. ponytail: one pruned shorter than that - // (its pages packed otherwise) stays shorter. - const have = primary.pages.total_rows - primary.pages.rows; - if (have > history) primary.pages.eraseHistory(.{ .history = .{ .y = @intCast(have - history - 1) } }); - r.trimHoles(primary); - for (0..tail) |j| { - const p = pinOf(&primary.pages, top, top - tail + j) orelse continue; - const h = std.mem.readInt(u64, tails[j * 8 ..][0..8], .little); - if (rowHash(p.node.page(), p.rowAndCell().row, t.cols) != h) try r.writeRow(gpa, primary, p, try blobOf(r, &fresh, h)); - } - - const screen = t.screens.active; - const held = &r.held[@backingInt(t.screens.active_key)]; - const blank_row = blankHash(t.cols); - while (held.items.len < nrows) try held.append(gpa, blank_row); - held.shrinkRetainingCapacity(nrows); - for (0..nrows) |y| { - const h = std.mem.readInt(u64, hashes[y * 8 ..][0..8], .little); - if (h == held.items[y]) continue; - try r.writeRow(gpa, screen, screen.pages.pin(.{ .active = .{ .y = @intCast(y) } }).?, try blobOf(r, &fresh, h)); - held.items[y] = h; - } - screen.cursorReload(); - screen.cursorAbsolute(@min(cx, t.cols - 1), @min(cy, t.rows - 1)); - screen.cursor.cursor_style = @fromBackingInt(@intCast(style)); - screen.cursor.pending_wrap = wrap != 0; - screen.cursor.semantic_content = @fromBackingInt(@intCast(semantic)); - screen.kitty_keyboard = kitty; - const oldest = r.top -| (primary.pages.total_rows - primary.pages.rows); - primary.pages.scroll(if (viewport == following) .active else .{ .row = @intCast(viewport -| oldest) }); - - // Hold the blobs of this state, and no others. - var keep: std.AutoHashMapUnmanaged(Hash, []u8) = .empty; - errdefer keep.deinit(gpa); - try keep.ensureTotalCapacity(gpa, nrows + tail + 1); - for (0..nrows + tail + 1) |i| { - const h = if (i == nrows + tail) meta else if (i < nrows) - std.mem.readInt(u64, hashes[i * 8 ..][0..8], .little) - else - std.mem.readInt(u64, tails[(i - nrows) * 8 ..][0..8], .little); - if (keep.contains(h)) continue; - const b = if (r.blobs.fetchRemove(h)) |kv| kv.value else try gpa.dupe(u8, try blobOf(r, &fresh, h)); - keep.putAssumeCapacity(h, b); - } - var old = r.blobs.valueIterator(); - while (old.next()) |b| gpa.free(b.*); - r.blobs.deinit(gpa); - r.blobs = keep; - r.seq = seq; - return .{ .seq = seq, .extra = extra }; - } - - /// The holes in `[lo, hi)` blank: until their rows come, a hole shows - /// nothing rather than what that row held before a flood renumbered it. - pub fn blank(r: *const Replica, t: *Terminal, lo: u64, hi: u64) void { - const primary = t.screens.get(.primary).?; - const oldest = r.top -| (primary.pages.total_rows - primary.pages.rows); - for (r.holes.items) |hole| { - const a = @max(lo, hole[0], oldest); - const b = @min(hi, hole[1], r.top); - if (a >= b) continue; - primary.clearRows(.{ .screen = .{ .y = @intCast(a - oldest) } }, .{ .screen = .{ .y = @intCast(b - 1 - oldest) } }, false); - } - } - - /// The holes in `[lo, hi)`: the rows to fetch before showing them. - pub fn missing(r: *const Replica, lo: u64, hi: u64, out: *std.ArrayList([2]u64), gpa: std.mem.Allocator) !void { - for (r.holes.items) |hole| { - const a = @max(lo, hole[0]); - const b = @min(hi, hole[1]); - if (a < b) try out.append(gpa, .{ a, b }); - } - } - - /// The absolute row the viewport of `t`'s primary screen starts at, and - /// how many it shows. - pub fn shown(r: *const Replica, t: *Terminal) [2]u64 { - const pages = &t.screens.get(.primary).?.pages; - const sb = pages.scrollbar(); - const oldest = r.top -| (pages.total_rows - pages.rows); - return .{ oldest + sb.offset, oldest + sb.offset + sb.len }; - } - - /// Write fetched history rows (`encodeRows`) into `t`. - pub fn applyRows(r: *Replica, gpa: std.mem.Allocator, t: *Terminal, bytes: []const u8) !void { - var in: std.Io.Reader = .fixed(bytes); - if (try in.takeInt(u32, .little) != r.epoch) return; // numbered before a resize - const primary = t.screens.get(.primary).?; - var blobs: std.AutoHashMapUnmanaged(Hash, []const u8) = .empty; - defer blobs.deinit(gpa); - for (0..try in.takeInt(u32, .little)) |_| { - const h = try in.takeInt(u64, .little); - try blobs.put(gpa, h, try in.take(try in.takeInt(u32, .little))); - } - for (0..try in.takeInt(u32, .little)) |_| { - const abs = try in.takeInt(u64, .little); - const blob = blobs.get(try in.takeInt(u64, .little)) orelse return error.MissingBlob; - // Only a hole is written: a row the replica holds is the - // authority's already, and newer than what this fetch saw. - if (abs >= r.top or !r.inHole(abs)) continue; - const p = pinOf(&primary.pages, r.top, abs) orelse continue; - try r.writeRow(gpa, primary, p, blob); - try r.fill(gpa, abs); - } - } - - fn inHole(r: *const Replica, abs: u64) bool { - for (r.holes.items) |hole| if (abs >= hole[0] and abs < hole[1]) return true; - return false; - } - - /// Row `abs` is written: out of the holes. - fn fill(r: *Replica, gpa: std.mem.Allocator, abs: u64) !void { - for (r.holes.items, 0..) |*hole, i| { - if (abs < hole[0] or abs >= hole[1]) continue; - if (abs == hole[0]) hole[0] += 1 else if (abs + 1 == hole[1]) hole[1] -= 1 else { - try r.holes.insert(gpa, i + 1, .{ abs + 1, hole[1] }); - r.holes.items[i][1] = abs; - } - if (r.holes.items[i][0] == r.holes.items[i][1]) _ = r.holes.orderedRemove(i); - return; - } - } - - fn trimHoles(r: *Replica, primary: *Screen) void { - clampHoles(&r.holes, r.top -| (primary.pages.total_rows - primary.pages.rows)); - } - - fn writeRow(r: *Replica, gpa: std.mem.Allocator, screen: *Screen, p: Pin, blob: []const u8) !void { - var reader: std.Io.Reader = .fixed(blob); - var dec: snapshot.page.Decoder = undefined; - try dec.init(&reader, try snapshot.record.nextHeader(&reader)); - const src = try scratchPage(&r.scratch, dec.capacity()); - try dec.decode(src, gpa); - if (src.size.cols != screen.pages.cols) return error.BadRow; - _ = screen.clonePartialRowGrowCapacity(p.node, p.y, src, src.getRow(0), 0, src.size.cols); - } -}; - -/// `k` blank rows onto the bottom of a screen's active area, its top `k` -/// going up into the history, as `k` linefeeds at the bottom would. A -/// flood's thousands are grown a row at a time without the cursor (the -/// page list's fast path, a counter), which is put back after. -fn scrollUp(screen: *Screen, k: u64) !void { - if (k == 0) return; - screen.cursorAbsolute(0, screen.pages.rows - 1); - if (k <= screen.pages.rows or screen.no_scrollback or screen.cursor.style_id != 0) { - for (0..@intCast(k)) |_| try screen.cursorDownScroll(); - return; - } - for (0..@intCast(k)) |_| _ = try screen.pages.grow(); - screen.cursorReload(); -} - -/// No row's address: what a row whose content is not known is held as. -const unknown: Hash = std.math.maxInt(Hash); - -/// `rowHash` of a row never written. -fn blankHash(cols: u16) Hash { - var h = std.hash.Wyhash.init(0); - h.update(&.{0}); - h.update(std.mem.asBytes(&cols)); - return h.final(); -} - -/// The terminal-wide state of `next` (a decoded TERMINAL record) into `t`, -/// whose screens and pages stay: what `snapshot.terminal.decode` sets. -fn takeMeta(t: *Terminal, next: *Terminal, io: std.Io, gpa: std.mem.Allocator) !void { - if (t.cols != next.cols or t.rows != next.rows) try t.resize(gpa, .{ .cols = next.cols, .rows = next.rows }); - t.width_px = next.width_px; - t.height_px = next.height_px; - t.scrolling_region = next.scrolling_region; - t.status_display = next.status_display; - t.previous_char = next.previous_char; - t.cursor = next.cursor; - t.modes = next.modes; - t.flags.shell_redraws_prompt = next.flags.shell_redraws_prompt; - t.flags.modify_other_keys_2 = next.flags.modify_other_keys_2; - t.flags.mouse_event = next.flags.mouse_event; - t.flags.mouse_format = next.flags.mouse_format; - t.flags.mouse_shift_capture = next.flags.mouse_shift_capture; - t.flags.password_input = next.flags.password_input; - t.mouse_shape = next.mouse_shape; - t.colors = next.colors; - try t.setPwd(next.getPwd() orelse ""); - try t.setTitle(next.getTitle() orelse ""); - std.mem.swap(@TypeOf(t.tabstops), &t.tabstops, &next.tabstops); - const key = next.screens.active_key; - if (key != t.screens.active_key) { - if (t.screens.get(key) == null) _ = try t.screens.getInit(io, gpa, key, .{ .cols = t.cols, .rows = t.rows, .max_scrollback_bytes = 0 }); - t.screens.switchTo(key); - } -} - -// ---- checks: a replica against its authority, cell for cell ---- - -/// What a row shows, written out value by value (not `rowHash`'s walk): -/// its flags, then each cell's word without its page's ids, its style, its -/// grapheme and its hyperlink's URI. -fn dumpRow(page: *Page, row: *Row, cols: u16, w: *std.Io.Writer) !void { - try w.print("{d}:", .{rowFlags(row)}); - const all = page.getCells(row); - for (all[0..@min(cols, all.len)]) |*c| { - var word = c.*; - word.style_id = 0; - try w.print(" {x}", .{@as(u64, @bitCast(word))}); - if (c.style_id != 0) try snapshot.style.encode(page.styles.get(page.memory, c.style_id).*, w); - if (c.hasGrapheme()) for (page.lookupGrapheme(c).?) |cp| try w.print("+{x}", .{cp}); - if (c.hyperlink) if (page.lookupHyperlink(c)) |id| try w.print("@{s}", .{page.hyperlink_set.get(page.memory, id).uri.slice(page.memory)}); - } - try w.writeByte('\n'); -} - -/// The state a replica must match: the terminal-wide state, the cursor, -/// the history's extent and the viewport, the active screen's rows. -pub fn dumpScreen(t: *Terminal, w: *std.Io.Writer) !void { - const screen = t.screens.active; - const sb = t.screens.get(.primary).?.pages.scrollbar(); - try w.print("{d}x{d} {s} cursor {d},{d} {s} {} {s} title {s} pwd {s} scrollbar {d} {d} {d}\n", .{ - t.cols, t.rows, @tagName(t.screens.active_key), - screen.cursor.x, screen.cursor.y, @tagName(screen.cursor.cursor_style), - screen.cursor.pending_wrap, @tagName(screen.cursor.semantic_content), t.getTitle() orelse "", - t.getPwd() orelse "", sb.total, sb.offset, - sb.len, - }); - try w.writeAll(std.mem.asBytes(&t.modes.values)); - try w.writeAll(std.mem.asBytes(&screen.kitty_keyboard)); - try w.print(" mouse {s} {s} {s}\n", .{ @tagName(t.flags.mouse_event), @tagName(t.flags.mouse_format), @tagName(t.mouse_shape) }); - for (t.colors.palette.current) |c| try w.print("{x}{x}{x}", .{ c.r, c.g, c.b }); - try w.writeByte('\n'); - var it = screen.pages.rowIterator(.right_down, .{ .active = .{} }, null); - while (it.next()) |p| try dumpRow(p.node.page(), p.rowAndCell().row, t.cols, w); -} - -/// An authority and its replica, fed one stream of pty bytes, the deltas -/// and fetches between them at random: a delta encoded at a random step -/// (so the states between are skipped), several in flight and each landing -/// a random number of steps later, in order, one lost now and then (the -/// replica refuses the next and is started afresh), random resizes of the -/// authority, random fetches of holes. After each delta, the replica's -/// screen is the authority's as it was encoded, and every history row it -/// holds outside its holes is what the authority holds at that absolute -/// row. -pub const Soak = struct { - gpa: std.mem.Allocator, - io: std.Io, - a: *Terminal, - stream: vt.TerminalStream, - track: Track, - enc: Encoder, - peer: Peer = .{}, - /// The authority's writes, as terminal.State counts them. - changes: u32 = 0, - b: *Terminal, - rep: Replica = .{}, - prng: std.Random.DefaultPrng, - /// The deltas in flight, oldest first, each with the authority's dump - /// when it was encoded and the step it lands at. - flight: std.ArrayList(struct { delta: []u8, expect: []u8, at: u64 }) = .empty, - got: std.Io.Writer.Allocating, - now: u64 = 0, - resizes: bool = true, - drops: bool = true, - /// The replica refused a delta and the authority started it afresh: - /// what was in flight before is refused too. - refused: bool = false, - stats: struct { deltas: u64 = 0, bytes: u64 = 0, fetched: u64 = 0, history_checked: u64 = 0, lost: u64 = 0, refused: u64 = 0, most_in_flight: u64 = 0 } = .{}, - - pub fn init(gpa: std.mem.Allocator, io: std.Io, cols: u16, rows: u16, scrollback: usize, seed: u64) !*Soak { - const s = try gpa.create(Soak); - errdefer gpa.destroy(s); - const a = try gpa.create(Terminal); - a.* = try Terminal.init(io, gpa, .{ .cols = cols, .rows = rows, .max_scrollback_bytes = scrollback }); - const b = try gpa.create(Terminal); - // Room to spare: its pages may pack rows otherwise, and it keeps the - // authority's history to the row. - b.* = try Terminal.init(io, gpa, .{ .cols = 2, .rows = 2, .max_scrollback_bytes = 2 * scrollback }); - s.* = .{ - .gpa = gpa, - .io = io, - .a = a, - .stream = a.vtStream(), - .track = .init(gpa), - .enc = .init(gpa), - .b = b, - .prng = .init(seed), - .got = .init(gpa), - }; - return s; - } - - pub fn deinit(s: *Soak) void { - const gpa = s.gpa; - s.stream.deinit(); - s.track.deinit(gpa, s.a); - s.a.deinit(gpa); - gpa.destroy(s.a); - s.b.deinit(gpa); - gpa.destroy(s.b); - s.enc.deinit(); - s.peer.deinit(gpa); - s.rep.deinit(gpa); - for (s.flight.items) |f| { - gpa.free(f.delta); - gpa.free(f.expect); - } - s.flight.deinit(gpa); - s.got.deinit(); - gpa.destroy(s); - } - - /// `bytes` into the authority in random pieces, a step after each. - pub fn feed(s: *Soak, bytes: []const u8) !void { - var at: usize = 0; - const random = s.prng.random(); - while (at < bytes.len) { - const n = @min(bytes.len - at, 1 + random.uintLessThan(usize, 512)); - s.stream.nextSlice(bytes[at..][0..n]); - s.changes +%= 1; - at += n; - try s.step(); - } - } - - pub fn step(s: *Soak) !void { - const random = s.prng.random(); - s.now += 1; - if (s.resizes and random.uintLessThan(u32, 200) == 0) { - try s.a.resize(s.gpa, .{ .cols = 10 + random.uintLessThan(u16, 200), .rows = 3 + random.uintLessThan(u16, 60) }); - s.changes +%= 1; - } - // A frame now and then; the states between are skipped. - if (random.boolean()) try s.send(s.now + random.uintLessThan(u64, 12)); - while (s.flight.items.len > 0 and s.flight.items[0].at <= s.now) try s.land(); - if (random.uintLessThan(u32, 8) == 0) try s.fetch(); - } - - /// A delta, if the peer is owed one, sent to land at step `at`. - fn send(s: *Soak, at: u64) !void { - var d: std.Io.Writer.Allocating = .init(s.gpa); - defer d.deinit(); - if (!try encode(&s.enc, &s.track, &s.peer, s.a, s.changes, "extra", &d.writer)) return; - var expect: std.Io.Writer.Allocating = .init(s.gpa); - defer expect.deinit(); - try dumpScreen(s.a, &expect.writer); - const last = if (s.flight.items.len > 0) s.flight.items[s.flight.items.len - 1].at else 0; - try s.flight.append(s.gpa, .{ .delta = try d.toOwnedSlice(), .expect = try expect.toOwnedSlice(), .at = @max(at, last) }); - s.stats.deltas += 1; - s.stats.bytes += s.flight.items[s.flight.items.len - 1].delta.len; - s.stats.most_in_flight = @max(s.stats.most_in_flight, s.flight.items.len); - } - - /// The oldest delta in flight applied (or lost), acknowledged, checked. - fn land(s: *Soak) !void { - const f = s.flight.orderedRemove(0); - defer s.gpa.free(f.delta); - defer s.gpa.free(f.expect); - if (s.drops and s.prng.random().uintLessThan(u32, 50) == 0) { - s.stats.lost += 1; - return; - } - const applied = s.rep.apply(s.gpa, s.io, s.b, f.delta) catch |err| switch (err) { - error.BaseMismatch => { - // Asked once: the authority starts it afresh. - if (!s.refused) s.peer.reset(); - s.refused = true; - s.stats.refused += 1; - return; - }, - else => return err, - }; - s.refused = false; - if (!std.mem.eql(u8, applied.extra, "extra")) return error.ExtraLost; - s.peer.ack(applied.seq); - s.got.clearRetainingCapacity(); - try dumpScreen(s.b, &s.got.writer); - if (!std.mem.eql(u8, f.expect, s.got.written())) { - reportDiff(f.expect, s.got.written()); - return error.ReplicaDiffers; - } - try s.checkHistory(); - } - - /// Everything in flight landed, then a last delta of the end, until the - /// replica holds it: what the replica shows at quiescence. - fn settle(s: *Soak) !void { - s.drops = false; - for (0..4) |_| { - while (s.flight.items.len > 0) try s.land(); - try s.send(0); - if (s.flight.items.len == 0) return; - } - return error.NeverSettled; - } - - /// Every history row the replica holds, outside its holes and inside - /// what the authority still has, is the authority's (rows in history - /// never change; a resize renumbers and starts the replica afresh). - fn checkHistory(s: *Soak) !void { - // Numbered as of now: the authority may have scrolled on since. - try s.track.rows.update(s.a); - if (s.rep.epoch != s.track.rows.epoch) return; - const pages = &s.b.screens.get(.primary).?.pages; - const have = pages.total_rows - pages.rows; - var ra: std.Io.Writer.Allocating = .init(s.gpa); - defer ra.deinit(); - var rb: std.Io.Writer.Allocating = .init(s.gpa); - defer rb.deinit(); - var d: u64 = 1; - while (d <= have) : (d += 1 + d / 8) { - const abs = s.rep.top - d; - if (s.rep.inHole(abs)) continue; - const pb = pinOf(pages, s.rep.top, abs) orelse continue; - const pa = s.track.rows.pinAt(s.a, abs) orelse continue; - ra.clearRetainingCapacity(); - rb.clearRetainingCapacity(); - try dumpRow(pa.node.page(), pa.rowAndCell().row, s.a.cols, &ra.writer); - try dumpRow(pb.node.page(), pb.rowAndCell().row, s.b.cols, &rb.writer); - if (!std.mem.eql(u8, ra.written(), rb.written())) { - std.debug.print("history row {d} ({d} above the top) differs\n", .{ abs, d }); - reportDiff(ra.written(), rb.written()); - return error.ReplicaHistoryDiffers; - } - s.stats.history_checked += 1; - } - } - - /// Some holes fetched from the authority, as a replica scrolled back. - fn fetch(s: *Soak) !void { - if (s.rep.holes.items.len == 0) return; - const random = s.prng.random(); - const hole = s.rep.holes.items[random.uintLessThan(usize, s.rep.holes.items.len)]; - const lo = hole[0] + random.uintLessThan(u64, hole[1] - hole[0]); - const hi = @min(hole[1], lo + 1 + random.uintLessThan(u64, 80)); - s.rep.blank(s.b, lo, hi); - var out: std.Io.Writer.Allocating = .init(s.gpa); - defer out.deinit(); - try encodeRows(&s.enc, &s.track, s.a, lo, hi, &out.writer); - try s.rep.applyRows(s.gpa, s.b, out.written()); - s.stats.fetched += hi - lo; - try s.checkHistory(); - } -}; - -fn reportDiff(want: []const u8, got: []const u8) void { - var wl = std.mem.splitScalar(u8, want, '\n'); - var gl = std.mem.splitScalar(u8, got, '\n'); - var line: usize = 0; - while (true) : (line += 1) { - const a = wl.next(); - const b = gl.next(); - if (a == null and b == null) return; - if (a != null and b != null and std.mem.eql(u8, a.?, b.?)) continue; - std.debug.print("line {d} differs:\n authority {s}\n replica {s}\n", .{ line, a orelse "(none)", b orelse "(none)" }); - return; - } -} - -/// Drive one stream through a soak, then settle: the replica's screen at -/// quiescence is the authority's. -pub fn soak(gpa: std.mem.Allocator, io: std.Io, bytes: []const u8, cols: u16, rows: u16, scrollback: usize, seed: u64, resizes: bool) !@FieldType(Soak, "stats") { - const s = try Soak.init(gpa, io, cols, rows, scrollback, seed); - defer s.deinit(); - s.resizes = resizes; - try s.feed(bytes); - try s.settle(); - return s.stats; -} - -const testing = std.testing; - -/// A shell's: prompts marked (OSC 133), colours of the three kinds, wide -/// and combined graphemes, hyperlinks, tabs, a title and a directory, long -/// lines that wrap, and a clear (ED2, ED3) now and then. -pub fn shellStream(gpa: std.mem.Allocator) ![]u8 { - var out: std.Io.Writer.Allocating = .init(gpa); - errdefer out.deinit(); - const w = &out.writer; - try w.writeAll("\x1b]0;a shell\x07\x1b]7;file://host/home/someone\x07"); - for (0..400) |i| { - try w.print("\x1b]133;A\x07$ \x1b]133;B\x07ls -l {d}\r\n\x1b]133;C\x07", .{i}); - try w.print("\x1b[1;31mred\x1b[0m \x1b[4;38;5;{d}m256\x1b[0m \x1b[38;2;{d};100;200;48;5;17mtrue\x1b[0m 漢字 e\u{301} 👩\u{200d}💻 ", .{ i % 256, i % 256 }); - try w.print("\x1b]8;;https://example.com/{d}\x07link\x1b]8;;\x07\tx\r\n", .{i}); - if (i % 7 == 0) { - for (0..12) |_| try w.writeAll("a long line that wraps "); - try w.writeAll("\r\n"); - } - try w.writeAll("\x1b]133;D;0\x07"); - if (i % 97 == 96) try w.writeAll("\x1b[H\x1b[2J\x1b[3J"); - if (i % 50 == 0) try w.print("\x1b]2;title {d}\x07\x1b]4;1;rgb:{x:0>2}/20/30\x07", .{ i, i % 256 }); - } - return out.toOwnedSlice(); -} - -/// A full-screen program's: the alternate screen and its modes, a status -/// line, a scrolling region scrolled both ways, lines inserted and -/// deleted, cursor shapes, the kitty keyboard pushed and popped. -pub fn tuiStream(gpa: std.mem.Allocator) ![]u8 { - var out: std.Io.Writer.Allocating = .init(gpa); - errdefer out.deinit(); - const w = &out.writer; - try w.writeAll("before the program\r\n\x1b[?1049h\x1b[?25l\x1b[?1000h\x1b[?1006h\x1b[?2004h\x1b[?1h\x1b[>1u\x1b[4 q\x1b[H\x1b[2J"); - for (0..300) |f| { - try w.print("\x1b[1;1H\x1b[44;97m status {d} \x1b[K\x1b[0m", .{f}); - try w.print("\x1b[3;18r\x1b[18;1H\r\n\x1b[3{d}mline {d}\x1b[0m", .{ f % 8, f }); - if (f % 3 == 0) try w.writeAll("\x1b[3;1H\x1bM\x1b[2mreversed in\x1b[0m"); - if (f % 5 == 0) try w.writeAll("\x1b[6;1H\x1b[2L\x1b[9;1H\x1b[M"); - try w.writeAll("\x1b[r"); - try w.print("\x1b[{d};{d}H\x1b[7m*\x1b[0m\x1b[{d}X", .{ 2 + f % 20, 1 + (f * 7) % 70, f % 5 }); - if (f % 11 == 0) try w.writeAll("\x1b[?25h\x1b[6 q") else if (f % 11 == 5) try w.writeAll("\x1b[?25l\x1b[2 q"); - } - try w.writeAll("\x1b[ 10); - fetched += st.fetched; - history += st.history_checked; - } - } - // The holes were fetched, and history rows compared, at all. - try testing.expect(fetched > 0 and history > 0); -} - -test "under a flood a delta is a screen of hashes: an unchanged row costs its address alone" { - const gpa = testing.allocator; - const s = try Soak.init(gpa, testing.io, 200, 60, 1 << 20, 1); - defer s.deinit(); - s.resizes = false; - s.drops = false; - const yes = try yesStream(gpa, 10_000); - defer gpa.free(yes); - var last: []u8 = &.{}; - defer gpa.free(last); - for (0..3) |_| { - s.stream.nextSlice(yes); - s.changes += 1; - try s.send(0); - try testing.expectEqual(@as(usize, 1), s.flight.items.len); - gpa.free(last); - last = try gpa.dupe(u8, s.flight.items[0].delta); - try s.land(); - } - // The last: 60 rows and the tail's 60, of hashes the replica holds, no - // blob; the header and counts around them. - const d = last; - const at = 4 + 4 + 1 + 4 + 8 + 2 + 2 + 1 + 1 + 1 + @sizeOf(KittyFlags) + 8 + 8 + 8 + 2 + "extra".len; - const nrows = std.mem.readInt(u16, d[at..][0..2], .little); - const tail = std.mem.readInt(u16, d[at + 2 + nrows * 8 ..][0..2], .little); - const blobs = std.mem.readInt(u16, d[at + 4 + (nrows + tail) * 8 ..][0..2], .little); - if (d.len >= (nrows + tail) * 8 + 128) std.debug.print("delta {d} bytes: {d} rows, {d} tail, {d} blobs\n", .{ d.len, nrows, tail, blobs }); - try testing.expectEqual(@as(u16, 0), blobs); - try testing.expect(d.len < (nrows + tail) * 8 + 128); - try testing.expect(s.rep.holes.items.len > 0); -} - -test "a reflow to fewer columns keeps every history row numbered at or past 0" { - const gpa = testing.allocator; - const s = try Soak.init(gpa, testing.io, 80, 24, 1 << 20, 3); - defer s.deinit(); - s.resizes = false; - s.drops = false; - // Lines of 69 columns scrolled into the history, then the screen - // narrowed so that each wraps in three: more rows above the last top - // than ever scrolled past it (a window client's font, 2026-10-30: the - // session's peer started afresh at `top - history`, which overflowed). - var line: [80]u8 = undefined; - for (0..200) |i| { - s.stream.nextSlice(try std.fmt.bufPrint(&line, "{d:0>4} xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n", .{i})); - s.changes += 1; - } - try s.send(0); - try s.land(); - try s.a.resize(gpa, .{ .cols = 30, .rows = 24 }); - s.changes += 1; - try s.send(0); - try s.land(); - try s.settle(); - try testing.expect(s.track.rows.top >= s.track.history); -} - -test "several deltas in flight land in order, and a peer at the bound waits for an acknowledgement" { - const gpa = testing.allocator; - const s = try Soak.init(gpa, testing.io, 80, 24, 1 << 20, 2); - defer s.deinit(); - s.resizes = false; - s.drops = false; - var line: [64]u8 = undefined; - for (0..bound + 5) |i| { - s.stream.nextSlice(try std.fmt.bufPrint(&line, "line {d}\r\n", .{i})); - s.changes += 1; - try s.send(1000); - } - // The bound's worth went; the rest wait, and are skipped. - try testing.expectEqual(@as(usize, bound), s.flight.items.len); - try s.land(); - try s.send(1000); - try testing.expectEqual(@as(usize, bound), s.flight.items.len); - try s.settle(); - try testing.expectEqual(@as(u64, 0), s.stats.refused); -} - diff --git a/core/term/term.zig b/core/term/term.zig index 59511727..058154a7 100644 --- a/core/term/term.zig +++ b/core/term/term.zig @@ -1,7 +1,7 @@ //! The terminal, a module of its own (docs/next-terminal.md, Phase 1): //! ghostty-vt's emulator and what pardes keeps beside it (terminal.zig), -//! the screen state its replicas are sent (screen_state.zig), the kitty -//! images it draws (TerminalImages.zig) and the pager's parse (pager.zig). +//! the kitty images it draws (TerminalImages.zig) and the pager's parse +//! (pager.zig). //! It imports std, ghostty-vt, wuffs, zstbi and `plain`, never the core: //! the core reaches it through `ops` (core/Term.zig), the records of //! abi/term.zig in and out. @@ -10,11 +10,8 @@ const plain = @import("plain"); const iface = plain.term; const terminal_ = @import("terminal.zig"); const pager = @import("pager.zig"); -const screen_state_ = @import("screen_state.zig"); const TerminalImages = terminal_.TerminalImages; -/// The screen state replicas are sent, its streams and soak (test/replicas.zig). -pub const screen_state = screen_state_; /// The emulator itself, for the tests that read it through a core /// (test/terminal.zig). pub const terminal = terminal_; @@ -39,7 +36,6 @@ pub const ops: iface.Ops = .{ .scroll = cast(iface.Ops, "scroll", terminal_.scroll), .follow = cast(iface.Ops, "follow", terminal_.follow), .resize = cast(iface.Ops, "resize", terminal_.resize), - .resizeDeferred = cast(iface.Ops, "resizeDeferred", terminal_.resizeDeferred), .cellPixels = cast(iface.Ops, "cellPixels", terminal_.cellPixels), .replies = cast(iface.Ops, "replies", terminal_.replies), .key = cast(iface.Ops, "key", terminal_.key), @@ -57,7 +53,6 @@ pub const ops: iface.Ops = .{ .viewport = cast(iface.Ops, "viewport", terminal_.viewport), .editRows = cast(iface.Ops, "editRows", terminal_.editRows), .promptCut = cast(iface.Ops, "promptCut", terminal_.promptCutAt), - .markRead = cast(iface.Ops, "markRead", terminal_.markRead), .echoCell = cast(iface.Ops, "echoCell", terminal_.echoCell), .page = pager.parse, .filter = terminal_.pagerFilter, @@ -65,32 +60,12 @@ pub const ops: iface.Ops = .{ .paint = cast(iface.Ops, "paint", terminal_.paint), .images = cast(iface.Ops, "images", terminal_.images), .hasImages = cast(iface.Ops, "hasImages", terminal_.hasImages), - .encoder = cast(iface.Ops, "encoder", terminal_.encoder), - .encoderFree = cast(iface.Ops, "encoderFree", terminal_.encoderFree), - .track = cast(iface.Ops, "track", terminal_.track), - .untrack = cast(iface.Ops, "untrack", terminal_.untrack), - .encode = cast(iface.Ops, "encode", terminal_.encode), - .encodeRows = cast(iface.Ops, "encodeRows", terminal_.encodeRows), - .wasRead = cast(iface.Ops, "wasRead", terminal_.wasRead), - .clearRead = cast(iface.Ops, "clearRead", terminal_.clearRead), - .replica = cast(iface.Ops, "replica", terminal_.replica), - .replicaFree = cast(iface.Ops, "replicaFree", terminal_.replicaFree), - .replicaTop = cast(iface.Ops, "replicaTop", terminal_.replicaTop), - .missing = cast(iface.Ops, "missing", terminal_.missing), - .apply = cast(iface.Ops, "apply", terminal_.apply), - .applyRows = cast(iface.Ops, "applyRows", terminal_.applyRows), - .shown = cast(iface.Ops, "shown", terminal_.shown), - .blank = cast(iface.Ops, "blank", terminal_.blank), - .dumpScreen = cast(iface.Ops, "dumpScreen", terminal_.dumpScreen), }; /// The term's handle types as the interface names them, and the module's /// own behind each: a pointer to one is a pointer to the other. const handles = .{ .{ iface.State, terminal_.State }, - .{ iface.Encoder, screen_state_.Encoder }, - .{ iface.Track, screen_state_.Track }, - .{ iface.Replica, screen_state_.Replica }, }; /// The interface's handle for one of this module's own types, or the type @@ -160,5 +135,4 @@ test { _ = &ops; _ = terminal_; _ = pager; - _ = screen_state_; } diff --git a/core/term/terminal.zig b/core/term/terminal.zig index 187ed144..1c54f2ac 100644 --- a/core/term/terminal.zig +++ b/core/term/terminal.zig @@ -5,7 +5,6 @@ const std = @import("std"); const plain = @import("plain"); const Key = plain.Key; const Term = plain.term; -const screen_state = @import("screen_state.zig"); const ghostty_vt = @import("ghostty-vt"); const Ink = plain.term.Ink; @@ -183,18 +182,6 @@ pub const State = struct { reply_dropped: u32 = 0, /// The kitty graphics its program placed, as drawn (TerminalImages.zig). images: TerminalImages = if (images_enabled) .{} else {}, - /// Counts the emulator's writes (output, a resize, its view scrolled): - /// a new count is a new state for its replicas (screen_state.Track). - changes: u32 = 0, - /// A step read its rows (its history too): a replica replaying that - /// step must hold them, so its authority sends the ones it does not - /// before the step's unit (replica.Screens.fill). - read: bool = false, - /// The size a step gave it, on an authority with screen-state replicas: - /// made after the step's unit (`resizeDeferred`), so that the rest of - /// the step reads the grid it had, as its replicas' replays do, and the - /// rows sent them for it (Screens.fill) are of that grid's numbering. - resize_to: ?struct { cols: u16, rows: u16 } = null, /// The stream over the emulator, its answers to the program and its /// size reports routed here, PNG decoded: what `create` and a dump's @@ -338,11 +325,10 @@ pub fn reload(s: *State) !u64 { var reply: [@typeInfo(@FieldType(State, "reply")).array.len]u8 = undefined; @memcpy(reply[0..saved.reply.len], saved.reply); saved.reply = reply[0..saved.reply.len]; - const kept = .{ s.changes, s.read, s.resize_to }; if (comptime images_enabled) s.images.deinit(gpa); s.stream.deinit(); s.vt.deinit(gpa); - s.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined, .changes = kept[0] +% 1, .read = kept[1], .resize_to = kept[2] }; + s.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined }; // Short of room for its sequence in flight it goes on without it (lost // at the next cut), as ghostty's stream does: not worth a terminal. _ = install(s, decoded.continuation, &saved); @@ -470,13 +456,13 @@ pub fn grid(state: ?*const State) Term.Grid { } /// What pardes made of a terminal's stream that its emulator does not hold -/// (the OSC 133 cycle, MarkedHandler), for a replica's delta: phase u8, -/// started, prompts, declined u32, continuation and lost u8, a finished -/// command's seq u32 and status i32 (all ones: none; i32 min: no status). -// ponytail: the output pins stay the authority's (its 9P pty/run reads them). -pub const marks_len = 1 + 4 * 3 + 2 + 4 + 4; +/// (the OSC 133 cycle, MarkedHandler), as bytes two terminals' compare by +/// (`expectSame`): phase u8, started, prompts, declined u32, continuation +/// and lost u8, a finished command's seq u32 and status i32 (all ones: +/// none; i32 min: no status). +const marks_len = 1 + 4 * 3 + 2 + 4 + 4; -pub fn marksOf(state: *const State, buf: *[marks_len]u8) []const u8 { +fn marksOf(state: *const State, buf: *[marks_len]u8) []const u8 { const m = &state.stream.handler; var w: std.Io.Writer = .fixed(buf); w.writeByte(@backingInt(m.phase)) catch unreachable; @@ -487,121 +473,43 @@ pub fn marksOf(state: *const State, buf: *[marks_len]u8) []const u8 { return w.buffered(); } -/// A replica's terminal takes its authority's marks (`marksOf`). -pub fn takeMarks(state: *State, bytes: []const u8) void { - if (bytes.len != marks_len) return; - const m = &state.stream.handler; - m.phase = @fromBackingInt(@intCast(bytes[0])); - m.started = std.mem.readInt(u32, bytes[1..5], .little); - m.prompts = std.mem.readInt(u32, bytes[5..9], .little); - m.declined = std.mem.readInt(u32, bytes[9..13], .little); - m.continuation = bytes[13] != 0; - m.lost = bytes[14] != 0; - const seq = std.mem.readInt(u32, bytes[15..19], .little); - const status = std.mem.readInt(i32, bytes[19..23], .little); - m.finished = if (seq == std.math.maxInt(u32)) null else .{ .seq = seq, .status = if (status == std.math.minInt(i32)) null else status }; -} - -// ---- its replicas: the screen state they are sent (screen_state.zig) ---- - -/// What `peer` is owed of it, a delta against what it was sent (with the -/// marks of its prompt cycle), onto `out`; false when it has it already. -pub fn encode(state: *State, enc: *screen_state.Encoder, tr: *screen_state.Track, peer: *screen_state.Peer, out: *std.Io.Writer) !bool { - var marks: [marks_len]u8 = undefined; - return screen_state.encode(enc, tr, peer, &state.vt, state.changes, marksOf(state, &marks), out); -} - -/// Its rows `lo` to `hi` (absolute), as a replica holding them as holes -/// is sent them. -pub fn encodeRows(state: *State, enc: *screen_state.Encoder, tr: *screen_state.Track, lo: u64, hi: u64, out: *std.Io.Writer) !void { - return screen_state.encodeRows(enc, tr, &state.vt, lo, hi, out); -} - -/// What a session's authority keeps to encode its terminals for its -/// peers, and what it keeps of one terminal for them: made and freed. -pub fn encoder(gpa: std.mem.Allocator) !*screen_state.Encoder { - const e = try gpa.create(screen_state.Encoder); - e.* = .init(gpa); - return e; -} - -pub fn encoderFree(e: *screen_state.Encoder) void { - const gpa = e.gpa; - e.deinit(); - gpa.destroy(e); -} - -pub fn track(gpa: std.mem.Allocator) !*screen_state.Track { - const t = try gpa.create(screen_state.Track); - t.* = .init(gpa); - return t; -} - -/// A replica's side of one terminal: made, freed, where its active area -/// begins, and the history rows `lo..hi` it does not hold. -pub fn replica(gpa: std.mem.Allocator) !*screen_state.Replica { - const r = try gpa.create(screen_state.Replica); - r.* = .{}; - return r; -} - -pub fn replicaFree(r: *screen_state.Replica, gpa: std.mem.Allocator) void { - r.deinit(gpa); - gpa.destroy(r); -} - -pub fn replicaTop(r: *const screen_state.Replica) u64 { - return r.top; -} - -pub fn missing(r: *const screen_state.Replica, lo: u64, hi: u64, out: *std.ArrayList([2]u64), gpa: std.mem.Allocator) !void { - return r.missing(lo, hi, out, gpa); -} - -/// What `track` kept of its versions, freed; `state` null when its pane is -/// gone with the emulator. -/// A peer's track of it let go, and freed (`state` null: it is gone). -pub fn untrack(t: *screen_state.Track, gpa: std.mem.Allocator, state: ?*State) void { - t.deinit(gpa, if (state) |s| &s.vt else null); - gpa.destroy(t); -} - -/// Whether a step read its rows since `clearRead` (`markRead`). -pub fn wasRead(state: *const State) bool { - return state.read; -} - -pub fn clearRead(state: *State) void { - state.read = false; -} - -/// A replica's terminal takes its authority's delta (and the marks riding -/// it); error.BaseMismatch when it is against a state not held here. -pub fn apply(state: *State, rep: *screen_state.Replica, bytes: []const u8) !Term.Applied { - const applied = try rep.apply(state.gpa, terminalIo(), &state.vt, bytes); - takeMarks(state, applied.extra); - return applied; -} - -/// ...and rows it asked for. -pub fn applyRows(state: *State, rep: *screen_state.Replica, bytes: []const u8) !void { - return rep.applyRows(state.gpa, &state.vt, bytes); -} - -/// The absolute rows its view shows on a replica. -pub fn shown(state: *State, rep: *const screen_state.Replica) [2]u64 { - return rep.shown(&state.vt); -} - -/// Its screen as text, every row's cells and flags (the replica tests -/// compare an authority's and a replica's). -pub fn dumpScreen(state: *State, w: *std.Io.Writer) !void { - return screen_state.dumpScreen(&state.vt, w); -} - -/// Rows `lo` to `hi` shown blank on a replica until they come. -pub fn blank(state: *State, rep: *const screen_state.Replica, lo: u64, hi: u64) void { - rep.blank(&state.vt, lo, hi); +/// What a row shows, written out value by value: its flags, then each +/// cell's word without its page's ids, its style, its grapheme and its +/// hyperlink's URI. +fn dumpRow(page: *ghostty_vt.page.Page, row: *ghostty_vt.page.Row, cols: u16, w: *std.Io.Writer) !void { + try w.print("{d}:", .{@as(u8, @intFromBool(row.wrap)) | @as(u8, @intFromBool(row.wrap_continuation)) << 1 | @as(u8, @backingInt(row.semantic_prompt)) << 2}); + const all = page.getCells(row); + for (all[0..@min(cols, all.len)]) |*c| { + var word = c.*; + word.style_id = 0; + try w.print(" {x}", .{@as(u64, @bitCast(word))}); + if (c.style_id != 0) try ghostty_vt.snapshot.style.encode(page.styles.get(page.memory, c.style_id).*, w); + if (c.hasGrapheme()) for (page.lookupGrapheme(c).?) |cp| try w.print("+{x}", .{cp}); + if (c.hyperlink) if (page.lookupHyperlink(c)) |id| try w.print("@{s}", .{page.hyperlink_set.get(page.memory, id).uri.slice(page.memory)}); + } + try w.writeByte('\n'); +} + +/// What an emulator shows, cell for cell: the terminal-wide state, the +/// cursor, the history's extent and the viewport, the active screen's rows +/// (test/replicas.zig compares a client's terminal with its session's by it). +pub fn dumpScreen(t: *ghostty_vt.Terminal, w: *std.Io.Writer) !void { + const screen = t.screens.active; + const sb = t.screens.get(.primary).?.pages.scrollbar(); + try w.print("{d}x{d} {s} cursor {d},{d} {s} {} {s} title {s} pwd {s} scrollbar {d} {d} {d}\n", .{ + t.cols, t.rows, @tagName(t.screens.active_key), + screen.cursor.x, screen.cursor.y, @tagName(screen.cursor.cursor_style), + screen.cursor.pending_wrap, @tagName(screen.cursor.semantic_content), t.getTitle() orelse "", + t.getPwd() orelse "", sb.total, sb.offset, + sb.len, + }); + try w.writeAll(std.mem.asBytes(&t.modes.values)); + try w.writeAll(std.mem.asBytes(&screen.kitty_keyboard)); + try w.print(" mouse {s} {s} {s}\n", .{ @tagName(t.flags.mouse_event), @tagName(t.flags.mouse_format), @tagName(t.mouse_shape) }); + for (t.colors.palette.current) |c| try w.print("{x}{x}{x}", .{ c.r, c.g, c.b }); + try w.writeByte('\n'); + var it = screen.pages.rowIterator(.right_down, .{ .active = .{} }, null); + while (it.next()) |p| try dumpRow(p.node.page(), p.rowAndCell().row, t.cols, w); } /// Its view to row `at` of its history (from the top), or onto its output. @@ -612,43 +520,26 @@ pub fn viewTo(state: *State, at: ?usize) void { /// Its view moved by `delta` rows (negative scrolls back). pub fn scroll(state: *State, delta: i32) void { state.vt.screens.active.scroll(.{ .delta_row = delta }); - state.changes +%= 1; } /// Its view back onto the output. pub fn follow(state: *State) void { - const moved = state.vt.screens.active.pages.viewport != .active; state.vt.screens.active.scroll(.active); - state.changes +%= @intFromBool(moved); } -/// Its grid reflowed to `cols` by `rows`, now or, `later`, when -/// `resizeDeferred` is called. A failed reflow keeps the grid it had -/// rather than dropping a scrollback; the next resize retries with the -/// same numbers. -pub fn resize(state: *State, cols: u16, rows: u16, later: bool) void { - if (later) { - state.resize_to = .{ .cols = cols, .rows = rows }; - return; - } +/// Its grid reflowed to `cols` by `rows`. A failed reflow keeps the grid +/// it had rather than dropping a scrollback; the next resize retries with +/// the same numbers. +pub fn resize(state: *State, cols: u16, rows: u16) void { reflow(state, cols, rows); } -/// The size `resize` left for later, made; whether there was one. -pub fn resizeDeferred(state: *State) bool { - const size = state.resize_to orelse return false; - state.resize_to = null; - reflow(state, size.cols, size.rows); - return true; -} - /// Its grid reflowed, and its view a row of its history again, as `viewTo` /// and `grid` have it: ghostty's view follows a cell, which a widening /// can leave mid-row (a wrapped line's second row joined to its first) and /// the next narrowing carries a row down, where a view put back at its row /// (a replica's rollback, core/replica.zig `putViews`) stays. fn reflow(state: *State, cols: u16, rows: u16) void { - state.changes +%= 1; state.vt.resize(state.gpa, .{ .cols = cols, .rows = rows }) catch {}; inline for (.{ .primary, .alternate }) |which| if (state.vt.screens.get(which)) |screen| { if (screen.pages.viewport == .pin) screen.pages.viewport_pin.x = 0; @@ -891,7 +782,6 @@ pub fn revive(state: *State) void { /// then apply different views. fn ingest(state: *State, bytes: []const u8) void { state.stream.nextSlice(bytes); - state.changes +%= 1; } const RowPin = struct { pin: ?*ghostty_vt.Pin = null, offset: i32 = 0 }; @@ -1227,12 +1117,6 @@ pub fn editRows(state: *State, arena: std.mem.Allocator, first: usize, count: us return shell; } -/// A step read its rows (its history too): a replica replaying the step -/// must hold them (`State.read`). -pub fn markRead(state: *State) void { - state.read = true; -} - /// Its rows from the top of its history as text, a prompt's own cells cut /// off the rows it starts (what typed text stays), joined by '\n' in /// `text` with `rows` slices into it and one empty row after them, the @@ -1616,10 +1500,10 @@ test "a view put back at the row it reports is the view it was, through a reflow // Lines two rows long at 20 columns, one at 40. for (0..30) |_| ingest(s, "abcdefghijklmnopqrstuvwxyz0123\r\n"); viewTo(s, 1); - resize(s, 40, 2, false); + resize(s, 40, 2); } viewTo(put, grid(put).view); - for ([_]*State{ left, put }) |s| resize(s, 20, 2, false); + for ([_]*State{ left, put }) |s| resize(s, 20, 2); try std.testing.expectEqual(grid(left), grid(put)); } @@ -1751,8 +1635,8 @@ fn feedReflowing(s: *State, bytes: []const u8, from: usize, to: usize, stops: [2 const rows = s.vt.rows; var at = from; while (at < to) { - if (at == stops[0]) resize(s, cols / 2 + 1, rows + 3, false); - if (at == stops[1]) resize(s, cols * 2 - 2, rows - 3, false); + if (at == stops[0]) resize(s, cols / 2 + 1, rows + 3); + if (at == stops[1]) resize(s, cols * 2 - 2, rows - 3); var end = @min(to, at + 4096); for (stops) |stop| if (at < stop and stop < end) { end = stop; diff --git a/test/replicas.zig b/test/replicas.zig index aa10d4a9..f4d8d450 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -39,7 +39,7 @@ const pardes = @import("pardes"); const replica = pardes.replica; const client_loop = @import("runtime").client; const session_loop = @import("runtime").session; -const screen_state = @import("term").screen_state; +const term = @import("term"); const Echo = pardes.Echo; const Key = pardes.Key; @@ -440,10 +440,10 @@ fn writeText(path: [:0]const u8, text: []const u8) !void { const Run = struct { seed: u64, rtt_ms: u64, steps: usize, clients: u16, flood_mb: u64 }; /// The terminal pane's screen as a hash of a dump of its cells. -fn screenHash(t: *screen_state.Terminal) u64 { +fn screenHash(t: anytype) u64 { var buf: [8192]u8 = undefined; var h: std.Io.Writer.Hashing(std.hash.Wyhash) = .initHasher(.init(0), &buf); - screen_state.dumpScreen(t, &h.writer) catch {}; + term.terminal.dumpScreen(t, &h.writer) catch {}; h.writer.flush() catch {}; return h.hasher.final(); } @@ -2125,9 +2125,9 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { // What the shell's program prints: a full-screen program, a shell's // session (prompts, titles, directories, a clear now and then), then a // flood of `yes` and of a `cat`, read 4 KB at a time as a pty gives it. - const tui = try screen_state.tuiStream(gpa); + const tui = try tuiStream(); defer gpa.free(tui); - const session_only = try screen_state.shellStream(gpa); + const session_only = try shellStream(); defer gpa.free(session_only); const shell_session = try std.mem.concat(gpa, u8, &.{ session_only, questions }); defer gpa.free(shell_session); @@ -2140,7 +2140,7 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { _ = shm.shm_unlink(object); } } - const yes_only = try screen_state.yesStream(gpa, @intCast(r.flood_mb * (1 << 20) / 3)); + const yes_only = try yesStream(@intCast(r.flood_mb * (1 << 20) / 3)); defer gpa.free(yes_only); const yes = try std.mem.concat(gpa, u8, &.{ yes_only, shown }); defer gpa.free(yes); @@ -2263,6 +2263,56 @@ fn images(dir: []const u8, seed: u64, media: *Media) ![]u8 { /// `before`, then `n` bytes of what a `cat` of source text prints through a /// pty: this file's lines, CR LF after each, again and again. +/// A shell's: prompts marked (OSC 133), colours of the three kinds, wide +/// and combined graphemes, hyperlinks, tabs, a title and a directory, long +/// lines that wrap, and a clear (ED2, ED3) now and then. +fn shellStream() ![]u8 { + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + const w = &out.writer; + try w.writeAll("\x1b]0;a shell\x07\x1b]7;file://host/home/someone\x07"); + for (0..400) |i| { + try w.print("\x1b]133;A\x07$ \x1b]133;B\x07ls -l {d}\r\n\x1b]133;C\x07", .{i}); + try w.print("\x1b[1;31mred\x1b[0m \x1b[4;38;5;{d}m256\x1b[0m \x1b[38;2;{d};100;200;48;5;17mtrue\x1b[0m 漢字 e\u{301} 👩\u{200d}💻 ", .{ i % 256, i % 256 }); + try w.print("\x1b]8;;https://example.com/{d}\x07link\x1b]8;;\x07\tx\r\n", .{i}); + if (i % 7 == 0) { + for (0..12) |_| try w.writeAll("a long line that wraps "); + try w.writeAll("\r\n"); + } + try w.writeAll("\x1b]133;D;0\x07"); + if (i % 97 == 96) try w.writeAll("\x1b[H\x1b[2J\x1b[3J"); + if (i % 50 == 0) try w.print("\x1b]2;title {d}\x07\x1b]4;1;rgb:{x:0>2}/20/30\x07", .{ i, i % 256 }); + } + return out.toOwnedSlice(); +} + +/// A full-screen program's: the alternate screen and its modes, a status +/// line, a scrolling region scrolled both ways, lines inserted and +/// deleted, cursor shapes, the kitty keyboard pushed and popped. +fn tuiStream() ![]u8 { + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + const w = &out.writer; + try w.writeAll("before the program\r\n\x1b[?1049h\x1b[?25l\x1b[?1000h\x1b[?1006h\x1b[?2004h\x1b[?1h\x1b[>1u\x1b[4 q\x1b[H\x1b[2J"); + for (0..300) |f| { + try w.print("\x1b[1;1H\x1b[44;97m status {d} \x1b[K\x1b[0m", .{f}); + try w.print("\x1b[3;18r\x1b[18;1H\r\n\x1b[3{d}mline {d}\x1b[0m", .{ f % 8, f }); + if (f % 3 == 0) try w.writeAll("\x1b[3;1H\x1bM\x1b[2mreversed in\x1b[0m"); + if (f % 5 == 0) try w.writeAll("\x1b[6;1H\x1b[2L\x1b[9;1H\x1b[M"); + try w.writeAll("\x1b[r"); + try w.print("\x1b[{d};{d}H\x1b[7m*\x1b[0m\x1b[{d}X", .{ 2 + f % 20, 1 + (f * 7) % 70, f % 5 }); + if (f % 11 == 0) try w.writeAll("\x1b[?25h\x1b[6 q") else if (f % 11 == 5) try w.writeAll("\x1b[?25l\x1b[2 q"); + } + try w.writeAll("\x1b[ Date: Sun, 22 Nov 2026 10:39:52 -0300 Subject: tape: no screen-state branch left, and a terminal's kitty images are each side's own emulator's again (the old road's deletion, piece 6 of 8): core/tape.zig loses `Tape.screen_state` and every branch on it (a terminal's output recorded without its bytes, the positions and prompt checks skipped, `screenReplica`, `screenAuthority`, `screenState`, `viewOnly`, which on the one road did nothing), and the tape site `images`; core/panes.zig its replica branches (a feed skipped and the session's positions taken, a view's scroll or follow noted, a resize left to the authority, the reloads at a join skipped); core/Term.zig a terminal's digest that returned early under screen state, and the medium read that went past the tape; core/dump.zig a join's dump always holds each terminal whole (`slim_terminals` stays for the exit dump); the tests' `t.screen_state = false` lines (4 in core/replica.zig, 3 in test/replicas.zig); THE IMAGES (the brief's choice): `Pane.term_images` and its taped read after each output (pardes-image-loop's cure for a screen-state client, whose emulator never held an image) go, the tag reads `Term.hasImages` again (core/tagline.zig), and a terminal's digest holds whether it has an image (core/term/terminal.zig `digest`: one bool among its facts), so the fact the tag shows is covered by the digest it is computed from (S1's rule) rather than by a pane field copied after each output, and a parting over it is named at the terminal; abi/wire.zig's line for 30 says so (the dump's shape changed with it); the image-loop's test runs on the one road (the client's emulator has the image, its tag says what the session's does); core-test 911/1068 (157 skipped), shell-test 1110/1113, term-test 15/15, pane-test 181/182, kitty-test 45/45, the soak's small run and `--echo` rc 0 (diverged 0, unequal 0, corpus 22) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- abi/wire.zig | 6 ++++-- core/Core.zig | 1 - core/Term.zig | 8 +------ core/dump.zig | 17 ++++++--------- core/echo.zig | 2 +- core/panes.zig | 30 +++----------------------- core/replica.zig | 4 ---- core/tagline.zig | 2 +- core/tape.zig | 57 +++----------------------------------------------- core/term/terminal.zig | 3 ++- test/replicas.zig | 3 --- 11 files changed, 21 insertions(+), 112 deletions(-) diff --git a/abi/wire.zig b/abi/wire.zig index 48b3ae51..8f7a7bdb 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -11,8 +11,10 @@ const config = @import("pardes_options"); const build_info = @import("build_info"); /// 30: the terminals' one road: the screen-state messages are retired (a -/// replica's `screen_ack`, 0x04, and the session's `screen`, 0x06: gaps) -/// and a welcome says no road (its `bytes` byte gone); +/// replica's `screen_ack`, 0x04, and the session's `screen`, 0x06: gaps), +/// a welcome says no road (its `bytes` byte gone), and a pane's +/// `term_images` and its tape site leave the dump (each side's emulator +/// answers; a terminal's digest holds whether it has an image); /// 29: a session's terminals reach its clients as the pty's bytes in its /// units, each client's emulator its own; a welcome says the road (`bytes`; /// screen state under PARDES_TERM_SCREEN), which the client loads its dump diff --git a/core/Core.zig b/core/Core.zig index 4c8c98dd..91f647d4 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -1685,7 +1685,6 @@ fn updateInner(p: *Pardes, ev: Event) void { pane.shell_spoke = true; ctlfs.events.notePtyOutput(p, o.pane.index(), o.bytes); pane.feedOutput(p, o.bytes); - pane.term_images = if (p.tape.screen_state) p.tape.value(.images, pardes.Term.hasImages, .{pane.terminal}) else pardes.Term.hasImages(pane.terminal); ctlfs.pty.noteMarks(p, o.pane.index(), pane); exec.flushReplEnter(p, o.pane.index(), true); }, diff --git a/core/Term.zig b/core/Term.zig index 86c7518b..968a8d68 100644 --- a/core/Term.zig +++ b/core/Term.zig @@ -68,11 +68,7 @@ pub const State = struct { written: bool = true, /// The emulator as its program has made it, for the replay digest. - /// Under screen-state terminals the emulator is the authority's, and a - /// replica's is what the last delta made it: compared as screens - /// (test/replicas.zig), not step by step. pub fn digest(s: *const State, h: *walk.Hasher) void { - if (tape.screenState()) return; s.digestScreen(h, true); } @@ -135,10 +131,8 @@ pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State { /// session's machine's) as its emulator reads it, made the tape's answer /// (P30: the device's answer as it was, as a file's bytes are): the session /// reads it, a temporary file deleted and shared memory unlinked there once, -/// and every replica is handed the same bytes, or the same failure. Under -/// screen state a replica feeds no emulator: the read is the session's. +/// and every replica is handed the same bytes, or the same failure. fn media(ctx: *const anyopaque, read: *const fn (*const anyopaque) iface.MediumError![]u8, gpa: std.mem.Allocator) iface.MediumError![]u8 { - if (tape.screenState()) return read(ctx); return tape.valueIn(.medium, gpa, readMedium, .{ read, ctx }); } diff --git a/core/dump.zig b/core/dump.zig index 18ac28f7..c3742a21 100644 --- a/core/dump.zig +++ b/core/dump.zig @@ -255,16 +255,12 @@ pub fn image(p: *Pardes, name: []const u8) ![]u8 { return pardes.Db.image(gpa, name, buf.written(), w.blobs.items, panes, names.written()); } -/// A dump for a screen-state replica's join (core/replica.zig): its blobs' -/// bytes left out and noted in `deferred` (they are the session's, alive -/// while pinned: memory.zig `pin`), its terminals' emulators left out (the -/// first delta brings each afresh). What is left is the session's mutable -/// state, made in its step. +/// A dump for a replica's join (core/replica.zig): its blobs' bytes left +/// out and noted in `deferred` (they are the session's, alive while pinned: +/// memory.zig `pin`), each terminal whole (as the join's step reloaded it +/// on every side: panes.reloadTerminals), its sequence in flight with it. +/// What is left is the session's mutable state, made in its step. pub fn dumpJoin(p: *Pardes, deferred: *std.ArrayListUnmanaged(walk.Deferred)) ![]u8 { - // Under bytes, each terminal whole (as the join's step reloaded it on - // every side: panes.reloadTerminals), its sequence in flight with it. - slim_terminals = p.tape.screen_state; - defer slim_terminals = false; // The join's file reads are the session's host's, between its steps: // with its io, which the core's tape holds (a walk's hook takes no more). join_files = p.tape.io; @@ -272,8 +268,7 @@ pub fn dumpJoin(p: *Pardes, deferred: *std.ArrayListUnmanaged(walk.Deferred)) ![ return dumpWith(p, deferred); } -/// `dumpJoin`'s under screen state and `dumpExit`'s: a terminal dumps its -/// size, not its emulator. +/// `dumpExit`'s: a terminal dumps its size, not its emulator. pub var slim_terminals = false; /// `dumpJoin`'s: a plain kind's pane carries its file (SlotRecord.file), /// read with this io. diff --git a/core/echo.zig b/core/echo.zig index e2a6521c..3b59788d 100644 --- a/core/echo.zig +++ b/core/echo.zig @@ -49,7 +49,7 @@ const never = std.math.maxInt(u64); const max = 64; /// A cell predicted: `cp` at column `x` of absolute row `row` (the -/// authority's numbering, screen_state's), a space for a cell backspace +/// authority's numbering), a space for a cell backspace /// cleared; `was` what the screen showed there before; `seq` the key's. pub const Cell = struct { x: u16, row: u64, cp: u21, was: u21, seq: u32, due: u64 = never }; pub const Cursor = struct { x: u16, row: u64, seq: u32, due: u64 = never }; diff --git a/core/panes.zig b/core/panes.zig index d58bf30b..a2e383c1 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -134,11 +134,6 @@ pub const Pane = struct { /// cell), and its kitty graphics drawn as glyph art (Petscii). term_mouse: ?Term.Coordinate = null, term_petscii: bool = false, - /// Whether its terminal holds a kitty image, as the session's emulator - /// said after its program's last output (taped under screen state: a - /// client's emulator is fed the session's cells, never an image). Its - /// tag says so (tagline.zig), on every side. - term_images: bool = false, gpa: std.mem.Allocator, serial: u32 = 0, /// What the control filesystem keeps of this pane -- addr and limit, the @@ -642,7 +637,6 @@ pub const Pane = struct { } } else if (pane.addon == null) { // the vt scrolls in SHELL rows; convert through the edit buffer - if (tape.viewOnly("scroll a terminal")) return; const state = pane.terminal orelse return; const off: i32 = @intCast(Term.grid(state).offset); Term.scroll(state, pane.gridRow(pane.surfRow(off) + delta) - off); @@ -743,12 +737,6 @@ pub const Pane = struct { const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or pane.body.nsel > 0 or pane.body.last_edit != null or pane.look_at != null or pane.body.ed_undo_len > 0 or pane.body.ed_redo_len > 0 or pane.pointerRowCount() > 0; - // A replica's emulator is what the authority's deltas make it; what - // pardes keeps over it moves as the authority's feed told it. - if (tape.screenReplica()) { - if (has_positions and pane.followRows(state, bytes)) if (paneIdOf(p, pane)) |id| p.setMessage(.at(id), positions_lost); - return; - } // Sticky bottom, as every other terminal does it: output drags the // viewport down only when the viewport was already on the last row, // so a reader scrolled back into the scrollback stays where they @@ -768,7 +756,6 @@ pub const Pane = struct { /// pointer's rows) moved as the rows move (`Term.Told`). True when one /// could not be kept (no memory for its pin). fn followRows(pane: *Pane, state: *Term.State, bytes: []const u8) bool { - const on_replica = tape.screenReplica(); const Group = struct { overlay: ?*Text.EditBuffer, cursor: *i32, selection: *Text.CharSel }; var groups: [Text.history_max * 2 + 1]Group = undefined; groups[0] = .{ @@ -879,13 +866,7 @@ pub const Pane = struct { track[k] = at.grid; k += 1; }; - // A replica's emulator is fed by its authority's deltas: it is told - // what the authority's feed told. - const fed: Term.Told = if (on_replica) told: { - @memset(rows_after, 0); - @memset(erased_after, false); - break :told .{ .rows = rows_after, .erased = erased_after, .cleared = false, .alive = false, .failed = false }; - } else Term.feed(state, bytes, track, rows_after, erased_after); + const fed = Term.feed(state, bytes, track, rows_after, erased_after); const after = tape.value(.positions, keepTold, .{Term.Told{ .rows = fed.rows, .erased = fed.erased, .cleared = fed.cleared, .alive = fed.alive, .failed = failed or fed.failed }}); if (after.rows.len != n or after.erased.len != n) return false; // a replica its authority's states apart (diverged) failed = after.failed; @@ -967,7 +948,7 @@ pub const Pane = struct { } fn feedLost(state: *Term.State, bytes: []const u8) bool { - if (!tape.screenReplica()) _ = Term.feed(state, bytes, &.{}, &.{}, &.{}); + _ = Term.feed(state, bytes, &.{}, &.{}, &.{}); return true; } @@ -981,14 +962,11 @@ pub const Pane = struct { /// Its terminal's view snapped back onto live output. pub fn followOutput(pane: *Pane) void { - if (tape.viewOnly("follow a terminal")) return; const state = pane.terminal orelse return; Term.follow(state); } - /// Its terminal's grid reflowed to `cols` by `rows`: on a screen-state - /// replica by its authority (the next delta says), on such an authority - /// once the step's unit is out (`resizeDeferred`). + /// Its terminal's grid reflowed to `cols` by `rows`. pub fn resizeGrid(pane: *Pane, cols: u16, rows: u16) void { // A client's speculation does what its replay does (its // selections) but the grid: it waits for no round trip. Under bytes @@ -999,7 +977,6 @@ pub const Pane = struct { pane.clearPointerSelection(button); pane.sel[button].state = .none; }; - if (tape.screenReplica()) return; if (tape.speculating()) return tape.touchTerminal(); Term.resize(state, cols, rows); } @@ -1152,7 +1129,6 @@ pub const positions_lost = "terminal edit position reset: out of memory"; /// session's snapshot's hash is taped, and each replica's own compared /// with it: a check of the whole emulator at every join. pub fn reloadTerminals(p: *Pardes) void { - if (tape.screenState()) return; for (p.panes) |slot| if (slot) |pane| if (pane.terminal) |state| { if (!tape.value(.reload, written, .{state})) continue; // Its cells' size in pixels as a feed sets it (`feedOutput`): a diff --git a/core/replica.zig b/core/replica.zig index 55e7a1f7..e9e29de0 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -4053,7 +4053,6 @@ test "bytes: a client joins from a dump with its terminals whole, and every side try std.testing.expect(pardes.Term.writes != reloads); const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); defer late.deinit(); - late.t.screen_state = false; late.core().echo = null; try std.testing.expectEqual(joined.digest, late.digest()); b.a.output(.{ .output = .{ .pane = b.shell, .bytes = ";30mthe rest of it\x1b[0m\r\n" } }); @@ -4377,7 +4376,6 @@ test "bytes: a join reloads only the terminals written since their last reload: try std.testing.expectEqual(2, pardes.Term.reloads.n - before); const late = try Replica.initDump(gpa, 3, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); defer late.deinit(); - late.t.screen_state = false; late.core().echo = null; try std.testing.expectEqual(joined.digest, late.digest()); // Output into both until each has pruned its history (whole pages, by @@ -7190,7 +7188,6 @@ test "a client joined from a dump takes a 9P pty/run in a shell as the session d r.confirm(joined.unit); const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); defer late.deinit(); - late.t.screen_state = false; late.core().echo = null; try std.testing.expectEqual(joined.digest, late.digest()); const node = pardes.ctlfs.Node.of(a.core.panes[shell].?.serial, .pty_run); @@ -7376,7 +7373,6 @@ const NinepJoin = struct { const joined = (try n.a.join(1, null)).?; defer std.testing.allocator.free(joined.dump); const r = try Replica.initDump(std.testing.allocator, 1, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); - r.t.screen_state = false; r.core().echo = null; n.late = r; try std.testing.expectEqual(joined.digest, r.digest()); diff --git a/core/tagline.zig b/core/tagline.zig index 26f83fba..02d1b277 100644 --- a/core/tagline.zig +++ b/core/tagline.zig @@ -160,7 +160,7 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co if (pane.terminal != null) { const chosen = pane.term_petscii; const on = chosen or !p.view().frontend.native_images; - if (chosen or pane.term_images) + if (chosen or pardes.Term.hasImages(pane.terminal)) return std.fmt.allocPrint(arena, "{s} petscii:{s}", .{ (try shownDir(arena, pane)), if (on) "on" else "off" }); } return (try shownDir(arena, pane)); diff --git a/core/tape.zig b/core/tape.zig index 5056f225..1cbf8aed 100644 --- a/core/tape.zig +++ b/core/tape.zig @@ -140,9 +140,6 @@ pub const Site = enum(u16) { /// A kitty image's medium as a terminal's emulator read it (a file, a /// temporary file, shared memory: Term.media), its bytes or its failure. medium, - /// Whether a terminal holds a kitty image after its program's output - /// (Pane.term_images): a screen-state replica's emulator never has one. - images, }; /// What the sites return. wire.semantics hashes their shape with the @@ -311,13 +308,6 @@ pub const Tape = struct { dump_check: bool = false, dumps: usize = 0, dump_bytes: usize = 0, - /// Screen-state terminals (core/term/screen_state.zig, docs/next-daemon.md - /// phase 5): an authority recording for replicas, or a replica. A - /// terminal's emulator is the authority's alone: its output is recorded - /// without its bytes (they cross as screen state), its pty writes are - /// not recorded, and no digest covers it. A replica's core never writes - /// one but by `apply`. - screen_state: bool = false, /// The session's (replica.Peers): called between two of its inputs once /// what it recorded since its last unit passes `unit_max`, to send that /// as a unit: a pump of a flood's reads is cut into units under it. @@ -423,12 +413,7 @@ pub const Tape = struct { t.noteWrites(); t.noteHost(core); } - // A terminal's output crosses as screen state, not as its bytes. - if (t.screen_state and input.* == .update and input.update.args[0] == .output) { - var bare = input.*; - bare.update.args[0].output.bytes = &.{}; - t.record(.input, Input, &bare); - } else t.record(.input, Input, input); + t.record(.input, Input, input); return .{ .tape = t }; } @@ -806,12 +791,12 @@ pub const Tape = struct { // output) is the session's answer, kept, and a replica whose // emulators are fed the same bytes asks its own and compares: a // check a unit, for nothing (P30: a digest, not state). - if (comptime s == .positions or s == .prompt) if (!t.screen_state) { + if (comptime s == .positions or s == .prompt) { const mine = @call(.auto, f, full); t.scratch.clearRetainingCapacity(); walk.encode(R, &mine, &t.scratch.writer) catch @panic("tape: out of memory"); if (!std.mem.eql(u8, t.scratch.written(), t.last_ret.bytes[t.last_ret.at..])) t.diverge("what this replica's terminal told ({t}) is not what the session's did", .{s}); - }; + } var ret = t.last_ret; return walk.decode(R, &ret, a orelse t.arena.allocator()) catch { t.diverge("the tape's answer to {t} is short", .{s}); @@ -885,17 +870,6 @@ pub const Tape = struct { return t.depth > 0 or t.replay or t.speculating; } - /// A replica's core under screen-state terminals: its emulators are - /// written by `apply` alone, never by its own steps. - pub fn screenReplica(t: *const Tape) bool { - return t.screen_state and (t.replay or t.speculating); - } - - /// An authority recording for screen-state replicas. - pub fn screenAuthority(t: *const Tape) bool { - return t.screen_state and !t.replay and !t.speculating; - } - /// What a speculation reached is the authority's (`why`): the input is /// undone and waits for the authority's order. pub fn poison(t: *Tape, why: []const u8) void { @@ -913,14 +887,6 @@ pub const Tape = struct { return true; } - /// A speculation that moves a terminal's view: it may (its rollback - /// puts the view back, replica.zig `views`); a screen-state replica's - /// says it did (a delta sets the view again). - pub fn viewOnly(t: *Tape, comptime _: []const u8) bool { - if (t.speculating and t.screen_state) t.touched = true; - return false; - } - /// A speculation read a terminal's rows or moved its view (`Tape.touched`). pub fn touchTerminal(t: *Tape) void { if (t.speculating) t.touched = true; @@ -1356,19 +1322,6 @@ pub fn stepping() bool { return (on orelse &none).stepping(); } -/// Screen-state terminals, on either side (`Tape.screen_state`). -pub fn screenState() bool { - return (on orelse &none).screen_state; -} - -pub fn screenReplica() bool { - return (on orelse &none).screenReplica(); -} - -pub fn screenAuthority() bool { - return (on orelse &none).screenAuthority(); -} - pub fn poison(why: []const u8) void { (on orelse &none).poison(why); } @@ -1383,10 +1336,6 @@ pub fn authorityOnly(comptime why: []const u8) bool { return (on orelse &none).authorityOnly(why); } -pub fn viewOnly(comptime why: []const u8) bool { - return (on orelse &none).viewOnly(why); -} - pub fn touchTerminal() void { (on orelse &none).touchTerminal(); } diff --git a/core/term/terminal.zig b/core/term/terminal.zig index 1c54f2ac..f130d7b9 100644 --- a/core/term/terminal.zig +++ b/core/term/terminal.zig @@ -211,7 +211,8 @@ pub fn digest(s: *const State, h: *std.hash.Wyhash, view: bool) void { const sb = screen.pages.scrollbar(); const cur = screen.cursor; const offset = if (view) sb.offset else 0; - const facts = .{ sb.total, offset, sb.len, cur.x, cur.y, s.vt.modes.get(.cursor_visible), s.vt.screens.active_key, s.reply_dropped }; + // Whether it holds a kitty image: the tag says so (tagline.zig). + const facts = .{ sb.total, offset, sb.len, cur.x, cur.y, s.vt.modes.get(.cursor_visible), s.vt.screens.active_key, s.reply_dropped, hasImages(s) }; inline for (facts) |fact| h.update(std.mem.asBytes(&fact)); h.update(s.reply[0..s.reply_len]); var buf: [4096]u8 = undefined; diff --git a/test/replicas.zig b/test/replicas.zig index f4d8d450..90f7c10d 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -984,7 +984,6 @@ const Witness = struct { // No client's id: every unit is another's. const rp = try replica.Replica.initDump(gpa, std.math.maxInt(u16), d.view, d.bytes, .{ .cols = d.cols, .rows = d.rows, .distrusted = &distrusted }); rp.guess = false; - rp.t.screen_state = false; rp.core().echo = null; rp.t.local_files = true; return rp; @@ -1950,7 +1949,6 @@ const Soak = struct { } } // Its terminals its own emulators, fed what the units carry. - rp.t.screen_state = false; rp.core().echo = null; rp.stats.samples = true; rp.t.local_files = true; @@ -3533,7 +3531,6 @@ fn corpusCase(dir: []const u8) !bool { defer gpa.free(j.dump); const rp = try replica.Replica.initDump(gpa, 1, j.view, j.dump, .{ .cols = 100, .rows = 22 }); defer rp.deinit(); - rp.t.screen_state = false; var fds: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; defer for (fds) |fd| { -- cgit v1.3 From 292ddaaa29a8253ea1672572496c2693ba24d820 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 22 Nov 2026 10:43:59 -0300 Subject: echo: judged when a terminal is fed, its delta's entry folded in (the old road's deletion, piece 7 of 8; echo.zig STAYS, round 7's ruling): `Echo.delta` had one caller left, `fed` (the screen-state replica's `screen` went in piece 3), so its body is `fed`'s, judged at the grid's active top on the echo's own pane; the words that said `delta` (the module's doc, `grace_ns`, `stale_ns`, `tops`, the Rig's comments) say output; nothing else changes; core-test 911/1068, shell-test 1110/1113 (the Rig's tests among them), `--echo --seeds 2 --rtt 30,207` rc 0 (30 ms: 50.1 -> 8.5 ms p50 with prediction; 207 ms: 239.3 -> 8.6; diverged 0, unequal 0, secret frames 0, drawn wrong 0) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/echo.zig | 51 +++++++++++++++++++++++---------------------------- 1 file changed, 23 insertions(+), 28 deletions(-) diff --git a/core/echo.zig b/core/echo.zig index 3b59788d..93b877b8 100644 --- a/core/echo.zig +++ b/core/echo.zig @@ -18,9 +18,10 @@ //! never drawn where the completion was not. //! //! Judged as mosh does, once the authority confirmed the key and `grace` -//! passed: at a delta, a cell the screen shows goes, and one it does not is -//! a misprediction, and every prediction goes. With no delta (nothing -//! changed: no echo), a frame judges it `stale` later. Shown at once at a +//! passed: when the terminal is fed a unit's output (`fed`), a cell the +//! screen shows goes, and one it does not is a misprediction, and every +//! prediction goes. With no output (no echo), a frame judges it `stale` +//! later. Shown at once at a //! shell's prompt (pardes's OSC 133 marks say its line editor echoes); //! elsewhere only once an echo was confirmed there since the last key that //! was not predicted (`cat`, a shell without marks), and underlined; never @@ -37,12 +38,12 @@ const Key = pardes.Key; const ms = std.time.ns_per_ms; /// After the authority confirmed a key, how long its echo has to come back -/// before a delta that does not show it makes a misprediction (mosh's +/// before output that does not show it makes a misprediction (mosh's /// ECHO_TIMEOUT): the shell's echo, then the authority's next frame. // ponytail: fixed; a loaded host's later echo makes a drawn character go and // come back. The echo delay measured per terminal would be the bound. pub const grace_ns = 50 * ms; -/// With no delta at all, how much longer a frame waits to judge a key. +/// With no output at all, how much longer a frame waits to judge a key. pub const stale_ns = 250 * ms; const never = std.math.maxInt(u64); /// Cells predicted at once: a line typed a round trip ahead. @@ -73,7 +74,7 @@ pub const Echo = struct { view: u8 = 0, pane: u8 = 0, serial: u32 = 0, - /// Each terminal's last delta: its active area's first row, absolute. + /// Each terminal's active area's first row, absolute, as last fed. tops: [pardes.MAX_PANES]u64 = @splat(0), cells: [max]Cell = undefined, n: u8 = 0, @@ -347,7 +348,7 @@ pub const Echo = struct { }; if (e.wait <= seq and e.wait_due == never) { // The authority stepped a key this did not predict, after every - // one it did: its deltas from here show that key's doing, which + // one it did: its output from here shows that key's doing, which // no prediction knew of. They go, judged neither way. e.wait_due = due; e.drop(); @@ -355,30 +356,24 @@ pub const Echo = struct { e.catchUp(c); } - /// Terminal `id`'s delta was applied, its active area's first row now - /// `top`. - pub fn delta(e: *Echo, c: *Pardes, id: u8, top: u64) void { - if (id == e.pane and top != e.tops[id] and (e.n > 0 or e.cursor != null)) { + /// The emulators were fed a unit's output (the session's echo among + /// it, perhaps): judged, the active area's first row its grid's. + /// ponytail: at the history's cap that row stops moving as the output + /// scrolls; a guess there is judged wrong and taken back, never kept. + pub fn fed(e: *Echo, c: *Pardes) void { + const pane = c.panes[e.pane] orelse return; + const g = Term.grid(pane.terminal orelse return); + const top = g.total - g.len; + if (top != e.tops[e.pane] and (e.n > 0 or e.cursor != null)) { // Scrolled: the rows predicted are others now. - e.tops[id] = top; + e.tops[e.pane] = top; return e.lose(); } - e.tops[id] = top; - if (id == e.pane) e.judge(c, 0); + e.tops[e.pane] = top; + e.judge(c, 0); e.catchUp(c); } - /// The pty's bytes road: the emulators were fed a unit's output (the - /// session's echo among it, perhaps): judged as at a delta, the active - /// area's first row its grid's. ponytail: at the history's cap that - /// row stops moving as the output scrolls; a guess there is judged - /// wrong and taken back, never kept. - pub fn fed(e: *Echo, c: *Pardes) void { - const pane = c.panes[e.pane] orelse return; - const g = Term.grid(pane.terminal orelse return); - e.delta(c, e.pane, g.total - g.len); - } - /// Once a frame: what is stale judged. Whether to draw. pub fn frame(e: *Echo, c: *Pardes) bool { if (e.n > 0 or e.cursor != null) e.judge(c, stale_ns); @@ -671,8 +666,8 @@ test "keys typed at a shell's prompt are drawn at once, and the authority's echo try testing.expectEqual(@as(u8, 's'), (try g.drawn(&arena, 3)).cp); // The authority's core draws no overlay of its own. try testing.expect(g.a.core.echo == null); - // The authority takes them, its shell echoes, the delta lands after the - // grace: confirmed, and the screen's own cells and cursor shown. + // The authority takes them, its shell echoes, its output lands after + // the grace: confirmed, and the screen's own cells and cursor shown. try g.take(l); try g.take(s); try testing.expectEqualStrings("ls", g.written.items); @@ -711,7 +706,7 @@ test "a password prompt shows nothing typed, and a full-screen program is not pr try testing.expectEqual(@as(u32, 1), g.r.echo.stats.predicted); try testing.expectEqual(@as(u8, ' '), (try g.drawn(&arena, x)).cp); try g.take(k); - // No echo, so no delta: a frame lets it go once it is stale. + // No echo, so no output: a frame lets it go once it is stale. g.later(grace_ns + stale_ns); _ = g.r.echoFrame(); try testing.expectEqual(@as(u8, 0), g.r.echo.n); -- cgit v1.3 From 6d075524729cc81fb157a587bef5481d6c36cb0b Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 22 Nov 2026 10:43:59 -0300 Subject: docs: next-daemon.md says terminals cross as the pty's bytes since 2026-11-22 (the old road's deletion, piece 8 of 8): one note under the design's "Terminals cross as authoritative screen state" (the user's ruling, pardes-flip, this line's deletion, the wire at 30; what the file says of screen state below is history) and a line under "Screen-state terminal notes" pointing to it; no other doc named screen state as current Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- docs/next-daemon.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/docs/next-daemon.md b/docs/next-daemon.md index 9ed25f9c..22837941 100644 --- a/docs/next-daemon.md +++ b/docs/next-daemon.md @@ -102,6 +102,14 @@ smallest common grid across them. A `cat` of 1 GB costs screens, not bytes. ghostty stays exact on the authority, and the local path keeps reading ghostty directly. + + > SINCE 2026-11-22 TERMINALS CROSS AS THE PTY'S BYTES (the user's + > ruling: "just start the structural fix"): a session's units carry its + > ptys' output and every client feeds its own emulator in the tape's + > order (pardes-flip), and the screen-state road is deleted + > (pardes-term-join-8: core/term/screen_state.zig, the deltas and their + > flight bound, the screen messages; the wire at 30). What this file says + > of screen state below is history. - **The reflective walker.** One comptime `@typeInfo` walk gives: - the digest; - the complete dump, which also serves join, Restore and Handover; @@ -885,6 +893,9 @@ Found and fixed 2026-10-29 (`dev/tui/tui.zig`, `waitInput`). ## Screen-state terminal notes +(History: deleted 2026-11-22; terminals cross as the pty's bytes, see the +note under "Terminals cross as authoritative screen state" above.) + Built 2026-10-29 (`src/screen_state.zig`), a pure encode and apply pair over byte buffers for the phase 5 stream; no transport yet. Only tests reference it, so the tty and GUI binaries carry none of it: no symbol of -- cgit v1.3 From 159fc78fc8d350f0f40f7f2fcf344377034c8f2f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 22 Nov 2026 10:48:07 -0300 Subject: term: the emulator's boundary written down and enforced (S1 on the one road, item 2 of pardes-term-join-8): abi/term.zig names `Ops` in two groups, `replicated` (what every side agrees on by construction, each emulator fed the same bytes in the tape's order, written only by a step or a load, read by a step as the digest covers it, or by a draw) and `local` (start, stop, gpa, due, cellPixels, echoCell, paint, images: this process's own), every entry in exactly one (a comptime check: a new entry fails to compile until it says which); the terminal's digest (core/term/terminal.zig `digest`) now covers what a step reads of it: its cols and rows, every mode bit (the alternate screen, the mouse's, focus reports, bracketed paste; `modes`), the mouse's event and format, and the OSC 133 cycle (`marksOf`, `prompt`'s), beside the view, the cursor, the reply buffer, whether it holds an image and the active area's text; NOT the history's text (its row count only: a step's read of it, a 9P read, a Save, a selection over a shell, is listed as not covered); the two tables of round 6 and pardes-image-loop are a test (core/Term.zig `calls`: every call of the core's into a terminal, by entry, file and count, with its rule: a WRITE outside the rollback copy and why no unit kept to replay makes it or how the copy puts it back, a READ by a step and whether the digest covers it, a LOCAL use and why no step's state reads it, PURE for the pager's; a new call fails until it is listed); the counted list, not a type, enforces that the digested paths call the replicated group (by type the digested code would need a handle of its own: every one of the 13 files that read `grid` and more, past the 200 lines the brief allows); core/root.zig's reasons that said a client's emulator is written by deltas, and that a terminal is in no digest, say what is true now; core-test 912/1069 (157 skipped: +1, the `calls` test), shell-test 1111/1114, term-test 15/15, pane-test 181/182, kitty-test 45/45, the soak's small run and `--echo` rc 0 (diverged 0, unequal 0) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- abi/term.zig | 30 ++++++++++++ core/Term.zig | 130 +++++++++++++++++++++++++++++++++++++++++++++++++ core/root.zig | 4 +- core/term/terminal.zig | 19 ++++++-- 4 files changed, 177 insertions(+), 6 deletions(-) diff --git a/abi/term.zig b/abi/term.zig index a0636509..d6c48f96 100644 --- a/abi/term.zig +++ b/abi/term.zig @@ -368,3 +368,33 @@ pub const Ops = struct { images: *const fn (s: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.ArrayList(plain.Placement), frame: []plain.Cell, frame_cols: u16) void, hasImages: *const fn (s: ?*const State) bool, }; + +/// `Ops` in its two groups (S1: the emulator's boundary). REPLICATED: what +/// every side agrees on by construction, each side's emulator fed the same +/// bytes in the tape's order: written only by a step or a load, read by a +/// step as the terminal's digest covers it (core/term/terminal.zig +/// `digest`), or by a draw. LOCAL: this process's own (its frontend's cell +/// size, the pixels and images it draws, its next wake, the module's start +/// and its allocator), never what a step's digested state is computed from. +/// core/Term.zig's `calls` lists every call of the core's into either, by +/// file, with its rule: a new one fails its test until it is listed. +pub const replicated = [_][]const u8{ + "open", "close", "revive", "digest", "parts", "snapshot", "load", "reload", + "media", "feed", "grid", "viewTo", "scroll", "follow", "resize", "replies", + "key", "mouse", "wheel", "paste", "modes", "promptMoves", "prompt", "commandOutput", + "endOutputHere", "scrollback", "scrollbackLen", "textRows", "viewport", "editRows", "promptCut", "page", + "filter", "spanColor", "hasImages", +}; +pub const local = [_][]const u8{ "start", "stop", "gpa", "due", "cellPixels", "echoCell", "paint", "images" }; + +comptime { + @setEvalBranchQuota(100_000); + for (@typeInfo(Ops).@"struct".field_names) |fname| { + var n = 0; + for (replicated ++ local) |name| { + if (std.mem.eql(u8, name, fname)) n += 1; + } + if (n != 1) @compileError("term.Ops." ++ fname ++ ": in neither group or in both (abi/term.zig `replicated`, `local`): say which, and why"); + } + for (replicated ++ local) |name| if (!@hasField(Ops, name)) @compileError("term.Ops has no " ++ name); +} diff --git a/core/Term.zig b/core/Term.zig index 968a8d68..580db4fa 100644 --- a/core/Term.zig +++ b/core/Term.zig @@ -403,6 +403,136 @@ pub fn hasImages(s: ?*const State) bool { return o.hasImages(if (s) |state| state.impl else null); } +// ---- the boundary (S1): every call of the core's into its terminal ---- + +/// Every call of the core's (core/, but this file and the module's own +/// core/term/) into a terminal, by entry, its files and how many in each +/// (a test's among them), and its rule: the emulator is outside the +/// rollback copy and its digest is the terminal's (`State.digest`, which +/// covers what abi/term.zig `replicated` lists a step reads, but the +/// history's text). A READ from a step is covered by the digest or is +/// said not to be; a WRITE outside the copy is never made by a unit kept +/// to replay, or its record puts it back exactly; a LOCAL entry +/// (abi/term.zig `local`) is never read into a step's state. A new call +/// fails the test below until it is listed here with its rule (round 6's +/// and pardes-image-loop's tables, kept as a test). +pub const calls = [_]struct { []const u8, []const u8, []const u8 }{ + // ---- writes: outside the copy ---- + .{ "open", "dump.zig:1 panes.zig:1", "WRITE: a terminal made by a step (a shell's pane) or a load; a copy held across a pane's opening is let go (replica.zig `confirm`: serials)" }, + .{ "close", "panes.zig:1", "WRITE: let go by a step that closes its pane: a copy held across it is let go (retiring panes); a unit that closes one is never kept over a copy" }, + .{ "revive", "dump.zig:1", "WRITE: a load's (a join's dump, a Restore): no copy is held" }, + .{ "reload", "panes.zig:1", "WRITE: a join's step remakes each terminal written since its last reload, on every side (panes.reloadTerminals, the session's choice taped, the snapshot's hash compared)" }, + .{ "feed", "keys.zig:1 panes.zig:3", "WRITE: the pty's bytes in a unit, every side in the tape's order; a unit that feeds lets a copy held ahead go (`Term.writes`), so none is replayed (keys.zig's: a test's)" }, + .{ "viewTo", "replica.zig:2", "WRITE: a rollback puts each view back by its row (`putViews`), exact since a reflow keeps a view a row (pardes-term-join-6)" }, + .{ "scroll", "Core.zig:2 panes.zig:1", "WRITE: a step moves the view; outside the copy, put back by `putViews`" }, + .{ "follow", "panes.zig:1", "WRITE: a step puts the view on the output; put back by `putViews`" }, + .{ "resize", "panes.zig:1", "WRITE: a step's reflow; a speculation owes it (`touchTerminal`): its input is taken when confirmed, never as speculated" }, + .{ "endOutputHere", "ninep/pty.zig:1", "WRITE: a 9P pty/run's step ends a command's output at the cursor: the session's step, replayed as such" }, + .{ "replies", "Core.zig:1", "WRITE: a step drains the reply buffer (in the digest); only the session writes it to the pty (pty_write is off the tape)" }, + // ---- reads by a step: in the digest ---- + .{ "grid", "Core.zig:8 ansi.zig:4 body_layer.zig:5 draw.zig:3 dump.zig:4 echo.zig:8 edit.zig:1 exec.zig:3 keys.zig:3 layout.zig:2 mouse.zig:1 panes.zig:6 replica.zig:4", "READ: the size, the view, the cursor: in the digest (ansi.zig, body_layer.zig, draw.zig, echo.zig: a draw's)" }, + .{ "modes", "Core.zig:5 draw.zig:1 dump.zig:2 echo.zig:3 exec.zig:3 mouse.zig:4 ninep/pty.zig:3 replica.zig:1", "READ: the program's modes (mouse, focus, bracketed paste, the alternate screen): in the digest (draw.zig, echo.zig: a draw's)" }, + .{ "prompt", "Core.zig:1 builtins.zig:1 echo.zig:1 exec.zig:3 ninep/pty.zig:1 panes.zig:1", "READ: the OSC 133 cycle: in the digest (`marksOf`); Core.zig's and ninep/pty.zig's also taped (`.prompt`, each side's compared)" }, + .{ "promptPrefix", "body_layer.zig:1 edit.zig:1 exec.zig:1", "READ: a row's prompt cells (`promptCut`): the active area's in the digest; a history row's text is not (below)" }, + .{ "hasImages", "replica.zig:3 tagline.zig:1", "READ: whether it holds a kitty image (the tag's prefix): in the digest" }, + .{ "key", "keys.zig:1", "READ: a key's bytes for the pty from its modes (in the digest): a write the session makes" }, + .{ "mouse", "mouse.zig:4", "READ: a report's bytes from its modes (in the digest); the last cell told is the pane's (in the copy)" }, + .{ "wheel", "mouse.zig:1", "READ: a wheel's report from its modes (in the digest)" }, + .{ "paste", "edit.zig:1", "READ: a paste's bracketing from its modes (in the digest)" }, + .{ "promptMoves", "keys.zig:1", "READ: the cursor keys a click at its prompt types, from the prompt's cells and the cursor (in the digest)" }, + .{ "page", "Core.zig:1 ninep/ctl.zig:1", "PURE: a pager's parse of bytes the step holds; no emulator" }, + .{ "filter", "File.zig:1", "PURE: a pager's colours from the theme; no emulator" }, + .{ "spanColor", "File.zig:2", "PURE: as `filter`" }, + // ---- reads by a step: NOT in the digest (the history's text) ---- + .{ "scrollback", "Core.zig:3 Effect.zig:1 dump.zig:1 ninep/pane.zig:1 ninep/screen.zig:2", "READ, NOT COVERED: the history's text (a 9P read, a Save, an exit dump): each side fed the same bytes; a parting there is found when it reaches the core's state" }, + .{ "scrollbackLen", "ninep/ctl.zig:1 ninep/pane.zig:1", "READ, NOT COVERED: the history's text's length (its row count is in the digest)" }, + .{ "commandOutput", "ninep/pty.zig:1", "READ, NOT COVERED: a command's output rows (a 9P pty/run): taped as the session's answer" }, + .{ "textRows", "edit.zig:2", "READ, NOT COVERED: every row's text, the history's among them (a selection, a Look over a shell)" }, + .{ "viewport", "body_layer.zig:1 replica.zig:1", "READ: the view's rows' text (body_layer.zig: a draw's; replica.zig: a test's)" }, + .{ "editRows", "ansi.zig:1", "READ: rows' text for a draw" }, + // ---- local ---- + .{ "due", "Core.zig:1", "LOCAL: its next wake (a blink, an animation): the loop's, never a step's state" }, + .{ "cellPixels", "ansi.zig:1 panes.zig:2", "LOCAL: a frontend's draw sets its view's cell size (ansi.zig); a step sets the view's (in the digest) before each feed (panes.zig), so a reply to CSI 16 t is the step's" }, + .{ "echoCell", "echo.zig:1", "LOCAL: the predicted echo's judge reads a cell; the echo is no core state" }, + .{ "paint", "ansi.zig:1", "LOCAL: its cells drawn" }, + .{ "images", "ansi.zig:1", "LOCAL: its kitty images drawn" }, + .{ "start", "tape.zig:1", "LOCAL: the module's start, a test's (its own process's)" }, + .{ "emulatorOf", "Core.zig:2 ninep/pty.zig:3", "the module's state itself: tests only" }, +}; + +test "every call of the core's into a terminal is listed with its rule (S1): a new read, writer or local use fails until it is" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var dir = try std.Io.Dir.cwd().openDir(io, "core", .{ .iterate = true }); + defer dir.close(io); + var walker = try dir.walk(gpa); + defer walker.deinit(); + var wrong: usize = 0; + var counts: std.StringHashMapUnmanaged(usize) = .empty; + defer { + var it = counts.keyIterator(); + while (it.next()) |k| gpa.free(k.*); + counts.deinit(gpa); + } + while (try walker.next(io)) |e| { + if (e.kind != .file or !std.mem.endsWith(u8, e.basename, ".zig")) continue; + if (std.mem.eql(u8, e.path, "Term.zig") or std.mem.startsWith(u8, e.path, "term/")) continue; + const src = try e.dir.readFileAlloc(io, e.basename, gpa, .limited(16 << 20)); + defer gpa.free(src); + var lines = std.mem.splitScalar(u8, src, '\n'); + while (lines.next()) |line| { + if (std.mem.startsWith(u8, std.mem.trimStart(u8, line, " \t"), "//")) continue; + var at: usize = 0; + while (std.mem.indexOfPos(u8, line, at, "Term.")) |i| { + at = i + 5; + var end = at; + while (end < line.len and (std.ascii.isAlphanumeric(line[end]) or line[end] == '_')) end += 1; + if (end == at or end >= line.len or line[end] != '(' or !std.ascii.isLower(line[at])) continue; + if (i > 0 and (std.ascii.isAlphanumeric(line[i - 1]) or line[i - 1] == '_')) continue; + const k = try std.fmt.allocPrint(gpa, "{s} {s}", .{ line[at..end], e.path }); + const got = try counts.getOrPut(gpa, k); + if (got.found_existing) { + gpa.free(k); + got.value_ptr.* += 1; + } else got.value_ptr.* = 1; + } + } + } + // Each listed file's count is what the tree has, and nothing else calls. + for (calls) |c| { + var files = std.mem.tokenizeScalar(u8, c[1], ' '); + while (files.next()) |fc| { + const colon = std.mem.lastIndexOfScalar(u8, fc, ':').?; + const want = try std.fmt.parseInt(usize, fc[colon + 1 ..], 10); + var buf: [256]u8 = undefined; + const pair = try std.fmt.bufPrint(&buf, "{s} {s}", .{ c[0], fc[0..colon] }); + const have = counts.get(pair) orelse 0; + if (have == want) continue; + wrong += 1; + std.debug.print("core/{s}: {d} calls of Term.{s}, Term.zig's `calls` says {d}: {s}\n", .{ fc[0..colon], have, c[0], want, c[2] }); + } + } + var it = counts.iterator(); + while (it.next()) |kv| { + const space = std.mem.indexOfScalar(u8, kv.key_ptr.*, ' ').?; + const name = kv.key_ptr.*[0..space]; + const file = kv.key_ptr.*[space + 1 ..]; + if (listedCall(name, file)) continue; + wrong += 1; + std.debug.print("core/{s}: {d} calls of Term.{s}, not in Term.zig's `calls`: list it with its rule (a step's read the digest covers, a write the copy puts back, a local use)\n", .{ file, kv.value_ptr.*, name }); + } + try std.testing.expectEqual(@as(usize, 0), wrong); +} + +fn listedCall(name: []const u8, file: []const u8) bool { + for (calls) |c| { + if (!std.mem.eql(u8, c[0], name)) continue; + var files = std.mem.tokenizeScalar(u8, c[1], ' '); + while (files.next()) |fc| if (std.mem.eql(u8, fc[0..std.mem.lastIndexOfScalar(u8, fc, ':').?], file)) return true; + } + return false; +} + // ---- a core without a terminal (core-test's) ---- test "a core without a terminal boots to a scratch pane" { diff --git a/core/root.zig b/core/root.zig index 171bdfef..0e02a9bc 100644 --- a/core/root.zig +++ b/core/root.zig @@ -643,7 +643,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{ .{ "ninep/pty.zig", 1, "a 9P exec's shell check (tape.site(.shell))" }, .{ "ninep/screen.zig", 1, "a 9P address's text type" }, .{ "ninep/tree.zig", 1, "the daemon's registry (/sessions, tape.site(.sessions))" }, - .{ "term/terminal.zig", 2, "the emulator's image files (TMPDIR) and its Io: the session's emulator (a client's are written by deltas)" }, + .{ "term/terminal.zig", 2, "the emulator's image files (TMPDIR) and its Io: each side's emulator, a medium's read taped (Term.media)" }, }; /// The lines of `src` that name the machine (`machine_lines`'s rules). @@ -738,7 +738,7 @@ const kept_out = [_]struct { []const u8, []const u8, []const u8 }{ .{ "Core.zig", "surface facts frames own_frames chrome frame_arena scratch echo undrawn", "the frame's own and the views drawn here: written by frames (and chrome by a theme's step), read by frames and the runner; no step reads them" }, .{ "Core.zig", "needs_frame", "whether to draw: steps set it, the loop reads it; no step's outcome reads it" }, .{ "Core.zig", "effects effects_head effects_len in_q in_head in_len opts dump_out dump_export tape", "this process's queues, options and tape, drained or set by its host" }, - .{ "Core.zig", "shell_rows", "a terminal's rows as read here, swept at every update; a terminal is in no digest (Term.zig)" }, + .{ "Core.zig", "shell_rows", "a terminal's rows as read here, swept at every update; the terminal's own digest covers its active area, not its history (Term.zig `calls`)" }, .{ "Core.zig", "diff_output locations_cache tty_filter_palette body_chrome", "caches of pure functions of their key (a text, a theme): a step finds what it would make; a query row's colours from them are out of its digest (locations.Row.digest), and what a step asks a worker to paint is never decided by them (Stream.paintRows)" }, .{ "Core.zig", "retired_panes", "panes torn down this step, freed at its end" }, .{ "Core.zig", "distrusted frames tape", "Options: the client's own list, its runner's statistics, its tape" }, diff --git a/core/term/terminal.zig b/core/term/terminal.zig index f130d7b9..44038a18 100644 --- a/core/term/terminal.zig +++ b/core/term/terminal.zig @@ -211,10 +211,22 @@ pub fn digest(s: *const State, h: *std.hash.Wyhash, view: bool) void { const sb = screen.pages.scrollbar(); const cur = screen.cursor; const offset = if (view) sb.offset else 0; - // Whether it holds a kitty image: the tag says so (tagline.zig). - const facts = .{ sb.total, offset, sb.len, cur.x, cur.y, s.vt.modes.get(.cursor_visible), s.vt.screens.active_key, s.reply_dropped, hasImages(s) }; + // Everything a step reads of it (abi/term.zig `replicated`): its + // size, the view and the cursor, its modes (the alternate screen, + // the mouse's, focus reports, bracketed paste: `modes`), whether it + // holds a kitty image (the tag says so: tagline.zig), the reply + // buffer, the OSC 133 cycle (`prompt`), the active area's text. Not + // the history's text, only its length (a step's read of it: not + // covered; core/Term.zig `calls`). + const Modes = @TypeOf(s.vt.modes.values); + const mode_bits: @Int(.unsigned, @bitSizeOf(Modes)) = @bitCast(s.vt.modes.values); + const modes_word: @Int(.unsigned, (@bitSizeOf(Modes) + 7) / 8 * 8) = mode_bits; + const mouse_flags: [2]u8 = .{ @intCast(@intFromEnum(s.vt.flags.mouse_event)), @intCast(@intFromEnum(s.vt.flags.mouse_format)) }; + const facts = .{ s.vt.cols, s.vt.rows, sb.total, offset, sb.len, cur.x, cur.y, modes_word, s.vt.screens.active_key, mouse_flags, s.reply_dropped, hasImages(s) }; inline for (facts) |fact| h.update(std.mem.asBytes(&fact)); h.update(s.reply[0..s.reply_len]); + var marks: [marks_len]u8 = undefined; + h.update(marksOf(s, &marks)); var buf: [4096]u8 = undefined; var text: std.Io.Writer.Hashing(std.hash.Wyhash) = .initHasher(h.*, &buf); if (screen.pages.getBottomRight(.active)) |br| @@ -457,8 +469,7 @@ pub fn grid(state: ?*const State) Term.Grid { } /// What pardes made of a terminal's stream that its emulator does not hold -/// (the OSC 133 cycle, MarkedHandler), as bytes two terminals' compare by -/// (`expectSame`): phase u8, started, prompts, declined u32, continuation +/// (the OSC 133 cycle, MarkedHandler), as bytes its digest holds: phase u8, started, prompts, declined u32, continuation /// and lost u8, a finished command's seq u32 and status i32 (all ones: /// none; i32 min: no status). const marks_len = 1 + 4 * 3 + 2 + 4 + 4; -- cgit v1.3 From 8caed8e7d894fee836c95f2ca83fda9b22e1db84 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 22 Nov 2026 14:01:03 -0300 Subject: replica: a client's own join again is judged after its goodbye (pardes-term-join-9, item 1 (a)): a client let go for its lag or after a divergence says bye, shuts its link and dials again naming its view (runtime/client.zig `run`), and the session takes its join from the daemon's hand-over and its bye from the old link's reader thread, in no order between them; judged first, `viewFor` found the view not away and opened a NEW one (the client's layout, scroll and focus lost, its old view then kept away 30 s for nobody), or at the cap refused it (a divergence's rejoin is not patient and then fails "could not join again"); now a join naming a view whose link has hung up (`hungUp`: POLLHUP or POLLRDHUP, the client having shut its link before it dialled) is held on that peer (`Peer.rejoin`) and posted again when the link is let go (`letGo`), its view away by then, a view whose link is up being another client's as before, and a Restore keeps a held join as it keeps the inbox's; measured with a raw replica that says bye and at once joins again naming its view, pinned to one CPU: the base 1 of 60 in another view and 27 refused, this 0 of 120; the cut-off test dials again before its old link's end is heard (fails on the base with `error.NotHeld`); root.zig's machine_lines for replica.zig 73 -> 76 (the session's own join, no replayed step); not covered: a relay that delays each connection on its own (test/delay_relay.py) can still bring the hello before the old link's hang-up Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/replica.zig | 46 +++++++++++++++++++++++++++++++++++++++------- core/root.zig | 2 +- 2 files changed, 40 insertions(+), 8 deletions(-) diff --git a/core/replica.zig b/core/replica.zig index e9e29de0..ae1ae6c3 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -1379,6 +1379,9 @@ pub const Peer = struct { /// Cut off (`send`): the words why are the last it is sent, and its /// view is kept for it (views.away), as for a bye's `again`. cut: bool = false, + /// Its client's join again for its view, come before this link's end + /// was heard: judged once it is let go (`Peers.join`, `letGo`). + rejoin: ?Peers.Joining = null, /// Its writer has ended (what it was sent, written). done: std.atomic.Value(bool) = .init(false), /// Its join, which its writer writes before what it is sent: the @@ -1722,6 +1725,13 @@ pub fn dying() void { }; } +/// Whether the other end of socket `fd` has hung up (shut, or closed). +fn hungUp(fd: c_int) bool { + const rdhup = if (@hasDecl(libc.POLL, "RDHUP")) libc.POLL.RDHUP else 0; + var p = [1]libc.pollfd{.{ .fd = fd, .events = libc.POLL.IN | rdhup, .revents = 0 }}; + return libc.poll(&p, 1, 0) == 1 and p[0].revents & (libc.POLL.HUP | rdhup) != 0; +} + /// The process at the other end of unix socket `fd` (Linux's SO_PEERCRED), /// or 0: a client's through ssh is ssh's. fn peerPid(fd: c_int) libc.pid_t { @@ -1905,6 +1915,16 @@ pub const Peers = struct { /// threads started. At a step boundary (`boundary`), or a session's /// first client before its first effects (runtime/session.zig). pub fn join(ps: *Peers, core: *Pardes, joining: Joining) void { + // A join for a view whose client's link has hung up is that client + // joining again (runtime/client.zig `run`: its bye, its link shut, + // then its dial): its goodbye comes on that link and this join + // through the daemon, in no order between them. Held until that + // link is let go, its view kept for it by then; a view whose link + // is up is another client's. + if (joining.view) |v| for (ps.list) |slot| if (slot) |p| if (p.view.index() == v and p.rejoin == null and hungUp(p.fd)) { + p.rejoin = joining; + return; + }; const fd = joining.fd; const t0 = nowNs(); defer { @@ -2106,6 +2126,7 @@ pub const Peers = struct { _ = ps.inbox.orderedRemove(i); } ps.lock.unlock(io); + if (peer.rejoin) |j| ps.post(.{ .join = j }); ps.gpa.destroy(peer); } @@ -2157,6 +2178,10 @@ pub const Peers = struct { _ = ps.inbox.orderedRemove(i); } ps.lock.unlock(ps.io); + for (ps.list) |slot| if (slot) |p| if (p.rejoin) |j| { + again.append(ps.gpa, j) catch continue; + p.rejoin = null; + }; ps.drop(core, false); ps.restored = true; for (again.items) |j| ps.post(.{ .join = j }); @@ -5007,13 +5032,21 @@ test "a client cut off for what it left unread is told why and joins again for i // welcome, the dump with its blobs in place); and what it queued for one, // down its link in order, the link's end after it if it was cut off. const MemoryLinks = struct { - fn join(ps: *Peers, core: *Pardes, view: ?u8, fd: *c_int) !struct { r: *Replica, peer: *Peer } { + /// `old`: the link it had, whose end the session hears after this + /// join came: held until then. + fn join(ps: *Peers, core: *Pardes, view: ?u8, fd: *c_int, old: ?*Peer) !struct { r: *Replica, peer: *Peer } { const gpa = std.testing.allocator; var fds: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; fd.* = fds[1]; ps.handed(fds[0], view); ps.boundary(core); + if (old) |o| { + for (ps.list) |slot| if (slot) |p| if (p.fd == fds[0]) return error.NotHeld; + ps.post(.{ .gone = o }); + ps.boundary(core); + ps.boundary(core); + } const peer = for (ps.list) |slot| { if (slot) |p| if (p.fd == fds[0]) break p; } else return error.Refused; @@ -5061,7 +5094,7 @@ test "a client cut off for what it left unread is told why and joins again for i defer ps.deinit(); defer ps.dropAll(core); var fd: c_int = -1; - const first = try MemoryLinks.join(&ps, core, null, &fd); + const first = try MemoryLinks.join(&ps, core, null, &fd, null); defer _ = libc.close(fd); var link: Link = .{ .r = first.r, .fd = fd }; defer link.deinit(gpa); @@ -5088,13 +5121,12 @@ test "a client cut off for what it left unread is told why and joins again for i // It was told why, and joins again (as a divergence's client does)... try std.testing.expect(link.rejoins()); try std.testing.expect(std.mem.indexOf(u8, link.notice(), "behind") != null); - // ...once its old link's end is heard: its view kept for it meanwhile. - ps.post(.{ .gone = first.peer }); - ps.boundary(core); - try std.testing.expect(pardes.views.isAway(core, view.index())); + // ...its old link shut, at once (runtime/client.zig `run`): a join that + // comes before that link's end is heard, on another connection, waits + // for it, its view kept for it meanwhile. first.r.deinit(); _ = libc.close(fd); - const back = try MemoryLinks.join(&ps, core, view.index(), &fd); + const back = try MemoryLinks.join(&ps, core, view.index(), &fd, first.peer); defer back.r.deinit(); try std.testing.expectEqual(view, back.peer.view); link.reset(back.r, &.{ .fd = fd, .pid = 0, .client = back.r.id, .view = view.index(), .gmtoff = 0, .dump = &.{} }); diff --git a/core/root.zig b/core/root.zig index 0e02a9bc..fb606909 100644 --- a/core/root.zig +++ b/core/root.zig @@ -632,7 +632,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{ .{ "jj.zig", 11, "jj run under tape.site(.jj) on an io of its own (the tape's spawns nothing) with this process's environment, the signal mask cleared as Stream's children's: the session's, a replica replays its answer; or on a worker for `Changes`, its answer an input, with the wall clock it was made at (tape.value(.clock) on the loop) for its descriptions' ages; a test's shell inbox (dev)" }, .{ "look.zig", 6, "openLink's fork (the host's: a view's frontend opens a link) and a remote's error name" }, .{ "memory.zig", 7, "the memory regions themselves (mmap, madvise, their locks)" }, - .{ "replica.zig", 73, "the client and session engines: sockets, threads, clocks, the blob cache, traces" }, + .{ "replica.zig", 76, "the client and session engines: sockets, threads, clocks, the blob cache, traces" }, .{ "rollback.zig", 1, "a test helper's directory" }, .{ "root.zig", 4, "dev's modules re-exported (host_io, file_watch, glide, fonts)" }, .{ "selection_pipe.zig", 14, "a pipe's child processes and their files: the host's `pipe` entry" }, -- cgit v1.3 From 85e793ae92683808d14433cb7c99ccdab4c967dc Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 22 Nov 2026 14:01:03 -0300 Subject: daemon.py: a terminal read after its writer ended waits for its last bytes, kept_views waits for the session to take the goodbyes it races, and far_flood keeps its evidence (pardes-term-join-9, item 1 (b), (a), (c)): `Term.last` reads a terminal's text once nothing waits on its master (FIONREAD, read under the reader's lock, which now reads and keeps in one hold) and nothing more came for 0.1 s, and the four reads that followed an exit or an event seen elsewhere at once use it (clients' detach words, the failing row R-plain-2 at load 7.6; a killed stub's put-back; "let this client go" not said, a negative that passed early; the old build's replica told to upgrade too); kept_views dials again until a refusal says a view is kept (two raw replicas' byes reach the session on their own connections and the next join through the daemon, in no order the session could keep: D-plain-3 and R-plain-1 of round 8) and waits the seconds that refusal states, not a fixed 31 from before the goodbyes were taken; far_flood copies the far client's check and stats files, its terminal and every process's threads with their wait channels beside its root at any failure (R--far-6 of round 8, not reproduced in 13 runs since, went with its root) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- test/daemon.py | 83 +++++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 68 insertions(+), 15 deletions(-) diff --git a/test/daemon.py b/test/daemon.py index c5c39be3..55cffaf4 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -102,13 +102,15 @@ class Term: try: if not select.select([self.master], [], [], 0.05)[0]: continue - got = os.read(self.master, 65536) + # Read and kept in one hold of the lock: `last` counts what + # waits on the master under it. + with self.lock: + got = os.read(self.master, 65536) + self.out += got except OSError: return if not got: return - with self.lock: - self.out += got # A request split across two reads is answered too. seen, self.tail = self.tail + got, got[-3:] if b'\x1b[5n' in seen: @@ -127,6 +129,23 @@ class Term: with self.lock: return bytes(self.out) + def last(self): + """Its text once what was written to it is read, for a read after + its writer ended (or wrote its last before an event seen + elsewhere): the reader may not have the last bytes yet (it reads + every 50 ms, later under load). Nothing waiting on the master and + nothing more read for 0.1 s.""" + quiet = None + def done(): + nonlocal quiet + with self.lock: + now = (struct.unpack('i', fcntl.ioctl(self.master, termios.FIONREAD, b'\0\0\0\0'))[0], len(self.out)) + if now[0] or quiet is None or quiet[0] != now: + quiet = (now, time.monotonic()) + return time.monotonic() - quiet[1] >= .1 + wait_for('the terminal\'s last bytes read', done) + return self.text() + def close(self): self.closing = True self.reader.join(timeout=2) @@ -523,7 +542,7 @@ def clients(binary): # Detach typed in it: it alone goes, and says so (exit 0). os.write(ta.master, b' sD') wait_for('client A let go', lambda: a.poll() is not None, timeout=10) - assert a.returncode == 0 and b"detached from 'files', which is still running" in ta.text(), ta.text()[-300:] + assert a.returncode == 0 and b"detached from 'files', which is still running" in ta.last(), ta.last()[-300:] # A third client, a shell: its keys wait for the session (a pty # write), its output comes back in units, the same on both sides. nine.write(f'/pane/{pane}/exec', b'Term\n') @@ -996,7 +1015,7 @@ def kept_views(binary): nobody types in: a `new --detach` session at its four views (a client attached, idle; raw replicas), two of them leaving to join again and never coming back; a join at once is refused and told for how long, one - 31 s later, nothing typed in between, is welcomed.""" + a second past that, nothing typed in between, is welcomed.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rk-', dir=scratch)) @@ -1023,15 +1042,29 @@ def kept_views(binary): for r in rs[:2]: r.send(0x02, b'\x01') r.close() - left = time.monotonic() - said = Replica(sock).hello('kv', build) - assert said[0] == 'refused' and re.search(r'as many views as it takes \(one is kept (\d+) s more for a client joining again\)', said[1]), said - print(f'kept views: {len(rs)} replicas and a client at the cap; two left to join again; a join at once refused: "{said[1]}"') - time.sleep(max(0, left + 31 - time.monotonic())) + + # The goodbyes reach the session on their own connections and the + # next join through the daemon, in no order between them: a join + # judged before the session took them is refused with no view kept + # yet. Dialled again until a refusal says one is. + dials = 0 + + def refused(): + nonlocal dials + dials += 1 + r = Replica(sock) + said = r.hello('kv', build) + r.close() + assert said[0] == 'refused' and 'as many views as it takes' in said[1], said + kept = re.search(r'as many views as it takes \(one is kept (\d+) s more for a client joining again\)', said[1]) + return kept and (said, int(kept.group(1)), time.monotonic()) + said, more, at = wait_for('a join refused, a view kept', refused) + print(f'kept views: {len(rs)} replicas and a client at the cap; two left to join again; a join at once refused: "{said[1]}" ({dials} dials)') + time.sleep(max(0, at + more + 1 - time.monotonic())) said = Replica(sock).hello('kv', build) - assert said[0] == 'welcome', ('a view kept 31 s in an idle session, still kept', said) + assert said[0] == 'welcome', ('a view kept past what its refusal said in an idle session, still kept', more, said) assert a.poll() is None - print('kept views: a join 31 s after, nothing typed in between, took a kept view') + print(f'kept views: a join {more + 1} s after, nothing typed in between, took a kept view') a.terminate() a.wait(timeout=20) assert subprocess.run([binary, 'kill', 'kv'], env=env, capture_output=True, timeout=30).returncode == 0 @@ -2211,6 +2244,25 @@ def far_flood(binary): sess.wait(timeout=60) nine.socket.close() wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10) + except BaseException: + # Its evidence kept, the root going: the far client's checks and + # stats, its terminal, and where each process's threads wait. + kept = Path(tempfile.mkdtemp(prefix='fl-kept-', dir=scratch)) + for f in ('f.check', 'f.stats'): + if (root / f).exists(): + shutil.copy(root / f, kept) + for i, term in enumerate(terms): + (kept / f'term-{i}.out').write_bytes(term.text()) + with open(kept / 'threads', 'w') as out: + for pid in started: + out.write(f'{pid} {cmdline(pid)[:3]} alive={alive(pid)}\n') + for task in sorted(Path(f'/proc/{pid}/task').glob('*')) if procfs and alive(pid) else []: + try: + out.write(f' {task.name} {(task / "comm").read_text().strip()} {(task / "wchan").read_text()}\n') + except OSError: + pass + print(f'far flood: kept {kept}', file=sys.stderr) + raise finally: for term in terms: term.close() @@ -2861,7 +2913,7 @@ def main(binary, cycles): os.kill(stub, signal.SIGKILL) wait_for('the stub gone', lambda: not alive(stub)) wait_for('the session detached from its killed stub', lambda: sized(client)) - assert b'\x1b[?1049l' in term.text()[drawn:], 'the terminal is put back' + assert b'\x1b[?1049l' in term.last()[drawn:], 'the terminal is put back' assert alive(session) shell.kill() shell.wait(timeout=10) @@ -2889,7 +2941,7 @@ def main(binary, cycles): # the daemon go. exit_session(client, pane) assert stub.wait(timeout=10) == 0, stub.returncode - assert b'let this client go' not in term.text(), term.text()[-300:] + assert b'let this client go' not in term.last(), term.last()[-300:] client.socket.close() term.close() wait_for('the adopted shell hung up', lambda: not alive(shell_pid)) @@ -3273,7 +3325,8 @@ def upgrades(old, new): replica.close() stale.wait(timeout=30) # (Across a change of the replica protocol, it says that instead.) - assert b'upgrade this client too' in term3.text() or b'run the same pardes at both ends' in term3.text(), term3.text()[-400:] + said = term3.last() + assert b'upgrade this client too' in said or b'run the same pardes at both ends' in said, said[-400:] term3.close() print('upgrade: a replica client of the old build was let go, dialled again and was told to upgrade too') # The old image's prompt files swept, the new one's made. -- cgit v1.3 From b0e96978b619e1111ee2fb30e3c4a48f9fac38b3 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 22 Nov 2026 14:14:39 -0300 Subject: pty: a shell forks at its pane's grid, and the core hands its host every pty's size, pixels too (pardes-term-join-9, item 2 (B), points (a) and (c)): the spawn host call took no size and both hosts forked at the session's live screen (dev/Ptys.zig `spawn`, runtime/macos.zig `spawnShell`: `core.view().screen_h/w`), so a shell started again into a pane already sized (pty/ctl's exec, a finished command pane run again by exec.zig `runCommand`, a Restore's `revivePane`) ran at the screen's size and nothing resized it, the grid unchanged and `sync` emitting nothing (`stty size` said 50 160 in a 44x158 pane); and a pty's pixels were the live view's (host_io.zig `ptyWinsize` read `core.view().cell_pixels`) whichever view sized it; now `Effect.PtySize` (cells and pixels) is what the core gives its host for `spawn` and `pty_resize`, made by `Core.ptySize` from the pane's grid (or 9P's numbers) at the cell of the view that sizes it, a spawn performed after its step's `sync` reading the laid-out grid, and the hosts fork and size from it alone (`Ptys.take` sizes an adopted shell from it too: 1x1 then the size, once, its forced redraw kept, an ioctl to the size a pty has already sending no SIGWINCH); test (test/process/terminals.zig, a new case): a Term pane's shell, the same shell started again by pty/ctl's exec and a finished command pane run again each say the grid their pty/ctl reads back (fails on the base: 50 160 against 44 158); not covered: a new command pane made over 9P is placed a step after its fork, so its first size can still be the screen's Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Core.zig | 12 +++++- core/Effect.zig | 11 ++++-- core/ninep/harness.zig | 2 +- core/replica.zig | 4 +- core/root.zig | 1 + dev/Host.zig | 4 +- dev/Ptys.zig | 27 +++++++------- dev/gui/gui.zig | 2 +- dev/host_io.zig | 42 +++++++++------------ runtime/macos.zig | 10 ++--- test/process/terminals.zig | 93 ++++++++++++++++++++++++++++++++++++++++++++++ 11 files changed, 155 insertions(+), 53 deletions(-) diff --git a/core/Core.zig b/core/Core.zig index 91f647d4..8616aa35 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -2013,6 +2013,16 @@ pub fn sync(p: *Pardes) void { tagline.revealHeader(p); } +/// Pane `id`'s pty as its host is to size it: its grid (or `cells`, a +/// size 9P's pty/ctl gave), in pixels at the cell of the view that sizes +/// it: a program sizes its kitty graphics by them. +pub fn ptySize(p: *const Pardes, id: Pane.Id, cells: ?[2]u16) pardes.PtySize { + const pane = p.panes[id.index()] orelse return .{ .cols = 1, .rows = 1 }; + const c = cells orelse .{ pane.cols, pane.rows }; + const cell = (p.views[pane.sized_by] orelse p.views[p.live].?).cell_pixels; + return .{ .cols = @max(c[0], 1), .rows = @max(c[1], 1), .w_px = std.math.cast(u16, @as(u32, c[0]) * cell.w) orelse 0, .h_px = std.math.cast(u16, @as(u32, c[1]) * cell.h) orelse 0 }; +} + /// The view typing goes into is the one its terminal is sized for /// (`sizes`). fn typedInto(p: *Pardes) void { @@ -2888,7 +2898,7 @@ test "a spawn is for the pane it was made for, not whatever took the slot since" var command: [32]u8 = undefined; var core: *Pardes = undefined; const vtable: Host.VTable = .{ .spawn = spawn }; - fn spawn(_: ?*anyopaque, id: pardes.Pane.Id, _: []const u8) void { + fn spawn(_: ?*anyopaque, id: pardes.Pane.Id, _: []const u8, _: pardes.PtySize) void { const pane = id.index(); spawns += 1; const line = core.panes[pane].?.command.?; diff --git a/core/Effect.zig b/core/Effect.zig index cabfe8ea..abfe4711 100644 --- a/core/Effect.zig +++ b/core/Effect.zig @@ -22,6 +22,10 @@ const Host = pardes.Host; /// to the shell itself when the shell is in the foreground. pub const PtySignal = enum(u8) { int, term, hup, quit, kill }; +/// A pty's size as the core gives it to its host: in cells, and in pixels +/// at the cell of the view that sizes its pane (Core.ptySize). +pub const PtySize = struct { cols: u16, rows: u16, w_px: u16 = 0, h_px: u16 = 0 }; + /// IO the core wants done. Payloads are inline (fixed buffers): effects are /// queued values with no lifetime ties back into the core. pub const WatchMode = enum { reconcile, baseline_disk }; @@ -118,14 +122,15 @@ fn performInner(p: *Pardes, e: Effect) void { defer panes.File.syncTwins(p); switch (e) { // The host reads the pane (its command, its shell) as it forks, - // so the slot must still hold the pane the spawn was for. - .spawn => |s| if (if (p.panes[s.pane.index()]) |pane| pane.serial != s.serial else true) {} else p.tape.host(p, .spawn, .{ s.pane, if (s.cwd.len == 0) (p.spawn_dirs[s.pane.index()] orelse "") else s.cwd.slice() }) orelse { + // so the slot must still hold the pane the spawn was for. It forks + // at the pane's grid: laid out by the step that asked (`sync`). + .spawn => |s| if (if (p.panes[s.pane.index()]) |pane| pane.serial != s.serial else true) {} else p.tape.host(p, .spawn, .{ s.pane, if (s.cwd.len == 0) (p.spawn_dirs[s.pane.index()] orelse "") else s.cwd.slice(), p.ptySize(s.pane, null) }) orelse { p.fallback.spawned[s.pane.index()] = true; }, // A pane with no child is silent: nothing invents output on its // screen, and the bytes are dropped rather than transcribed. .write => |w| _ = p.tape.host(p, .pty_write, .{ w.pane, w.bytes.slice() }), - .resize_pty => |r| _ = p.tape.host(p, .pty_resize, .{ r.pane, r.cols, r.rows }), + .resize_pty => |r| _ = p.tape.host(p, .pty_resize, .{ r.pane, p.ptySize(r.pane, .{ r.cols, r.rows }) }), // A signal for a pane that closed, its slot retaken in the same // step, would reach another pane's child. .signal_pty => |s| if (if (p.panes[s.pane.index()]) |pane| pane.serial != s.serial else true) {} else p.tape.host(p, .pty_signal, .{ s.pane, s.sig }) orelse {}, diff --git a/core/ninep/harness.zig b/core/ninep/harness.zig index cf75d80d..1449ae54 100644 --- a/core/ninep/harness.zig +++ b/core/ninep/harness.zig @@ -153,7 +153,7 @@ pub fn nameAt(list: []const Dirent, want: []const u8) ?Dirent { /// none. pub const starting: pardes.Host.VTable = .{ .spawn = startNothing }; -fn startNothing(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {} +fn startNothing(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8, _: pardes.PtySize) void {} pub const FakeTty = struct { taken: bool, diff --git a/core/replica.zig b/core/replica.zig index ae1ae6c3..3aac5e82 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -3298,7 +3298,7 @@ const TestHost = struct { /// A host with ptys whose pump polls for a frame, as a client's does. const PtyHost = struct { - fn resized(_: ?*anyopaque, _: pardes.Pane.Id, _: u16, _: u16) void {} + fn resized(_: ?*anyopaque, _: pardes.Pane.Id, _: pardes.PtySize) void {} fn poll(_: ?*anyopaque) void {} const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .pty_resize = resized, .poll_frame = poll }; fn host() pardes.Host { @@ -4238,7 +4238,7 @@ fn firstOnPair(by_dump: bool) !void { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const Spawns = struct { - fn spawn(ctx: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void { + fn spawn(ctx: ?*anyopaque, _: pardes.Pane.Id, _: []const u8, _: pardes.PtySize) void { const n: *u32 = @ptrCast(@alignCast(ctx.?)); n.* += 1; } diff --git a/core/root.zig b/core/root.zig index fb606909..99fb4845 100644 --- a/core/root.zig +++ b/core/root.zig @@ -66,6 +66,7 @@ pub const CellPixels = @import("Event.zig").CellPixels; pub const Event = @import("Event.zig").Event; /// What goes out (Effect.zig). pub const PtySignal = @import("Effect.zig").PtySignal; +pub const PtySize = @import("Effect.zig").PtySize; pub const WatchMode = @import("Effect.zig").WatchMode; pub const effect_path_cap = @import("Effect.zig").effect_path_cap; pub const effect_write_cap = @import("Effect.zig").effect_write_cap; diff --git a/dev/Host.zig b/dev/Host.zig index cb7aefe1..52205518 100644 --- a/dev/Host.zig +++ b/dev/Host.zig @@ -30,9 +30,9 @@ pub const VTable = struct { /// Upgrade: this process exec'd as the pardes installed since, at /// the step's end (upgrade.zig); `pane` hears why if it cannot be. upgrade: ?*const fn (ctx: ?*anyopaque, pane: pardes.Pane.Id) void = null, - spawn: ?*const fn (ctx: ?*anyopaque, pane: pardes.Pane.Id, cwd: []const u8) void = null, + spawn: ?*const fn (ctx: ?*anyopaque, pane: pardes.Pane.Id, cwd: []const u8, size: pardes.PtySize) void = null, pty_write: ?*const fn (ctx: ?*anyopaque, pane: pardes.Pane.Id, bytes: []const u8) void = null, - pty_resize: ?*const fn (ctx: ?*anyopaque, pane: pardes.Pane.Id, cols: u16, rows: u16) void = null, + pty_resize: ?*const fn (ctx: ?*anyopaque, pane: pardes.Pane.Id, size: pardes.PtySize) void = null, pty_signal: ?*const fn (ctx: ?*anyopaque, pane: pardes.Pane.Id, sig: pardes.PtySignal) void = null, close_pty: ?*const fn (ctx: ?*anyopaque, pane: pardes.Pane.Id) void = null, tty_taken: ?*const fn (ctx: ?*anyopaque, pane: pardes.Pane.Id) bool = null, diff --git a/dev/Ptys.zig b/dev/Ptys.zig index 583e3c38..5b8705ef 100644 --- a/dev/Ptys.zig +++ b/dev/Ptys.zig @@ -45,16 +45,15 @@ pub fn Calls(comptime Ctx: type) type { fn of(ctx: ?*anyopaque) *Ctx { return @ptrCast(@alignCast(ctx.?)); } - pub fn spawn(ctx: ?*anyopaque, id: pardes.Pane.Id, cwd: []const u8) void { + pub fn spawn(ctx: ?*anyopaque, id: pardes.Pane.Id, cwd: []const u8, size: pardes.PtySize) void { const s = of(ctx); - s.ptys.spawn(s.core, id, cwd); + s.ptys.spawn(s.core, id, cwd, size); } pub fn write(ctx: ?*anyopaque, id: pardes.Pane.Id, bytes: []const u8) void { of(ctx).ptys.write(id, bytes); } - pub fn resize(ctx: ?*anyopaque, id: pardes.Pane.Id, cols: u16, rows: u16) void { - const s = of(ctx); - s.ptys.resize(s.core, id, cols, rows); + pub fn resize(ctx: ?*anyopaque, id: pardes.Pane.Id, size: pardes.PtySize) void { + of(ctx).ptys.resize(id, size); } pub fn signal(ctx: ?*anyopaque, id: pardes.Pane.Id, sig: pardes.PtySignal) void { of(ctx).ptys.signal(id, sig); @@ -82,14 +81,14 @@ pub fn Calls(comptime Ctx: type) type { } /// Pane `id`'s shell, in `cwd` (empty: where its pane's directory says), -/// or the adopted one waiting for it. -pub fn spawn(p: *Ptys, core: *pardes.Pardes, id: pardes.Pane.Id, cwd: []const u8) void { +/// at `size`, or the adopted one waiting for it. +pub fn spawn(p: *Ptys, core: *pardes.Pardes, id: pardes.Pane.Id, cwd: []const u8, size: pardes.PtySize) void { const pane = id.index(); - if (p.adoptions.take(id)) |a| return p.take(core, pane, a); + if (p.adoptions.take(id)) |a| return p.take(core, pane, a, size); // The new shell starts before a running one goes: one that cannot // start leaves the running one be (pty/ctl's exec). const running = p.slots[pane] != null; - const child = host_io.forkShell(core, pane, p.prompt_rcs, core.shellBin(), cwd, core.view().screen_h, core.view().screen_w) catch |err| { + const child = host_io.forkShell(core, pane, p.prompt_rcs, core.shellBin(), cwd, size) catch |err| { if (running) return core.restartFailed(id, err); return core.shellFailed(id, err); }; @@ -107,7 +106,7 @@ pub fn spawn(p: *Ptys, core: *pardes.Pardes, id: pardes.Pane.Id, cwd: []const u8 /// An adopted shell, running already, as pane `pane`'s: told the size /// twice (a size it never had, then the pane's), which makes it redraw. -fn take(p: *Ptys, core: *pardes.Pardes, pane: u8, a: host_io.Adoption) void { +fn take(p: *Ptys, core: *pardes.Pardes, pane: u8, a: host_io.Adoption, size: pardes.PtySize) void { p.close(.at(pane)); p.gens[pane] +%= 1; p.slots[pane] = .{ .fd = a.fd, .pid = a.pid }; @@ -117,7 +116,7 @@ fn take(p: *Ptys, core: *pardes.Pardes, pane: u8, a: host_io.Adoption) void { if (host_io.shellCwd(a.pid, &lbuf)) |wd| core.setCwd(.at(pane), wd); const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 }; _ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny)); - if (core.panes[pane]) |pn| p.resize(core, .at(pane), @max(pn.cols, 1), @max(pn.rows, 1)); + p.resize(.at(pane), size); p.read(core, pane); } @@ -144,9 +143,9 @@ pub fn write(p: *Ptys, id: pardes.Pane.Id, bytes: []const u8) void { if (p.slots[id.index()]) |pt| _ = host_io.writeFd(pt.fd, bytes); } -pub fn resize(p: *Ptys, core: *const pardes.Pardes, id: pardes.Pane.Id, cols: u16, rows: u16) void { +pub fn resize(p: *Ptys, id: pardes.Pane.Id, size: pardes.PtySize) void { const pt = p.slots[id.index()] orelse return; - const ws = host_io.ptyWinsize(core, cols, rows); + const ws = host_io.ptyWinsize(size); _ = posix.system.ioctl(pt.fd, TIOCSWINSZ, @intFromPtr(&ws)); } @@ -290,7 +289,7 @@ fn testing(queue: *Inbox) Ptys { } fn testShell(p: *Ptys, pane: u8) !libc.pid_t { - const child = try host_io.forkShell(null, pane, p.prompt_rcs, "/bin/sh", "", 24, 80); + const child = try host_io.forkShell(null, pane, p.prompt_rcs, "/bin/sh", "", .{ .cols = 80, .rows = 24 }); p.slots[pane] = .{ .fd = child.file.handle, .pid = child.pid }; p.slots[pane].?.reader = try p.queue.startReader(.{ .handle = child.file.handle, .flags = .{ .nonblocking = false } }, .at(pane), p.gens[pane]); return child.pid; diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index bfe658f9..d9d38f06 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -7677,7 +7677,7 @@ test "a detached GUI authority follows terminal directory changes with no window defer ptys.deinit(); var no_peers: replica.Peers = .{}; var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .ptys = &ptys, .queue = &queue, .watches = undefined, .peers = &no_peers }; - const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); + const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", start, .{ .cols = 80, .rows = 24 }); ptys.slots[0] = .{ .fd = child.file.handle, .pid = child.pid }; try std.testing.expect(host_io.writeFd(child.file.handle, "cd child\n")); const until = std.Io.Clock.awake.now(io).toMilliseconds() + 2_000; diff --git a/dev/host_io.zig b/dev/host_io.zig index 419c4570..f189c8ea 100644 --- a/dev/host_io.zig +++ b/dev/host_io.zig @@ -420,13 +420,8 @@ pub const exec_command_max = pardes.exec.command_max; /// A pane's pty size, in cells and in pixels: a program sizes its kitty /// graphics by the pixels (yazi's previews; pardes nested in a pane). -pub fn ptyWinsize(core: ?*const pardes.Pardes, cols: u16, rows: u16) posix.winsize { - var ws: posix.winsize = .{ .row = rows, .col = cols, .xpixel = 0, .ypixel = 0 }; - if (core) |c| { - ws.xpixel = std.math.cast(u16, @as(u32, cols) * c.view().cell_pixels.w) orelse 0; - ws.ypixel = std.math.cast(u16, @as(u32, rows) * c.view().cell_pixels.h) orelse 0; - } - return ws; +pub fn ptyWinsize(size: pardes.PtySize) posix.winsize { + return .{ .row = size.rows, .col = size.cols, .xpixel = size.w_px, .ypixel = size.h_px }; } pub fn forkShell( @@ -435,8 +430,7 @@ pub fn forkShell( prompt_rcs: *const Shell.PromptFiles, bin: []const u8, cwd: []const u8, - rows: u16, - cols: u16, + size: pardes.PtySize, ) !Child { const native_cwd = filesystem.localPath(cwd) orelse cwd; if (std.mem.indexOfScalar(u8, native_cwd, 0) != null) return error.InvalidPath; @@ -494,7 +488,7 @@ pub fn forkShell( else .terminal; const envp = ChildEnv.build(&env_slots, paging); - const ws = ptyWinsize(core, cols, rows); + const ws = ptyWinsize(size); // The child says here why it could not become the shell (its chdir or // its exec failed, as for a script whose interpreter is not there): the // pipe closes on exec, so the parent reads nothing when the shell runs, @@ -1672,9 +1666,9 @@ test "the child environment replaces the launcher's terminal identity exactly on test "shell spawn rejects invalid directories before creating a child" { const rcs: Shell.PromptFiles = .{}; - try std.testing.expectError(error.InvalidPath, forkShell(null, 0, &rcs, "/bin/sh", "/tmp\x00/ignored", 24, 80)); + try std.testing.expectError(error.InvalidPath, forkShell(null, 0, &rcs, "/bin/sh", "/tmp\x00/ignored", .{ .cols = 80, .rows = 24 })); const too_long = @as([4096]u8, @splat('x')); - try std.testing.expectError(error.NameTooLong, forkShell(null, 0, &rcs, "/bin/sh", &too_long, 24, 80)); + try std.testing.expectError(error.NameTooLong, forkShell(null, 0, &rcs, "/bin/sh", &too_long, .{ .cols = 80, .rows = 24 })); var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -1683,12 +1677,12 @@ test "shell spawn rejects invalid directories before creating a child" { const directory = directory_buf[0..try tmp.dir.realPath(std.testing.io, &directory_buf)]; var path_buf: [4096]u8 = undefined; const file = try std.fmt.bufPrint(&path_buf, "{s}/file", .{directory}); - try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", file, 24, 80)); + try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", file, .{ .cols = 80, .rows = 24 })); const explicit_file = try std.fmt.bufPrint(&path_buf, "/n/os{s}/file", .{directory}); - try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", explicit_file, 24, 80)); + try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", explicit_file, .{ .cols = 80, .rows = 24 })); const missing = try std.fmt.bufPrint(&path_buf, "{s}/missing/" ++ (std.mem.asBytes(&@as([50][6]u8, @splat("child/".*)))), .{directory}); try std.testing.expect(missing.len > 256); - try std.testing.expectError(error.FileNotFound, forkShell(null, 0, &rcs, "/bin/sh", missing, 24, 80)); + try std.testing.expectError(error.FileNotFound, forkShell(null, 0, &rcs, "/bin/sh", missing, .{ .cols = 80, .rows = 24 })); } test "a forked shell is told which terminal it is talking to" { @@ -1711,7 +1705,7 @@ test "a forked shell is told which terminal it is talking to" { _ = Shell.setenv("TERM", "dumb", 1); const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); + const child = try forkShell(null, 0, &rcs, "/bin/sh", "", .{ .cols = 80, .rows = 24 }); defer { _ = libc.kill(child.pid, libc.SIG.KILL); _ = libc.waitpid(child.pid, null, 0); @@ -1739,7 +1733,7 @@ test "shell spawn uses an explicit OS directory longer than 256 bytes" { var explicit_buf: [4096]u8 = undefined; const explicit = try std.fmt.bufPrint(&explicit_buf, "/n/os{s}", .{directory}); const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(null, 0, &rcs, "/bin/sh", explicit, 24, 80); + const child = try forkShell(null, 0, &rcs, "/bin/sh", explicit, .{ .cols = 80, .rows = 24 }); defer { _ = libc.kill(child.pid, libc.SIG.KILL); _ = libc.waitpid(child.pid, null, 0); @@ -1768,7 +1762,7 @@ test "a terminal is where its shell is: under a wrapper the foreground shell, ne // A wrapper exec'd over the shell (timeout standing in for 9ns) runs // another, two directories down, in the foreground. { - const child = try forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); + const child = try forkShell(null, 0, &rcs, "/bin/sh", start, .{ .cols = 80, .rows = 24 }); defer { _ = libc.kill(child.pid, libc.SIG.KILL); _ = libc.waitpid(child.pid, null, 0); @@ -1787,7 +1781,7 @@ test "a terminal is where its shell is: under a wrapper the foreground shell, ne // A job of the shell's own, gone into a/b, leaves the pane where the // shell is. { - const child = try forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); + const child = try forkShell(null, 0, &rcs, "/bin/sh", start, .{ .cols = 80, .rows = 24 }); defer { _ = libc.kill(child.pid, libc.SIG.KILL); _ = libc.waitpid(child.pid, null, 0); @@ -1812,7 +1806,7 @@ test "shell cwd rejects truncation and preserves an owned child path longer than const directory = path_buf[0..try tmp.dir.realPathFile(io, nested, &path_buf)]; try std.testing.expect(directory.len > 1024); const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(null, 0, &rcs, "/bin/sh", directory, 24, 80); + const child = try forkShell(null, 0, &rcs, "/bin/sh", directory, .{ .cols = 80, .rows = 24 }); defer { _ = libc.kill(child.pid, libc.SIG.KILL); _ = libc.waitpid(child.pid, null, 0); @@ -1839,7 +1833,7 @@ test "a shell whose directory was removed is not named `... (deleted)`" { var path_buf: [4096]u8 = undefined; const directory = path_buf[0..try tmp.dir.realPathFile(io, "gone", &path_buf)]; const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(null, 0, &rcs, "/bin/sh", directory, 24, 80); + const child = try forkShell(null, 0, &rcs, "/bin/sh", directory, .{ .cols = 80, .rows = 24 }); defer { _ = libc.kill(child.pid, libc.SIG.KILL); _ = libc.waitpid(child.pid, null, 0); @@ -1949,7 +1943,7 @@ test "a command pane's child is its shell running the one line, and its exit sta _ = try panes.newCommand(core, id, "", "printf 'said '; exit 7"); while (core.nextEffect()) |_| {} const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(core, id, &rcs, "/bin/sh", "", 24, 80); + const child = try forkShell(core, id, &rcs, "/bin/sh", "", .{ .cols = 80, .rows = 24 }); defer _ = libc.close(child.file.handle); var got: [256]u8 = undefined; var n: usize = 0; @@ -1980,7 +1974,7 @@ test "a command's exit is its process's, told by its watcher, whether or not its const id = core.freeSlot().?; _ = try panes.newCommand(core, id, "", c.line); while (core.nextEffect()) |_| {} - const child = try forkShell(core, id, &rcs, "/bin/sh", "", 24, 80); + const child = try forkShell(core, id, &rcs, "/bin/sh", "", .{ .cols = 80, .rows = 24 }); defer _ = libc.close(child.file.handle); try std.testing.expect(watchExit(child.pid)); var got: ?libc.pid_t = null; @@ -2021,7 +2015,7 @@ test "a command's background job outlives it and its pty, and Kill stops its who const id = core.freeSlot().?; _ = try panes.newCommand(core, id, dir, c.line); while (core.nextEffect()) |_| {} - const child = try forkShell(core, id, &rcs, "/bin/sh", dir, 24, 80); + const child = try forkShell(core, id, &rcs, "/bin/sh", dir, .{ .cols = 80, .rows = 24 }); if (c.kill) { sleepMs(150); signalTty(child.pid, child.file.handle, .term, true); diff --git a/runtime/macos.zig b/runtime/macos.zig index 23d70b27..3221737a 100644 --- a/runtime/macos.zig +++ b/runtime/macos.zig @@ -1649,14 +1649,14 @@ fn hostState(ctx: ?*anyopaque) *State { return @ptrCast(@alignCast(ctx.?)); } -fn spawnShell(ctx: ?*anyopaque, id: pardes.Pane.Id, cwd: []const u8) void { +fn spawnShell(ctx: ?*anyopaque, id: pardes.Pane.Id, cwd: []const u8, size: pardes.PtySize) void { const pane = id.index(); const st = hostState(ctx); const core = st.core; // The new shell starts before a running one goes: one that cannot // start leaves the running one be (pty/ctl's exec). const running = st.ptys[pane] != null; - const child = host_io.forkShell(core, pane, &st.prompt_rcs, core.shellBin(), cwd, core.view().screen_h, core.view().screen_w) catch |err| { + const child = host_io.forkShell(core, pane, &st.prompt_rcs, core.shellBin(), cwd, size) catch |err| { if (running) return core.restartFailed(id, err); return core.shellFailed(id, err); }; @@ -1685,11 +1685,11 @@ fn ptyWrite(ctx: ?*anyopaque, id: pardes.Pane.Id, bytes: []const u8) void { if (st.ptys[pane]) |pt| _ = host_io.writeFd(pt.file.handle, bytes); } -fn ptyResize(ctx: ?*anyopaque, id: pardes.Pane.Id, cols: u16, rows: u16) void { +fn ptyResize(ctx: ?*anyopaque, id: pardes.Pane.Id, size: pardes.PtySize) void { const pane = id.index(); const st = hostState(ctx); const pt = st.ptys[pane] orelse return; - const ws: posix.winsize = .{ .row = rows, .col = cols, .xpixel = 0, .ypixel = 0 }; + const ws = host_io.ptyWinsize(size); _ = posix.system.ioctl(pt.file.handle, TIOCSWINSZ, @intFromPtr(&ws)); } @@ -2339,7 +2339,7 @@ test "mac Restore cancels a PTY reader waiting for output capacity" { while (st.core.nextEffect()) |_| {} st.inbox.acceptReader(.at(1), 1); for (0..Inbox.output_capacity) |_| _ = st.inbox.pushOutput(.at(1), 1, try gpa.dupe(u8, "retained output")); - const child = try host_io.forkShell(null, 0, &st.prompt_rcs, "/bin/sh", "", 12, 40); + const child = try host_io.forkShell(null, 0, &st.prompt_rcs, "/bin/sh", "", .{ .cols = 40, .rows = 12 }); st.gens[0] = 1; st.ptys[0] = .{ .file = child.file, .pid = child.pid, .gen = 1, .reader = .{ .any_future = null, .result = {} } }; defer { diff --git a/test/process/terminals.zig b/test/process/terminals.zig index d9c3bcca..151b221b 100644 --- a/test/process/terminals.zig +++ b/test/process/terminals.zig @@ -16,6 +16,7 @@ pub const cases = .{ .{ "terminals: a program's prompt shows and holds still, input sent unsubmitted shows, and ^U takes the screen back to what it was", prompt }, .{ "terminals: what a program prints past a screenful stays in the terminal's body, and its prompt after it shows", history }, .{ "terminals: a control byte through pty/data reaches a program in raw mode, which then carries on", rawKey }, + .{ "terminals: a shell started into a pane runs at the pane's grid, not the screen's: a new terminal, its shell started again by pty/ctl's exec, a finished command pane run again", sizedFork }, }; fn has(hay: []const u8, needle: []const u8) bool { @@ -78,6 +79,98 @@ const Other = struct { } }; +/// What `stty size` in terminal `term` says, beside the grid its pty/ctl +/// reads back, each as "rows cols". +fn sttySize(a: std.mem.Allocator, c: *process.Conn, term: u32) ![2][]const u8 { + var lines = std.mem.splitScalar(u8, try run(a, c, term, "stty size\n"), '\n'); + _ = lines.next(); + return .{ lines.next() orelse "", try grid(a, c, term) }; +} + +/// Pane `n`'s grid, as pty/ctl reads it back ("winsize C R"): "rows cols". +fn grid(a: std.mem.Allocator, c: *process.Conn, n: u32) ![]const u8 { + var w = std.mem.tokenizeAny(u8, try c.read(a, try std.fmt.allocPrint(a, "/pane/{d}/pty/ctl", .{n})), " \n"); + _ = w.next(); + const cols = w.next() orelse ""; + return std.fmt.allocPrint(a, "{s} {s}", .{ w.next() orelse "", cols }); +} + +/// The lines of pane `n`'s body that are two numbers (`stty size`'s). +fn sizeLines(a: std.mem.Allocator, c: *process.Conn, n: u32) ![]const []const u8 { + var out: std.ArrayList([]const u8) = .empty; + var rows = std.mem.tokenizeScalar(u8, try c.read(a, try std.fmt.allocPrint(a, "/pane/{d}/body", .{n})), '\n'); + while (rows.next()) |row| { + var w = std.mem.tokenizeScalar(u8, std.mem.trim(u8, row, " \r"), ' '); + const r = w.next() orelse continue; + const k = w.next() orelse continue; + if (w.next() != null) continue; + _ = std.fmt.parseInt(u16, r, 10) catch continue; + _ = std.fmt.parseInt(u16, k, 10) catch continue; + try out.append(a, try std.fmt.allocPrint(a, "{s} {s}", .{ r, k })); + } + return out.items; +} + +/// A shell takes runs: its first prompt, or the one started again. +fn prompted(a: std.mem.Allocator, c: *process.Conn, term: u32) !void { + const deadline = eh.nowMs() + 10_000; + while (!std.mem.eql(u8, try run(a, c, term, "true\n"), "exit 0\n")) { + if (eh.nowMs() > deadline) return error.NoPrompt; + process.sleep(50); + } +} + +fn sizedFork(gpa: std.mem.Allocator, exe: [:0]const u8) !void { + var d = try process.Detached.start(gpa, exe, "sized", .{}); + defer d.deinit(); + const f = &d.files; + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const c = try process.Conn.dial(gpa, d.socket()); + defer c.deinit(gpa); + const text = (try serials(a, c))[0]; + try c.write("/exec", "Shell bash\n"); + // A terminal beside the text: its grid is its rect less the tag, never + // the screen's 160x50. + try c.write("/exec", "Term\n"); + const term = try c.newest(gpa); + try prompted(a, c, term); + var got = try sttySize(a, c, term); + try expect(!std.mem.eql(u8, got[1], "50 160")); + try expectEqualStrings(got[1], got[0]); + // Its shell started again: the pane is sized already, and nothing + // resizes it after. + const pid = try run(a, c, term, "echo $$\n"); + try c.write(f.at("/pane/{d}/pty/ctl", .{term}), "exec\n"); + const again_by = eh.nowMs() + 10_000; + while (true) { + const now = run(a, c, term, "echo $$\n") catch ""; + if (std.mem.startsWith(u8, now, "exit 0\n") and !std.mem.eql(u8, now, pid)) break; + if (eh.nowMs() > again_by) return error.NeverStartedAgain; + process.sleep(50); + } + got = try sttySize(a, c, term); + try expectEqualStrings(got[1], got[0]); + // A command pane, then the same line again: the finished pane is run + // again (exec.zig `runCommand`), a pane sized already. (The new one is + // placed a step after its fork: its first size can be the screen's.) + try c.exec(text, "stty size"); + var words = std.mem.tokenizeAny(u8, try c.pane(a, text, "exec"), " \n"); + var last: []const u8 = ""; + while (words.next()) |w| last = w; + const cmd = try std.fmt.parseInt(u32, last, 10); + for (1..3) |k| { + if (k == 2) try c.exec(text, "stty size"); + const by = eh.nowMs() + 10_000; + while ((try sizeLines(a, c, cmd)).len < k) { + if (eh.nowMs() > by) return error.NoSize; + process.sleep(50); + } + if (k == 2) try expectEqualStrings(try grid(a, c, cmd), (try sizeLines(a, c, cmd))[1]); + } +} + fn runFile(gpa: std.mem.Allocator, exe: [:0]const u8) !void { var d = try process.Detached.start(gpa, exe, "run", .{}); defer d.deinit(); -- cgit v1.3 From 9041c9d48326ac13e30ffbb0d6df636cc058c6dc Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 22 Nov 2026 14:14:40 -0300 Subject: views: a closed view sizes no terminal, and none takes its size until a view types into it (pardes-term-join-9, item 2 (B), point (b)): `sizes` handed a terminal whose sizing view had closed to whichever view was live at the next `sync`, a view nobody looks at among them, and a client given the closed view's index later sized it without typing; now `Pane.sized_by` is `?u8`, `views.dropView` clears it (the terminal keeps the size it has), `closeKeeping` hands it to the view that takes the closing one's place (the session's own laid out as it was: the size it promised to keep), and `sizes` is `sized_by == live` alone, typing (`typedInto`) the one act that moves it; test (core/views.zig "a terminal shown at two sizes ...", extended): the pty's pixels at the sizing view's cell whichever view is live (point (c) of the change before); the sizing view closed, the size stays until the view left types; a view opened at the closed index sizes nothing until it types (on the base the size moved at the close) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Core.zig | 17 ++++++++--------- core/panes.zig | 7 ++++--- core/views.zig | 25 +++++++++++++++++++++++-- 3 files changed, 35 insertions(+), 14 deletions(-) diff --git a/core/Core.zig b/core/Core.zig index 8616aa35..1dd03524 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -2019,7 +2019,7 @@ pub fn sync(p: *Pardes) void { pub fn ptySize(p: *const Pardes, id: Pane.Id, cells: ?[2]u16) pardes.PtySize { const pane = p.panes[id.index()] orelse return .{ .cols = 1, .rows = 1 }; const c = cells orelse .{ pane.cols, pane.rows }; - const cell = (p.views[pane.sized_by] orelse p.views[p.live].?).cell_pixels; + const cell = (if (pane.sized_by) |k| p.views[k] orelse p.views[p.live].? else p.views[p.live].?).cell_pixels; return .{ .cols = @max(c[0], 1), .rows = @max(c[1], 1), .w_px = std.math.cast(u16, @as(u32, c[0]) * cell.w) orelse 0, .h_px = std.math.cast(u16, @as(u32, c[1]) * cell.h) orelse 0 }; } @@ -2030,16 +2030,15 @@ fn typedInto(p: *Pardes) void { } /// Whether the live view sizes terminal `pane`: a terminal shown at two -/// sizes takes the size of the view that typed into it last, and any -/// view's once that one is gone. The others show it at that size, a -/// shorter one passed down to its cursor (`Pane.pan`, Pane.panFor). +/// sizes takes the size of the view that typed into it last, and keeps it +/// once that view is gone until another types into it (views.dropView): +/// a view nobody types in never takes it. The others show it at that +/// size, a shorter one passed down to its cursor (`Pane.pan`, +/// Pane.panFor). // ponytail: a panned view's pointer reports to a terminal's program and // its kitty images are placed as the unpanned rows are. -fn sizes(p: *Pardes, pane: *Pane) bool { - if (pane.sized_by == p.live) return true; - if (Views.isOpen(p, pane.sized_by)) return false; - pane.sized_by = p.live; - return true; +fn sizes(p: *const Pardes, pane: *const Pane) bool { + return pane.sized_by == p.live; } pub fn theme(p: *const Pardes) *const Theme { diff --git a/core/panes.zig b/core/panes.zig index a2e383c1..d9759d18 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -367,9 +367,10 @@ pub const Pane = struct { /// The views `pv` holds a share for (a pane retired before a view came /// has none of it). pv_known: u8 = 0, - /// The view that last typed into it: a terminal shown at two sizes takes - /// that view's (Pardes.sync). - sized_by: u8 = 0, + /// The view that last typed into it, while that view is open: a + /// terminal shown at two sizes takes that view's (Pardes.sync); none, + /// it keeps the size it has. + sized_by: ?u8 = 0, /// A terminal shown in a view shorter than it (one that does not size /// it): the rows its top is passed over by, so its cursor stays in /// sight (Pane.panFor); 0 everywhere else. diff --git a/core/views.zig b/core/views.zig index 704fc859..663610c3 100644 --- a/core/views.zig +++ b/core/views.zig @@ -423,6 +423,7 @@ pub fn closeKeeping(p: *Pardes, k: u8) void { inline for (sized ++ laid_out) |name| @field(v, name) = @field(p.views[k].?, name); v.jumps.force = force; for (p.panes) |s| if (s) |pane| { + if (pane.sized_by == k) pane.sized_by = other; if (pane.pv_known & bit(other) != 0 and pane.pv[other].body.sels.len > 0) p.gpa.free(pane.pv[other].body.sels); pane.pv[other] = fresh(pane); pane.pv_known |= bit(other); @@ -447,8 +448,10 @@ fn dropView(p: *Pardes, k: u8) void { } pane.pv[k].body.sels = &.{}; pane.pv_known &= ~bit(k); - // A name it was drafting goes with it. + // A name it was drafting goes with it; a terminal it sized keeps + // its size (Pardes.sizes), for no view that is not typed in. if (pane.prompt == .name and pane.prompt_view == k) pane.closePrompt(); + if (pane.sized_by == k) pane.sized_by = null; }; p.views_open &= ~bit(k); p.views_away &= ~bit(k); @@ -700,10 +703,28 @@ test "a terminal shown at two sizes takes the size of the view that typed into i try testing.expectEqual(big, .{ term.cols, term.rows }); p.update(.{ .key = .{ .cp = Key.right } }); try testing.expectEqual(small, .{ term.cols, term.rows }); - // That view gone, the one left sizes it. + // Its pty in pixels at the cell of the view that sizes it, whichever + // is live. + p.views[k.index()].?.cell_pixels = .{ .w = 10, .h = 20 }; + p.update(.{ .key = .{ .cp = Key.right } }); + p.toView(k); + p.update(.{ .key = .{ .cp = Key.right } }); + p.toView(.at(0)); + try testing.expectEqual(pardes.PtySize{ .cols = big[0], .rows = big[1], .w_px = big[0] * 10, .h_px = big[1] * 20 }, p.ptySize(.at(p.view().active), null)); + p.update(.{ .key = .{ .cp = Key.right } }); + try testing.expectEqual(pardes.PtySize{ .cols = small[0], .rows = small[1], .w_px = small[0] * 8, .h_px = small[1] * 16 }, p.ptySize(.at(p.view().active), null)); + // That view gone, the size stays until the one left types into it; a + // view opened in its place sizes nothing it has not typed into. p.toView(k); p.closeView(.at(0)); try testing.expectEqual(k.index(), p.live); + try testing.expectEqual(small, .{ term.cols, term.rows }); + const again = p.openView().?; + p.toView(again); + p.update(.{ .resize = .{ .cols = 100, .rows = 30 } }); + try testing.expectEqual(small, .{ term.cols, term.rows }); + p.toView(k); + p.update(.{ .key = .{ .cp = Key.right } }); try testing.expectEqual(big, .{ term.cols, term.rows }); } -- cgit v1.3 From bad506bd45846e012246a33b5d3097b3e92f02bc Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 22 Nov 2026 15:37:05 -0300 Subject: docs: pty/ctl's winsize sets the pty alone, apart from the grid, until the pane's size changes or its shell is started again (pardes-term-join-9, item 2 (e), round 8's row 11: on purpose, said in the manual's words): reference.typ's pty/ctl entry Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- docs/typ/reference.typ | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index 425209a0..ac61ca74 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -897,7 +897,7 @@ Terminal panes also have #file("pty/"): command runs or text is typed at the prompt. A terminal whose program was killed on the alternate screen is at its prompt once the shell draws one there: busy is 0, and the next #file("pty/run") reads its output whole. -- #file("pty/ctl"): `winsize C R` (at least 2 rows, fewer refused `invalid winsize: at least 2 rows`; at most 4096 a side), `sig INT|TERM|HUP|QUIT|KILL`, `exec` (restart the shell in its directory: +- #file("pty/ctl"): `winsize C R` (the pty's size alone, apart from the terminal's grid, which stays its pane's: until the pane's size changes or its shell is started again, both of which give the pty the grid's; at least 2 rows, fewer refused `invalid winsize: at least 2 rows`; at most 4096 a side), `sig INT|TERM|HUP|QUIT|KILL`, `exec` (restart the shell in its directory: refused on a command pane, `a command pane does not restart`; `exec: : no such directory` if it is gone; a shell that cannot start fails and leaves the old one running). - #file("pty/run"): one line a write (two lines in one write are refused -- cgit v1.3