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 --- core/term/screen_state.zig | 1213 -------------------------------------------- core/term/term.zig | 30 +- core/term/terminal.zig | 220 ++------ 3 files changed, 54 insertions(+), 1409 deletions(-) delete mode 100644 core/term/screen_state.zig (limited to 'core/term') 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; -- cgit v1.3 From 94561bf0e13d034384eae01d2cb9d48a8fe0a502 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider 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(-) (limited to 'core/term') 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 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/term') 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