diff options
| -rw-r--r-- | src/Layer.zig | 70 | ||||
| -rw-r--r-- | src/builtins.zig | 3 | ||||
| -rw-r--r-- | src/daemon.zig | 7 | ||||
| -rw-r--r-- | src/detached/wire.zig | 26 | ||||
| -rw-r--r-- | src/gui/gui.zig | 2 | ||||
| -rw-r--r-- | src/main.zig | 39 | ||||
| -rw-r--r-- | src/mouse.zig | 140 | ||||
| -rw-r--r-- | src/ninep/pty.zig | 2 | ||||
| -rw-r--r-- | src/pardes.zig | 46 | ||||
| -rw-r--r-- | src/replica.zig | 124 | ||||
| -rw-r--r-- | src/rollback.zig | 11 | ||||
| -rw-r--r-- | src/tape.zig | 83 | ||||
| -rw-r--r-- | src/tty/tty.zig | 4 | ||||
| -rw-r--r-- | src/views.zig | 67 | ||||
| -rw-r--r-- | test/daemon.py | 122 |
15 files changed, 666 insertions, 80 deletions
diff --git a/src/Layer.zig b/src/Layer.zig index ba45bc88..609ddbc4 100644 --- a/src/Layer.zig +++ b/src/Layer.zig @@ -28,6 +28,18 @@ pub const Metrics = struct { tagline_h: u16 = 1, }; +/// What a hit is resolved against: the layer it landed on, as the frame +/// the frontend hit-tested had it. A hit carries it, so the step resolves +/// the hit (again, or clamped back onto it) from the input, never from a +/// frame: the frame is the process's own (Pardes.replica's `surface`), and +/// a session never draws a replica's view. +pub const Place = struct { + viewport: pardes.Rect = .{}, + cols: u16 = 0, + rows: u16 = 0, + context_rows: u16 = 0, +}; + /// A point on a tag, notice or header layer: which row of it and which /// column at the tagline's pitch. pub const TagHit = struct { @@ -40,6 +52,7 @@ pub const TagHit = struct { pixel_x: f32, pixel_y: f32, metrics: Metrics, + place: Place = .{}, }; kind: Kind = .body, @@ -103,14 +116,22 @@ const Point = struct { index: u16, col: u16, metrics: Metrics }; /// The row and column a window pixel lands on, each row at its own pitch: /// a tag's at the tagline's width, a body's compact rows too. +pub fn place(layer: *const Layer) Place { + return .{ .viewport = layer.viewport, .cols = layer.cols, .rows = layer.rows, .context_rows = layer.context_rows }; +} + fn pointAt(layer: *const Layer, x: f32, y: f32, body_w: f32, body_h: f32, tagline_w: f32, tagline_h: f32) ?Point { + return pointIn(layer.kind, layer.place(), x, y, body_w, body_h, tagline_w, tagline_h); +} + +fn pointIn(kind: Kind, layer: Place, x: f32, y: f32, body_w: f32, body_h: f32, tagline_w: f32, tagline_h: f32) ?Point { if (layer.rows == 0 or !std.math.isFinite(x) or !std.math.isFinite(y)) return null; // A band's hit is refused outright on metrics no host could have; a // body's has always been floored to a pixel instead, and both refuse // what is no number or past a u16 (a host's floats: web's exports). for ([_]f32{ body_w, body_h, tagline_w, tagline_h }) |metric| { if (!std.math.isFinite(metric) or metric > std.math.maxInt(u16)) return null; - if (layer.kind != .body and metric < 1) return null; + if (kind != .body and metric < 1) return null; } const bw = @max(1, body_w); const bh = @max(1, body_h); @@ -122,7 +143,7 @@ fn pointAt(layer: *const Layer, x: f32, y: f32, body_w: f32, body_h: f32, taglin const headers = @as(f32, @floatFromInt(layer.context_rows)) * th; const index: u16 = @intFromFloat(if (dy < headers) @floor(dy / th) else @as(f32, @floatFromInt(layer.context_rows)) + @floor((dy - headers) / bh)); if (index >= layer.rows) return null; - const pitch = if (layer.kind != .body or index < layer.context_rows) tw else bw; + const pitch = if (kind != .body or index < layer.context_rows) tw else bw; return .{ .index = index, .col = @intFromFloat(@min(@as(f32, @floatFromInt(layer.cols -| 1)), @floor(dx / pitch))), @@ -134,15 +155,39 @@ fn pointAt(layer: *const Layer, x: f32, y: f32, body_w: f32, body_h: f32, taglin /// pane's text edge). pub fn bodyHit(layer: *const Layer, x: f32, y: f32, body_w: f32, body_h: f32, tagline_w: f32, tagline_h: f32) ?pardes.Mouse.BodyHit { if (layer.kind != .body) return null; - const point = layer.pointAt(x, y, body_w, body_h, tagline_w, tagline_h) orelse return null; - return .{ .serial = layer.serial, .row = point.index, .col = point.col + config.GUTTER, .pixel_x = x, .pixel_y = y, .metrics = point.metrics }; + return bodyHitIn(layer.place(), layer.serial, x, y, .{ .body_w = body_w, .body_h = body_h, .tagline_w = tagline_w, .tagline_h = tagline_h }); } /// A band's pixel as the tag cell under it. pub fn tagHit(layer: *const Layer, x: f32, y: f32, body_w: f32, body_h: f32, tagline_w: f32, tagline_h: f32) ?TagHit { if (layer.kind == .body) return null; - const point = layer.pointAt(x, y, body_w, body_h, tagline_w, tagline_h) orelse return null; - return .{ .kind = layer.kind, .id = layer.id, .serial = layer.serial, .line = point.index, .col = point.col, .pixel_x = x, .pixel_y = y, .metrics = point.metrics }; + return tagHitIn(layer.kind, layer.id, layer.serial, layer.place(), x, y, .{ .body_w = body_w, .body_h = body_h, .tagline_w = tagline_w, .tagline_h = tagline_h }); +} + +const Pixels = struct { body_w: f32, body_h: f32, tagline_w: f32, tagline_h: f32 }; + +fn pixelsOf(m: Metrics) Pixels { + return .{ .body_w = @floatFromInt(m.body_w), .body_h = @floatFromInt(m.body_h), .tagline_w = @floatFromInt(m.tagline_w), .tagline_h = @floatFromInt(m.tagline_h) }; +} + +fn bodyHitIn(at: Place, serial: u32, x: f32, y: f32, m: Pixels) ?pardes.Mouse.BodyHit { + const point = pointIn(.body, at, x, y, m.body_w, m.body_h, m.tagline_w, m.tagline_h) orelse return null; + return .{ .serial = serial, .row = point.index, .col = point.col + config.GUTTER, .pixel_x = x, .pixel_y = y, .metrics = point.metrics, .place = at }; +} + +fn tagHitIn(kind: Kind, id: u16, serial: u32, at: Place, x: f32, y: f32, m: Pixels) ?TagHit { + const point = pointIn(kind, at, x, y, m.body_w, m.body_h, m.tagline_w, m.tagline_h) orelse return null; + return .{ .kind = kind, .id = id, .serial = serial, .line = point.index, .col = point.col, .pixel_x = x, .pixel_y = y, .metrics = point.metrics, .place = at }; +} + +/// A body hit at its own pixel, on the place it carries. +pub fn bodyAgain(hit: pardes.Mouse.BodyHit) ?pardes.Mouse.BodyHit { + return bodyHitIn(hit.place, hit.serial, hit.pixel_x, hit.pixel_y, pixelsOf(hit.metrics)); +} + +/// A tag hit at its own pixel, on the place it carries. +pub fn tagAgain(hit: TagHit) ?TagHit { + return tagHitIn(hit.kind, hit.id, hit.serial, hit.place, hit.pixel_x, hit.pixel_y, pixelsOf(hit.metrics)); } test "compact body layer rows fill reclaimed height and invert exact boundaries" { @@ -215,15 +260,14 @@ pub fn sameCell(a: ?TagHit, b: ?TagHit) bool { pub fn columnAt(p: *const pardes.Pardes, kind: Kind, id: usize, supplied: ?TagHit, clamp: bool, line: u16) ?u16 { var point = supplied orelse return null; if (point.kind != kind or point.id != id) return null; - if (clamp) for (p.surface.tagLayers()) |*layer| { - if (layer.rows == 0 or layer.kind != kind or layer.id != id or layer.serial != point.serial or line >= layer.rows) continue; + if (clamp and line < point.place.rows) { + const v = point.place.viewport; const bw: f32 = @floatFromInt(point.metrics.body_w); const bh: f32 = @floatFromInt(point.metrics.body_h); - const left = @as(f32, @floatFromInt(layer.viewport.x)) * bw; - const right = @as(f32, @floatFromInt(layer.viewport.x + layer.viewport.w)) * bw; + const left = @as(f32, @floatFromInt(v.x)) * bw; + const right = @as(f32, @floatFromInt(v.x + v.w)) * bw; point.pixel_x = std.math.clamp(point.pixel_x, left, @max(left, right - 0.001)); - point.pixel_y = (@as(f32, @floatFromInt(layer.viewport.y + line)) + 0.5) * bh; - break; - }; + point.pixel_y = (@as(f32, @floatFromInt(v.y + line)) + 0.5) * bh; + } return if (p.reprojectTagHit(point)) |mapped| mapped.col else null; } diff --git a/src/builtins.zig b/src/builtins.zig index 97cdc5a0..b101e34d 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1475,7 +1475,8 @@ pub const Tty = struct { // start its fallback in its place. if (comptime pardes.hosted) if (arg.len > 0) { var why: [320]u8 = undefined; - if (@import("host_io.zig").Shell.refusal(arg[0..@min(arg.len, 200)], &why)) |refused| { + // The authority's lookup, taped, as Shell's (exec.zig). + if (pardes.tape.value(.shell, @import("host_io.zig").Shell.refusal, .{ arg[0..@min(arg.len, 200)], &why })) |refused| { var said: [340]u8 = undefined; return c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "Tty: {s}", .{refused}) catch "Tty: no such shell"); } diff --git a/src/daemon.zig b/src/daemon.zig index c6cd7f85..467af8b8 100644 --- a/src/daemon.zig +++ b/src/daemon.zig @@ -577,9 +577,10 @@ pub var stub: c_int = -1; extern "c" fn procctl(idtype: c_int, id: i64, cmd: c_int, data: ?*anyopaque) c_int; -/// A HUP when this process's parent dies (a forked session's stub), or no -/// longer. Linux keeps it per thread: set and cleared on the main one. -fn hupOnStubDeath(on: bool) void { +/// A HUP when this process's parent dies (a forked session's stub, an +/// --attach client's ssh), or no longer. Linux keeps it per thread: set and +/// cleared on the main one. +pub fn hupOnStubDeath(on: bool) void { var sig: c_int = if (on) @backingInt(posix.SIG.HUP) else 0; switch (builtin.os.tag) { .linux => _ = std.os.linux.prctl(@backingInt(std.os.linux.PR.SET_PDEATHSIG), @intCast(sig), 0, 0, 0), diff --git a/src/detached/wire.zig b/src/detached/wire.zig index 1c9e554e..a809bebd 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -9,6 +9,8 @@ const builtin = @import("builtin"); const pardes = @import("../pardes.zig"); const config = @import("pardes_config"); +/// 17: a pointer's hit carries the place it was made on (Layer.Place) and +/// a tag hit its line, which the step resolves it by, not by its frame; /// 16: a far client says so, the session sends it its blobs' hashes before /// the rest and only the blobs it asks for, all of it in zstd (phase 6's /// content cache and zstd notes), and a client says its frontend (a window @@ -18,7 +20,7 @@ const config = @import("pardes_config"); /// part B); 14: the hello names a session and /// carries the semantics hash, and a ping is answered (phase 5's /// groundwork); 13: the frames went (phase 3). -pub const version: u16 = 16; +pub const version: u16 = 17; /// The terminal's build and the window's step alike (`semantics`). const family = switch (config.platform) { @@ -417,6 +419,17 @@ fn getMetrics(r: *std.Io.Reader) Error!?pardes.RowMetrics { return m; } +fn putPlace(w: *std.Io.Writer, at: pardes.Layer.Place) Error!void { + for ([_]u16{ at.viewport.x, at.viewport.y, at.viewport.w, at.viewport.h, at.cols, at.rows, at.context_rows }) |n| try w.writeInt(u16, n, .little); +} + +fn getPlace(r: *std.Io.Reader) Error!pardes.Layer.Place { + var n: [7]u16 = undefined; + for (&n) |*x| x.* = try r.takeInt(u16, .little); + if (n[6] > n[5]) return error.BadValue; + return .{ .viewport = .{ .x = n[0], .y = n[1], .w = n[2], .h = n[3] }, .cols = n[4], .rows = n[5], .context_rows = n[6] }; +} + fn putBodyHit(w: *std.Io.Writer, hit: ?pardes.Mouse.BodyHit) Error!void { try w.writeByte(@intFromBool(hit != null)); if (hit) |h| { @@ -426,12 +439,13 @@ fn putBodyHit(w: *std.Io.Writer, hit: ?pardes.Mouse.BodyHit) Error!void { try w.writeInt(u32, @bitCast(h.pixel_x), .little); try w.writeInt(u32, @bitCast(h.pixel_y), .little); try putMetrics(w, h.metrics); + try putPlace(w, h.place); } } fn getBodyHit(r: *std.Io.Reader) Error!?pardes.Mouse.BodyHit { if (!try getBool(r)) return null; - const hit: pardes.Mouse.BodyHit = .{ .serial = try r.takeInt(u32, .little), .row = try r.takeInt(u16, .little), .col = try r.takeInt(u16, .little), .pixel_x = try getF32(r), .pixel_y = try getF32(r), .metrics = (try getMetrics(r)) orelse return error.BadValue }; + const hit: pardes.Mouse.BodyHit = .{ .serial = try r.takeInt(u32, .little), .row = try r.takeInt(u16, .little), .col = try r.takeInt(u16, .little), .pixel_x = try getF32(r), .pixel_y = try getF32(r), .metrics = (try getMetrics(r)) orelse return error.BadValue, .place = try getPlace(r) }; if (!std.math.isFinite(hit.pixel_x) or !std.math.isFinite(hit.pixel_y)) return error.BadValue; return hit; } @@ -443,9 +457,11 @@ fn putTagHit(w: *std.Io.Writer, hit: ?pardes.TagHit) Error!void { try w.writeInt(u16, h.id, .little); try w.writeInt(u32, h.serial, .little); try w.writeInt(u16, h.col, .little); + try w.writeInt(u16, h.line, .little); try w.writeInt(u32, @bitCast(h.pixel_x), .little); try w.writeInt(u32, @bitCast(h.pixel_y), .little); try putMetrics(w, h.metrics); + try putPlace(w, h.place); } } @@ -456,9 +472,11 @@ fn getTagHit(r: *std.Io.Reader) Error!?pardes.TagHit { .id = try r.takeInt(u16, .little), .serial = try r.takeInt(u32, .little), .col = try r.takeInt(u16, .little), + .line = try r.takeInt(u16, .little), .pixel_x = try getF32(r), .pixel_y = try getF32(r), .metrics = (try getMetrics(r)) orelse return error.BadValue, + .place = try getPlace(r), }; if (!std.math.isFinite(hit.pixel_x) or !std.math.isFinite(hit.pixel_y)) return error.BadValue; return hit; @@ -618,7 +636,9 @@ pub fn clientBound(msg: ClientMsg) usize { .bye, .ping, .check, .far => 0, .screen_ack, .want => |bytes| bytes.len, .event => |ev| switch (ev) { - .mouse, .resize, .pdf_scroll, .pinch, .touch_scroll, .pointer_leave, .focus, .frontend => 0, + // Its hits' places (14 bytes each) past the slack. + .mouse => 28, + .resize, .pdf_scroll, .pinch, .touch_scroll, .pointer_leave, .focus, .frontend => 0, .key => |k| k.text.len, .paste => |b| b.len, .command => |line| line.len, diff --git a/src/gui/gui.zig b/src/gui/gui.zig index ff1c7793..c3fdd63a 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -2889,7 +2889,7 @@ fn remoteSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ // The session again, the core it leaves held meanwhile. if (have) |h| h.leaving(r.core()); dial_t0 = std.Io.Clock.awake.now(io).nanoseconds; - joined = replica.Link.redial(gpa, to.path, to.session, &why, have) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + joined = replica.Link.redial(gpa, to.path, to.session, &why, have, r.diverged == null) orelse Said.no(io, "could not join again: {s}", .{std.mem.sliceTo(&why, 0)}); if (have) |h| h.left(); r.deinit(); r = replica.Link.load(gpa, &joined, o, &why, have) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); diff --git a/src/main.zig b/src/main.zig index ada5f3b9..f9118dfc 100644 --- a/src/main.zig +++ b/src/main.zig @@ -44,7 +44,10 @@ fn logFn( pub const panic = if (is_emscripten) std.debug.FullPanic(std.debug.defaultPanic) else std.debug.FullPanic(struct { fn call(msg: []const u8, ret_addr: ?usize) noreturn { - if (!recovering.swap(true, .seq_cst)) @import("vaxis").recover(); + if (!recovering.swap(true, .seq_cst)) { + pardes.replica.dying(); + @import("vaxis").recover(); + } @import("crash.zig").record(msg); std.debug.defaultPanic(msg, ret_addr); } @@ -54,7 +57,10 @@ var recovering: std.atomic.Value(bool) = .init(false); pub const debug = if (is_emscripten) struct {} else struct { pub fn handleSegfault(addr: ?usize, name: []const u8, opt_ctx: anytype) noreturn { - if (!recovering.swap(true, .seq_cst)) @import("vaxis").recover(); + if (!recovering.swap(true, .seq_cst)) { + pardes.replica.dying(); + @import("vaxis").recover(); + } return std.debug.defaultHandleSegfault(addr, name, opt_ctx); } }; @@ -883,6 +889,7 @@ fn nativeMain(std_init: std.process.Init) !void { } extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; +extern "c" fn atexit(f: *const fn () callconv(.c) void) c_int; /// `pardes --ps`: what the per-user daemon keeps, as a tree; `--kill=<name>` /// and `--kill-all`: those sessions ended with their shells, a TERM and, @@ -1050,38 +1057,42 @@ fn remoteAttach(init: std.process.Init, opts: pardes.Options, where: []const u8, const pid = std.c.fork(); if (pid < 0) Say.no(io, "no fork for ssh", .{}); if (pid == 0) { + // A client killed outright takes its ssh with it. + daemon.hupOnStubDeath(true); const null_fd = std.c.open("/dev/null", .{ .ACCMODE = .RDONLY }, @as(std.c.mode_t, 0)); if (null_fd >= 0) _ = std.c.dup2(null_fd, 0); _ = execvp(argv[0].?, &argv); std.c._exit(127); } + // Ended at the client's exit, whatever path it takes there (its own + // words on a refused redial exit from inside it). ponytail: a client + // that crashes leaves its socket's file behind; its ssh goes. const Ssh = struct { var child: std.c.pid_t = 0; var path: [:0]const u8 = ""; - fn end() void { - _ = std.c.kill(child, .TERM); - _ = std.c.waitpid(child, null, 0); + fn end() callconv(.c) void { + if (child > 0) { + _ = std.c.kill(child, .TERM); + _ = std.c.waitpid(child, null, 0); + } _ = std.c.unlink(path); } }; Ssh.child = pid; Ssh.path = here; + _ = atexit(Ssh.end); var waited: u32 = 0; while (std.c.access(here, std.c.F_OK) != 0) : (waited += 1) { var status: c_int = 0; - if (std.c.waitpid(pid, &status, std.c.W.NOHANG) == pid) Say.no(io, "ssh to {s} ended before its forward was up", .{where}); - if (waited > 3000) { - Ssh.end(); - Say.no(io, "ssh to {s} set up no forward in 30 s", .{where}); + if (std.c.waitpid(pid, &status, std.c.W.NOHANG) == pid) { + Ssh.child = 0; + Say.no(io, "ssh to {s} ended before its forward was up", .{where}); } + if (waited > 3000) Say.no(io, "ssh to {s} set up no forward in 30 s", .{where}); const ts: std.c.timespec = .{ .sec = 0, .nsec = 10 * std.time.ns_per_ms }; _ = std.c.nanosleep(&ts, null); } - clientOf(init, opts, here, name, true) catch |err| { - Ssh.end(); - Say.no(io, "{t}", .{err}); - }; - Ssh.end(); + clientOf(init, opts, here, name, true) catch |err| Say.no(io, "{t}", .{err}); std.process.exit(0); } diff --git a/src/mouse.zig b/src/mouse.zig index 3281f48a..b7307f2d 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -59,6 +59,9 @@ pub const Drag = union(enum) { /// This gesture began over a usable native PDF raster. The payload is /// zero-bit when PDF support is absent. pdf: panes.Pdf.PointerDrag = .{}, + /// Where its body was in the frontend's frame at its last hit there: + /// a sweep that leaves it is clamped back onto it (`bodyHitForPane`). + body: ?Layer.Place = null, }, fn button(drag: Drag) ?Mouse.Button { @@ -288,22 +291,29 @@ pub fn bodyHitForPane(p: *const Pardes, id: usize, supplied: Mouse.BodyHit, clam supplied.metrics.tagline_w == 0 or supplied.metrics.tagline_h == 0) return null; var mapped_hit = supplied; if (clamp) { + // Onto the body the sweep is in: the place of its last hit there + // (the drag's `body`), the hit's own while it is over it. + if (supplied.serial != pane.serial) mapped_hit.place = (if (p.drag == .select) p.drag.select.body else null) orelse return null; mapped_hit.serial = pane.serial; - const layer = for (&p.surface.body_layers) |*layer| { - if (layer.rows > 0 and layer.serial == pane.serial) break layer; - } else return null; + if (mapped_hit.place.rows == 0) return null; + const v = mapped_hit.place.viewport; const bw: f32 = @floatFromInt(mapped_hit.metrics.body_w); const bh: f32 = @floatFromInt(mapped_hit.metrics.body_h); - const x0 = @as(f32, @floatFromInt(layer.viewport.x)) * bw; - const y0 = @as(f32, @floatFromInt(layer.viewport.y)) * bh; - const x1 = x0 + @as(f32, @floatFromInt(layer.viewport.w)) * bw; - const y1 = y0 + @as(f32, @floatFromInt(layer.viewport.h)) * bh; + const x0 = @as(f32, @floatFromInt(v.x)) * bw; + const y0 = @as(f32, @floatFromInt(v.y)) * bh; + const x1 = x0 + @as(f32, @floatFromInt(v.w)) * bw; + const y1 = y0 + @as(f32, @floatFromInt(v.h)) * bh; mapped_hit.pixel_x = std.math.clamp(mapped_hit.pixel_x, x0, @max(x0, x1 - 0.001)); mapped_hit.pixel_y = std.math.clamp(mapped_hit.pixel_y, y0, @max(y0, y1 - 0.001)); } return p.reprojectBodyHit(mapped_hit); } +fn bodyPlace(hit: ?Mouse.BodyHit, pane: *const Pane) ?Layer.Place { + const h = hit orelse return null; + return if (h.serial == pane.serial) h.place else null; +} + pub fn sameBodyCell(a: ?Mouse.BodyHit, b: ?Mouse.BodyHit) bool { const first = a orelse return b == null; const second = b orelse return false; @@ -514,6 +524,8 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { current.kind = previous.kind; current.id = previous.id; current.serial = previous.serial; + // ...and its place, which a clamp brings the pointer back onto. + current.place = previous.place; }; } // A drag can leave the compact text viewport. Preserve its metrics so @@ -805,6 +817,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { .id = id, .button = config.select_button, .ctrl = m.ctrl, + .body = bodyPlace(m.body_hit, pane), .pdf = panes.Pdf.pointerStart( p, pane, @@ -862,6 +875,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { .select = .{ .id = id, .button = m.button, + .body = bodyPlace(m.body_hit, pane), // A native body gesture stays native even when its // point later misses a letterbox or selection. .pdf = panes.Pdf.pointerStart( @@ -933,6 +947,7 @@ pub fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16, body_hit: ?Mouse.BodyHit) vo const tag_rows: i32 = pane.tag_rows; panes.File.geometry(pane); if (pane.body_rows > 0 and pane.sel[b].r0 >= tag_rows) if (body_hit) |supplied| { + if (supplied.serial == pane.serial) s.body = supplied.place; const mapped_hit = bodyHitForPane(p, s.id, supplied, true) orelse return; pane.sel[b].c1 = @as(i32, mapped_hit.col) - config.GUTTER; pane.sel[b].r1 = @as(i32, mapped_hit.row) + tag_rows; @@ -2224,3 +2239,114 @@ test "a program tracking the mouse gets its clicks, drags and moves over its gri try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .left, .kind = .press })); try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .left, .kind = .release })); } + +const test_metrics: pardes.RowMetrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 6, .tagline_h = 12 }; + +/// A session and a replica joined to it from its dump: digest for digest +/// the same, and only the session has drawn a frame (its surface is its +/// own, `.local`). What a step does with one input must not depend on that. +fn sessionAndReplica(gpa: std.mem.Allocator, opts: pardes.Options) !struct { a: *Pardes, b: *Pardes } { + const a = try Pardes.init(gpa, opts); + errdefer a.deinit(); + a.update(.{ .resize = .{ .cols = opts.cols, .rows = opts.rows, .row_metrics = test_metrics } }); + a.sync(); + const bytes = try pardes.dump.dumpBytes(a); + defer gpa.free(bytes); + const b = try pardes.dump.load(gpa, a.opts, bytes, null); + errdefer b.deinit(); + var frame: std.heap.ArenaAllocator = .init(gpa); + defer frame.deinit(); + _ = try a.render(frame.allocator()); + try expectSame(a, b, "before the press"); + return .{ .a = a, .b = b }; +} + +/// The two cores' digests equal, else the fields (and pane fields) that differ. +fn expectSame(a: *const Pardes, b: *const Pardes, when: []const u8) !void { + if (pardes.walk.digest(Pardes, a) == pardes.walk.digest(Pardes, b)) return; + const names = comptime pardes.walk.fieldNames(Pardes); + var da: [names.len]u64 = undefined; + var db: [names.len]u64 = undefined; + _ = pardes.walk.fieldDigests(Pardes, a, &da); + _ = pardes.walk.fieldDigests(Pardes, b, &db); + for (names, da, db) |name, x, y| if (x != y) std.debug.print("{s}: {s} differs\n", .{ when, name }); + const pane_names = comptime pardes.walk.fieldNames(pardes.Pane); + for (a.panes, b.panes, 0..) |pa, pb, id| { + const x = pa orelse continue; + const y = pb orelse continue; + var pda: [pane_names.len]u64 = undefined; + var pdb: [pane_names.len]u64 = undefined; + _ = pardes.walk.fieldDigests(pardes.Pane, x, &pda); + _ = pardes.walk.fieldDigests(pardes.Pane, y, &pdb); + for (pane_names, pda, pdb) |name, u, v| if (u != v) std.debug.print("{s}: pane {d}.{s} differs\n", .{ when, id, name }); + } + return error.DigestsDiffer; +} + +fn layerCenter(layer: *const Layer, col: u16, comptime tag: bool) [2]f32 { + const w: f32 = if (tag) test_metrics.tagline_w else test_metrics.body_w; + const h: f32 = if (tag) test_metrics.tagline_h else test_metrics.body_h; + return .{ + @as(f32, @floatFromInt(layer.viewport.x)) * test_metrics.body_w + (@as(f32, @floatFromInt(col)) + 0.5) * w, + @as(f32, @floatFromInt(layer.viewport.y)) * test_metrics.body_h + 0.5 * h, + }; +} + +// A frontend's pointer hit is its own frame's: a step resolves it on the +// place the hit carries (Layer.Place), never on this process's last frame +// (`surface`, `.local`), so a session and its replica take one input alike +// (the variant hunt's, 2026-10-30, after a window client's tag hover). +test "a tag press is the same state whichever frame this process drew last" { + const gpa = std.testing.allocator; + const two = try sessionAndReplica(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer two.a.deinit(); + defer two.b.deinit(); + const layer = for (two.a.surface.tagLayers()) |*l| { + if (l.rows != 0 and l.kind == .pane) break l; + } else return error.NoPaneTag; + const at = layerCenter(layer, 2, true); + const hit = layer.tagHit(at[0], at[1], test_metrics.body_w, test_metrics.body_h, test_metrics.tagline_w, test_metrics.tagline_h) orelse return error.NoHit; + const press: pardes.Event = .{ .mouse = .{ .button = .left, .kind = .press, .col = layer.viewport.x + 2, .row = layer.viewport.y, .tag_hit = hit } }; + two.a.update(press); + two.b.update(press); + try expectSame(two.a, two.b, "after the press"); +} + +// The same through a body hit (edit.pointerTextSelection, a sweep's drag), +// on a compact body layer (TreeContext), which a pixel shell inverts. +test "a body press, drag and release are the same state whichever frame this process drew last" { + if (comptime !pardes.syntax.enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const a = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); + defer a.deinit(); + const pane = try a.setTestFile("pub const Box = struct {\n pub fn run() void {\n" ++ (std.mem.asBytes(&@as([30][16]u8, @splat(" // body\n".*)))) ++ " }\n};\n"); + a.gpa.free(pane.file.?.path); + pane.file.?.path = try a.gpa.dupe(u8, "/test.zig"); + if (!pardes.panes.File.supportsContext(pane)) return error.SkipZigTest; + a.update(.{ .resize = .{ .cols = 60, .rows = 16, .row_metrics = test_metrics } }); + pane.file.?.tree_context = true; + pane.file.?.scroll = 8; + a.sync(); + const bytes = try pardes.dump.dumpBytes(a); + defer gpa.free(bytes); + const b = try pardes.dump.load(gpa, a.opts, bytes, null); + defer b.deinit(); + var frame: std.heap.ArenaAllocator = .init(gpa); + defer frame.deinit(); + _ = try a.render(frame.allocator()); + // The join agrees, the frame drawn and all. + try expectSame(a, b, "before the press"); + const layer = for (&a.surface.body_layers) |*l| { + if (l.rows > 0 and l.serial == pane.serial) break l; + } else return error.NoBodyLayer; + const at = layerCenter(layer, 8, false); + const hit = layer.bodyHit(at[0], at[1], test_metrics.body_w, test_metrics.body_h, test_metrics.tagline_w, test_metrics.tagline_h) orelse return error.NoHit; + const col: u16 = @intFromFloat(at[0] / test_metrics.body_w); + const row: u16 = @intFromFloat(at[1] / test_metrics.body_h); + for ([_]pardes.Mouse.Kind{ .press, .drag, .release }) |kind| { + const ev: pardes.Event = .{ .mouse = .{ .button = .left, .kind = kind, .col = col, .row = row, .body_hit = hit } }; + a.update(ev); + b.update(ev); + } + try expectSame(a, b, "after the press"); +} diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index 53fc5c68..ee8c618e 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -86,7 +86,7 @@ pub fn writeCtl(p: *Pardes, req: Req, id: usize) Reply { if (comptime pardes.hosted) if (!apply and std.mem.eql(u8, line, "exec")) if (p.panes[id]) |pane| { const bin = pane.shell orelse p.shellBin(); var why: [320]u8 = undefined; - if (@import("../host_io.zig").Shell.refusal(bin[0..@min(bin.len, 200)], &why)) |refused| + if (pardes.tape.value(.shell, @import("../host_io.zig").Shell.refusal, .{ bin[0..@min(bin.len, 200)], &why })) |refused| return tree.failText(req.tag, E.NOENT, std.fmt.bufPrint(&p.fs.ename, "exec: {s}", .{refused}) catch "exec: no such shell"); }; if (!verb(p, id, line, apply)) return tree.failText(req.tag, E.INVAL, if (tooFewRows(line)) e_winsize_rows else if (outOfRange(line)) e_winsize_range else e_bad_pty_ctl); diff --git a/src/pardes.zig b/src/pardes.zig index 5b37342e..189a5b02 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -172,8 +172,10 @@ pub const Turn = struct { /// a step. Nests: a directory listing that resolves each entry yields /// inside a yield, and only the outermost one lets go. pub fn yield(t: *Turn) void { - // A replica makes no syscall: each is a site of the tape's. - if (tape.replaying()) @panic("tape: a syscall that is no tape site, made replaying"); + // A replica makes no syscall: each is a site of the tape's. One that + // is none stops a speculation and diverges a replay (it joins + // again), never the process (a window client's `Tty fish`, H17). + if (tape.replaying()) tape.stray(); const io = t.io orelse return; yield_depth += 1; if (yield_depth != 1) return; @@ -478,6 +480,7 @@ pub const Loc = struct { test { _ = @import("rollback.zig"); + _ = @import("tape.zig"); _ = @import("replica.zig"); _ = @import("echo.zig"); _ = @import("modal.zig"); @@ -3595,6 +3598,7 @@ pub const Mouse = struct { pixel_x: f32, pixel_y: f32, metrics: RowMetrics, + place: Layer.Place = .{}, }; // sel indexing relies on left/middle/right being 0/1/2 pub const Button = enum { left, middle, right, wheel_up, wheel_down, wheel_left, wheel_right, none, back, forward }; @@ -5692,6 +5696,17 @@ pub const Pardes = struct { p.settle(); } + /// The last client of a session no one else watches gone: its view + /// goes, and the session's own is laid out as it was (views.closeKeeping), + /// which the client's rejoin copies. Settled as `closeView` is. + pub fn leaveView(p: *Pardes, k: u8) void { + const taped = tape.enter(p, .{ .leave_view = k }); + defer tape.leave(p, taped); + views.closeKeeping(p, k); + p.sync(); + p.settle(); + } + /// Into view `k`, before the input its client sent. pub fn toView(p: *Pardes, k: u8) void { if (k == p.view) return; @@ -8176,18 +8191,16 @@ pub const Pardes = struct { return p.haptic; } + /// A frontend's tag hit, if what it names is still there: resolved on + /// the place it carries (Layer.Place), not on this process's frame. pub fn reprojectTagHit(p: *const Pardes, tag_hit: TagHit) ?TagHit { - for (p.surface.tagLayers()) |*layer| { - if (layer.rows == 0 or layer.kind != tag_hit.kind or layer.id != tag_hit.id or layer.serial != tag_hit.serial) continue; - if (layer.kind == .pane) { - if (layer.id >= p.panes.len) return null; - const pane = p.panes[layer.id] orelse return null; - if (pane.serial != layer.serial) return null; - } - if (layer.kind == .column and (layer.id >= p.ncol or p.col_serial[layer.id] != layer.serial)) return null; - return layer.tagHit(tag_hit.pixel_x, tag_hit.pixel_y, @floatFromInt(tag_hit.metrics.body_w), @floatFromInt(tag_hit.metrics.body_h), @floatFromInt(tag_hit.metrics.tagline_w), @floatFromInt(tag_hit.metrics.tagline_h)) orelse continue; + if (tag_hit.kind == .pane) { + if (tag_hit.id >= p.panes.len) return null; + const pane = p.panes[tag_hit.id] orelse return null; + if (pane.serial != tag_hit.serial) return null; } - return null; + if (tag_hit.kind == .column and (tag_hit.id >= p.ncol or p.col_serial[tag_hit.id] != tag_hit.serial)) return null; + return Layer.tagAgain(tag_hit); } /// The pane's first body row: under the tag when it is on top, over it @@ -8207,12 +8220,9 @@ pub const Pardes = struct { return layer.capacity(p.row_metrics); } - pub fn reprojectBodyHit(p: *const Pardes, body_hit: Mouse.BodyHit) ?Mouse.BodyHit { - for (&p.surface.body_layers) |*layer| { - if (layer.rows == 0 or layer.serial != body_hit.serial) continue; - return layer.bodyHit(body_hit.pixel_x, body_hit.pixel_y, @floatFromInt(body_hit.metrics.body_w), @floatFromInt(body_hit.metrics.body_h), @floatFromInt(body_hit.metrics.tagline_w), @floatFromInt(body_hit.metrics.tagline_h)); - } - return null; + /// A frontend's body hit, resolved on the place it carries. + pub fn reprojectBodyHit(_: *const Pardes, body_hit: Mouse.BodyHit) ?Mouse.BodyHit { + return Layer.bodyAgain(body_hit); } // ---- render: build the canonical surface (draw.zig) ---- diff --git a/src/replica.zig b/src/replica.zig index 22de375f..2af32cdb 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -235,6 +235,16 @@ pub const Authority = struct { return .{ .view = k, .unit = try a.unit(0, a.seq) }; } + /// Client `client`'s view gone (its link ended), as its unit. + pub fn closeView(a: *Authority, client: u16) ![]const u8 { + std.debug.assert(a.batched == 0); + const was = Stepping.begin(&a.t, null); + a.core.closeView(a.view_of[client]); + was.end(); + a.seq += 1; + return a.unit(0, a.seq); + } + /// One client's input, applied in the order it came, in its view: the /// unit every replica takes. pub fn take(a: *Authority, msg: []const u8) ![]const u8 { @@ -687,7 +697,23 @@ pub const Replica = struct { r.applied -= 1; if (r.applied == 0) { // Nothing speculative on top any more: the state is the - // confirmed one. + // confirmed one, which its digest says. A step of its own + // that read what the session's did not (a frame's, a + // derived field's) shows here, at the input that did it, + // not at some later unit replayed. + if (lastDigest(u.tape)) |d| { + tape.checkDigest(&r.t, d); + if (r.t.diverged) |why| { + if (std.c.getenv("PARDES_REPLICA_TRACE") != null) { + var w: std.Io.Writer.Allocating = .init(r.gpa); + defer w.deinit(); + w.writer.print("replica {d}: its input {d} came to another state than the session's: {s}\n", .{ r.id, u.seq, why }) catch {}; + tape.describe(u.tape, &w.writer); + std.debug.print("{s}", .{w.written()}); + } + return r.fail(why); + } + } r.copy.release(); rollback.Epoch.select(null); r.clearSince(); @@ -1320,6 +1346,9 @@ pub const Peer = struct { var list: std.ArrayListUnmanaged(u8) = .empty; defer list.deinit(gpa); for (peer.blobs.items) |b| { + // Gone meanwhile: its leave waits for this thread in the + // session's step, so the hashing stops here. + if (peer.letting()) return false; var entry: [blob_entry]u8 = undefined; std.mem.writeInt(u64, entry[0..8], b.at, .little); std.mem.writeInt(u64, entry[8..16], b.bytes.len, .little); @@ -1350,6 +1379,14 @@ pub const Peer = struct { return peer.z != null; } + /// Whether it is being let go (or was cut off). + fn letting(peer: *Peer) bool { + const io = peer.peers.io; + peer.lock.lockUncancelable(io); + defer peer.lock.unlock(io); + return peer.closing or peer.cut; + } + /// One message into its stream's compressor. fn zMessage(peer: *Peer, tag: wire.ServerTag, payload: []const u8) bool { const head = wire.header(@backingInt(tag), payload.len); @@ -1513,6 +1550,18 @@ pub const Peer = struct { } }; +/// The session's clients, for `dying`. +var live_peers: ?*Peers = null; + +/// The process is panicking: each client's link shut first, so that it +/// hears the end now, not when the trace is written (seconds, symbolized). +pub fn dying() void { + const ps = live_peers orelse return; + for (ps.list) |slot| if (slot) |peer| { + _ = libc.shutdown(peer.fd, 2); + }; +} + pub const Peers = struct { gpa: Allocator = std.heap.c_allocator, io: std.Io = undefined, @@ -1750,6 +1799,7 @@ pub const Peers = struct { const slot = for (&ps.list) |*s| { if (s.* == null) break s; } else return refuse(fd, "that session has as many clients as it takes"); + live_peers = ps; if (!ps.recording) { // A session recording to a file (PARDES_RECORD) has its tape. if (tape.on != null) return refuse(fd, "that session records a tape of its own (PARDES_RECORD)"); @@ -1836,7 +1886,7 @@ pub const Peers = struct { log.info("client {d} left '{s}'", .{ peer.id, ps.name }); ps.screens.dropPeer(peer.sid); core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view)); - core.closeView(peer.view); + ps.closeViewOf(core, peer); if (ps.count() == 0) core.unattended = ps.alone_unattended; ps.seq += 1; ps.unit(0, ps.seq); @@ -1844,6 +1894,13 @@ pub const Peers = struct { if (ps.count() == 0) ps.stop(core); } + /// A gone client's view closed (its slot let go already): the last one + /// of a session no one else watches leaves the session its layout, for + /// its rejoin (an Upgrade's, a diverged one's) to find. + fn closeViewOf(ps: *Peers, core: *Pardes, peer: *Peer) void { + if (ps.count() == 0 and ps.alone_unattended) core.leaveView(peer.view) else core.closeView(peer.view); + } + /// Its threads ended and joined, its link closed. fn letGo(ps: *Peers, peer: *Peer) void { const io = ps.io; @@ -1949,7 +2006,7 @@ pub const Peers = struct { for (&ps.list) |*slot| if (slot.*) |peer| { slot.* = null; core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view)); - core.closeView(peer.view); + ps.closeViewOf(core, peer); ps.screens.dropPeer(peer.sid); ps.letGo(peer); }; @@ -2770,7 +2827,10 @@ pub const Link = struct { /// dialled every 100 ms for 20 s. A far client's (`have`) holds the /// core it leaves meanwhile (`Have.leaving`): its blobs are not sent /// again. Null, and why in `why`. - pub fn redial(gpa: Allocator, path: []const u8, session: []const u8, why: *[600]u8, have: ?*Have) ?Joined { + /// `patient`: after an Upgrade's `refused` alone, while the session is + /// away a moment; after a divergence a session that will not answer is + /// gone, and the client says so at once (it froze 20 s, 2026-10-30). + pub fn redial(gpa: Allocator, path: []const u8, session: []const u8, why: *[600]u8, have: ?*Have, patient: bool) ?Joined { var tries: u32 = 0; while (true) : (tries += 1) { why.* = @splat(0); @@ -2788,13 +2848,20 @@ pub const Link = struct { _ = std.fmt.bufPrint(why, "{s}\x00", .{upgrade_words}) catch {}; return null; } - if (tries > 200) return null; + if (!patient or tries > 200) return null; const ts: libc.timespec = .{ .sec = 0, .nsec = 100 * std.time.ns_per_ms }; _ = libc.nanosleep(&ts, null); } } }; +test "a client joining again after a divergence is told at once that its session is gone" { + var why: [600]u8 = undefined; + const t0 = nowNs(); + try std.testing.expect(Link.redial(std.testing.allocator, "/nonexistent/pardes-replica.sock", "gone", &why, null, false) == null); + try std.testing.expect(nowNs() - t0 < 100 * std.time.ns_per_ms); +} + fn appendTo(path: [:0]const u8, line: []const u8) void { const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644)); if (fd < 0) return; @@ -3007,6 +3074,53 @@ test "a delta applied under a speculation outlives its rollback: the terminal st for (rows_a[rows_a.len - shown ..], rows_r[rows_r.len - shown ..]) |x, y| try std.testing.expectEqualStrings(x, y); } +test "a view that sized a terminal closing leaves nothing queued: the others' replicas copy, type and agree" { + if (comptime !terminal.enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, TestHost.host(), true); + defer a.deinit(); + const first = try gpa.dupe(u8, try a.unit(0, 0)); + defer gpa.free(first); + const r1 = try Replica.init(gpa, 1, first, true); + defer r1.deinit(); + const r2 = try Replica.init(gpa, 2, first, true); + defer r2.deinit(); + a.core.active = for (a.core.panes, 0..) |slot, id| { + if (slot) |pane| if (pane.isTerminal()) break id; + } else return error.NoShell; + const opened = try a.openView(2); + r2.view = opened.view; + for ([_]*Replica{ r1, r2 }) |r| r.confirm(opened.unit); + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| gpa.free(m); + sent.deinit(gpa); + } + // The second client, at another size, types into the terminal: its + // view sizes it. Then it goes (H10, 2026-10-30: the first aborted). + try sent.append(gpa, try gpa.dupe(u8, try r2.input(.{ .resize = .{ .cols = 50, .rows = 20 } }))); + try key(r2, 'x', &sent); + for (sent.items) |m| { + const u = try gpa.dupe(u8, try a.take(m)); + defer gpa.free(u); + r1.confirm(u); + r1.settle(); + } + r1.confirm(try a.closeView(2)); + try std.testing.expectEqual(@as(usize, 0), a.core.effects_len); + try std.testing.expectEqual(@as(usize, 0), r1.core().effects_len); + r1.ready(); + try std.testing.expect(r1.copy.held); + for (sent.items) |m| gpa.free(m); + sent.clearRetainingCapacity(); + try key(r1, 'y', &sent); + r1.confirm(try a.take(sent.items[0])); + r1.settle(); + if (r1.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); + try std.testing.expect(r1.diverged == null and r1.quiet()); + try std.testing.expectEqual(digestOf(a), r1.digest()); +} + /// p50 and p99 of `samples`, sorted in place. fn spread(samples: []u64) [2]u64 { std.mem.sort(u64, samples, {}, std.sort.asc(u64)); diff --git a/src/rollback.zig b/src/rollback.zig index 9c4f6c05..cc10d2cc 100644 --- a/src/rollback.zig +++ b/src/rollback.zig @@ -221,7 +221,9 @@ pub const Copy = struct { return a.addr == b.addr and a.ty == b.ty; } }; - pub const Error = Allocator.Error; + /// Queued: the core holds effects or inputs not drained yet, which no + /// copy is taken over (the replica's input waits for the authority). + pub const Error = Allocator.Error || error{Queued}; pub fn deinit(c: *Copy) void { c.regions.deinit(c.meta); @@ -244,14 +246,15 @@ pub const Copy = struct { /// it held stays where it is until the copy is put back or let go. pub fn take(c: *Copy, e: *Epoch, p: *const Pardes) Error!void { std.debug.assert(!c.held); + // A step drains these before it ends, and a copy is taken between + // steps; an input of a host's without one (a view closed) may leave + // some until it is drained. + if (p.effects_len != 0 or p.in_len != 0) return error.Queued; c.regions.clearRetainingCapacity(); c.bytes.clearRetainingCapacity(); c.seen.clearRetainingCapacity(); c.pins.clearRetainingCapacity(); c.epoch = e; - // A step drains these before it ends: between steps they hold - // nothing, and a copy is taken between steps. - std.debug.assert(p.effects_len == 0 and p.in_len == 0); if (c.epoch.?.owns(@intFromPtr(p)) == null) @panic("rollback: the core is not its epoch's"); try c.object(Pardes, p); e.begin(); diff --git a/src/tape.zig b/src/tape.zig index b16f39f9..12e3bdec 100644 --- a/src/tape.zig +++ b/src/tape.zig @@ -62,6 +62,7 @@ pub const Input = union(enum) { file_deleted: u8, open_view, close_view: u8, + leave_view: u8, to_view: u8, /// What a window says of its font and its opacity (gui.zig). take_font_request, @@ -605,6 +606,7 @@ pub const Tape = struct { .file_deleted => |id| pardes.panes.File.deleted(p, id), .open_view => _ = p.openView(), .close_view => |k| p.closeView(k), + .leave_view => |k| p.leaveView(k), .to_view => |k| p.toView(k), .take_font_request => _ = p.takeFontRequest(), .observe_font => |f| _ = p.observeFont(f.name, f.size, f.unit), @@ -845,12 +847,14 @@ fn call(comptime s: Site, a: ?std.mem.Allocator, comptime f: anytype, args: anyt const t = on orelse return if (yields) out(f, args) else @call(.auto, f, args); const id: u16 = @as(u16, host_fns.len) + @backingInt(s); if (t.replay) { - if (!t.expectHost(id, @tagName(s))) { - std.debug.print("replay: {s}\n", .{t.diverged orelse "?"}); - @panic("tape: the replay diverged at a host call of the core's own"); - } + // Diverged (said in `diverged`): what a speculation gets, harmless, + // for the rest of the input. A replica joins again; a replay says so. + if (!t.expectHost(id, @tagName(s))) return poisonOf(R); var ret = t.last_ret; - return walk.decode(R, &ret, a orelse t.arena.allocator()) catch @panic("tape: a short result"); + return walk.decode(R, &ret, a orelse t.arena.allocator()) catch { + t.diverge("the tape's answer to {t} is short", .{s}); + return poisonOf(R); + }; } // The host's own (a shell's spawn asking the shell), or one inside a // site's syscall: the outer call is the record. @@ -906,6 +910,13 @@ pub fn recordDigest(t: *Tape) void { t.record(.digest, []const u64, &d); } +/// The core's digest against a digest record's payload (a unit's last): a +/// difference is `diverged`, its fields named when the record has them. +pub fn checkDigest(t: *Tape, payload: []const u8) void { + var r: walk.Reader = .{ .bytes = payload }; + t.check(&r); +} + /// A core made outside the tape (a replica client's, from a dump) is the /// one it replays into. pub fn adoptCore(t: *Tape, p: *Pardes) void { @@ -945,6 +956,14 @@ pub fn replaying() bool { return if (on) |t| t.replay or t.speculating else false; } +/// A syscall of the core's that is no site, made by a replica: what it +/// returns is the authority's to say. A speculation waits for it, and a +/// replay has diverged. +pub fn stray() void { + const t = on orelse return; + if (t.speculating) t.poisoned = true else t.diverge("a syscall that is no tape site, made replaying", .{}); +} + /// A replica speculating (src/replica.zig): state only the authority /// changes (a terminal's emulator) is left alone, and the input waits. pub fn speculating() bool { @@ -1115,6 +1134,16 @@ pub fn describe(bytes: []const u8, w: *std.Io.Writer) void { const tag = std.mem.bytesToValue(std.meta.Tag(Input), payload[0..@sizeOf(std.meta.Tag(Input))]); w.print("input {t}", .{tag}) catch {}; if (tag == .update) w.print(" {t}", .{std.mem.bytesToValue(std.meta.Tag(pardes.Event), payload[@sizeOf(std.meta.Tag(Input))..][0..@sizeOf(std.meta.Tag(pardes.Event))])}) catch {}; + // A key's or a pointer's own words: which one a divergence + // starts at. + var room: [4096]u8 = undefined; + var fixed: std.heap.FixedBufferAllocator = .init(&room); + var in: walk.Reader = .{ .bytes = payload }; + if (tag == .update) if (walk.decode(Input, &in, fixed.allocator())) |input| switch (input.update) { + .key => |k| w.print(" {any}", .{k}) catch {}, + .mouse => |m| w.print(" {t} {t} {d},{d} body {any} tag {any}", .{ m.button, m.kind, m.col, m.row, m.body_hit != null, m.tag_hit != null }) catch {}, + else => {}, + } else |_| {}; }, .host => { const id = std.mem.bytesToValue(u16, payload[0..2]); @@ -1201,3 +1230,47 @@ pub fn replayMain(io: std.Io, path: []const u8) u8 { } return if (failed) 1 else 0; } + +test "a syscall that is no site, made replaying, diverges the replay and poisons a speculation" { + if (comptime !pardes.hosted) return; + const gpa = std.testing.allocator; + var t: Tape = .{ .gpa = gpa, .replay = true, .scratch = .init(gpa), .arena = .init(gpa) }; + defer t.scratch.deinit(); + defer t.arena.deinit(); + defer if (t.diverged) |why| gpa.free(why); + on = &t; + defer on = null; + pardes.turn.yield(); + pardes.turn.back(); + try std.testing.expect(t.diverged != null); + t.replay = false; + t.speculating = true; + pardes.turn.yield(); + pardes.turn.back(); + try std.testing.expect(t.poisoned); +} + +test "a replay that finds no answer where its core reads one diverges, and the read goes on harmless" { + if (comptime !pardes.hosted) return; + const gpa = std.testing.allocator; + var t: Tape = .{ .gpa = gpa, .replay = true, .scratch = .init(gpa), .arena = .init(gpa) }; + defer t.scratch.deinit(); + defer t.arena.deinit(); + defer if (t.diverged) |why| gpa.free(why); + // The input's end where the core reads a value of the host's (a + // window client's step that took a turn the session's had not, H9 of + // 2026-10-30: it aborted the client). + const bytes = [5]u8{ @backingInt(Kind.done), 0, 0, 0, 0 }; + t.in = .{ .bytes = &bytes }; + t.host_side = false; + on = &t; + defer on = null; + const read = struct { + fn f() bool { + return true; + } + }.f; + try std.testing.expect(!value(.denied, read, .{})); + try std.testing.expect(t.diverged != null); + try std.testing.expect(!value(.denied, read, .{})); +} diff --git a/src/tty/tty.zig b/src/tty/tty.zig index a1a28181..39c287f7 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -1482,9 +1482,9 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se // are not sent again. if (have) |h| h.leaving(r.core()); dial_t0 = std.Io.Clock.awake.now(io).nanoseconds; - joined = replica.Link.redial(gpa, path, session, &why, have) orelse { + joined = replica.Link.redial(gpa, path, session, &why, have, r.diverged == null) orelse { screen.leave(); - Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + Said.no(io, "could not join again: {s}", .{std.mem.sliceTo(&why, 0)}); }; if (have) |h| h.left(); r.deinit(); diff --git a/src/views.zig b/src/views.zig index 34644a96..ac274621 100644 --- a/src/views.zig +++ b/src/views.zig @@ -422,7 +422,7 @@ pub fn open(p: *Pardes) ?u8 { }; const slot = p.parked[k].?; slot.* = .{ .view = .{ .screen_w = p.screen_w, .screen_h = p.screen_h } }; - inline for (.{ "screen_w", "screen_h", "cell_pixels", "row_metrics", "ncol", "col_weight", "col_panes", "col_n", "col_serial", "finder", "active", "active_column", "jumps", "njumps", "jcur", "windowed", "native_images", "native_image_patches" }) |name| + inline for (sized ++ laid_out ++ .{ "windowed", "native_images", "native_image_patches" }) |name| @field(slot.view, name) = @field(p, name); slot.view.col_tags = @splat(.{ .what = .column, .gpa = p.gpa }); for (p.panes, 0..) |s, id| { @@ -435,6 +435,39 @@ pub fn open(p: *Pardes) ?u8 { return k; } +/// How a view is laid out and focused: what a new one takes of the live +/// one (`open`), and what one going leaves the view that stays (`closeKeeping`). +const laid_out = .{ "ncol", "col_weight", "col_panes", "col_n", "col_serial", "finder", "active", "active_column", "jumps", "njumps", "jcur" }; +const sized = .{ "screen_w", "screen_h", "cell_pixels", "row_metrics" }; + +/// View `k` gone, and the view that stays live laid out as `k` was: its +/// columns, its focus, its panes where they were scrolled and its cursors +/// where they were. For a session's last client while no one else watches +/// it (replica.Peers.leave): the client's rejoin (an Upgrade's, a diverged +/// one's) copies the live view (`open`), so it finds its own again. +pub fn closeKeeping(p: *Pardes, k: u8) void { + if (!isOpen(p, k) or count(p) == 1) return; + to(p, k); + const other: u8 = for (0..max) |i| { + if (i != k and isOpen(p, @intCast(i))) break @intCast(i); + } else unreachable; + const slot = p.parked[other].?; + // Its size too: the terminals it sized keep theirs, no shell redrawn for + // a size it is given back at the rejoin. + inline for (sized ++ laid_out) |name| @field(slot.view, name) = @field(p, name); + for (p.panes, 0..) |s, id| { + const pane = s orelse { + slot.serials[id] = 0; + continue; + }; + if (pane.pv_known & (@as(u8, 1) << @intCast(other)) != 0 and pane.pv[other].body.sels.len > 0) p.gpa.free(pane.pv[other].body.sels); + slot.serials[id] = pane.serial; + pane.pv[other] = fresh(pane); + pane.pv_known |= @as(u8, 1) << @intCast(other); + } + close(p, k); +} + /// View `k` gone, and all it held; the live one moves to another first. /// The last view stays: a session without a client keeps its own. pub fn close(p: *Pardes, k: u8) void { @@ -771,6 +804,38 @@ test "a view closing leaves the others as they were" { try testing.expectEqual(@as(i32, 70), pane.body.cur_row); } +test "the last client's view going leaves the session its layout, which a rejoin copies" { + const gpa = testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); + defer p.deinit(); + const text = try numbered(gpa, 100); + defer gpa.free(text); + const pane = try p.setTestFile(text); + const k = p.openView().?; + p.toView(k); + p.update(.{ .resize = .{ .cols = 120, .rows = 40 } }); + p.update(.{ .command = "Newcol" }); + p.update(.{ .command = "New" }); + const made = p.active; + const ncol = p.ncol; + p.active = 0; + p.sync(); + cursorTo(p, pane, 60); + p.leaveView(k); + try testing.expectEqual(@as(usize, 1), count(p)); + try testing.expectEqual(ncol, p.ncol); + try testing.expect(layout.findPane(p, made) != null); + try testing.expectEqual(@as(i32, 60), pane.body.cur_row); + try testing.expectEqual(@as(u16, 120), p.screen_w); + // Its client back (a view copied from the live one): all of it again. + const again = p.openView().?; + p.toView(again); + try testing.expectEqual(ncol, p.ncol); + try testing.expect(layout.findPane(p, made) != null); + try testing.expectEqual(@as(usize, 0), p.active); + try testing.expectEqual(@as(i32, 60), pane.body.cur_row); +} + test "drawing the other views leaves the live one as it was, to the digest" { const gpa = testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); diff --git a/test/daemon.py b/test/daemon.py index 1086dac3..7b0e5343 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -193,7 +193,7 @@ class Replica: """A replica's connection (src/detached/wire.zig): length-prefixed messages, a tag byte and a little-endian u32 length. It is a near client: its first word after the hello says so.""" - WIRE = 16 + WIRE = 17 def __init__(self, path, timeout=10): self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) @@ -547,6 +547,11 @@ class Window: self.p.stdin.write(text.replace(b'\x1b', b'\x1b[27u')) self.p.stdin.flush() + def mouse(self, kind, button, x, y): + """A pointer event at window pixels (gui.zig's test feed).""" + self.p.stdin.write(f'\x1b]777;mouse;{kind};{button};{x};{y}\x07'.encode()) + self.p.stdin.flush() + def said(self): return self.err.read_text(errors='replace') if self.err.exists() else '' @@ -632,6 +637,24 @@ def window_clients(binary, gui_binary): n = len(checks(check)) w.keys(b'jjjjjkkk\x06\x06\x02') wait_for(f'the window client agrees again ({rtt} ms)', lambda: agreed(check, n), timeout=30) + if rtt in (0, 207): + # The pointer over the tags (the workspace's, the column's, + # the pane's: the top rows, a test window's cells about 16 by + # 33 pixels) and over the body, a click there: a window's + # hits are its own frame's, which the session never draws, + # so they are its input's, not re-made from a frame. Each + # tag motion made it join again (the user's, 2026-10-30). + n = len(checks(check)) + for y in range(5, 170, 11): + for x in range(4, 1280, 23): + w.mouse('motion', 0, x, y) + for k in range(40): + w.mouse('motion', 0, 100 + 25 * k, 200 + 9 * k) + w.mouse('down', 1, 400, 300) + w.mouse('motion', 1, 600, 360) + w.mouse('up', 1, 600, 360) + wait_for(f'the window client agrees after its pointer ({rtt} ms)', lambda: agreed(check, n), timeout=30) + assert 'joined again' not in w.said(), w.said()[-800:] agreements.append(len(checks(check))) assert w.close() == 0, w.said()[-800:] if relay: @@ -891,6 +914,30 @@ def far(binary): detach('f', tf, f) f_join = joins(root / 'f.stats')[0] assert f_join['from_disk'] > 0 and sum(cached(cache).values()) <= 1 << 20, (f_join, cached(cache)) + far_joins(root / 'pardes-replica.sock', 'files', binary, 200) + # Through ssh (a stand-in forwarding as `ssh -L` does): a client + # refused and one detached each end their ssh and its socket (one + # refused left both, 2026-10-30). + fake = root / 'ssh' + fake.write_text('#!/bin/sh\nwhile [ $# -gt 0 ]; do case $1 in -L) fwd=$2; shift;; esac; shift; done\n' + f'exec {sys.executable} -B {Path(__file__).parent / "delay_relay.py"} "${{fwd%%:*}}" "${{fwd#*:}}" --delay 0\n') + fake.chmod(0o755) + senv = dict(env, PARDES_SSH=str(fake), PARDES_REMOTE_RUNTIME=str(root), TMPDIR=str(root)) + + def forwarded(): + return [q for q in processes(root) if alive(q) and any(b'pardes-ssh-' in a for a in cmdline(q))] or list(root.glob('pardes-ssh-*')) + for name in ('nobody', 'files'): + ts = Term(24, 90) + terms.append(ts) + sc = ts.spawn([binary, f'--attach=box:{name}'], senv) + started.append(sc.pid) + if name == 'files': + wait_for('the client through ssh\'s first frame', lambda: b'line 3 of the notes' in ts.text(), timeout=30) + time.sleep(.3) + os.write(ts.master, b' sD') + wait_for(f'the client through ssh ends ({name})', lambda: sc.poll() is not None, timeout=30) + assert name == 'files' or b"no session called 'nobody'" in ts.text(), ts.text()[-300:] + wait_for(f'its ssh and socket gone ({name})', lambda: not forwarded(), timeout=10) body = texts() for words in (b'from-A', b'from-B', b'again-A', b'from-C', b'from-D', b'from-E', b'from-F'): assert words in body, words @@ -919,6 +966,67 @@ def far(binary): shutil.rmtree(root, ignore_errors=True) +def far_joins(sock, session, binary, n): + """`n` far joins of one session in a row, each read whole (its blobs + asked for by none, its zstd frames unpacked) and answering a ping, then + gone: the session's fds and threads as they were, its RSS within a + bound. Each join made zstd contexts through the C heap, whose release + builds named a new allocator at every malloc and aborted at the 65th + (the box's session, after 15 far joins, 2026-10-30).""" + from compression import zstd + build = semantics(binary) + + def join(): + r = Replica(sock, timeout=30) + name = session.encode() + r.send(0x01, struct.pack('<HQH', Replica.WIRE, build, len(name)) + name) + r.send(0x06, b'\x01') + tag, body = r.read() + assert tag == 0x01, (tag, body) + pid, k = struct.unpack_from('<IH', body) + blobs, = struct.unpack_from('<I', body, len(body) - 4) + if blobs: + r.send(0x07, bytes((blobs + 7) // 8)) + r.send(0x03, struct.pack('<Q', 7)) + d, inner = zstd.ZstdDecompressor(), b'' + while True: + tag, body = r.read() + assert tag == 0x09, tag + inner += d.decompress(body) + while d.eof: + rest, d = d.unused_data, zstd.ZstdDecompressor() + inner += d.decompress(rest) if rest else b'' + while len(inner) >= 5: + t, m = struct.unpack_from('<BI', inner) + if len(inner) < 5 + m: + break + payload, inner = inner[5:5 + m], inner[5 + m:] + if t == 0x03: + assert payload == struct.pack('<Q', 7), payload + r.send(0x02, b'') + r.close() + return pid + + def threads(pid): + return len(os.listdir(f'/proc/{pid}/task')) if procfs else int(ps('-o', 'nlwp=', '-p', str(pid))) + + def rss_kb(pid): + if procfs: + return next(int(line.split()[1]) for line in open(f'/proc/{pid}/status') if line.startswith('VmRSS:')) + return int(ps('-o', 'rss=', '-p', str(pid))) + pid = join() + time.sleep(.5) + before = fds(pid), threads(pid), rss_kb(pid) + t = time.monotonic() + for _ in range(n): + assert join() == pid + wait_for('the far joins\' fds and threads let go', lambda: (fds(pid), threads(pid)) == before[:2], timeout=10) + grown = rss_kb(pid) - before[2] + assert grown < 64 << 10, (before, grown) + print(f'daemon: {n} far joins of one session in {time.monotonic() - t:.1f} s: its fds and threads as they were ' + f'({before[0]}, {before[1]}), its RSS {grown:+d} KB') + + def terminals(client): return [int(row.split()[0]) for row in client.read('/index').splitlines() if row.split()[1] == b'term'] @@ -1014,8 +1122,18 @@ def main(binary, cycles): assert now[:3] == baseline[:3], (how, now, baseline) print('daemon: a second terminal on an attached session drawn beside the first, then detached and closed; the first drew on') - # Killed outright: its shells live on, their masters the daemon's. + # Killed outright: its shells live on, their masters the daemon's, + # and a replica client of it hears so at once, in words (one froze + # 20 s and then said only that there was no such session). + tr = Term(24, 90) + rc = tr.spawn([binary, f'--attach={root / "pardes-replica.sock"}:work'], env) + started.append(rc.pid) + wait_for('the replica client\'s first frame', lambda: len(tr.text()) > 2000, timeout=30) os.kill(session, signal.SIGKILL) + killed = time.monotonic() + wait_for('the replica client ended with its session', lambda: rc.poll() is not None, timeout=10) + assert time.monotonic() - killed < 2 and b'let this client go' in tr.text(), (time.monotonic() - killed, tr.text()[-300:]) + tr.close() stub.wait(timeout=10) client.socket.close() term.close() |
