From 3703c2526fb59708b00e12816bd88ffd8a15fc69 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 30 Oct 2026 01:34:23 -0300 Subject: echo: a replica draws a key typed into a terminal at once, mosh's way (a printable character at the cursor, Backspace, Left and Right, in tty mode on the primary screen), from an overlay of its own that no digest, dump or rollback copy sees, painted over the terminal's body at the end of renderBody (the tty's and the GUI's); judged at each delta once the authority has the key and 50 ms have passed, every prediction taken back on a mismatch; drawn at once at a prompt pardes's marks vouch for, elsewhere only once an echo was confirmed, never after a drawn misprediction until one is, so a password prompt or a program that ignores input shows nothing typed; the keys typed behind one not predicted (Tab, Enter) predicted over the screen that shows its doing; zig build replicas -- --echo types a corpus into a played shell at 30/80/207 ms: a key to its character p50 239 -> 8.9 ms and p90 248 -> 15.8 ms at 207, no wrong character drawn; docs/next-daemon.md: the decisions, the hook for the remote client, the numbers, the gates and what is not done Co-Authored-By: Claude Opus 5.5 --- src/echo.zig | 781 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 781 insertions(+) create mode 100644 src/echo.zig (limited to 'src/echo.zig') diff --git a/src/echo.zig b/src/echo.zig new file mode 100644 index 00000000..4acd3d11 --- /dev/null +++ b/src/echo.zig @@ -0,0 +1,781 @@ +//! Predicted echo for a replica's terminal panes, mosh's way +//! (docs/next-daemon.md, "Phase 6: predicted echo notes"). A key typed into +//! a terminal goes to the authority, and its echo comes back as screen state +//! a round trip later: this shows it at once. +//! +//! Presentation only. The overlay is the replica's own (`Pardes.echo`, a +//! `.local` field the rollback copy skips), painted over a terminal's body +//! after it is drawn (`paint`, from body_layer.renderBody, which the tty and +//! the GUI share). The core's emulator stays the authority's, and no digest +//! sees any of this. +//! +//! What is predicted: a printable character at the cursor, backspace, and +//! left and right, in tty mode on the primary screen at the live bottom. Any +//! other input this replica could not apply itself (Enter, Tab, a chord, a +//! paste, a click) stops prediction until the authority has confirmed it and +//! its echo has had `grace` to come back: predictions start again from the +//! screen's own cursor. So a key typed after Tab waits a round trip; it is +//! never drawn where the completion was not. +//! +//! Judged as mosh does, once the authority confirmed the key and `grace` +//! passed: at a delta, a cell the screen shows goes, and one it does not is +//! a misprediction, and every prediction goes. With no delta (nothing +//! changed: no echo), a frame judges it `stale` later. Shown at once at a +//! shell's prompt (pardes's OSC 133 marks say its line editor echoes); +//! elsewhere only once an echo was confirmed there since the last key that +//! was not predicted (`cat`, a shell without marks), and underlined; never +//! after a shown misprediction until an echo is confirmed again. A password +//! prompt or a program that ignores input confirms none, so nothing typed +//! there is ever shown. +const std = @import("std"); +const pardes = @import("pardes.zig"); +const terminal = pardes.panes.terminal; +const Pardes = pardes.Pardes; +const Pane = pardes.Pane; +const Surface = pardes.Surface; +const Key = pardes.Key; + +const ms = std.time.ns_per_ms; +/// After the authority confirmed a key, how long its echo has to come back +/// before a delta that does not show it makes a misprediction (mosh's +/// ECHO_TIMEOUT): the shell's echo, then the authority's next frame. +// ponytail: fixed; a loaded host's later echo makes a drawn character go and +// come back. The echo delay measured per terminal would be the bound. +pub const grace_ns = 50 * ms; +/// With no delta at all, how much longer a frame waits to judge a key. +pub const stale_ns = 250 * ms; +const never = std.math.maxInt(u64); +/// Cells predicted at once: a line typed a round trip ahead. +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 +/// 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 }; + +pub const Stats = struct { + /// Keys into a terminal predicted, and not. + predicted: u32 = 0, + unpredicted: u32 = 0, + /// Cells the screen showed when judged; cells and cursors it did not. + confirmed: u32 = 0, + mispredicted: u32 = 0, + cursor_missed: u32 = 0, +}; + +pub const Echo = struct { + /// Off: nothing predicted (the harness's baseline). + on: bool = true, + /// The harness's clock (ns); the monotonic one when null. + now: ?u64 = null, + /// Its client's view, and the terminal it predicts into. + view: u8 = 0, + pane: u8 = 0, + serial: u32 = 0, + /// Each terminal's last delta: its active area's first row, absolute. + tops: [pardes.MAX_PANES]u64 = @splat(0), + cells: [max]Cell = undefined, + n: u8 = 0, + cursor: ?Cursor = null, + /// The newest of its client's inputs the authority confirmed. + acked: u32 = 0, + /// The newest input not predicted, and when its echo is due: nothing is + /// predicted until then. `wait_key`: it was a key forwarded to this + /// terminal (no other pane's), so the keys typed into it meanwhile wait + /// in `deferred`, to be predicted over the screen that shows its doing. + wait: u32 = 0, + wait_due: u64 = 0, + wait_key: bool = false, + deferred: [max]Deferred = undefined, + nd: u8 = 0, + /// An echo confirmed since the last key not predicted: shown off a + /// prompt too. A shown misprediction since the last confirmed echo: + /// shown nowhere. + trusted: bool = false, + doubt: bool = false, + /// What it draws changed: the client draws a frame. + changed: bool = false, + stats: Stats = .{}, + /// Each key's prediction as it is made, when set (the harness's; on + /// the C heap). + log: ?*std.ArrayListUnmanaged(Predicted) = null, + + pub const Predicted = struct { seq: u32, cell: ?Cell, cursor: Cursor }; + + fn time(e: *const Echo) u64 { + return e.now orelse pardes.FrameStats.nowNs(); + } + + const Deferred = struct { seq: u32, kind: ?Kind, due: u64 = never }; + + fn drop(e: *Echo) void { + if (e.n > 0 or e.cursor != null) e.changed = true; + e.n = 0; + e.cursor = null; + } + + fn waiting(e: *const Echo) bool { + return e.acked < e.wait or e.time() < e.wait_due; + } + + fn waitFor(e: *Echo, seq: u32, key: bool) void { + e.wait = seq; + e.wait_due = never; + e.wait_key = key; + e.nd = 0; + } + + /// Its client's input `seq`, after the replica took it: `applied`, + /// it was applied here at once (so it was no key into a terminal). + pub fn typed(e: *Echo, c: *Pardes, view: u8, ev: pardes.Event, seq: u32, applied: bool) void { + e.view = view; + if (applied or comptime !terminal.enabled) return; + switch (ev) { + // ponytail: a motion or focus report a program asked for could + // move its cursor; the judgement catches that. + .mouse => |m| if (m.kind == .motion) return, + .pointer_leave, .focus => return, + else => {}, + } + const id = keyboardPane(c, view) orelse { + // Another pane's, or not a key: where the keys after it go is + // not known here until the authority has it. ponytail: so they + // wait for it too, each, until a pause. + e.waitFor(seq, false); + return; + }; + if (id != e.pane or c.panes[id].?.serial != e.serial) { + e.drop(); + e.nd = 0; + e.pane = @intCast(id); + e.serial = c.panes[id].?.serial; + } + const kind = kindOf(ev); + const key = forwarded(c, ev); + // A key that is not one of those predicted says nothing of the + // program the keys after it reach (Enter: a password prompt's). + if (kind == null) e.trusted = false; + if (!e.on) { + e.stats.unpredicted += 1; + return e.waitFor(seq, key); + } + // Behind keys still deferred: after them, in order. + e.catchUp(c); + if (e.waiting() or e.nd > 0) { + if (e.wait_key and key and e.nd < max) { + e.deferred[e.nd] = .{ .seq = seq, .kind = kind }; + e.nd += 1; + return; + } + e.stats.unpredicted += 1; + return e.waitFor(seq, false); + } + if (kind) |k| if (e.predict(c.panes[id].?, k, seq)) { + e.stats.predicted += 1; + e.changed = true; + return; + }; + e.stats.unpredicted += 1; + e.waitFor(seq, key); + } + + /// The wait over (its key's doing on the screen), the keys deferred + /// behind it that the screen does not show yet are predicted over it, + /// in order; those it shows are not. One the authority has whose echo + /// may be on its way puts it off until its grace has passed. + fn catchUp(e: *Echo, c: *Pardes) void { + if (e.nd == 0 or e.waiting()) return; + const now = e.time(); + var i: usize = 0; + while (i < e.nd and e.deferred[i].due <= now) i += 1; + if (i < e.nd and e.deferred[i].due != never) return; + e.stats.unpredicted += @intCast(i); + const pane = c.panes[e.pane] orelse return e.waitFor(e.wait, false); + if (pane.serial != e.serial) return e.waitFor(e.wait, false); + while (i < e.nd) : (i += 1) { + const d = e.deferred[i]; + if (d.kind) |k| if (e.predict(pane, k, d.seq)) { + e.stats.predicted += 1; + e.changed = true; + continue; + }; + // The next to wait for, the rest behind it. + e.stats.unpredicted += 1; + const rest = e.nd - i - 1; + std.mem.copyForwards(Deferred, e.deferred[0..rest], e.deferred[i + 1 .. e.nd]); + e.wait = d.seq; + e.wait_due = never; + e.wait_key = true; + e.nd = @intCast(rest); + return; + } + e.nd = 0; + } + + /// Whether a key `kind` into terminal `pane` was predicted. + fn predict(e: *Echo, pane: *Pane, kind: Kind, seq: u32) bool { + const state = pane.terminal orelse return false; + const vt = &state.vt; + if (vt.screens.active_key != .primary or !terminal.atBottom(pane) or !vt.modes.get(.cursor_visible)) return false; + const top = e.tops[e.pane]; + const screen = vt.screens.active; + const cur: Cursor = e.cursor orelse .{ .x = @intCast(screen.cursor.x), .row = top + screen.cursor.y, .seq = 0 }; + if (cur.row < top or cur.row - top >= vt.rows or e.n == max) return false; + var next: Cursor = .{ .x = cur.x, .row = cur.row, .seq = seq }; + var cell: ?Cell = null; + switch (kind) { + .char => |cp| { + // The last column wraps as a program pleases; a cell that + // holds another character is a line edited in its middle, + // or a suggestion (fish's) being left: the shell redraws + // what is right of it. ponytail: mosh's shift of the rest + // would cover bash's middle, and mispredict fish's. + if (cur.x + 1 >= vt.cols) return false; + const under = e.cpAt(state, cur.x, cur.row); + if (!blank(under) and under != cp) return false; + cell = .{ .x = cur.x, .row = cur.row, .cp = cp, .was = under, .seq = seq }; + next.x += 1; + }, + // At the end of a line only: in its middle a line editor moves + // the rest left. + .backspace => { + if (cur.x == 0 or !e.isInput(state, cur.x - 1, cur.row) or !blank(e.cpAt(state, cur.x, cur.row))) return false; + cell = .{ .x = cur.x - 1, .row = cur.row, .cp = ' ', .was = e.cpAt(state, cur.x - 1, cur.row), .seq = seq }; + next.x -= 1; + }, + .left => { + if (cur.x == 0 or !e.isInput(state, cur.x - 1, cur.row)) return false; + next.x -= 1; + }, + // Over typed text only: past its end, fish takes the right + // arrow for its suggestion (another colour). + .right => { + if (cur.x + 1 >= vt.cols or !e.isText(state, cur.x, cur.row)) return false; + next.x += 1; + }, + } + if (cell) |want| e.put(want); + e.cursor = next; + if (e.log) |l| l.append(std.heap.c_allocator, .{ .seq = seq, .cell = cell, .cursor = next }) catch {}; + return true; + } + + fn put(e: *Echo, want: Cell) void { + for (e.cells[0..e.n]) |*have| if (have.x == want.x and have.row == want.row) { + const was = have.was; + have.* = want; + have.was = was; + return; + }; + e.cells[e.n] = want; + e.n += 1; + } + + fn mine(e: *const Echo, x: u16, row: u64) ?*const Cell { + for (e.cells[0..e.n]) |*have| if (have.x == x and have.row == row) return have; + return null; + } + + /// What the screen shows at a cell as predicted so far. + fn cpAt(e: *const Echo, state: *terminal.State, x: u16, row: u64) u21 { + if (e.mine(x, row)) |have| return have.cp; + return e.screenCp(state, x, row); + } + + /// What the screen itself shows there; off its active area, a + /// codepoint no key types. + fn screenCp(e: *const Echo, state: *terminal.State, x: u16, row: u64) u21 { + const ci = e.screenCell(state, x, row) orelse return 0x10ffff; + return ci.cell.codepoint(); + } + + fn screenCell(e: *const Echo, state: *terminal.State, x: u16, row: u64) ?terminal.PageCell { + if (comptime !terminal.enabled) return null; + const top = e.tops[e.pane]; + if (row < top or row - top >= state.vt.rows) return null; + return state.vt.screens.active.pages.getCell(.{ .active = .{ .x = x, .y = @intCast(row - top) } }); + } + + /// A prompt's input there, or a character predicted. + fn isInput(e: *const Echo, state: *terminal.State, x: u16, row: u64) bool { + if (e.mine(x, row)) |have| return !blank(have.cp); + const ci = e.screenCell(state, x, row) orelse return false; + return ci.cell.semantic_content == .input; + } + + /// Typed text there: a character predicted, or a prompt's input in the + /// colour of the cell before it. + fn isText(e: *const Echo, state: *terminal.State, x: u16, row: u64) bool { + if (e.mine(x, row)) |have| return !blank(have.cp); + const ci = e.screenCell(state, x, row) orelse return false; + if (ci.cell.semantic_content != .input or blank(ci.cell.codepoint())) return false; + if (x == 0) return true; + const before = e.screenCell(state, x - 1, row) orelse return false; + return before.cell.style_id == ci.cell.style_id; + } + + /// The authority confirmed its client's input `seq`. + pub fn confirmed(e: *Echo, c: *Pardes, seq: u32) void { + e.acked = seq; + const due = e.time() + grace_ns; + for (e.deferred[0..e.nd]) |*d| if (d.seq <= seq and d.due == never) { + d.due = due; + }; + for (e.cells[0..e.n]) |*cell| if (cell.seq <= seq and cell.due == never) { + cell.due = due; + }; + if (e.cursor) |*cur| if (cur.seq <= seq and cur.due == never) { + cur.due = due; + }; + if (e.wait <= seq and e.wait_due == never) { + // The authority stepped a key this did not predict, after every + // one it did: its deltas from here show that key's doing, which + // no prediction knew of. They go, judged neither way. + e.wait_due = due; + e.drop(); + } + e.catchUp(c); + } + + /// Terminal `id`'s delta was applied, its active area's first row now + /// `top`. + pub fn delta(e: *Echo, c: *Pardes, id: u8, top: u64) void { + if (id == e.pane and top != e.tops[id] and (e.n > 0 or e.cursor != null)) { + // Scrolled: the rows predicted are others now. + e.tops[id] = top; + return e.drop(); + } + e.tops[id] = top; + if (id == e.pane) e.judge(c, 0); + e.catchUp(c); + } + + /// Once a frame: what is stale judged. Whether to draw. + pub fn frame(e: *Echo, c: *Pardes) bool { + if (e.n > 0 or e.cursor != null) e.judge(c, stale_ns); + e.catchUp(c); + defer e.changed = false; + return e.changed; + } + + fn judge(e: *Echo, c: *Pardes, slack: u64) void { + if (comptime !terminal.enabled) return; + if (e.n == 0 and e.cursor == null) return; + const now = e.time(); + const pane = c.panes[e.pane] orelse return e.drop(); + if (pane.serial != e.serial) return e.drop(); + const state = pane.terminal orelse return e.drop(); + if (state.vt.screens.active_key != .primary) return e.drop(); + const shown = e.visible(c); + var i: usize = 0; + while (i < e.n) { + const cell = e.cells[i]; + if (now < cell.due) { + i += 1; + continue; + } + if (!blank(cell.cp) and e.screenCp(state, cell.x, cell.row) != cell.cp) { + if (now < cell.due + slack) { + i += 1; + continue; + } + e.stats.mispredicted += 1; + if (shown) e.doubt = true; + e.trusted = false; + return e.drop(); + } + // Shown, or a space (mosh: too easy to show by chance to vouch). + // A key before the last one not predicted vouches for nothing + // after it (a line's characters for the password prompt its + // Enter brought up). + if (!blank(cell.cp)) { + e.stats.confirmed += 1; + if (cell.was != cell.cp and cell.seq > e.wait) { + e.trusted = true; + e.doubt = false; + } + } + e.cells[i] = e.cells[e.n - 1]; + e.n -= 1; + e.changed = true; + } + const cur = e.cursor orelse return; + if (now < cur.due) return; + const screen = state.vt.screens.active; + if (screen.cursor.x == cur.x and e.tops[e.pane] + screen.cursor.y == cur.row) { + e.cursor = null; + e.changed = true; + } else if (now >= cur.due + slack) { + e.stats.cursor_missed += 1; + e.drop(); + } + } + + /// Whether its predictions are drawn now. + pub fn visible(e: *const Echo, c: *const Pardes) bool { + if (e.doubt) return false; + if (e.trusted) return true; + const pane = c.panes[e.pane] orelse return false; + return atPrompt(pane); + } + + /// Over terminal pane `id`'s body, as renderBody drew it: the + /// characters predicted and the cursor after them. + pub fn paint(e: *const Echo, p: *const Pardes, s: *Surface, pane: *const Pane, id: usize, tx: u16, tw: u16, body_y: u16, body_h: u16, active: bool) void { + if (comptime !terminal.enabled) return; + if (e.n == 0 and e.cursor == null) return; + if (id != e.pane or pane.serial != e.serial or p.view != e.view or pane.body.mode != .tty) return; + if (!e.visible(p)) return; + const state = pane.terminal orelse return; + const sb = state.vt.screens.active.pages.scrollbar(); + const top = e.tops[id]; + // Off a prompt, the trust is inferred: underlined, as mosh does. + const flag = !atPrompt(pane); + const at = struct { + fn f(sb_: @TypeOf(sb), pan: u16, h: u16, top_: u64, row: u64) ?u16 { + if (row < top_ or row - top_ >= sb_.len) return null; + const screen_row = sb_.total - sb_.len + (row - top_); + if (screen_row < sb_.offset + pan) return null; + const y = screen_row - sb_.offset - pan; + return if (y < h) @intCast(y) else null; + } + }.f; + for (e.cells[0..e.n]) |cell| { + const y = at(sb, pane.pan, body_h, top, cell.row) orelse continue; + if (cell.x >= tw) continue; + const dst = s.at(tx + cell.x, body_y + y); + // Typed text continues the text before it (mosh's heuristic). + var style = dst.style; + if (cell.x > 0) { + const before = s.at(tx + cell.x - 1, body_y + y); + if (!before.default and !blank(before.text[0])) style = before.style; + } + if (flag and !blank(cell.cp)) style.ul = .single; + dst.default = false; + dst.text[0] = @intCast(cell.cp); + dst.len = 1; + dst.style = style; + } + if (!active or pane.focus != .body) return; + const cur = e.cursor orelse return; + const y = at(sb, pane.pan, body_h, top, cur.row) orelse return; + if (cur.x < tw) s.cursor = .{ .x = tx + cur.x, .y = body_y + y }; + } +}; + +const Kind = union(enum) { char: u21, backspace, left, right }; + +fn kindOf(ev: pardes.Event) ?Kind { + const k = switch (ev) { + .key => |k| k, + else => return null, + }; + if (k.ctrl or k.alt) return null; + switch (k.cp) { + Key.backspace => return .backspace, + Key.left => return .left, + Key.right => return .right, + else => {}, + } + // As forwardKey sends it. ponytail: ASCII only; a width table would + // let the rest in. + const cp: u21 = if (k.text.len == 1) + k.text[0] + else if (k.text.len == 0 and k.cp >= 'a' and k.cp <= 'z' and k.shift) + k.cp - 'a' + 'A' + else if (k.text.len == 0) + k.cp + else + return null; + return if (cp >= 0x20 and cp < 0x7f) .{ .char = cp } else null; +} + +/// Whether key `ev` goes to the terminal's program as it is (forwardKey's) +/// and not to pardes: Esc backs out of the pane, the tty chord leaves tty +/// mode, Ctrl-V pastes the register. +fn forwarded(c: *const Pardes, ev: pardes.Event) bool { + const k = switch (ev) { + .key => |k| k, + else => return false, + }; + if (k.cp == Key.escape) return false; + return !(k.ctrl and (k.cp == c.opts.tty_toggle or k.cp == 'v' or k.cp == 'V')); +} + +fn blank(cp: u21) bool { + return cp == 0 or cp == ' '; +} + +/// At a shell's prompt, reading its input: pardes's marks (a B and no C +/// since) and the cursor's own, on the primary screen. A shell without +/// pardes's marks is trusted only once its echo is confirmed. +fn atPrompt(pane: *const Pane) bool { + if (comptime !terminal.enabled) return false; + const state = pane.terminal orelse return false; + return state.vt.screens.active_key == .primary and state.stream.handler.phase == .input and terminal.promptInputReady(pane); +} + +/// The terminal view `view`'s keys go to, in tty mode: none when they go +/// elsewhere (a prompt, a header, window mode, another pane). +fn keyboardPane(c: *const Pardes, view: u8) ?usize { + const live = c.view == view; + const part = if (live) null else &(c.parked[view] orelse return null).view; + const id = if (part) |v| v.active else c.active; + if (if (part) |v| v.window_pick != null or v.header_focus else c.window_pick != null or c.header_focus) return null; + const pane = c.panes[id] orelse return null; + if (!pane.isTerminal() or pane.terminal == null or pane.prompt != .none) return null; + const mode = if (live) pane.body.mode else pane.pv[view].body.mode; + const focus = if (live) pane.focus else pane.pv[view].focus; + return if (mode == .tty and focus == .body) id else null; +} + +// ---- tests: one authority and one replica, its shell played by hand ---- + +const testing = std.testing; +const replica = @import("replica.zig"); + +const Rig = struct { + a: *replica.Authority, + r: *replica.Replica, + screens: replica.Screens, + peer: u16, + shell: u8, + /// What the authority wrote its shell's pty. + written: std.ArrayListUnmanaged(u8) = .empty, + now: u64 = 1_000 * ms, + + fn ptyWrite(ctx: ?*anyopaque, _: u8, bytes: []const u8) void { + const g: *Rig = @ptrCast(@alignCast(ctx.?)); + g.written.appendSlice(testing.allocator, bytes) catch {}; + } + fn watched(_: ?*anyopaque) bool { + return false; + } + const vtable: pardes.Host.VTable = .{ .watched = watched, .pty_write = ptyWrite }; + + fn init(g: *Rig) !void { + const gpa = testing.allocator; + g.written = .empty; + g.now = 1_000 * ms; + g.a = try replica.Authority.init(gpa, .{ .cols = 60, .rows = 16, .boot = .tty_shell }, .{ .ctx = g, .vtable = &vtable }, true); + g.screens = .init(gpa); + g.peer = try g.screens.addPeer(); + g.r = try replica.Replica.init(gpa, 1, try g.a.unit(0, 0), true); + g.shell = for (g.a.core.panes, 0..) |slot, id| { + if (slot) |pane| if (pane.isTerminal()) break @intCast(id); + } else return error.NoShell; + g.r.echo.now = g.now; + } + + fn deinit(g: *Rig) void { + g.r.deinit(); + g.screens.deinit(g.a.core); + g.a.deinit(); + g.written.deinit(testing.allocator); + } + + fn later(g: *Rig, dt: u64) void { + g.now += dt; + g.r.echo.now = g.now; + } + + /// The shell prints `bytes`; the replica gets the unit and the delta. + fn prints(g: *Rig, bytes: []const u8) !void { + g.a.output(.{ .output = .{ .pane = g.shell, .bytes = bytes } }); + try g.sync(); + } + + fn sync(g: *Rig) !void { + const gpa = testing.allocator; + if (try g.a.pending()) |u| g.r.confirm(u); + g.r.settle(); + var msgs: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (msgs.items) |m| gpa.free(m); + msgs.deinit(gpa); + } + try g.screens.flush(g.a.core, g.peer, &msgs); + for (msgs.items) |m| if (g.r.screen(m)) |reply| { + _ = try g.screens.take(g.a.core, g.peer, reply); + }; + } + + /// The replica's client types `k`; the message for the authority. + fn key(g: *Rig, k: Key) ![]u8 { + return testing.allocator.dupe(u8, try g.r.input(.{ .key = k })); + } + + /// The authority takes it, and the replica its unit. + fn take(g: *Rig, msg: []u8) !void { + defer testing.allocator.free(msg); + if (try g.a.pending()) |u| g.r.confirm(u); + g.r.confirm(try g.a.take(msg)); + g.r.settle(); + } + + /// What the replica's screen shows at the shell's cursor row, drawn, + /// and whether the cell at `x` is underlined. + fn drawn(g: *Rig, arena: *std.heap.ArenaAllocator, x: u16) !struct { cp: u8, ul: bool, cursor: ?u16 } { + _ = arena.reset(.retain_capacity); + const c = g.r.core(); + c.needs_frame = true; + const s = try c.render(arena.allocator()); + const pane = c.panes[g.shell].?; + const body = s.region(.body, g.shell).?.rect; + const y = body.y + terminal.gridCursor(pane).y; + const cell = s.at(body.x + x, y); + return .{ .cp = cell.text[0], .ul = cell.style.ul != .off, .cursor = if (s.cursor) |cur| if (cur.y == y) cur.x - body.x else null else null }; + } +}; + +const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; + +test "keys typed at a shell's prompt are drawn at once, and the authority's echo takes their place" { + if (comptime !terminal.enabled) return error.SkipZigTest; + var g: Rig = undefined; + try g.init(); + defer g.deinit(); + try g.prints(prompt); + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const before = try g.drawn(&arena, 2); + try testing.expectEqual(@as(?u16, 2), before.cursor); + // Typed: shown at once, the cursor past it, and nothing underlined at + // a prompt. + const l = try g.key(.{ .cp = 'l', .text = "l" }); + const s = try g.key(.{ .cp = 's', .text = "s" }); + try testing.expectEqual(@as(u32, 2), g.r.echo.stats.predicted); + var shown = try g.drawn(&arena, 2); + try testing.expectEqual(@as(u8, 'l'), shown.cp); + try testing.expect(!shown.ul); + try testing.expectEqual(@as(?u16, 4), shown.cursor); + try testing.expectEqual(@as(u8, 's'), (try g.drawn(&arena, 3)).cp); + // The authority's core draws no overlay of its own. + try testing.expect(g.a.core.echo == null); + // The authority takes them, its shell echoes, the delta lands after the + // grace: confirmed, and the screen's own cells and cursor shown. + try g.take(l); + try g.take(s); + try testing.expectEqualStrings("ls", g.written.items); + g.later(grace_ns); + try g.prints("ls"); + try testing.expectEqual(@as(u8, 0), g.r.echo.n); + try testing.expect(g.r.echo.cursor == null); + try testing.expectEqual(@as(u32, 2), g.r.echo.stats.confirmed); + shown = try g.drawn(&arena, 3); + try testing.expectEqual(@as(u8, 's'), shown.cp); + try testing.expectEqual(@as(?u16, 4), shown.cursor); + // Backspace at the end of the line, shown at once. + const bs = try g.key(.{ .cp = Key.backspace }); + shown = try g.drawn(&arena, 3); + try testing.expectEqual(@as(u8, ' '), shown.cp); + try testing.expectEqual(@as(?u16, 3), shown.cursor); + try g.take(bs); + g.later(grace_ns); + try g.prints("\x08\x1b[K"); + try testing.expectEqual(@as(u32, 0), g.r.echo.stats.mispredicted + g.r.echo.stats.cursor_missed); + try testing.expect(g.r.quiet()); + try testing.expectEqual(replica.digestOf(g.a), g.r.digest()); +} + +test "a password prompt shows nothing typed, and a full-screen program is not predicted" { + if (comptime !terminal.enabled) return error.SkipZigTest; + var g: Rig = undefined; + try g.init(); + defer g.deinit(); + try g.prints(prompt ++ "sudo ls\r\n\x1b]133;C;aid=pardes\x07[sudo] password: "); + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const x = terminal.gridCursor(g.r.core().panes[g.shell].?).x; + const k = try g.key(.{ .cp = 'h', .text = "h" }); + // Predicted, and not drawn: nothing has confirmed an echo here. + try testing.expectEqual(@as(u32, 1), g.r.echo.stats.predicted); + try testing.expectEqual(@as(u8, ' '), (try g.drawn(&arena, x)).cp); + try g.take(k); + // No echo, so no delta: a frame lets it go once it is stale. + g.later(grace_ns + stale_ns); + _ = g.r.echoFrame(); + try testing.expectEqual(@as(u8, 0), g.r.echo.n); + try testing.expectEqual(@as(u32, 1), g.r.echo.stats.mispredicted); + // The next key still shows nothing. + const k2 = try g.key(.{ .cp = 'i', .text = "i" }); + try testing.expectEqual(@as(u8, ' '), (try g.drawn(&arena, x)).cp); + try g.take(k2); + // vim: the alternate screen, never predicted. + try g.prints("\r\n\x1b]133;D;1;aid=pardes\x07" ++ prompt ++ "vim\r\n\x1b]133;C;aid=pardes\x07\x1b[?1049h\x1b[H~"); + g.later(grace_ns + stale_ns); + _ = g.r.echoFrame(); + const before = g.r.echo.stats.predicted; + try g.take(try g.key(.{ .cp = 'i', .text = "i" })); + try testing.expectEqual(before, g.r.echo.stats.predicted); +} + +test "a misprediction takes every prediction back and shows none until an echo is confirmed; after Tab nothing is predicted until its echo" { + if (comptime !terminal.enabled) return error.SkipZigTest; + var g: Rig = undefined; + try g.init(); + defer g.deinit(); + try g.prints(prompt); + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + // A line editor that echoes something else (vi's command mode): shown, + // then taken back. + const a = try g.key(.{ .cp = 'a', .text = "a" }); + try testing.expectEqual(@as(u8, 'a'), (try g.drawn(&arena, 2)).cp); + try g.take(a); + g.later(grace_ns); + try g.prints("A"); + try testing.expectEqual(@as(u32, 1), g.r.echo.stats.mispredicted); + try testing.expect(g.r.echo.doubt); + try testing.expectEqual(@as(u8, 'A'), (try g.drawn(&arena, 2)).cp); + // Doubted: predicted, not drawn, until one is confirmed. + const b = try g.key(.{ .cp = 'b', .text = "b" }); + try testing.expectEqual(@as(u8, ' '), (try g.drawn(&arena, 3)).cp); + try g.take(b); + g.later(grace_ns); + try g.prints("b"); + try testing.expect(!g.r.echo.doubt); + const c = try g.key(.{ .cp = 'c', .text = "c" }); + try testing.expectEqual(@as(u8, 'c'), (try g.drawn(&arena, 4)).cp); + // Tab: not predicted, and neither is what follows until the authority + // has it and its echo has had its grace. + const tab = try g.key(.{ .cp = Key.tab }); + const d = try g.key(.{ .cp = 'd', .text = "d" }); + try testing.expectEqual(@as(u32, 1), g.r.echo.stats.unpredicted); + try g.take(c); + try testing.expectEqual(@as(u8, 'c'), (try g.drawn(&arena, 4)).cp); + // The authority has Tab (and the key after it): what was predicted + // before it goes, the screen's own shown. + try g.take(tab); + try g.take(d); + try testing.expectEqual(@as(u8, 0), g.r.echo.n); + g.later(grace_ns); + try g.prints("c" ++ "ompleted d"); + // `d`, typed behind Tab, the screen showed by then: not predicted. + try testing.expectEqual(@as(u32, 2), g.r.echo.stats.unpredicted); + const e = try g.key(.{ .cp = 'e', .text = "e" }); + try testing.expectEqual(@as(u8, 'e'), (try g.drawn(&arena, 15)).cp); + try g.take(e); + g.later(grace_ns); + try g.prints("e"); + // A key typed behind Tab that the authority does not have yet is + // predicted once Tab's doing is on the screen, where it now goes. + const tab2 = try g.key(.{ .cp = Key.tab }); + const f = try g.key(.{ .cp = 'f', .text = "f" }); + try g.take(tab2); + try g.prints("ff"); + try testing.expectEqual(@as(u8, 0), g.r.echo.n); + g.later(grace_ns); + _ = g.r.echoFrame(); + try testing.expectEqual(@as(u8, 1), g.r.echo.n); + try testing.expectEqual(@as(u8, 'f'), (try g.drawn(&arena, 18)).cp); + try g.take(f); + g.later(grace_ns); + try g.prints("f"); + try testing.expectEqual(@as(u8, 0), g.r.echo.n); + try testing.expectEqual(@as(u32, 1), g.r.echo.stats.mispredicted); + try testing.expectEqual(@as(u32, 0), g.r.echo.stats.cursor_missed); + try testing.expect(g.r.quiet()); + try testing.expectEqual(replica.digestOf(g.a), g.r.digest()); +} -- cgit v1.3 From 5af775e9817395af39792cc609b832394d4a4fb8 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 30 Oct 2026 15:15:01 -0300 Subject: replica: what only the authority holds, a step reads off the tape (tape.authority): the store's closed panes and Recent, a script's hold on a pane's events, the 9P socket, the session's config directory and startup file; a replica's own are never read, and never put back by a rollback The Panes picker's closed rows, Recent's rows, a closed pane brought back (a Look at @pN, a Panes row), a jump to a closed file and the +Jumps rows read `p.store` and `p.recent`, `.authority` state a replica keeps on its own: its store has no file, its Recent only what it replayed since it joined. The rows made of them went into digested state, so every client of a session diverged together after a Del (H4), every client that joined after one diverged at its first unit forever (H11: trackJump dropped a closed file's jumps at every step when Recent did not know the file), a client's Del of a file the session's Recent knew made the stat the session skipped (H12: noteClosed looked in Recent first), and a client on another machine read its own store (H13). - tape.authority: poison, then a value read: the authority's answer is taped, a replay takes it, a speculation waits for it. One site, `.authority`. - Readers through it: Query's Recent and closed-pane rows, Store.reopen's record, Pardes.recentByHash (jumps, +Jumps), mouse.reportRange's readers check (a script reading a pane's events takes a look or exec: `pane.fs.readers`, the 9P server's), Tty9p's socket check, Pardes.configDir and startupPath (ThemeFile, DumpThemes, Config, DumpConfig, an init file saved), DumpConfig's dump directory. - trackJump no longer reads Recent at every step: a closed file's jump stays; the jump to it drops that file's entries when Recent has forgotten it, as when the file is gone. - noteClosed asks the host (recentKeeps, a taped stat) before it looks in Recent: the same syscall on every side. - The tty toggle, read on every key, is session state: Pardes.tty_toggle, from the options when the core is made, dumped. - The rollback copy no longer saves `store` and `recent` (rollback.zig `unsaved`): their bytes put back pointed at lists the host's heap (recentGpa) had freed, which the epoch never holds. A speculated Del then a Panes listing read a freed name (H8, the segfault). Tests, each failing before: a rollback leaves the store and Recent as a speculation left them; a replica joined after a pane closed has the session's jump to it, its Panes and Recent rows, asked by either (and the variant hunt's Recent written by another window); a replica's Del of a file its session's Recent knows asks the host what the session asked. Co-Authored-By: Claude Opus 5.5 --- src/Output.zig | 10 ++++-- src/Query.zig | 21 +++++++----- src/Store.zig | 46 ++++++++++++++++++++----- src/builtins.zig | 4 +-- src/colors.zig | 5 +-- src/echo.zig | 2 +- src/exec.zig | 9 +++-- src/look.zig | 2 +- src/mouse.zig | 15 ++++++-- src/pardes.zig | 75 ++++++++++++++++++++++++++++++---------- src/replica.zig | 102 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/rollback.zig | 51 ++++++++++++++++++++++++++-- src/tape.zig | 19 +++++++++++ 13 files changed, 311 insertions(+), 50 deletions(-) (limited to 'src/echo.zig') diff --git a/src/Output.zig b/src/Output.zig index 359db1cf..7c8b7f59 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -1005,6 +1005,12 @@ test "full Help renders builtin rows, a call hierarchy guide, then language keys try std.testing.expect(std.mem.indexOf(u8, group, "Callstack: static caller chains") != null); } +/// Where a dump goes by default, as the session's environment says (the +/// authority's, `tape.authority`): in `buf`. +fn dumpDirectory(buf: []u8) []const u8 { + return pardes.dump.defaultDirectory(buf) orelse ""; +} + pub fn openConfig(p: *Pardes, id: usize) !void { var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); @@ -1015,8 +1021,8 @@ pub fn openConfig(p: *Pardes, id: usize) !void { try p.locations_config.write(&located.writer); try config.Runtime.writeReport(&out.writer, .{ .locations = located.written(), - .default_dump_dir = if (host_fs) (pardes.dump.defaultDirectory(&dir_buf) orelse "") else "", - .startup_config_path = p.opts.startup_config_path, + .default_dump_dir = if (host_fs) pardes.tape.authority(dumpDirectory, .{@as([]u8, &dir_buf)}) else "", + .startup_config_path = p.startupPath(), .platform = builtins.viewPlatform(p), .theme_name = p.theme().name, .theme_file = pardes.colors.loadedThemeFile(p), diff --git a/src/Query.zig b/src/Query.zig index 49f58a0e..2f417a68 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -48,6 +48,7 @@ const memory = @import("memory.zig"); const Names = @import("Names.zig"); const Places = @import("Places.zig"); const Stream = @import("Stream.zig"); +const Store = @import("Store.zig"); const Surface = @import("surface.zig").Surface; const Pardes = pardes.Pardes; const Pane = panes.Pane; @@ -591,12 +592,9 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz if (p.fs.serving) Stream.step(p); }, .recent => { - // Every window's files: what the others wrote since, read. - p.store.refresh(p); var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); - Output.recentText(p, &out.writer, true) catch {}; - var lines = std.mem.splitScalar(u8, out.written(), '\n'); + var lines = std.mem.splitScalar(u8, pardes.tape.authority(recentRows, .{ p, &out }), '\n'); while (lines.next()) |ln| { if (ln.len == 0) continue; const rel = Names.relative(ln, dir); @@ -617,10 +615,9 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz } // Then the panes this session closed, the latest first, each // `(closed)` and dimmer (makeNameRows): Enter brings one back - // where it was. Its name alone is matched, not the word. - var i = p.store.closed.items.len; - while (i > 0) : (i -= 1) { - const c = p.store.closed.items[i - 1]; + // where it was. Its name alone is matched, not the word. The + // store's, which a replica has from the authority. + for (pardes.tape.authority(Store.closedNames, .{p})) |c| { var buf: [4096 + 48]u8 = undefined; const row = std.fmt.bufPrint(&buf, config.pane_addr ++ "{d} {s}" ++ closed_word, .{ c.serial, Names.relative(c.name, dir) }) catch continue; const key_at = std.mem.indexOfScalar(u8, row, ' ').? + 1; @@ -652,6 +649,14 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz /// What a Panes row of a closed pane ends with. const closed_word = " (closed)"; +/// Every window's files, as a Recent query lists them: what the others +/// wrote since, read first. The store's (`tape.authority`): in `out`. +fn recentRows(p: *Pardes, out: *std.Io.Writer.Allocating) []const u8 { + p.store.refresh(p); + Output.recentText(p, &out.writer, true) catch {}; + return out.written(); +} + /// The owner's declarations, from a parse that already exists: its sticky /// headers' (TreeContext) at this revision, or the locations cache's. None /// is made here, on the loop, unless `small` and the text is small: a diff --git a/src/Store.zig b/src/Store.zig index 36215234..9c726705 100644 --- a/src/Store.zig +++ b/src/Store.zig @@ -468,6 +468,21 @@ fn unlist(s: *Store, gpa: std.mem.Allocator, serial: u32) void { }; } +/// A closed pane as Panes lists it: its serial and what its row shows. +pub const Named = struct { serial: u32, name: []const u8 }; + +/// This session's closed panes, the latest first (scratch; the names the +/// store's): what a step lists of them (`tape.authority`). +pub fn closedNames(p: *Pardes) []const Named { + const items = p.store.closed.items; + const out = p.scratch.allocator().alloc(Named, items.len) catch return &.{}; + for (out, 0..) |*o, i| { + const c = items[items.len - 1 - i]; + o.* = .{ .serial = c.serial, .name = c.name }; + } + return out; +} + /// The closed pane with this serial, if this session has it. pub fn closedBySerial(s: *const Store, serial: u32) ?*Closed { for (s.closed.items) |*c| if (c.serial == serial) return c; @@ -785,12 +800,10 @@ fn compact(s: *Store, p: *Pardes, file: File, st: File.Stat, path: []const u8) v /// from `from`. False when it is not this session's, or its record is gone /// or bad; the keyboard on it otherwise. pub fn reopen(s: *Store, p: *Pardes, serial: u32, from: usize) bool { - s.refresh(p); const gpa = p.recentGpa(); - const place = (s.closedBySerial(serial) orelse return false).*; - const body = s.bodyOf(p, place) orelse return false; - // Read from the file: this call's to free (`unlist` frees one held). - defer if (place.body.len == 0) gpa.free(body); + // The store's: a replica has the authority's (`tape.authority`). + const place = pardes.tape.authority(record, .{ s, p, serial }) orelse return false; + const body = place.body; const m = parseMeta(body) orelse return false; const free = p.freeSlot() orelse { p.reportError(from, "Panes", error.NoPaneSlots); @@ -826,6 +839,21 @@ pub fn reopen(s: *Store, p: *Pardes, serial: u32, from: usize) bool { return true; } +/// Where a closed pane goes back, and its record's body (scratch). +pub const Record = struct { gainer: u32, below: bool, owner: u32, rows: u16, body: []const u8 }; + +/// Closed pane `serial`'s record, the store read on first; null when it is +/// not this session's, or its record is gone or bad. +fn record(s: *Store, p: *Pardes, serial: u32) ?Record { + s.refresh(p); + const c = (s.closedBySerial(serial) orelse return null).*; + const body = s.bodyOf(p, c) orelse return null; + // Read from the file: this call's to free (`unlist` frees one held). + defer if (c.body.len == 0) p.recentGpa().free(body); + const copy = p.scratch.allocator().dupe(u8, body) catch return null; + return .{ .gainer = c.gainer, .below = c.below, .owner = c.owner, .rows = c.rows, .body = copy }; +} + /// A closed pane's record body: held here, or read from the file and /// checked against its CRC (gpa; the caller frees it when it is not /// `c.body`). @@ -855,8 +883,9 @@ fn bodyOf(s: *Store, p: *Pardes, c: Closed) ?[]u8 { return body; } -/// `@p` naming a pane this session closed: its serial. -pub fn closedAddress(s: *const Store, word: []const u8) ?u32 { +/// `@p` alone, the pane and no place in it: its serial, for a pane +/// this session closed to come back by (`reopen` says whether it did). +pub fn closedAddress(word: []const u8) ?u32 { const addr = @import("config.zig").pane_addr; if (!std.mem.startsWith(u8, word, addr)) return null; const digits = word[addr.len..]; @@ -865,8 +894,7 @@ pub fn closedAddress(s: *const Store, word: []const u8) ?u32 { } else digits.len; // `@p7` alone, or `@p7:` with nothing after it: the pane, no place in it. if (end == 0 or (end < digits.len and !(digits[end] == ':' and end + 1 == digits.len))) return null; - const serial = std.fmt.parseInt(u32, digits[0..end], 10) catch return null; - return if (s.closedBySerial(serial) != null) serial else null; + return std.fmt.parseInt(u32, digits[0..end], 10) catch null; } // ---- tests ---- diff --git a/src/builtins.zig b/src/builtins.zig index 69ac3113..97cdc5a0 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -941,7 +941,7 @@ pub const DumpThemes = struct { pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { if (comptime enabled) { - if (c.p.opts.config_dir == null) { + if (c.p.configDir() == null) { c.p.reportError(c.id, "dump themes", error.NoConfigDirectory); return; } @@ -1607,7 +1607,7 @@ pub const Help = struct { pub const Config = struct { pub const scope: Scope = .session; pub fn run(c: Ctx) void { - const path = c.p.opts.startup_config_path orelse + const path = c.p.startupPath() orelse return c.p.reportFailure(c.id, "Config: no startup file here: no configuration directory"); var real_buf: [4096]u8 = undefined; const real = if (pardes.filesystem.resolveOs(path, &real_buf)) |r| r.path else null; diff --git a/src/colors.zig b/src/colors.zig index c016434b..cc417ccb 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -677,14 +677,15 @@ pub fn requestThemeFile(p: *Pardes, id: usize, argument: []const u8) void { } const absolute = std.fs.path.isAbsolute(input); - if (!absolute and p.opts.config_dir == null) { + const config_dir = if (absolute) null else p.configDir(); + if (!absolute and config_dir == null) { p.reportError(id, "theme file", error.NoConfigDirectory); return; } var joined: [4095]u8 = undefined; const resolved = if (absolute) input else path: { - const dir = p.opts.config_dir.?; + const dir = config_dir.?; const separator = if (dir.len > 0 and dir[dir.len - 1] != std.Io.Dir.path.sep) std.Io.Dir.path.sep_str else ""; break :path std.fmt.bufPrint(&joined, "{s}{s}{s}", .{ dir, separator, input }) catch { p.reportError(id, "theme file", error.PathTooLong); diff --git a/src/echo.zig b/src/echo.zig index 4acd3d11..4560930c 100644 --- a/src/echo.zig +++ b/src/echo.zig @@ -500,7 +500,7 @@ fn forwarded(c: *const Pardes, ev: pardes.Event) bool { else => return false, }; if (k.cp == Key.escape) return false; - return !(k.ctrl and (k.cp == c.opts.tty_toggle or k.cp == 'v' or k.cp == 'V')); + return !(k.ctrl and (k.cp == c.tty_toggle or k.cp == 'v' or k.cp == 'V')); } fn blank(cp: u21) bool { diff --git a/src/exec.zig b/src/exec.zig index e1c13daa..c5218279 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -411,11 +411,16 @@ pub fn spawnTty(p: *Pardes, from: usize) ?*Pane { pub fn spawnV9fsTty(p: *Pardes, from: usize) void { if (comptime !hosted or @import("builtin").os.tag != .linux) return p.reportError(from, "Tty9p", error.LinuxRequired); - if (p.fs.socket_path.len == 0) + // The 9P server's: a replica has the authority's answer. + if (!pardes.tape.authority(servesSocket, .{p})) return p.reportError(from, "Tty9p", error.SessionSocketRequired); _ = spawnTtyWithMount(p, from, true); } +fn servesSocket(p: *Pardes) bool { + return p.fs.socket_path.len != 0; +} + fn spawnTtyWithMount(p: *Pardes, from: usize, v9fs: bool) ?*Pane { // No pane asking (an empty window's tag): the session's directory, as // New's scratch is. @@ -1009,7 +1014,7 @@ pub fn applyStartupConfig(p: *Pardes) void { /// setting lines: a command in it (`Newcol`) is the session's start, and /// would not be right twice. pub fn reapplyInitFile(p: *Pardes, path: []const u8, text: []const u8) void { - const init_path = p.opts.startup_config_path orelse return; + const init_path = p.startupPath() orelse return; if (!std.mem.eql(u8, init_path, path)) return; applyInitText(p, text, true); } diff --git a/src/look.zig b/src/look.zig index 226c96e3..09a22266 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1816,7 +1816,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { // `@p` names no open pane: one this session closed comes // back where it was (Store.reopen), any other is a miss, said. if (t.id >= MAX_PANES or p.panes[t.id] == null) { - if (p.store.closedAddress(pl.path)) |serial| if (p.store.reopen(p, serial, id)) return; + if (@TypeOf(p.store).closedAddress(pl.path)) |serial| if (p.store.reopen(p, serial, id)) return; return missed(p, id, "no pane {s}", .{pl.path[0..@min(pl.path.len, 32)]}); } const target = p.panes[t.id].?; diff --git a/src/mouse.zig b/src/mouse.zig index 67ebf7cf..3281f48a 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -990,10 +990,17 @@ fn reportGesture( operand: exec.PointerOperand, chord_arg: ?[]const u8, ) bool { - if ((p.panes[id] orelse return false).fs.readers == 0) return false; return reportRange(p, id, cmd, text, on_tag, gestureRange(p, id, text, on_tag, operand), chord_arg); } +/// Whether a script reads pane `id`'s events, and so takes its looks and +/// execs: the 9P server's, the authority's alone (a replica has its +/// answer, `tape.authority`). +fn readsEvents(p: *Pardes, id: usize) bool { + const pane = p.panes[id] orelse return false; + return pane.fs.readers != 0; +} + /// An event reader told of a look or an exec of `text` at `range` of the /// tag or body, by a click or a key alike: false when the pane has none. pub fn reportRange( @@ -1006,7 +1013,7 @@ pub fn reportRange( chord_arg: ?[]const u8, ) bool { const scripted = p.panes[id] orelse return false; - if (scripted.fs.readers == 0) return false; + if (!pardes.tape.authority(readsEvents, .{ p, id })) return false; const is_look = cmd == config.look_cmd; const action: ctlfs.events.Action = if (is_look) (if (on_tag) .tag_look else .body_look) @@ -1020,7 +1027,9 @@ pub fn reportRange( if (is_look) { if (!named and std.mem.indexOfAny(u8, text, "/.:") != null) flag |= ctlfs.events.flag_filename; } else if (chord_arg != null) flag |= ctlfs.events.flag_chorded; - if (!ctlfs.events.noteAction(p, id, action, range.q0, range.q1, flag, text)) return false; + // Taken whether or not this process's server has the reader: the + // session's said it has (a replica's has none). + _ = ctlfs.events.noteAction(p, id, action, range.q0, range.q1, flag, text); // A chorded exec's argument follows as two records, its text and where // it came from (`file:#q0,#q1`, empty when that is not known), as acme // sends them (exec.c:182-188); the pane keeps it for the write-back. diff --git a/src/pardes.zig b/src/pardes.zig index f0d2cd0c..36ce6bdb 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -857,7 +857,7 @@ test "Togglettymode builtin and keyboard chord share mode transitions including try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); try std.testing.expect(p.executeBuiltinLine(0, "Togglettymode")); try std.testing.expectEqual(Text.Mode.normal, pane.body.mode); - p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); + p.update(.{ .key = .{ .cp = p.tty_toggle, .ctrl = true } }); try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); // The tag has its own mode: the body keeps tty while the tag is typed into. tagline.enterTag(p, pane); @@ -867,7 +867,7 @@ test "Togglettymode builtin and keyboard chord share mode transitions including try std.testing.expectEqual(Text.Mode.normal, pane.body.mode); try std.testing.expect(pane.focus == .body); tagline.enterTag(p, pane); - p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); + p.update(.{ .key = .{ .cp = p.tty_toggle, .ctrl = true } }); try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); try std.testing.expect(pane.focus == .body); @@ -4732,6 +4732,10 @@ pub const Pardes = struct { /// The views no frontend here draws: a replica client's, which its own /// process draws (src/replica.zig). A pump skips them. undrawn: u8 = 0, + /// The Ctrl key into a terminal's tty mode and out (`--tty-toggle`): the + /// session's, taken from its options when it is made, so a dump carries + /// it to a replica, whose own options are its process's. + tty_toggle: u21 = config.tty_toggle_default, /// per-update scratch (paneCursorLines, selection text); reset each update scratch: std.heap.ArenaAllocator, /// The arena each frame's Surface text is built in, reset by `pump`. Hosts @@ -4797,6 +4801,7 @@ pub const Pardes = struct { .tree_sitter_gpa = opts.tree_sitter_allocator orelse gpa, .opts = opts, .windowed = opts.windowed, + .tty_toggle = opts.tty_toggle, .col_tags = @splat(.{ .what = .column, .gpa = gpa }), .global_tag = .{ .what = .workspace, .gpa = gpa }, .fs = .{}, @@ -4989,7 +4994,10 @@ pub const Pardes = struct { /// Recent keeps it. fn noteClosed(p: *Pardes, pane: *const Pane) void { const d = recentPlace(pane) orelse return; - if (p.recent.get(d.path) == null and !recentKeeps(d.path)) return; + // The host asked first, always: what Recent holds is the + // authority's, and a step that asked only when it did not know the + // file would ask on one side and not the other. + if (!recentKeeps(d.path) and p.recent.get(d.path) == null) return; p.recent.closedSel(p.recentGpa(), d.path, d.line, d.col, d.aline, d.acol); } @@ -5024,9 +5032,38 @@ pub const Pardes = struct { }; } - /// The recent entry a closed jump names, by its path's hash. - pub fn recentByHash(p: *const Pardes, hash: u64) ?recent_files.Entry { - for (p.recent.entries.items) |e| if (std.hash.Wyhash.hash(0, e.path) == hash) return e; + /// The session's configuration directory and startup file, as a step + /// reads them: its process's options, so the authority's + /// (`tape.authority`); a replica's are its own process's. + pub fn configDir(p: *Pardes) ?[]const u8 { + return tape.authority(optsConfigDir, .{p}); + } + + pub fn startupPath(p: *Pardes) ?[]const u8 { + return tape.authority(optsStartupPath, .{p}); + } + + fn optsConfigDir(p: *Pardes) ?[]const u8 { + return p.opts.config_dir; + } + + fn optsStartupPath(p: *Pardes) ?[]const u8 { + return p.opts.startup_config_path; + } + + /// The recent entry a closed jump names, by its path's hash, its path + /// in scratch. Recent is the authority's (every window of its user + /// writes it): a replica has its answer (`tape.authority`). + pub fn recentByHash(p: *Pardes, hash: u64) ?recent_files.Entry { + return tape.authority(recentFound, .{ p, hash }); + } + + fn recentFound(p: *Pardes, hash: u64) ?recent_files.Entry { + for (p.recent.entries.items) |e| if (std.hash.Wyhash.hash(0, e.path) == hash) { + var found = e; + found.path = p.scratch.allocator().dupe(u8, e.path) catch return null; + return found; + }; return null; } @@ -6607,7 +6644,7 @@ pub const Pardes = struct { if (header == null and pane.isTerminal() and pane.body.mode == .tty and pane.focus == .body and pane.prompt == .none) { p.leader_on = false; p.ctrl_w_pending = false; - if (key.ctrl and !key.alt and key.cp == p.opts.tty_toggle) + if (key.ctrl and !key.alt and key.cp == p.tty_toggle) return p.toggleTty(p.active); // With ProgramEsc on, bare Escape leaves only at a shell prompt // (Shift-Esc, above, always). @@ -6672,7 +6709,7 @@ pub const Pardes = struct { } return; } - const tty_toggle = key.ctrl and key.cp == p.opts.tty_toggle; + const tty_toggle = key.ctrl and key.cp == p.tty_toggle; if (pane.isTerminal() and tty_toggle) { return p.toggleTty(p.active); } @@ -7624,10 +7661,12 @@ pub const Pardes = struct { if (i == p.jcur) cur = w; // survives -> lands at w; dies -> the next one does var kept = j; const live = if (j.serial == 0) false else if (p.panes[j.pane]) |pane| pane.serial == j.serial else false; - // A file's pane closed: its entry stays, closed, while the recent - // list knows the file, and a jump to it opens it again. + // A file's pane closed: its entry stays, closed, and a jump to it + // opens it again from Recent, or drops it when Recent has + // forgotten it (`jumpBy`: Recent is the authority's, read when + // it is wanted, not at every step). if (!live) { - if (j.path_hash == 0 or p.recentByHash(j.path_hash) == null) continue; + if (j.path_hash == 0) continue; kept.serial = 0; // Open again in some pane (a look, Recent): the entry is that // pane's, and closed only while no pane has the file. @@ -7727,12 +7766,13 @@ pub const Pardes = struct { // A closed file's entry: opened again at its dot, placed as a look // places it, and the entry is that pane from here on. if (j.serial == 0) { - const e = p.recentByHash(j.path_hash) orelse return; - // Deleted since: its entries go, it is said, and the step goes - // on to the next place, never stuck on one that cannot open. - if (!recentKeeps(e.path)) { + const found = p.recentByHash(j.path_hash); + // Deleted since, or Recent has forgotten it: its entries go (the + // first said), and the step goes on to the next place, never + // stuck on one that cannot open. + if (found == null or !recentKeeps(found.?.path)) { var said: [recent_path_cap + 32]u8 = undefined; - p.setMessage(p.active, std.fmt.bufPrint(&said, "{s}: deleted, skipped", .{e.path}) catch "deleted, skipped"); + if (found) |e| p.setMessage(p.active, std.fmt.bufPrint(&said, "{s}: deleted, skipped", .{e.path}) catch "deleted, skipped"); const hash = j.path_hash; var w: usize = 0; var cur = p.jcur; @@ -7750,6 +7790,7 @@ pub const Pardes = struct { // round takes one file's entries away, so it ends. return p.jumpBy(delta); } + const e = found.?; const from = p.active; look.reopenAt(p, from, e.path, .{ .line = @max(1, j.line), .col = if (j.pdf) 0 else @max(1, j.col) }); const opened = p.panes[p.active] orelse return; @@ -9284,7 +9325,7 @@ test "raw tty forwards Ctrl letters and former global shortcuts to the child" { _ = drainWrites(p, &buf); edit.setYank(p, "register text"); for ('a'..'z' + 1) |letter| { - if (letter == p.opts.tty_toggle) continue; // editor/TTY mode shortcut + if (letter == p.tty_toggle) continue; // editor/TTY mode shortcut if (letter == 'v') continue; // the window's paste, asserted just below p.update(.{ .key = .{ .cp = @intCast(letter), .ctrl = true } }); const expected = [_]u8{@intCast(letter - 'a' + 1)}; diff --git a/src/replica.zig b/src/replica.zig index d6a2e0ef..8b1d84f4 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -3337,3 +3337,105 @@ test "a far join is sent each blob once: joined again with them on disk or in th try std.testing.expectEqual(@as(u64, 0), j.sent_bytes); endJoin(&j, &have); } + +/// A replica joined from the session's dump as it is now, between units, +/// as `Peers.join` sends it: its state, its blobs put back where they go. +fn joinedNow(a: *Authority, id: u16, view: u8) !*Replica { + const gpa = std.testing.allocator; + const was = Stepping.begin(&a.t, null); + var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; + defer blobs.deinit(a.core.gpa); + const state = try pardes.dump.dumpJoin(a.core, &blobs); + defer a.core.gpa.free(state); + tape.resync(&a.t); + was.end(); + var whole: std.ArrayListUnmanaged(u8) = .empty; + defer whole.deinit(gpa); + var pos: usize = 0; + for (blobs.items) |b| { + try whole.appendSlice(gpa, state[pos..b.at]); + try whole.appendSlice(gpa, b.bytes); + pos = b.at; + } + try whole.appendSlice(gpa, state[pos..]); + return Replica.initDump(gpa, id, view, whole.items, .{ .cols = 80, .rows = 24 }); +} + +fn agrees(a: *Authority, r: *Replica) !void { + if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); + try std.testing.expect(r.diverged == null); + try std.testing.expect(r.quiet()); + try std.testing.expectEqual(digestOf(a), r.digest()); +} + +test "a replica joined after a pane closed: the session's jump to it, its Panes and Recent rows, asked by either" { + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + defer a.deinit(); + // A file looked at and closed: a jump to it, Recent's, a closed pane. + var cwd: [std.fs.max_path_bytes]u8 = undefined; + var line: [std.fs.max_path_bytes + 32]u8 = undefined; + const dir = std.mem.span(@as([*:0]u8, @ptrCast(std.c.getcwd(&cwd, cwd.len) orelse return error.NoCwd))); + _ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/build.zig.zon", .{dir}) }); + _ = try a.local(.{ .command = "Del" }); + try std.testing.expectEqual(@as(usize, 1), a.core.store.closed.items.len); + try std.testing.expect(a.core.njumps > 1); + // What another window of the user's wrote to the store, which the + // session read (src/variants_test.zig's case, the variant hunt's). + a.core.recent.opened(a.core.recentGpa(), try std.fmt.bufPrint(&line, "{s}/build.zig", .{dir})); + const r = try joinedNow(a, 1, 0); + defer r.deinit(); + try std.testing.expectEqual(digestOf(a), r.digest()); + r.confirm(try a.local(.{ .key = .{ .cp = 'j', .text = "j" } })); + r.confirm(try a.local(.{ .command = "Search Panes" })); + r.confirm(try a.local(.{ .command = "Search Recent" })); + try agrees(a, r); + // The replica's own: it waits for the session's rows. + for ([_][]const u8{ "Search Panes", "Search Recent" }) |asked| { + const msg = try gpa.dupe(u8, try r.input(.{ .command = asked })); + defer gpa.free(msg); + r.confirm(try a.take(msg)); + r.settle(); + } + try agrees(a, r); + // The closed pane brought back by the replica's Look at it: the + // session's record of it, off the tape. + { + const closed = try std.fmt.bufPrint(&line, "Look @p{d}", .{a.core.store.closed.items[0].serial}); + const msg = try gpa.dupe(u8, try r.input(.{ .command = closed })); + defer gpa.free(msg); + r.confirm(try a.take(msg)); + r.settle(); + try std.testing.expectEqual(@as(usize, 0), a.core.store.closed.items.len); + try agrees(a, r); + r.confirm(try a.local(.{ .command = "Del" })); + } + // A jump back onto the closed file: opened again, from Recent. + for (0..3) |_| { + const msg = try gpa.dupe(u8, try r.input(.{ .key = .{ .cp = 'o', .ctrl = true } })); + defer gpa.free(msg); + r.confirm(try a.take(msg)); + r.settle(); + } + try agrees(a, r); +} + +test "a replica's Del of a file its session's Recent knows asks the host what the session asked" { + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + defer a.deinit(); + var cwd: [std.fs.max_path_bytes]u8 = undefined; + var line: [std.fs.max_path_bytes + 32]u8 = undefined; + const dir = std.mem.span(@as([*:0]u8, @ptrCast(std.c.getcwd(&cwd, cwd.len) orelse return error.NoCwd))); + _ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/build.zig.zon", .{dir}) }); + // Joined while it is open: in the session's Recent, in no replica's. + const r = try joinedNow(a, 1, 0); + defer r.deinit(); + const msg = try gpa.dupe(u8, try r.input(.{ .command = "Del" })); + defer gpa.free(msg); + r.confirm(try a.take(msg)); + r.settle(); + try std.testing.expectEqual(@as(usize, 1), a.core.store.closed.items.len); + try agrees(a, r); +} + diff --git a/src/rollback.zig b/src/rollback.zig index b0394d22..bb3ac2dc 100644 --- a/src/rollback.zig +++ b/src/rollback.zig @@ -399,7 +399,7 @@ pub const Copy = struct { const s = @typeInfo(T).@"struct"; inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| { if (attr.@"comptime") continue; - if (comptime (annotated(T, "local", name) or annotated(T, "derived", name)) and unsaved(name)) continue; + if (comptime (annotated(T, "local", name) or annotated(T, "derived", name) or annotated(T, "authority", name)) and unsaved(name)) continue; const at = @intFromPtr(&@field(v, name)); if (comptime walk.lengthOf(T, name) != null and @typeInfo(F) == .array) { try c.save(at, walk.lengthIn(v, comptime walk.lengthOf(T, name).?) * @sizeOf(@typeInfo(F).array.child)); @@ -436,10 +436,15 @@ fn annotatedStruct(comptime T: type) bool { /// (numbers, and a static name), and the rows a terminal was last read as /// (a grid's worth of text, emptied when a copy is taken and when it is /// put back: src/replica.zig), and a replica's predicted echo (src/echo.zig: -/// the replica's, never its core's). +/// the replica's, never its core's). And the store and Recent, a replica's +/// own: on the host's heap (Pardes.recentGpa), which the epoch never puts a +/// free off for, so their bytes put back would point at what is freed. A +/// step reads what the authority holds of them off the tape +/// (tape.authority), never a replica's. fn unsaved(comptime name: []const u8) bool { return std.mem.eql(u8, name, "effects") or std.mem.eql(u8, name, "in_q") or std.mem.eql(u8, name, "frames") or - std.mem.eql(u8, name, "shell_rows") or std.mem.eql(u8, name, "echo"); + std.mem.eql(u8, name, "shell_rows") or std.mem.eql(u8, name, "echo") or std.mem.eql(u8, name, "store") or + std.mem.eql(u8, name, "recent"); } fn annotated(comptime T: type, comptime kind: []const u8, comptime name: []const u8) bool { @@ -601,3 +606,43 @@ test "a file's location rows are pinned whole, with what they own, and come back p.deinit(); try std.testing.expectEqual(@as(usize, 0), e.live.count()); } + +/// `Look `, the name a file of the repository's, absolute. +fn lookAt(buf: []u8, name: []const u8) ![]const u8 { + var cwd: [std.fs.max_path_bytes]u8 = undefined; + const dir = std.c.getcwd(&cwd, cwd.len) orelse return error.NoCwd; + return std.fmt.bufPrint(buf, "Look {s}/{s}", .{ std.mem.span(@as([*:0]u8, @ptrCast(dir))), name }); +} + +test "a rollback leaves the store and Recent as a speculation left them: they live on the host's heap, which no copy holds" { + var e: Epoch = .{ .child = std.testing.allocator }; + defer e.deinit(); + const gpa = e.allocator(); + const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .image_allocator = gpa, .pdf_allocator = gpa, .tree_sitter_allocator = gpa, .frame_allocator = gpa }); + p.pump(.{}) catch {}; + var line: [std.fs.max_path_bytes + 16]u8 = undefined; + p.update(.{ .command = try lookAt(&line, "build.zig.zon") }); + p.update(.{ .command = "Del" }); + p.pump(.{}) catch {}; + try std.testing.expectEqual(@as(usize, 1), p.store.closed.items.len); + // Both lists full to what they hold: the next of each moves them. + p.store.closed.shrinkAndFree(p.recentGpa(), p.store.closed.items.len); + p.recent.entries.shrinkAndFree(p.recentGpa(), p.recent.entries.items.len); + const recents = p.recent.entries.items.len; + var c: Copy = .{}; + defer c.deinit(); + try c.take(&e, p); + // A speculation opens a file and closes it (a Del a replica applies at + // once), and is undone. + p.update(.{ .command = try lookAt(&line, "build.zig") }); + p.update(.{ .command = "Del" }); + p.pump(.{}) catch {}; + c.restore(); + // What the store and Recent hold is where they say it is. + try std.testing.expectEqual(@as(usize, 2), p.store.closed.items.len); + try std.testing.expect(std.mem.endsWith(u8, p.store.closed.items[1].name, "build.zig")); + try std.testing.expectEqual(recents + 1, p.recent.entries.items.len); + p.deinit(); + try std.testing.expectEqual(@as(usize, 0), e.live.count()); +} + diff --git a/src/tape.zig b/src/tape.zig index 3c8dd765..b16f39f9 100644 --- a/src/tape.zig +++ b/src/tape.zig @@ -107,6 +107,8 @@ pub const Site = enum(u16) { /// command printed (a pty/run's answer): a screen-state replica's /// emulator is the last delta's until the next. prompt, + /// What the authority alone holds and a step reads (`authority`). + authority, }; /// What the sites return. wire.semantics hashes their shape with the @@ -125,6 +127,10 @@ pub const results = .{ anyerror![]u8, anyerror!void, terminal.Told, ?pardes.ctlfs.pty.Printed, @typeInfo(@TypeOf(terminal.greeting)).@"fn".return_type.?, + // What only the authority holds (`authority`): a closed pane's record, + // Recent's entry for a closed jump, the closed panes' names. + ?@import("Store.zig").Record, ?@import("recent.zig").Entry, + []const @import("Store.zig").Named, }; /// What a host reports to the core as failed (`shell_failed`, `save_failed`, @@ -813,6 +819,19 @@ pub fn value(comptime s: Site, comptime f: anytype, args: anytype) @typeInfo(@Ty return call(s, null, f, args, false); } +/// A read of what the authority alone holds (`.authority` state a step +/// makes digested state from: the store's closed panes and Recent, which +/// every window of its user writes; the 9P server's readers and socket), +/// taped as `value` is; a speculation that reaches it waits for the +/// authority's answer, as at a host call. A replica's own is never read. +/// What it returns is the tape's arena's on a replay: `f` returns what +/// lives to the step's end (scratch, or the authority's own), and the +/// caller copies what it keeps. +pub fn authority(comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? { + poison(); + return value(.authority, f, args); +} + fn call(comptime s: Site, a: ?std.mem.Allocator, comptime f: anytype, args: anytype, comptime yields: bool) @typeInfo(@TypeOf(f)).@"fn".return_type.? { const R = @typeInfo(@TypeOf(f)).@"fn".return_type.?; comptime { -- cgit v1.3 From 31faf4ea430c1fa60903a7bd8adfe62630e48f7f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 30 Oct 2026 16:39:25 -0300 Subject: echo: predictions lost while their keys are still on their way (a delta that moved the screen's top, a misprediction, a cursor missed) make the keys typed next wait for the newest of them to show, as keys behind one not predicted do: predicted at once from the screen's cursor, they landed where those keys' echo was about to, and at 207 ms (three keys in flight) one such drop misjudged every key after it, so the line's typing was predicted and drawn nowhere (p50 65 ms key to output, 5 of 6 judged wrong); a trace of each misjudged cell (PARDES_REPLICA_TRACE) Co-Authored-By: Claude Opus 5.5 --- src/echo.zig | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 64 insertions(+), 3 deletions(-) (limited to 'src/echo.zig') diff --git a/src/echo.zig b/src/echo.zig index 4560930c..e25953e0 100644 --- a/src/echo.zig +++ b/src/echo.zig @@ -115,6 +115,25 @@ pub const Echo = struct { e.cursor = null; } + /// Every prediction goes, and the keys that made them may still be on + /// their way: the keys typed next wait for the newest of them to show, + /// as keys typed behind one not predicted do (`deferred`). Predicted + /// at once from the screen's cursor, they would land where those keys' + /// echo is about to (found at 207 ms, where three keys are in flight: + /// one drop, and every key after it misjudged, drawn nowhere). + fn lose(e: *Echo) void { + // The cursor after the newest key: its `due` is that key's, never + // until the authority has it. + const newest = e.cursor; + e.drop(); + const cur = newest orelse return; + if (e.waiting() or e.time() >= cur.due) return; + e.wait = cur.seq; + e.wait_key = true; + e.nd = 0; + e.wait_due = cur.due; + } + fn waiting(e: *const Echo) bool { return e.acked < e.wait or e.time() < e.wait_due; } @@ -344,7 +363,7 @@ pub const Echo = struct { if (id == e.pane and top != e.tops[id] and (e.n > 0 or e.cursor != null)) { // Scrolled: the rows predicted are others now. e.tops[id] = top; - return e.drop(); + return e.lose(); } e.tops[id] = top; if (id == e.pane) e.judge(c, 0); @@ -381,9 +400,13 @@ pub const Echo = struct { continue; } e.stats.mispredicted += 1; + if (std.c.getenv("PARDES_REPLICA_TRACE") != null) { + const cur = state.vt.screens.active.cursor; + std.debug.print("echo: key {d}'s {u} at {d},{d} not shown ({u} there) {d} ms past due; top {d}, the screen's cursor {d},{d}, acked {d}\n", .{ cell.seq, cell.cp, cell.x, cell.row, e.screenCp(state, cell.x, cell.row), (now - cell.due) / ms, e.tops[e.pane], cur.x, cur.y, e.acked }); + } if (shown) e.doubt = true; e.trusted = false; - return e.drop(); + return e.lose(); } // Shown, or a space (mosh: too easy to show by chance to vouch). // A key before the last one not predicted vouches for nothing @@ -408,7 +431,7 @@ pub const Echo = struct { e.changed = true; } else if (now >= cur.due + slack) { e.stats.cursor_missed += 1; - e.drop(); + e.lose(); } } @@ -711,6 +734,44 @@ test "a password prompt shows nothing typed, and a full-screen program is not pr try testing.expectEqual(before, g.r.echo.stats.predicted); } +test "keys still on their way when their predictions go: the next waits for their echo, never predicted where it is about to land" { + if (comptime !terminal.enabled) return error.SkipZigTest; + var g: Rig = undefined; + try g.init(); + defer g.deinit(); + try g.prints(prompt); + // Three keys typed a round trip ahead; the authority has the first, + // and its shell echoes something else: every prediction goes. + const a = try g.key(.{ .cp = 'a', .text = "a" }); + const b = try g.key(.{ .cp = 'b', .text = "b" }); + const c = try g.key(.{ .cp = 'c', .text = "c" }); + try testing.expectEqual(@as(u32, 3), g.r.echo.stats.predicted); + try g.take(a); + g.later(grace_ns); + try g.prints("A"); + try testing.expectEqual(@as(u32, 1), g.r.echo.stats.mispredicted); + try testing.expectEqual(@as(u8, 0), g.r.echo.n); + // The next key is not predicted at the screen's cursor, where b's + // echo lands: it waits for b and c. + const d = try g.key(.{ .cp = 'd', .text = "d" }); + try testing.expectEqual(@as(u32, 3), g.r.echo.stats.predicted); + try testing.expectEqual(@as(u8, 0), g.r.echo.n); + try g.take(b); + try g.take(c); + g.later(grace_ns); + try g.prints("bc"); + // Their echo shown: d is predicted after it. + try testing.expectEqual(@as(u32, 4), g.r.echo.stats.predicted); + try testing.expectEqual(@as(u8, 1), g.r.echo.n); + try testing.expectEqual(@as(u16, 5), g.r.echo.cells[0].x); + try g.take(d); + g.later(grace_ns); + try g.prints("d"); + try testing.expectEqual(@as(u32, 1), g.r.echo.stats.mispredicted); + try testing.expect(!g.r.echo.doubt); + try testing.expectEqual(@as(u8, 0), g.r.echo.n); +} + test "a misprediction takes every prediction back and shows none until an echo is confirmed; after Tab nothing is predicted until its echo" { if (comptime !terminal.enabled) return error.SkipZigTest; var g: Rig = undefined; -- cgit v1.3