summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-20 09:23:54 -0300
committerGabriel Schneider <[email protected]>2026-11-20 11:15:26 -0300
commitc6234f250ee6f94bdeb57e1d77045d74149325fa (patch)
tree52cf0c0beb4dd7fcab41c39b0877278ada99b1b4
parent446cde19a6b6fb7125fc749608cc12b7452dad6e (diff)
downloadpardes-c6234f250ee6f94bdeb57e1d77045d74149325fa.tar.gz
pardes-c6234f250ee6f94bdeb57e1d77045d74149325fa.zip
pair: under PARDES_PAIR `pardes-gui FILE` is a window client and a session with no SDL (the last step's design 1.2, Z1's rest): the child of a fork before SDL_Init EXECS the `pardes` beside it (`--paired=FD` first, the window's arguments after; its end of the socket pair kept across the exec), since a window binary's session loop is woken through SDL (gui.zig `sdlWake` is the Inbox's and the Peers' wake) and the terminal's binary needs none; with no `pardes` beside it the window is its own session as before; the session registers itself (and starts the daemon when none runs); the window's close button ends the session when it was its last client and no Detach was typed in any (a CLOSE: the client's bye says so, wire byte 2, protocol 24), a killed window leaves it running (a LOSS), with no daemon it ends with its last link; a client dialling again after an Upgrade that moved the protocol now stops at the daemon's "run the same pardes at both ends" as at "runs another build" (it dialled 20 s in vain); test/daemon.py `gui_pair` (in --gui, alone --pair-gui; on the base: the window was its own session) and `upgrade_clients` (in --upgrade when a pardes-gui is beside each build); the window's start, ReleaseFast, medium.zig, offscreen test mode, one build alternated, instructions:u (perf stat total, perf record split by pid): own 387.9-393.3 M, pair 397.5-398.3 M = window client 379.8-380.5 M + session 17.6-17.9 M (wall best 260 ms own, 282 pair, NOT judged, load 12-14); idle pair 0 wakeups in 2 s on the session side, terminal client 0, a window client unmeasurable offscreen (SDL's offscreen driver polls ~920/s, the own window the same); tui core-test 858/1013 (155 skipped), shell-test 1053/1056, term 17/17, pane 183/184, kitty 45/45, behaviour 275/275 and --replay 275/275, process-test 0 of 144 failed, soaks --clients 5 and --bytes --clients 5 diverged 0 unequal 0 corpus 22, daemon.py plain, --far, --games, --window-clients, --gui and --upgrade both ways (the base built once, pfx-old) pass, gui unit-test 1650/1654 with the perf check's BaselineHarnessMismatch its one failure (loads 5-25)
Co-Authored-By: Claude Opus <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
-rw-r--r--abi/wire.zig20
-rw-r--r--core/replica.zig28
-rw-r--r--dev/gui/gui.zig19
-rw-r--r--runtime/client.zig2
-rw-r--r--runtime/main.zig99
-rw-r--r--runtime/session.zig6
-rw-r--r--runtime/upgrade.zig4
-rw-r--r--test/daemon.py216
-rw-r--r--test/replicas.zig2
9 files changed, 350 insertions, 46 deletions
diff --git a/abi/wire.zig b/abi/wire.zig
index 8713ba98..6c86685d 100644
--- a/abi/wire.zig
+++ b/abi/wire.zig
@@ -10,6 +10,8 @@ const pardes = @import("core");
const config = @import("pardes_options");
const build_info = @import("build_info");
+/// 24: a bye's byte says the client's window was closed (2), which ends a
+/// pair's session at its last client;
/// 23: a pane of a kind's frame names its rasters by key, their pixels
/// crossing before it as strips of 4 MiB at most over the rows it shows
/// (screen kind 5), and a replica lacking one asks for its pane again
@@ -36,7 +38,7 @@ const build_info = @import("build_info");
/// part B); 14: the hello names a session and
/// carries the semantics hash, and a ping is answered (phase 5's
/// groundwork); 13: the frames went (phase 3).
-pub const version: u16 = 23;
+pub const version: u16 = 24;
/// The terminal's build and the window's step alike (`semantics`).
const family = switch (config.platform) {
@@ -296,8 +298,9 @@ pub fn helloVersion(payload: []const u8) Error!u16 {
/// one call and no longer.
pub const ClientMsg = union(enum) {
hello: Hello,
- /// The client's end: `again`, it joins again for its view at once.
- bye: struct { again: bool = false },
+ /// The client's end: `again`, it joins again for its view at once;
+ /// `close`, its window was closed (a pair's session ends at its last).
+ bye: struct { again: bool = false, close: bool = false },
/// A round trip's probe, answered `pong` with the same value.
ping: u64,
screen_ack: []const u8,
@@ -514,7 +517,8 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 {
try putSlice16(&w, h.session);
try w.writeByte(h.view orelse 0xff);
},
- .bye => |b| try w.writeByte(@intFromBool(b.again)),
+ // 0 it leaves, 1 it joins again, 2 its window was closed.
+ .bye => |b| try w.writeByte(if (b.close) 2 else @intFromBool(b.again)),
.ping => |v| try w.writeInt(u64, v, .little),
.screen_ack, .want => |bytes| try w.writeAll(bytes),
.check => {},
@@ -584,7 +588,12 @@ pub fn decodeClient(tag: u8, payload: []const u8) Error!ClientMsg {
else => |k| k,
},
} },
- .bye => .{ .bye = .{ .again = try getBool(&r) } },
+ .bye => .{ .bye = switch (try r.takeByte()) {
+ 0 => .{},
+ 1 => .{ .again = true },
+ 2 => .{ .close = true },
+ else => return error.BadValue,
+ } },
.ping => .{ .ping = try r.takeInt(u64, .little) },
.screen_ack => return .{ .screen_ack = payload },
.check => .check,
@@ -699,6 +708,7 @@ test "detached wire: every Event variant round-trips" {
try testing.expectEqualStrings("work", got.hello.session);
}
try testing.expect((try roundClient(&buf, .{ .bye = .{ .again = true } })).bye.again);
+ try testing.expect((try roundClient(&buf, .{ .bye = .{ .close = true } })).bye.close);
try testing.expectEqual(@as(?u8, 2), (try roundClient(&buf, .{ .hello = .{ .session = "work", .view = 2 } })).hello.view);
try testing.expectEqual(@as(u64, 0xfeed_beef_0000_0001), (try roundClient(&buf, .{ .ping = 0xfeed_beef_0000_0001 })).ping);
{
diff --git a/core/replica.zig b/core/replica.zig
index 781bd211..8ca505ec 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -1672,6 +1672,8 @@ pub const Peer = struct {
/// Its bye said it joins again for its view (a divergence's rejoin):
/// kept for it (views.away), not closed. Its reader's, read after its end.
again: bool = false,
+ /// ...or that its window was closed (Peers.closed).
+ close: bool = false,
/// Its number in the session's `Screens`.
sid: u16 = 0,
/// Inputs read (each one's seq, as the client numbered them).
@@ -1931,7 +1933,9 @@ pub const Peer = struct {
switch (t) {
.hello => return false,
.bye => {
- peer.again = (wire.decodeClient(tag, payload) catch return false).bye.again;
+ const b = (wire.decodeClient(tag, payload) catch return false).bye;
+ peer.again = b.again;
+ peer.close = b.close;
return false;
},
.ping => {
@@ -2054,6 +2058,10 @@ pub const Peers = struct {
/// No frontend of its own (the host says): with no client either, the
/// session is unattended.
detached: bool = false,
+ /// Its last client left by closing its window, and no Detach was typed
+ /// in any (`kept`): a pair's session ends there (runtime/session.zig).
+ closed: bool = false,
+ kept: bool = false,
/// The worst a join cost the session's step, and the last one's dump.
join_ns: u64 = 0,
each_join: std.ArrayListUnmanaged(u64) = .empty,
@@ -2353,6 +2361,7 @@ pub const Peers = struct {
core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view));
ps.closeViewOf(core, peer, peer.again);
if (ps.count() == 0) core.unattended = ps.detached;
+ if (ps.count() == 0 and peer.close and !ps.kept) ps.closed = true;
ps.seq += 1;
ps.unit(0, ps.seq);
ps.letGo(peer);
@@ -2457,6 +2466,7 @@ pub const Peers = struct {
/// (`left`), its last word; the client goes, and its reader says so.
pub fn detach(ps: *Peers, k: u8) bool {
for (ps.list) |slot| if (slot) |peer| if (peer.view == k) {
+ ps.kept = true;
var out: [wire.max_name + 8]u8 = undefined;
peer.last(wire.encodeServer(&out, .{ .left = ps.name[0..@min(ps.name.len, wire.max_name)] }) catch unreachable);
return true;
@@ -2927,10 +2937,11 @@ pub fn askCheck(fd: c_int) bool {
return writeAll(fd, wire.encodeClient(&out, .check) catch unreachable);
}
-/// The client's last word: `again`, it joins again for its view at once.
-pub fn bye(fd: c_int, again: bool) void {
+/// The client's last word: `again`, it joins again for its view at once;
+/// `close`, its window was closed.
+pub fn bye(fd: c_int, how: @FieldType(wire.ClientMsg, "bye")) void {
var out: [16]u8 = undefined;
- if (wire.encodeClient(&out, .{ .bye = .{ .again = again } })) |b| _ = writeAll(fd, b) else |_| {}
+ if (wire.encodeClient(&out, .{ .bye = how })) |b| _ = writeAll(fd, b) else |_| {}
}
/// What the session streams a client after its dump, as its frontend's loop
@@ -3043,7 +3054,7 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
/// an upgrade under way may not have said yet.
fn sameBuild(gpa: Allocator, j: Joined, why: []u8) ?Joined {
if (j.semantics == wire.semantics) return j;
- bye(j.fd, false);
+ bye(j.fd, .{});
_ = libc.close(j.fd);
var jj = j;
jj.rest.deinit(gpa);
@@ -3064,7 +3075,10 @@ fn redial(gpa: Allocator, path: []const u8, session: []const u8, why: *[600]u8,
while (true) : (tries += 1) {
why.* = @splat(0);
if (dial(gpa, path, session, why, have, view)) |j| return sameBuild(gpa, j, why);
- if (std.mem.indexOf(u8, std.mem.sliceTo(why, 0), "runs another build") != null) {
+ // Another build, or another protocol (the daemon moved with its
+ // session): no dial again will do.
+ const words = std.mem.sliceTo(why, 0);
+ if (std.mem.indexOf(u8, words, "runs another build") != null or std.mem.indexOf(u8, words, "run the same pardes at both ends") != null) {
_ = std.fmt.bufPrint(why, "{s}\x00", .{upgrade_words}) catch {};
return null;
}
@@ -3081,6 +3095,8 @@ pub const Link = struct {
r: *Replica,
fd: c_int,
quit: bool = false,
+ /// ...because its window was closed: said in its bye.
+ close: bool = false,
/// The session hung up.
gone: bool = false,
/// Something to draw: an input applied, a unit taken.
diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig
index 59e70935..36243c71 100644
--- a/dev/gui/gui.zig
+++ b/dev/gui/gui.zig
@@ -1449,7 +1449,15 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes-gui: detached from '{s}', which is still running; come back with `pardes-gui attach {s}`\n", .{ to.session, to.session }) catch "pardes-gui: detached\n") catch {};
std.process.exit(0);
},
- .ended => |code| std.process.exit(code),
+ .ended => |code| {
+ // A pair's window is its session's parent: its status once it
+ // is gone, as the terminal's (tui.zig `runClient`).
+ if (opts_in.pair != null) {
+ var status: c_int = 0;
+ while (libc.waitpid(@intCast(start.joined.pid), &status, 0) < 0 and libc.errno(-1) == .INTR) {}
+ }
+ std.process.exit(code);
+ },
}
}
@@ -1501,6 +1509,7 @@ const StdinFeed = struct {
// so a driver exercises the real pointer path (pixel to cell,
// tag and body hits). SGR mouse carries only cells.
// finger;<kind>;<id>;<x>;<y>;<pressure>
+ // close: the window's close button
// One the read cut short, or what may yet begin one, waits for
// the next read.
const rest = f.buf[seq_start..len];
@@ -1564,6 +1573,12 @@ const StdinFeed = struct {
dispatch(gp, in, &sev);
c.SDL_SetModState(before);
}
+ } else if (std.mem.eql(u8, event[0..semi], "close")) {
+ if (g) |gp| {
+ var sev = std.mem.zeroes(c.SDL_Event);
+ sev.type = c.SDL_EVENT_WINDOW_CLOSE_REQUESTED;
+ dispatch(gp, in, &sev);
+ }
} else if (std.mem.eql(u8, event[0..semi], "finger")) {
if (parseFinger(fields)) |finger| if (g) |gp| {
var wpw: c_int = 0;
@@ -1744,6 +1759,8 @@ const Input = struct {
fn close(in: *Input) void {
if (in.client) |r| {
+ // Its bye says so: a pair's session ends at its last client's.
+ r.loop.link.close = true;
r.loop.link.quit = true;
in.quit = true;
return;
diff --git a/runtime/client.zig b/runtime/client.zig
index 1314d3fb..1949d618 100644
--- a/runtime/client.zig
+++ b/runtime/client.zig
@@ -152,7 +152,7 @@ pub fn Loop(comptime Frontend: type) type {
l.after();
}
if (s.env.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file);
- if (!link.gone) replica.bye(s.joined.fd, s.r.diverged != null);
+ if (!link.gone) replica.bye(s.joined.fd, .{ .again = s.r.diverged != null, .close = link.close });
// The link's reader ends with the link, posting as it goes:
// what it posted is let go until it has (a terminal's queue
// is bounded: a reader blocked on it would never end).
diff --git a/runtime/main.zig b/runtime/main.zig
index 29c19bc0..bbe73a87 100644
--- a/runtime/main.zig
+++ b/runtime/main.zig
@@ -1157,6 +1157,13 @@ fn nativeMain(std_init: std.process.Init) !void {
upgrade.resumed = upgrade.Record.decode(args[1][upgrade.flag.len..]) catch badArgs(init.io, "--upgraded: a record this build cannot read", .{});
};
const resuming = upgrade.resumed != null;
+ // A window's pair's session (`pair`): the pardes beside a pardes-gui,
+ // exec'd in its child, its first client on the fd named, the window's
+ // arguments after it.
+ const paired: ?c_int = if (!resuming and args.len > 1 and std.mem.startsWith(u8, args[1], upgrade.paired_flag))
+ std.fmt.parseInt(c_int, args[1][upgrade.paired_flag.len..], 10) catch badArgs(init.io, "{s}: not a descriptor", .{args[1]})
+ else
+ null;
var session_only = true;
var new_session = false;
// `pardes new`: with --detach it returns once the session runs.
@@ -1166,21 +1173,21 @@ fn nativeMain(std_init: std.process.Init) !void {
var attach: ?[]const u8 = null;
var positional: ?[:0]const u8 = null;
var wait = false;
- var i: usize = if (resuming) 2 else 1;
+ var i: usize = if (resuming or paired != null) 2 else 1;
// A command's name first: new and attach go on to start or join a
// session, with the flags after them; the rest are done in `command`.
- if (!resuming and args.len > 1) if (std.meta.stringToEnum(Cmd, args[1])) |cmd| switch (cmd) {
+ if (!resuming and args.len > i) if (std.meta.stringToEnum(Cmd, args[i])) |cmd| switch (cmd) {
.new => {
new_session = true;
new_verb = true;
- i = 2;
+ i += 1;
},
.attach => {
- const named = args.len > 2 and args[2].len > 0 and args[2][0] != '-';
- attach = if (named) args[2] else "";
- i = if (named) 3 else 2;
+ const named = args.len > i + 1 and args[i + 1].len > 0 and args[i + 1][0] != '-';
+ attach = if (named) args[i + 1] else "";
+ i += if (named) 2 else 1;
},
- else => runCommand(init, cmd, args[2..]),
+ else => runCommand(init, cmd, args[i + 1 ..]),
};
while (i < args.len) : (i += 1) {
const a = args[i];
@@ -1521,11 +1528,8 @@ fn nativeMain(std_init: std.process.Init) !void {
// detached session, as `pardes --detach` (`ps` says tty), its
// windows clients. Without one there, it carries on as a window's.
if (comptime pardes.platform == .gui) if (!resuming) {
- var exe: [4096]u8 = undefined;
- const n = std.c.readlink("/proc/self/exe", &exe, exe.len);
- if (n > 0) if (std.Io.Dir.path.dirname(exe[0..@intCast(n)])) |bin| if (args.len < 64) {
- var path_buf: [4104]u8 = undefined;
- const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/pardes", .{bin}, 0) catch unreachable; // 4096 + 8 fits
+ var path_buf: [4104]u8 = undefined;
+ if (pardesBeside(&path_buf)) |path| if (args.len < 64) {
var argv: [64:null]?[*:0]const u8 = @splat(null);
argv[0] = path.ptr;
for (args[1..], 1..) |a, k| argv[k] = a.ptr;
@@ -1567,10 +1571,18 @@ fn nativeMain(std_init: std.process.Init) !void {
};
detached = if (pardes.platform == .gui) !rec.window else rec.nttys == 0;
daemon.resumeLink(rec.link, rec.stub, kind, opts.ninep_name, detached);
- } else if (pardes.platform == .tui and detach == null and std.c.getenv("PARDES_PAIR") != null) {
+ } else if (paired) |fd| {
+ // A window's pair's session: its first client on `fd`, the daemon
+ // its own to dial (and to start, when none runs).
+ opts.pair = fd;
+ term = .detached;
+ detached = true;
+ if (daemon.wanted()) _ = daemon.register(null, kind, opts.ninep_name, true);
+ } else if (detach == null and std.c.getenv("PARDES_PAIR") != null) {
// The last step's way, behind its variable until it is the default:
- // this terminal a client of a session forked off for it (`pair`).
- pair(init, &opts);
+ // this terminal or window a client of a session forked off for it
+ // (`pair`).
+ pair(init, &opts, args);
term = .detached;
} else if (daemon.wanted()) {
if (detach != null or pardes.platform == .gui) {
@@ -1708,23 +1720,48 @@ fn commOf(io: std.Io, pid: []const u8, buf: *[64]u8) []const u8 {
return std.mem.trimEnd(u8, std.Io.Dir.cwd().readFile(io, path, buf) catch return "", "\n");
}
-/// PARDES_PAIR: `pardes` in a terminal as a session and its first client
-/// over a socket pair (docs/next-run.md; the last step's design, 1.1). The
-/// daemon dialled first, as for a stub; then a fork: the parent the CLIENT
-/// (the shell's job, the terminal its own; signals reach what draws), its
-/// first join on its end of the pair; the child the SESSION (setsid, 0, 1
-/// and 2 on /dev/null, detached), its end of the pair its first client,
-/// taken before its first effects (runtime/session.zig). Returns in the
-/// session; the client exits. No fork to be had: returns, and this process
-/// is the session, with no terminal: said by the caller's run.
-fn pair(init: std.process.Init, opts: *pardes.Options) void {
- const conn: ?c_int = if (daemon.wanted()) daemon.connect(true) else null;
+/// The terminal's binary beside this one, as /proc names this one (Linux),
+/// in `buf`.
+fn pardesBeside(buf: *[4104]u8) ?[:0]const u8 {
+ var exe: [4096]u8 = undefined;
+ const n = std.c.readlink("/proc/self/exe", &exe, exe.len);
+ if (n <= 0) return null;
+ const bin = std.Io.Dir.path.dirname(exe[0..@intCast(n)]) orelse return null;
+ return std.fmt.bufPrintSentinel(buf, "{s}/pardes", .{bin}, 0) catch unreachable; // 4096 + 8 fits
+}
+
+/// PARDES_PAIR: `pardes` in a terminal, or `pardes-gui`, as a session and
+/// its first client over a socket pair (docs/next-run.md; the last step's
+/// design, 1.1 and 1.2). The daemon dialled first, as for a stub; then a
+/// fork: the parent the CLIENT (the shell's job, the terminal its own,
+/// signals reach what draws; or the window), its first join on its end of
+/// the pair; the child the SESSION (setsid, 0, 1 and 2 on /dev/null,
+/// detached), its end of the pair its first client, taken before its first
+/// effects (runtime/session.zig). A window's child execs the `pardes`
+/// beside it (`--paired=FD` first, its arguments after), which dials the
+/// daemon itself: a window's session loop is woken through SDL (gui.zig
+/// `sdlWake`), a terminal's needs none. Returns in a terminal's session;
+/// the client exits. No fork to be had: returns, and this process is the
+/// session, with no terminal: said by the caller's run. A window with no
+/// `pardes` beside it returns at once, its own session as before.
+fn pair(init: std.process.Init, opts: *pardes.Options, args: []const [:0]const u8) void {
+ var path_buf: [4104]u8 = undefined;
+ var fd_buf: [32]u8 = undefined;
+ var argv: [64:null]?[*:0]const u8 = @splat(null);
+ if (pardes.platform == .gui) {
+ const path = pardesBeside(&path_buf) orelse return;
+ if (args.len >= argv.len - 1 or std.c.access(path, std.c.X_OK) != 0) return;
+ argv[0] = path.ptr;
+ for (args[1..], 2..) |a, k| argv[k] = a.ptr;
+ }
+ const conn: ?c_int = if (pardes.platform == .tui and daemon.wanted()) daemon.connect(true) else null;
var fds: [2]c_int = undefined;
if (std.c.socketpair(std.c.AF.UNIX, std.c.SOCK.STREAM | std.c.SOCK.CLOEXEC, 0, &fds) != 0)
die(init.io, "no socket pair for a session and its terminal", .{});
+ if (pardes.platform == .gui) argv[1] = (std.fmt.bufPrintSentinel(&fd_buf, upgrade.paired_flag ++ "{d}", .{fds[0]}, 0) catch unreachable).ptr; // an fd fits 32
// The session laid out at the terminal's size: no reflow at the join.
var ws: std.posix.winsize = undefined;
- if (std.c.ioctl(0, std.posix.T.IOCGWINSZ, &ws) == 0 and ws.col > 0 and ws.row > 0) {
+ if (pardes.platform == .tui and std.c.ioctl(0, std.posix.T.IOCGWINSZ, &ws) == 0 and ws.col > 0 and ws.row > 0) {
opts.cols = ws.col;
opts.rows = ws.row;
}
@@ -1738,6 +1775,12 @@ fn pair(init: std.process.Init, opts: *pardes.Options) void {
_ = std.c.dup2(null_fd, @intCast(i));
};
if (null_fd > 2) _ = std.c.close(null_fd);
+ if (pardes.platform == .gui) {
+ // Its end of the pair across the exec.
+ _ = std.c.fcntl(fds[0], std.c.F.SETFD, @as(c_int, 0));
+ _ = execvp(argv[0].?, &argv);
+ std.c._exit(127);
+ }
opts.pair = fds[0];
// The daemon is the client's to start; the hello is this one's.
daemon.startPending(false);
@@ -1752,7 +1795,7 @@ fn pair(init: std.process.Init, opts: *pardes.Options) void {
var sock_buf: [ninep_io.sun_path_len:0]u8 = undefined;
var o = opts.*;
o.pair = fds[1];
- @import("dev").tui.runClient(init, o, daemon.replicaSocket(&sock_buf) orelse "", name, false) catch |err| die(init.io, "{t}", .{err});
+ clientOf(init, o, daemon.replicaSocket(&sock_buf) orelse "", name, false) catch |err| die(init.io, "{t}", .{err});
std.process.exit(0);
}
diff --git a/runtime/session.zig b/runtime/session.zig
index 5d7eff78..0bd38c86 100644
--- a/runtime/session.zig
+++ b/runtime/session.zig
@@ -126,8 +126,10 @@ pub fn Loop(comptime Frontend: type) type {
// Its unit to each replica client, and theirs taken in.
l.peers.boundary(l.core);
// A pair's session with no daemon ends with its last link:
- // nothing could attach to it again.
- if (o.pair != null and daemon.link < 0 and l.peers.count() == 0) break;
+ // nothing could attach to it again; with one, when its last
+ // client closed its window (a close, not a loss), no Detach
+ // typed in any.
+ if (o.pair != null and l.peers.count() == 0 and (daemon.link < 0 or l.peers.closed)) break;
fe.sent();
upgrade.locate();
// Asked in the step (the word), done between steps: the
diff --git a/runtime/upgrade.zig b/runtime/upgrade.zig
index 2a8d6edf..dcc705a5 100644
--- a/runtime/upgrade.zig
+++ b/runtime/upgrade.zig
@@ -22,6 +22,9 @@ const pardes = @import("core");
pub const supported = builtin.os.tag == .linux or builtin.os.tag == .freebsd;
pub const flag = "--upgraded=";
+/// A window's pair's session's first word (main.zig `pair`): its first
+/// client's fd, which an Upgrade does not name again (that client joined).
+pub const paired_flag = "--paired=";
/// What this build says it is (`pardes --version`'s first line).
pub const version_line = if (pardes.commit) |c| "pardes " ++ pardes.version ++ " (" ++ c ++ ")" else "pardes " ++ pardes.version;
@@ -46,6 +49,7 @@ var located = false;
/// deleted).
pub fn remember(args: []const [:0]const u8) void {
given = if (args.len > 1 and std.mem.startsWith(u8, args[1], flag)) args[2..] else if (args.len > 0) args[1..] else &.{};
+ if (given.len > 0 and std.mem.startsWith(u8, given[0], paired_flag)) given = given[1..];
if (resumed) |*rec| if (rec.exe.len > 0 and rec.exe.len < exe_buf.len) {
@memcpy(exe_buf[0..rec.exe.len], rec.exe);
exe_buf[rec.exe.len] = 0;
diff --git a/test/daemon.py b/test/daemon.py
index 7dc1b4bd..1daebea8 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -240,7 +240,7 @@ class Replica:
"""A replica's connection (abi/wire.zig): length-prefixed
messages, a tag byte and a little-endian u32 length. It is a near
client: its first word after the hello says so."""
- WIRE = 23
+ WIRE = 24
def __init__(self, path, timeout=10):
self.path, self.timeout = path, timeout
@@ -2039,6 +2039,90 @@ def gui(binary, cycles):
shutil.rmtree(root, ignore_errors=True)
+def gui_pair(gui_binary):
+ """PARDES_PAIR in a window (the last step's design, 1.2): `pardes-gui
+ FILE` is a window client and a session with no SDL, the `pardes` beside
+ it exec'd in a child (a window's session needs SDL for its wake, a
+ terminal's binary none): the session the window's child, in a session
+ of its own, listed detached with the window its client; the file in
+ the window's first frame, keys in. The window's close ends the session,
+ its last client (a CLOSE); the window killed leaves it running (a LOSS),
+ and with no daemon the session ends with its last link. Test mode:
+ hidden windows, offscreen."""
+ binary = gui_binary.replace('pardes-gui', 'pardes')
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rgp-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_DAEMON='on', TERM='xterm-256color', PARDES_PAIR='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
+ windows = []
+
+ def listed():
+ return subprocess.run([binary, 'ps'], env=env, capture_output=True, timeout=30).stdout.decode()
+
+ def started(name, e):
+ w = Window(root, name, [gui_binary, f'--9p={name}', str(notes)], e)
+ windows.append(w)
+ sock = root / f'pardes-9p-{name}.sock'
+ wait_for(f'session {name}\'s 9P socket', sock.exists, timeout=30)
+ nine = Client(sock)
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ assert session != w.pid and ppid(session) == w.pid and os.getsid(session) == session, (session, w.pid)
+ assert Path(cmdline(session)[0].decode()).name == 'pardes', ('the session is the pardes beside it', cmdline(session))
+ wait_for('the window\'s first frame', lambda: (root / name / 'latest.ppm').exists(), timeout=30)
+ pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ assert nine.read(f'/pane/{pane}/body').startswith(b'line 0 of the notes'), 'the file is the session\'s'
+ return w, nine, session, pane
+
+ try:
+ w, nine, session, pane = started('gp', env)
+ wait_for('the window listed its client', lambda: f'session gp {session} (tty, detached)' in listed()
+ and f'client {w.pid} ' in listed())
+ w.keys(b'Ofrom-the-window\x1b')
+ wait_for('its keys in the session\'s text', lambda: b'from-the-window' in nine.read(f'/pane/{pane}/body'))
+ # The close button (the test feed's word for it): its last client
+ # closed, the session ends.
+ w.p.stdin.write(b'\x1b]777;close\x07')
+ w.p.stdin.flush()
+ assert w.p.wait(timeout=30) == 0, (w.p.returncode, w.said()[-400:])
+ wait_for('the session ended with its window', lambda: not alive(session), timeout=20)
+ nine.socket.close()
+ print(f'pair window: client {w.pid} (the window) and session {session} (the pardes beside it, exec\'d in its child, '
+ 'setsid, listed detached with the window); drawn, typed; the window closed ended both')
+ w, nine, session, pane = started('gl', env)
+ wait_for('the client listed', lambda: f'client {w.pid} ' in listed())
+ os.kill(w.pid, signal.SIGKILL)
+ w.p.wait(timeout=10)
+ wait_for('the client unlisted', lambda: f'client {w.pid} ' not in listed())
+ assert alive(session) and f'session gl {session} (tty, detached)' in listed(), listed()
+ nine.socket.close()
+ assert subprocess.run([binary, 'kill', 'gl'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('the session ended', lambda: not alive(session), timeout=30)
+ print('pair window: the window killed: the session runs on, listed (a loss); killed by name')
+ w, nine, session, pane = started('gn', dict(env, PARDES_DAEMON='off'))
+ nine.socket.close()
+ os.kill(w.pid, signal.SIGKILL)
+ w.p.wait(timeout=10)
+ wait_for('the lone session ended with its last link', lambda: not alive(session), timeout=20)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
+ print('pair window: with no daemon, the window killed, its session ended; nothing left behind')
+ finally:
+ for w in windows:
+ if w.p.poll() is None:
+ w.p.kill()
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
def screen_text(client):
shown = client.screen()
cells = ''.join(cell[0] for cell in shown['cells'])
@@ -2239,7 +2323,9 @@ def upgrades(old, new):
# build's own, let go (a session shows one frontend of its own now),
# its stub told.
wait_for('the second terminal redrawn or let go', lambda: b'\x1b[?1049h' in term2.text()[before[1]:] or
- (stub2.poll() is not None and (b'detached from' in term2.text() or b'upgrade this client too' in term2.text())))
+ (stub2.poll() is not None and (b'detached from' in term2.text() or b'upgrade this client too' in term2.text()
+ or b'run the same pardes at both ends' in term2.text())),
+ timeout=30)
wait_for('the word said', lambda: 'Upgrade: now pardes' in screen_text(client))
# The daemon lists the session under its new build.
said = Replica(root / 'pardes-replica.sock').hello('work', new_build)
@@ -2368,6 +2454,124 @@ def upgrades(old, new):
shutil.rmtree(root, ignore_errors=True)
+def knows_exec(binary):
+ """Whether a build's client execs the build at its start path at an
+ Upgrade, for the view it is handed (PARDES_JOIN_VIEW)."""
+ return b'PARDES_JOIN_VIEW' in Path(binary).read_bytes()
+
+
+def upgrade_clients(old, new):
+ """Upgrade with near clients (the last step's design, 1.4): a session
+ (`new --detach`) with a terminal client and a window client attached,
+ each in its own view with a pane of its own there, onto another build installed at the path all three were
+ started from. A client of a build that execs (its start path holding
+ another file than the one it runs, the session another build than its
+ own) comes back on the build at its start path, the same process, for
+ its view: the terminal's leaves its screen and enters it again (the
+ blink), the window is a new one; in ITS view when that build joins for
+ a view it is handed (PARDES_JOIN_VIEW), else in a view of its own. One
+ of a build before it is let go and told to upgrade too. The session's
+ shell alive throughout; nothing left behind."""
+ old_gui, new_gui = old.with_name('pardes-gui'), new.with_name('pardes-gui')
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='ruc-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ (root / 'bin').mkdir()
+ binary, gui_binary = root / 'bin' / 'pardes', root / 'bin' / 'pardes-gui'
+ install(old, binary)
+ install(old_gui, gui_binary)
+ terms = []
+ procs = []
+
+ def still(check, key):
+ """Its view the live one (made_live's, for either client)."""
+ seen = len(checks(check))
+ key(b'gg')
+ wait_for('the client\'s key stepped', lambda: agreed(check, seen + 1), timeout=30)
+
+ try:
+ out = subprocess.run([str(binary), 'new', '--detach=up'], env=env, cwd=root, capture_output=True, timeout=30)
+ assert out.returncode == 0, out
+ sock = root / 'pardes-9p-up.sock'
+ nine = Client(sock)
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ shell = terminals(nine)[0]
+ shell_pid = int(run(nine, shell, b'echo $$\n').split(b'\n')[1])
+ t = Term(30, 100)
+ terms.append(t)
+ tc = t.spawn([str(binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 't.check')))
+ procs.append(tc)
+ wait_for('the terminal client drawn', lambda: b'\x1b[?1049h' in t.text(), timeout=30)
+ w = Window(root, 'w', [str(gui_binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 'w.check')))
+ procs.append(w.p)
+ wait_for('the window client drawn', lambda: (root / 'w' / 'latest.ppm').exists(), timeout=30)
+ tkey = lambda b: os.write(t.master, b) # noqa: E731
+ # Each client's view live in turn, a pane of its own made there (New).
+ owners = ((w.keys, root / 'w.check'), (tkey, root / 't.check'))
+ mine = []
+ for key, check in owners:
+ still(check, key)
+ shown = view_panes(nine)
+ nine.write('/exec', b'New\n')
+ mine.append(wait_for('a pane in the client\'s view', lambda: view_panes(nine) - shown).pop())
+ for (key, check), pane, theirs in zip(owners, mine, reversed(mine)):
+ still(check, key)
+ assert pane in view_panes(nine) and theirs not in view_panes(nine), ('each its own view', pane, theirs, nine.read('/layout'))
+ install(new, binary)
+ install(new_gui, gui_binary)
+ mark = len(t.text())
+ nine.write('/ctl', b'Upgrade\n')
+ nine.socket.close()
+ wait_for('the session on the new build', lambda: exe_of(session) == (str(binary), True), timeout=30)
+ nine = reconnect(sock)
+ if not knows_exec(old):
+ # A build before the exec: let go, dialled again for 20 s, told.
+ assert tc.wait(timeout=60) == 1 and w.p.wait(timeout=60) == 1, (tc.returncode, w.p.returncode)
+ said = t.text()[mark:] + w.said().encode()
+ assert b'upgrade this client too' in said or b'run the same pardes at both ends' in said, said[-600:]
+ print('upgrade with clients: the clients of a build before it were let go, dialled again, and told to upgrade too')
+ else:
+ wait_for('the terminal client on the new build', lambda: exe_of(tc.pid) == (str(binary), True), timeout=30)
+ wait_for('the window client on the new build', lambda: exe_of(w.pid) == (str(gui_binary), True), timeout=30)
+ # The blink: its screen left, and entered again.
+ wait_for('the terminal entered again', lambda: t.text().rfind(b'\x1b[?1049h') > t.text().rfind(b'\x1b[?1049l') > mark, timeout=30)
+ assert tc.poll() is None and w.p.poll() is None
+ for (key, check), pane, theirs in zip(owners, mine, reversed(mine)):
+ still(check, key)
+ if knows_exec(new):
+ shown = view_panes(nine)
+ assert pane in shown and theirs not in shown, ('its own view again', pane, theirs, nine.read('/layout'))
+ print('upgrade with clients: a terminal client and a window client exec\'d the build at their start path, the same processes, '
+ + ('each back in its own view, its own pane in it' if knows_exec(new) else 'each in a view of its own (that build joins for no view it is handed)'))
+ assert alive(shell_pid) and ppid(shell_pid) == session
+ for p in procs:
+ if p.poll() is None:
+ p.terminate()
+ p.wait(timeout=20)
+ nine.socket.close()
+ assert subprocess.run([str(binary), 'kill', 'up'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('the session ended', lambda: not alive(session), timeout=30)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
+ print('upgrade with clients: the shell ran on throughout; nothing left behind')
+ finally:
+ for p in procs:
+ if p.poll() is None:
+ p.kill()
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ for t in terms:
+ t.close()
+ shutil.rmtree(root, ignore_errors=True)
+
+
def gui_upgrades(old, new):
"""Upgrade in a window session (test mode: hidden windows, captured):
its window, a client window, an unsaved edit and a shell's job, onto
@@ -2462,6 +2666,11 @@ if __name__ == '__main__':
gui_upgrades(Path(sys.argv[3]).resolve(), Path(sys.argv[4]).resolve())
elif sys.argv[1:2] == ['--upgrade']:
upgrades(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
+ # With a pardes-gui beside each: the clients carried too.
+ if all(Path(a).resolve().with_name('pardes-gui').exists() for a in sys.argv[2:4]):
+ upgrade_clients(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
+ elif sys.argv[1:2] == ['--upgrade-clients']:
+ upgrade_clients(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
elif sys.argv[1:2] == ['--clients']:
clients(sys.argv[2])
elif sys.argv[1:2] == ['--manage']:
@@ -2483,8 +2692,11 @@ if __name__ == '__main__':
pdf_window(sys.argv[2], sys.argv[3])
elif sys.argv[1:2] == ['--ping']:
ping(sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5]) if len(sys.argv) > 5 else 50)
+ elif sys.argv[1:2] == ['--pair-gui']:
+ gui_pair(sys.argv[2])
elif '--gui' in sys.argv:
args = [a for a in sys.argv[1:] if a != '--gui']
gui(args[0], int(args[1]) if len(args) > 1 else 50)
+ gui_pair(args[0])
else:
main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 50)
diff --git a/test/replicas.zig b/test/replicas.zig
index 7bf79055..e07949fb 100644
--- a/test/replicas.zig
+++ b/test/replicas.zig
@@ -699,7 +699,7 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run,
const r = cl.r.?;
const link = &cl.loop.link;
// Its link ended by the session (a Detach), it says nothing more.
- if (!link.gone) replica.bye(link.fd, r.diverged != null);
+ if (!link.gone) replica.bye(link.fd, .{ .again = r.diverged != null });
try drain(cl, c, net, now);
cl.live = 0;
if (r.diverged) |why| {