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 --- core/root.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'core/root.zig') 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" }, -- cgit v1.3 From 70c9e3fbf9cdc7139b4da0142f3a44741a7e1491 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider 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(-) (limited to 'core/root.zig') 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 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(-) (limited to 'core/root.zig') 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(-) (limited to 'core/root.zig') 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 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(-) (limited to 'core/root.zig') 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