summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-20 08:36:06 -0300
committerGabriel Schneider <[email protected]>2026-11-20 08:36:06 -0300
commit446cde19a6b6fb7125fc749608cc12b7452dad6e (patch)
treea7c2792ecdb1833a2e5a3ef99b9fb6ce96c01a00
parent2c2800c93e5417297dd06d3e52d5d336d975560c (diff)
parentae3b9e9d19492c827f257da8a224a19d77de51c1 (diff)
downloadpardes-446cde19a6b6fb7125fc749608cc12b7452dad6e.tar.gz
pardes-446cde19a6b6fb7125fc749608cc12b7452dad6e.zip
integration: a session's first client over an inherited socket before its first effects, the pair under PARDES_PAIR, and a session's last word, on the 9P run's fixes and the build's second pass: pardes-first-client (new --detach forks and returns; Options.pair and the join by fd; pardes FILE as a client and a session under the variable; ended CODE and left NAME: a client's own Detach exits 0 with its line again) and pardes-merge33, merged without a textual conflict; tui core-test 858/1013 (155 skipped), shell-test 1053/1056, the window builds; the coordinator's gate in the ledger (reorg/merge34)
Co-Authored-By: Claude Fable 5.2 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
-rw-r--r--abi/wire.zig10
-rw-r--r--core/CHANGELOG.md9
-rw-r--r--core/Core.zig5
-rw-r--r--core/replica.zig196
-rw-r--r--core/root.zig2
-rw-r--r--dev/gui/gui.zig8
-rw-r--r--dev/tui/tui.zig26
-rw-r--r--docs/next-run.md13
-rw-r--r--docs/typ/command-line.txt6
-rw-r--r--runtime/client.zig9
-rw-r--r--runtime/daemon.zig57
-rw-r--r--runtime/main.zig65
-rw-r--r--runtime/session.zig11
-rw-r--r--test/daemon.py256
-rw-r--r--test/process.zig3
15 files changed, 620 insertions, 56 deletions
diff --git a/abi/wire.zig b/abi/wire.zig
index a36e746b..8713ba98 100644
--- a/abi/wire.zig
+++ b/abi/wire.zig
@@ -192,6 +192,10 @@ pub const ServerTag = enum(u8) {
/// unit naming it: the hash, the whole's length and this piece's place
/// (u64le each), then at most 1 MiB of it (core/replica.zig).
blob = 0x0a,
+ /// The session's last word on a link: it ended, with its exit code.
+ ended = 0x0b,
+ /// ...or this client left it running (a Detach typed in it): its name.
+ left = 0x0c,
};
pub const ServerMsg = union(ServerTag) {
@@ -209,6 +213,8 @@ pub const ServerMsg = union(ServerTag) {
blobs: []const u8,
zstd: []const u8,
blob: []const u8,
+ ended: u8,
+ left: []const u8,
};
/// A message's header, for a payload sent on its own (a unit, a dump's
@@ -244,6 +250,8 @@ pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg {
.blobs => return .{ .blobs = payload },
.zstd => return .{ .zstd = payload },
.blob => return .{ .blob = payload },
+ .ended => .{ .ended = try r.takeByte() },
+ .left => .{ .left = try r.take(try r.takeInt(u16, .little)) },
};
try end(&r);
return msg;
@@ -268,6 +276,8 @@ pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 {
.pong => |v| try w.writeInt(u64, v, .little),
.dump, .unit, .screen, .blobs, .zstd, .blob => |bytes| try w.writeAll(bytes),
.check => |v| try w.writeInt(u64, v, .little),
+ .ended => |code| try w.writeByte(code),
+ .left => |name| try putSlice16(&w, name),
}
try finishMessage(&w, at);
return w.buffered();
diff --git a/core/CHANGELOG.md b/core/CHANGELOG.md
index 67fbdf69..faa02ade 100644
--- a/core/CHANGELOG.md
+++ b/core/CHANGELOG.md
@@ -2,6 +2,10 @@
## Unreleased
+- `pardes new --detach[=NAME]` returns once the session runs (registered
+ and listening), printing its name, exit 0; the session runs on in a
+ session of its own. `pardes --detach=NAME` without `new` is still the
+ session itself, until it ends.
- `pardes attach NAME` (and `pardes-gui attach NAME`) is always a client:
a process of its own with its own view, whatever the session was
started in. A session's own terminal or window is only the one it was
@@ -9,8 +13,9 @@
back. Before, an attach to a detached terminal's session handed it this
terminal (the attach waiting as its stub), and `pardes-gui attach` asked
a detached window's session to open its own window again and exited 0.
- A client's Detach ends it with "'NAME' let this client go" and exit 1,
- where the stub said "detached from 'NAME'" and exited 0. Bare, `pardes
+ A client's Detach ends it with "detached from 'NAME', which is still
+ running" and exit 0, as the stub's did (the session's last word on a
+ link, `left`); a session's end, with its code (`ended`). Bare, `pardes
attach` takes the one detached session, else the one session, of either
kind; with several it names them all.
diff --git a/core/Core.zig b/core/Core.zig
index da1dc4b8..7ebcc020 100644
--- a/core/Core.zig
+++ b/core/Core.zig
@@ -2279,6 +2279,11 @@ pub const Options = struct {
startup_config: ?[]const u8 = null,
ninep_name: []const u8 = "",
ninep_tcp: ?[]const u8 = null,
+ /// This process's end of a socket pair its launch made (runtime/main.zig,
+ /// PARDES_PAIR): a session's first client is on it, taken before its
+ /// first effects (runtime/session.zig); a client's session is on it,
+ /// its first join made there with no hello (replica.join).
+ pair: ?c_int = null,
mounts: []const filesystem.Mount = &.{},
config_dir: ?[]const u8 = null,
/// Where what outlives the session is kept (Db.zig): the user's state
diff --git a/core/replica.zig b/core/replica.zig
index 3f92603c..781bd211 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -1887,6 +1887,16 @@ pub const Peer = struct {
peer.cond.signal(io);
}
+ /// Its last message: queued, and its writer ends once it is written.
+ fn last(peer: *Peer, words: []const u8) void {
+ const io = peer.peers.io;
+ peer.send(&.{words});
+ peer.lock.lockUncancelable(io);
+ peer.closing = true;
+ peer.cond.signal(io);
+ peer.lock.unlock(io);
+ }
+
fn writeLoop(peer: *Peer) void {
const io = peer.peers.io;
defer peer.done.store(true, .release);
@@ -2230,7 +2240,10 @@ pub const Peers = struct {
}
}
- fn join(ps: *Peers, core: *Pardes, joining: Joining) void {
+ /// A client on `joining.fd` joined: a dump of the session now, its
+ /// threads started. At a step boundary (`boundary`), or a session's
+ /// first client before its first effects (runtime/session.zig).
+ pub fn join(ps: *Peers, core: *Pardes, joining: Joining) void {
const fd = joining.fd;
const t0 = nowNs();
defer {
@@ -2401,14 +2414,14 @@ pub const Peers = struct {
if (ps.count() == 0) return;
var out: [600]u8 = undefined;
const words = wire.encodeServer(&out, .{ .refused = why }) catch return;
- const io = ps.io;
- for (ps.list) |slot| if (slot) |peer| {
- peer.send(&.{words});
- peer.lock.lockUncancelable(io);
- peer.closing = true;
- peer.cond.signal(io);
- peer.lock.unlock(io);
- };
+ for (ps.list) |slot| if (slot) |peer| peer.last(words);
+ ps.flushed200();
+ // Each joins again for its view, kept in the dump (views.away).
+ ps.drop(core, true);
+ }
+
+ /// What each client was sent goes first, for up to 200 ms.
+ fn flushed200(ps: *Peers) void {
const until = nowNs() + 200 * std.time.ns_per_ms;
while (nowNs() < until) {
const busy = for (ps.list) |slot| {
@@ -2418,8 +2431,6 @@ pub const Peers = struct {
const ts: libc.timespec = .{ .sec = 0, .nsec = 2 * std.time.ns_per_ms };
_ = libc.nanosleep(&ts, null);
}
- // Each joins again for its view, kept in the dump (views.away).
- ps.drop(core, true);
}
/// A join's dump and pins let go: written, or its client gone.
@@ -2442,16 +2453,26 @@ pub const Peers = struct {
daemon.clients(pids[0..n]);
}
- /// Detach typed in client view `k`'s: its link ends (its reader says
- /// it is gone, and the next boundary lets it go).
+ /// Detach typed in client view `k`'s: told it left the session running
+ /// (`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) {
- _ = libc.shutdown(peer.fd, 2);
+ 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;
};
return false;
}
+ /// The session ends with `code`: every client told so (`ended`), its
+ /// last word, before the links are let go (`dropAll`).
+ pub fn ended(ps: *Peers, code: u8) void {
+ var out: [16]u8 = undefined;
+ const words = wire.encodeServer(&out, .{ .ended = code }) catch unreachable;
+ for (ps.list) |slot| if (slot) |peer| peer.last(words);
+ ps.flushed200();
+ }
+
fn stop(ps: *Peers, core: *Pardes) void {
if (!ps.recording) return;
pardes.panes.resizeDeferred(core);
@@ -2575,13 +2596,14 @@ pub fn dial(gpa: Allocator, path: []const u8, session: []const u8, why: []u8, ha
}
/// `dial`'s, on a connection made: the hello, then the join. The
-/// connection is closed if the join fails.
-fn joinOn(gpa: Allocator, fd: c_int, session: []const u8, why: []u8, have: ?*Have, view: ?u8) ?Joined {
+/// connection is closed if the join fails. No session named: no hello, a
+/// pair's (Options.pair), whose session took it as its first client.
+fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Have, view: ?u8) ?Joined {
var out: [wire.hello_max + 16]u8 = undefined;
- const hello = wire.encodeClient(&out, .{ .hello = .{ .session = session, .view = view } }) catch {
+ const hello = if (session) |name| wire.encodeClient(&out, .{ .hello = .{ .session = name, .view = view } }) catch {
_ = libc.close(fd);
return said(why, "that session's name is too long", .{});
- };
+ } else out[0..0];
// Its first word, in the same write: whether it is far.
const far = wire.encodeClient(out[hello.len..], .{ .far = have != null }) catch unreachable;
var j: Joined = .{ .fd = fd, .pid = 0, .client = 0, .view = 0, .gmtoff = 0, .dump = &.{} };
@@ -2914,7 +2936,7 @@ pub fn bye(fd: c_int, again: bool) void {
/// What the session streams a client after its dump, as its frontend's loop
/// takes it: a unit's and a terminal message's bytes and a refusal's words
/// on the C heap, the loop's to free.
-pub const Said = union(enum) { unit: []u8, screen: []u8, checked: u64, refused: []u8, blob: []u8 };
+pub const Said = union(enum) { unit: []u8, screen: []u8, checked: u64, refused: []u8, blob: []u8, ended: u8, left };
/// The session's stream off `fd`, each message handed to `post` until the
/// link ends (a refusal ends it too); `post` says whether it took it (one
@@ -2929,13 +2951,16 @@ pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime
.blob => .{ .blob = std.heap.c_allocator.dupe(u8, payload) catch return false },
.check => .{ .checked = (wire.decodeServer(tag, payload) catch return false).check },
.refused => .{ .refused = std.heap.c_allocator.dupe(u8, (wire.decodeServer(tag, payload) catch return false).refused) catch return false },
+ .ended => .{ .ended = (wire.decodeServer(tag, payload) catch return false).ended },
+ .left => .left,
.pong, .welcome, .dump, .blobs, .zstd => return true,
};
if (!post(x, msg)) switch (msg) {
.unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b),
- .checked => {},
+ .checked, .ended, .left => {},
};
- return msg != .refused;
+ // A last word ends the stream.
+ return msg == .unit or msg == .screen or msg == .checked or msg == .blob;
}
};
rest.run(gpa, fd, ctx, Take.take);
@@ -2960,7 +2985,8 @@ pub fn ended(why: []const u8) bool {
const upgrade_words = "session upgraded to a newer pardes: upgrade this client too";
/// A replica client's join, the terminal's and the window's alike (their
-/// `runClient`): the session at `path` dialled, its build checked to be this
+/// `runClient`): the session at `path` dialled (or, first, the one on its
+/// pair, `o.pair`), its build checked to be this
/// one's, and its dump loaded into a replica checked against the session
/// as it was dumped. Or, `old` given, joined again once old's link has
/// ended, for old's view (`redial`): the core it leaves held meanwhile so
@@ -2982,7 +3008,7 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
};
if (have) |h| h.left();
prev.deinit();
- } else j.* = sameBuild(gpa, dial(gpa, path, session, why, have, null) orelse return null, why) orelse return null;
+ } else j.* = sameBuild(gpa, (if (o.pair) |fd| joinOn(gpa, fd, null, why, have, null) else dial(gpa, path, session, why, have, null)) orelse return null, why) orelse return null;
defer {
if (have) |h| h.store(gpa, j) else gpa.free(j.dump);
j.dump = &.{};
@@ -3084,6 +3110,9 @@ pub const Link = struct {
visible: u32 = 0,
/// What the session said as it let this client go (the C heap's).
refused: ?[]u8 = null,
+ /// Its last word: it ended, with this code; or this client left it.
+ ended: ?u8 = null,
+ left: bool = false,
/// A line over its frame, until its next key (`notify`): why it joined
/// again. The client's own, never the session's core.
notice_buf: [240]u8 = undefined,
@@ -3202,6 +3231,14 @@ pub const Link = struct {
c.refused = words;
c.quit = true;
},
+ .ended => |code| {
+ c.ended = code;
+ c.quit = true;
+ },
+ .left => {
+ c.left = true;
+ c.quit = true;
+ },
}
if (c.r.diverged != null) c.quit = true;
}
@@ -4408,6 +4445,119 @@ test "bytes: a client joins from a dump with its terminals whole, and every side
try sameTerminals(b.a, late);
}
+test "a session's first client on the socket it starts with (Options.pair), joined there with no hello before the session's first effects: the boot shell's spawn and first bytes reach it and the digests agree" {
+ try firstOnPair(false);
+}
+
+test "bytes: a session's first client on its pair, taken before its first effects, has the boot shell's first bytes with no reload of them (the session's one at the join is of its emulator before any byte, the client's none); a client after them makes every side reload" {
+ try firstOnPair(true);
+}
+
+/// A session's first client on a socket pair (runtime/session.zig's, then
+/// the client's first join on its end), the session's first effects after:
+/// its boot shell spawned, its first bytes output; the client quiet and
+/// checked. Bytes: the client loaded as the soak's bytes clients are
+/// (`replica.join` loads the screen-state kind until the switch).
+fn firstOnPair(bytes: bool) !void {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const gpa = std.testing.allocator;
+ const Spawns = struct {
+ fn spawn(ctx: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {
+ const n: *u32 = @ptrCast(@alignCast(ctx.?));
+ n.* += 1;
+ }
+ const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .spawn = spawn };
+ };
+ var spawns: u32 = 0;
+ var fds: [2]c_int = undefined;
+ if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket;
+ const opts: pardes.Options = .{ .cols = 80, .rows = 24, .boot = .tty };
+ const core = try Pardes.init(gpa, opts);
+ defer core.deinit();
+ core.host = .{ .ctx = &spawns, .vtable = &Spawns.vtable };
+ var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .name = "pair", .bytes = bytes, .detached = true };
+ defer ps.deinit();
+ defer live_peers = null;
+ defer ps.dropAll(core);
+ const reloads = pardes.Term.reloads.n;
+ ps.join(core, .{ .fd = fds[0] });
+ var j: Joined = undefined;
+ var why: [600]u8 = @splat(0);
+ const r = if (bytes) r: {
+ j = joinOn(gpa, fds[1], null, &why, null, null) orelse return error.JoinFailed;
+ defer gpa.free(j.dump);
+ const r = try Replica.initDump(gpa, j.client, j.view, j.dump, opts);
+ r.t.screen_state = false;
+ r.core().echo = null;
+ break :r r;
+ } else r: {
+ var o = opts;
+ o.pair = fds[1];
+ break :r join(gpa, &j, "", "", o, null, &why, null) orelse {
+ std.debug.print("the join failed: {s}\n", .{std.mem.sliceTo(&why, 0)});
+ return error.JoinFailed;
+ };
+ };
+ defer r.deinit();
+ defer {
+ _ = libc.close(j.fd);
+ j.rest.deinit(gpa);
+ }
+ try std.testing.expect(r.loaded(j.digest));
+ // The first effects, the boot shell's spawn among them; its first bytes.
+ while (core.nextEffect()) |e| core.perform(e);
+ try std.testing.expectEqual(@as(u32, 1), spawns);
+ const shell: u8 = for (core.panes, 0..) |slot, id| {
+ if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
+ } else return error.NoShell;
+ core.update(.{ .output = .{ .pane = .at(shell), .bytes = "first$ " } });
+ ps.boundary(core);
+ // Its check, answered after every unit and terminal message before it.
+ try std.testing.expect(askCheck(j.fd));
+ while (!ps.mail.load(.acquire)) std.Thread.yield() catch {};
+ ps.boundary(core);
+ const Take = struct {
+ r: *Replica,
+ fd: c_int,
+ digest: ?u64 = null,
+ fn take(t: *@This(), tag: u8, payload: []const u8) bool {
+ switch (std.enums.fromInt(wire.ServerTag, tag) orelse return false) {
+ .unit => t.r.confirm(payload),
+ .screen => if (t.r.screen(payload)) |reply| {
+ _ = sendScreen(t.fd, reply);
+ },
+ .check => {
+ t.digest = (wire.decodeServer(tag, payload) catch return false).check;
+ return false;
+ },
+ else => {},
+ }
+ return true;
+ }
+ };
+ var take: Take = .{ .r = r, .fd = j.fd };
+ j.rest.run(gpa, j.fd, &take, Take.take);
+ r.settle();
+ if (r.diverged) |w| std.debug.print("diverged: {s}\n", .{w});
+ try std.testing.expect(r.diverged == null);
+ try std.testing.expectEqual(take.digest.?, r.digest());
+ // Bytes: the session's reload at the join, of an emulator that held
+ // nothing yet (Pardes.init made it, the spawn is a first effect); the
+ // client loaded it from the dump and replayed every byte since.
+ try std.testing.expectEqual(reloads + @intFromBool(bytes), pardes.Term.reloads.n);
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const rows = try pardes.Term.viewport(r.core().panes[shell].?.terminal.?, arena.allocator(), false);
+ try std.testing.expect(std.mem.indexOf(u8, rows[0], "first$") != null);
+ if (!bytes) return;
+ // One that comes after the shell's bytes: every side reloads.
+ var late: [2]c_int = undefined;
+ if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &late) != 0) return error.NoSocket;
+ defer _ = libc.close(late[1]);
+ ps.join(core, .{ .fd = late[0] });
+ try std.testing.expectEqual(reloads + 2, pardes.Term.reloads.n);
+}
+
test "bytes: a session's output past a unit's bound is cut into units under it, between two reads" {
if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
const gpa = std.testing.allocator;
diff --git a/core/root.zig b/core/root.zig
index 9509439a..5300ce93 100644
--- a/core/root.zig
+++ b/core/root.zig
@@ -630,7 +630,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{
.{ "hunks.zig", 1, "a test helper's file read" },
.{ "look.zig", 6, "openLink's fork (the host's: a view's frontend opens a link) and a remote's error name" },
.{ "memory.zig", 7, "the memory regions themselves (mmap, madvise, their locks)" },
- .{ "replica.zig", 70, "the client and session engines: sockets, threads, clocks, the blob cache, traces" },
+ .{ "replica.zig", 73, "the client and session engines: sockets, threads, clocks, the blob cache, traces" },
.{ "rollback.zig", 1, "a test helper's directory" },
.{ "root.zig", 4, "dev's modules re-exported (host_io, file_watch, glide, fonts)" },
.{ "selection_pipe.zig", 14, "a pipe's child processes and their files: the host's `pipe` entry" },
diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig
index ab33abe9..59e70935 100644
--- a/dev/gui/gui.zig
+++ b/dev/gui/gui.zig
@@ -1356,7 +1356,7 @@ const Client = struct {
defer cl.lock.unlock(cl.io);
for (cl.inbox.items) |msg| switch (msg) {
.unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b),
- .checked => {},
+ .checked, .ended, .left => {},
};
cl.inbox.clearRetainingCapacity();
}
@@ -1444,6 +1444,12 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
.done => {},
.gone => Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{to.session}),
.failed => Said.no(io, "{s}", .{start.said()}),
+ .left => {
+ var said: [600]u8 = undefined;
+ 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),
}
}
diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig
index dce71fd5..bf051e9a 100644
--- a/dev/tui/tui.zig
+++ b/dev/tui/tui.zig
@@ -710,7 +710,7 @@ const Tty = struct {
while (t.loop.tryEvent() catch null) |ev| switch (ev) {
.said => |msg| switch (msg) {
.unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b),
- .checked => {},
+ .checked, .ended, .left => {},
},
.paste => |b| t.sh.gpa.free(@constCast(b)),
else => {},
@@ -797,6 +797,22 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8,
screen.leave();
Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{session});
},
+ .left => {
+ screen.leave();
+ var said: [600]u8 = undefined;
+ std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes: detached from '{s}', which is still running; come back with `pardes attach {s}`\n", .{ session, session }) catch "pardes: detached\n") catch {};
+ std.process.exit(0);
+ },
+ .ended => |code| {
+ screen.leave();
+ // A pair's client is its session's parent: its status once it
+ // is gone, as a terminal's job ends with its program.
+ if (opts.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);
+ },
.failed => {
screen.leave();
Said.no(io, "{s}", .{start.said()});
@@ -1256,10 +1272,10 @@ const Shell = struct {
/// and the shell has its terminal again), the session left running.
fn detach(ctx: ?*anyopaque) void {
const s = of(ctx);
- // A replica client's: its link ends.
+ if (!daemon.kept()) return s.core.reportFailure(s.core.view().active, "Detach: no pardes daemon lists this session (it is its terminal's job)");
+ // A replica client's: its last word, and its link ends.
if (s.peers.detach(s.core.live)) return;
if (s.detached()) return s.core.reportFailure(s.core.view().active, "Detach: detached already (no terminal of its own)");
- if (!daemon.kept()) return s.core.reportFailure(s.core.view().active, "Detach: no pardes daemon lists this session (it is its terminal's job)");
s.leaveTerminal();
}
@@ -1600,10 +1616,10 @@ const Shell = struct {
};
if (echo) s.focused_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
c.take(said);
- if (said == .refused) return true;
+ if (said == .refused or said == .ended or said == .left) return true;
} else switch (said) {
.unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b),
- .checked => {},
+ .checked, .ended, .left => {},
},
.link_gone => if (s.client) |c| {
c.link.quit = true;
diff --git a/docs/next-run.md b/docs/next-run.md
index 74eab197..c2d3488b 100644
--- a/docs/next-run.md
+++ b/docs/next-run.md
@@ -56,11 +56,11 @@ work` (or `pardes-gui attach work`) is a client of the detached session,
its own process in this terminal or window. What differs from having the
session's own frontend back: the client is a second process (a terminal's
10-16 MB, a window's about 110 MB); an addon that is not plain runs in the
-session alone (its panes show a line saying so); its Detach, or its
-terminal closing, ends the client with "'work' let this client go" and exit
-1, where the stub said "detached from 'work'" and exit 0 (the last word a
-session sends its client, and exit codes, are the next steps: "B" in
-`.scratch/sketch/reports/pardes-last-step-design.md`).
+session alone (its panes show a line saying so); its Detach ends the
+client with "detached from 'work', which is still running" and exit 0, as
+the stub's did: the session's last word on a link says which of two things
+happened, `left` (a Detach in that client) or `ended` with the session's
+exit code, which the client exits with.
## What it removed
@@ -212,6 +212,3 @@ session takes back.
own (the daemon's list, and so /sessions, still says `attached`, a wire
word). After the change that frontend can only be the first one: is
"has a frontend" the word, or "with its first frontend"?
-- A client's Detach exits 1 with "let this client go", where the stub's
- said "detached from" and exited 0: the session's last word to a client
- (step B of the last-step design) would let it say which.
diff --git a/docs/typ/command-line.txt b/docs/typ/command-line.txt
index 3c73fed4..0ced145f 100644
--- a/docs/typ/command-line.txt
+++ b/docs/typ/command-line.txt
@@ -95,8 +95,10 @@ See also: ps, attach
Start a session here, even in a pane of another: in this terminal for
pardes, a window for pardes-gui, or with --detach none until one
-attaches. Bare `pardes` takes the same flags, and starts one unless
-it is in a pane (where it hands its FILE to that session).
+attaches, which returns once the session runs and prints its name.
+Bare `pardes` takes the same flags, and starts one unless it is in a
+pane (where it hands its FILE to that session); its --detach is the
+session itself, until it ends (a supervisor's way).
Usage:
pardes new [flags] [FILE]
diff --git a/runtime/client.zig b/runtime/client.zig
index 75518552..1314d3fb 100644
--- a/runtime/client.zig
+++ b/runtime/client.zig
@@ -109,9 +109,10 @@ pub const Start = struct {
}
};
-/// How a client's joins ended: it quit, the session let it go, or it could
-/// not join again (`Start.said`).
-pub const Ended = enum { done, gone, failed };
+/// How a client's joins ended: it quit, the session let it go, it could
+/// not join again (`Start.said`), it left the session running (a Detach in
+/// it), or the session ended, with its code.
+pub const Ended = union(enum) { done, gone, failed, left, ended: u8 };
pub fn Loop(comptime Frontend: type) type {
return struct {
@@ -170,6 +171,8 @@ pub fn Loop(comptime Frontend: type) type {
// What it made since it joined, kept for its next start.
if (s.have) |h| h.keep(s.r.core());
s.r.deinit();
+ if (link.left) return .left;
+ if (link.ended) |code| return .{ .ended = code };
return if (link.gone) .gone else .done;
}
// The session again, the core it leaves held meanwhile: its
diff --git a/runtime/daemon.zig b/runtime/daemon.zig
index 80e1cc09..a2e890f9 100644
--- a/runtime/daemon.zig
+++ b/runtime/daemon.zig
@@ -600,6 +600,12 @@ fn stubWait(session: libc.pid_t, pipe: c_int) noreturn {
const said = buf[0..len];
const out = std.Io.File.stderr();
const io = std.Io.Threaded.global_single_threaded.io();
+ // `new --detach`'s session runs (`launched`): its name, for a script.
+ if (said.len > 0 and said[0] == 'r') {
+ var text: [520]u8 = undefined;
+ std.Io.File.stdout().writeStreamingAll(io, std.fmt.bufPrint(&text, "{s}\n", .{said[1..]}) catch said[1..]) catch {};
+ libc._exit(0);
+ }
if (said.len > 0 and said[0] == 'd') {
var text: [700]u8 = undefined;
const who = said[1..];
@@ -695,6 +701,57 @@ pub fn forkSession(conn: c_int) ?void {
stubWait(pid, pipe[0]);
}
+/// `pardes new --detach`: the session forked off in a session of its own,
+/// its stdin /dev/null, and this process its stub until the session runs
+/// (`launched`): it then prints the name and exits 0, or with the
+/// session's status if it ended first. Returns in the session, called
+/// `named` (else by its pid); when no fork can be made, here, which is
+/// then the session.
+pub fn launch(named: []const u8) void {
+ var pipe: [2]c_int = undefined;
+ if (libc.pipe(&pipe) != 0) return;
+ ninep_io.setCloexec(pipe[0]);
+ ninep_io.setCloexec(pipe[1]);
+ const pid = libc.fork();
+ if (pid < 0) {
+ _ = libc.close(pipe[0]);
+ _ = libc.close(pipe[1]);
+ return;
+ }
+ if (pid == 0) {
+ _ = libc.close(pipe[0]);
+ _ = libc.setsid();
+ const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(libc.mode_t, 0));
+ if (null_fd >= 0) _ = libc.dup2(null_fd, 0);
+ if (null_fd > 0) _ = libc.close(null_fd);
+ stub = pipe[1];
+ launching = true;
+ setName(named);
+ return;
+ }
+ _ = libc.close(pipe[1]);
+ stubWait(pid, pipe[0]);
+}
+
+/// Forked by `launch`, and its stub not told yet.
+var launching = false;
+
+/// The session of a `new --detach` runs: registered (the daemon took its
+/// hello, when there is one) and listening. Its stub told, with its name;
+/// its stdout and stderr, still the launch's until now, let go.
+pub fn launched() void {
+ if (!launching) return;
+ launching = false;
+ _ = kept();
+ tellStub(stub, "r{s}", .{name()});
+ stub = -1;
+ const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(libc.mode_t, 0));
+ if (null_fd < 0) return;
+ _ = libc.dup2(null_fd, 1);
+ _ = libc.dup2(null_fd, 2);
+ if (null_fd > 2) _ = libc.close(null_fd);
+}
+
// ---- the daemon ----
const Conn = struct {
diff --git a/runtime/main.zig b/runtime/main.zig
index 36c25f2b..29c19bc0 100644
--- a/runtime/main.zig
+++ b/runtime/main.zig
@@ -323,8 +323,10 @@ const cmds = std.EnumArray(Cmd, Doc).init(.{
.doc =
\\Start a session here, even in a pane of another: in this terminal for
\\pardes, a window for pardes-gui, or with --detach none until one
- \\attaches. Bare `pardes` takes the same flags, and starts one unless
- \\it is in a pane (where it hands its FILE to that session).
+ \\attaches, which returns once the session runs and prints its name.
+ \\Bare `pardes` takes the same flags, and starts one unless it is in a
+ \\pane (where it hands its FILE to that session); its --detach is the
+ \\session itself, until it ends (a supervisor's way).
,
.examples = &.{
.{ "pardes new", "a session here, its shell pane in tty mode" },
@@ -1157,6 +1159,8 @@ fn nativeMain(std_init: std.process.Init) !void {
const resuming = upgrade.resumed != null;
var session_only = true;
var new_session = false;
+ // `pardes new`: with --detach it returns once the session runs.
+ var new_verb = false;
var explicit_tty = false;
var detach: ?[]const u8 = null;
var attach: ?[]const u8 = null;
@@ -1168,6 +1172,7 @@ fn nativeMain(std_init: std.process.Init) !void {
if (!resuming and args.len > 1) if (std.meta.stringToEnum(Cmd, args[1])) |cmd| switch (cmd) {
.new => {
new_session = true;
+ new_verb = true;
i = 2;
},
.attach => {
@@ -1531,6 +1536,9 @@ fn nativeMain(std_init: std.process.Init) !void {
// socket holds already (a plain session is named by its pid too).
if (name.len != 0 and !resuming and ninep_io.taken(name)) die(init.io, "a session named {s} is already running", .{name});
if (opts.ninep_name.len == 0) opts.ninep_name = name;
+ // `new --detach` forks the session and returns once it runs; the
+ // flag alone is the session itself (a supervisor's, a harness's).
+ if (new_verb and !resuming) daemon.launch(opts.ninep_name);
// Said where it was started (stderr, as the log says it): no pane
// anyone sees would show it. The session runs on, with no 9P.
var pid_buf: [16]u8 = undefined;
@@ -1559,6 +1567,11 @@ 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) {
+ // 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);
+ term = .detached;
} else if (daemon.wanted()) {
if (detach != null or pardes.platform == .gui) {
_ = daemon.register(null, kind, opts.ninep_name, detach != null);
@@ -1695,6 +1708,54 @@ 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;
+ 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", .{});
+ // 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) {
+ opts.cols = ws.col;
+ opts.rows = ws.row;
+ }
+ const pid = std.c.fork();
+ if (pid < 0) die(init.io, "no fork for a session and its terminal", .{});
+ if (pid == 0) {
+ _ = std.c.close(fds[1]);
+ _ = std.c.setsid();
+ const null_fd = std.c.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(std.c.mode_t, 0));
+ if (null_fd >= 0) for (0..3) |i| {
+ _ = std.c.dup2(null_fd, @intCast(i));
+ };
+ if (null_fd > 2) _ = std.c.close(null_fd);
+ opts.pair = fds[0];
+ // The daemon is the client's to start; the hello is this one's.
+ daemon.startPending(false);
+ if (conn) |c| _ = daemon.register(c, .tty, opts.ninep_name, true);
+ return;
+ }
+ _ = std.c.close(fds[0]);
+ if (conn) |c| _ = std.c.close(c);
+ daemon.startPending(true);
+ var name_buf: [16]u8 = undefined;
+ const name = if (opts.ninep_name.len != 0) opts.ninep_name else std.fmt.bufPrint(&name_buf, "{d}", .{pid}) catch unreachable; // a pid fits 16
+ 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});
+ std.process.exit(0);
+}
+
/// The replica client of this build's frontend: a terminal's (tui.zig) or a
/// window's (gui.zig).
fn clientOf(init: std.process.Init, opts: pardes.Options, path: []const u8, name: []const u8, far: bool) !void {
diff --git a/runtime/session.zig b/runtime/session.zig
index fdd72c2b..5d7eff78 100644
--- a/runtime/session.zig
+++ b/runtime/session.zig
@@ -103,6 +103,10 @@ pub fn Loop(comptime Frontend: type) type {
defer l.peers.deinit();
// Before the core goes: each client sees its link end.
defer l.peers.dropAll(l.core);
+ // A first client on the socket it was started with, before its
+ // first effects: it has every terminal from its first byte, and
+ // no reload (Core.openView).
+ if (o.pair) |fd| l.peers.join(l.core, .{ .fd = fd });
l.effects();
// ...and its shells, once a fresh session's own has a directory
// to adopt them in.
@@ -113,12 +117,17 @@ pub fn Loop(comptime Frontend: type) type {
l.ptys.start(l.core);
l.watches.start();
try fe.start(&l);
+ // A `new --detach`'s launch returns now.
+ daemon.launched();
while (!l.core.quit) {
pardes.turn.bump(&pardes.turn.restores);
try l.core.pump(l.host);
// 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;
fe.sent();
upgrade.locate();
// Asked in the step (the word), done between steps: the
@@ -132,6 +141,8 @@ pub fn Loop(comptime Frontend: type) type {
if (l.core.quit) break;
if (l.core.takeRestore()) |rp| l.restore(rp);
}
+ // The clients' last word: the session ended (Exit).
+ l.peers.ended(0);
// Its serve threads read the core: they end first.
if (l.fs) |f| {
f.deinit(l.gpa);
diff --git a/test/daemon.py b/test/daemon.py
index d134732b..7dc1b4bd 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -25,6 +25,10 @@ private HOME and runtime directory:
`ssh -L` forwards, say), timed
python3 -B test/daemon.py --clients <pardes>
the replica clients alone
+ python3 -B test/daemon.py --launch <pardes>
+ `pardes new --detach` returns once its session runs
+ python3 -B test/daemon.py --pair <pardes>
+ PARDES_PAIR: a terminal's session and its first client
python3 -B test/daemon.py --relink <pardes>
the daemon killed: its sessions register again with the next
python3 -B test/daemon.py --far <pardes>
@@ -479,10 +483,10 @@ def clients(binary):
wait_for('client A out of insert mode', lambda: normal_again(ta))
wait_for('client A agrees again', lambda: agreed(root / 'a.check', seen))
assert sess.poll() is None
- # Detach typed in it: it alone goes.
+ # Detach typed in it: it alone goes, and says so (exit 0).
os.write(ta.master, b' sD')
wait_for('client A let go', lambda: a.poll() is not None, timeout=10)
- assert b'let this client go' in ta.text(), ta.text()[-300:]
+ assert a.returncode == 0 and b"detached from 'files', which is still running" in ta.text(), ta.text()[-300:]
# A third client, a shell: its keys wait for the session (a pty
# write), its output comes back in units, the same on both sides.
nine.write(f'/pane/{pane}/exec', b'Term\n')
@@ -526,6 +530,234 @@ def clients(binary):
shutil.rmtree(root, ignore_errors=True)
+def launch(binary):
+ """`pardes new --detach=NAME` returns once its session is registered
+ and listening: exit 0, the name on stdout, the session a process of its
+ own in a session of its own, listed by `ps` and answering 9P at once;
+ bare `--detach`, its pid is its name; a name taken is refused in words,
+ exit 1; `pardes --detach=NAME` (no `new`) is still the session itself;
+ nothing left behind."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rl-', 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 / 'notes.txt').write_text('notes\n')
+
+ def cli(*args, timeout=30):
+ return subprocess.run([binary, *args], env=env, cwd=root, capture_output=True, timeout=timeout,
+ stdin=subprocess.DEVNULL)
+
+ def status_pid(name):
+ with Client(root / f'pardes-9p-{name}.sock') as c:
+ return int(dict(line.split(maxsplit=1) for line in c.read('/status').decode().splitlines())['pid'])
+
+ try:
+ t0 = time.monotonic()
+ try:
+ out = cli('new', '--detach=work', 'notes.txt', timeout=15)
+ except subprocess.TimeoutExpired:
+ raise AssertionError(f'launch: `new --detach=work` had not returned after {time.monotonic() - t0:.1f} s')
+ took = time.monotonic() - t0
+ assert out.returncode == 0 and out.stdout == b'work\n', out
+ # Registered and listening when it returned: no wait here.
+ assert (root / 'pardes-9p-work.sock').exists(), list(root.iterdir())
+ pid = status_pid('work')
+ listed = cli('ps').stdout.decode()
+ assert f'session work {pid} (tty, detached)' in listed, listed
+ assert alive(pid) and os.getsid(pid) == pid, (pid, os.getsid(pid))
+ out = cli('new', '--detach')
+ assert out.returncode == 0 and out.stdout.strip().isdigit(), out
+ unnamed = int(out.stdout)
+ assert status_pid(str(unnamed)) == unnamed and f'session {unnamed} {unnamed} (tty, detached)' in cli('ps').stdout.decode()
+ taken = cli('new', '--detach=work')
+ assert taken.returncode == 1 and taken.stderr == b'pardes: a session named work is already running\n', taken
+ # The flag alone runs the session in this process, as a supervisor
+ # or a harness wants it.
+ fg = subprocess.Popen([binary, '--detach=fg'], env=env, cwd=root, stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
+ wait_for('the foreground session\'s socket', (root / 'pardes-9p-fg.sock').exists)
+ assert status_pid('fg') == fg.pid and fg.poll() is None
+ print(f'launch: `new --detach=work` returned 0 in {took:.2f} s with its name, session {pid} listed and listening '
+ f'in a session of its own; unnamed it said {unnamed}; a taken name refused; `--detach=fg` is its own session')
+ for name in ('work', str(unnamed), 'fg'):
+ assert cli('kill', name).returncode == 0
+ fg.wait(timeout=10)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10)
+ print('launch: nothing left behind')
+ finally:
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
+def pair(binary):
+ """PARDES_PAIR: `pardes FILE` in a terminal is a session forked off for
+ it with this terminal its first client (the last step's design, 1.1):
+ the job the client, the terminal its own; the session its child, in a
+ session of its own, registered (`ps`: detached, the client listed),
+ the file drawn, keys in, the digests agreed once quiet; the session's
+ Exit ends both. With no daemon the client killed outright ends the
+ session (its last link). Nothing left behind."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rp-', 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', 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)))
+ terms = []
+
+ def session_of(name):
+ sock = root / f'pardes-9p-{name}.sock'
+ wait_for(f'session {name}\'s 9P socket', sock.exists)
+ nine = Client(sock)
+ return nine, int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+
+ try:
+ t = Term(30, 100)
+ terms.append(t)
+ c = t.spawn([binary, '--9p=pair', str(notes)], dict(env, PARDES_REPLICA_CHECK=str(root / 'pair.check')))
+ nine, session = session_of('pair')
+ assert session != c.pid and ppid(session) == c.pid and os.getsid(session) == session, (session, c.pid)
+ wait_for('the file drawn on the terminal', lambda: b'line 3 of the notes' in t.text(), timeout=30)
+ listed = lambda: subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode()
+ wait_for('the client listed', lambda: f'session pair {session} (tty, detached)' in listed()
+ and f'client {c.pid} ' in listed())
+ pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ os.write(t.master, b'Ofrom-the-pair\x1b')
+ wait_for('its keys in the session\'s text', lambda: b'from-the-pair' in nine.read(f'/pane/{pane}/body'))
+ wait_for('out of insert mode', lambda: normal_again(t))
+ wait_for('the client agrees once quiet', lambda: agreed(root / 'pair.check', 0))
+ exit_session(nine, pane)
+ code = c.wait(timeout=60)
+ assert code == 0 and not alive(session), (code, alive(session))
+ print(f'pair: client {c.pid} (the job) and session {session} (its child, setsid, listed detached with the client); '
+ f'drawn, typed, agreed; Exit ended both (the client exit {code})')
+ nine.socket.close()
+ lone = Term(24, 80)
+ terms.append(lone)
+ c2 = lone.spawn([binary, '--9p=lone', str(notes)], dict(env, PARDES_DAEMON='off'))
+ nine2, session2 = session_of('lone')
+ wait_for('the lone pair drawn', lambda: b'line 3 of the notes' in lone.text(), timeout=30)
+ nine2.socket.close()
+ os.kill(c2.pid, signal.SIGKILL)
+ c2.wait(timeout=10)
+ wait_for('the lone session ended with its last link', lambda: not alive(session2), timeout=20)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
+ print(f'pair: with no daemon, client {c2.pid} killed outright, its session {session2} ended; nothing left behind')
+ finally:
+ 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 pair_rows(binary):
+ """PARDES_PAIR, the shell's view (the last step's design, 1.1) and a
+ session's lifetime (2.2 B), one row a step. With a daemon: a Detach in
+ the pair's client says so and exits 0, the session runs on (listed); an
+ attach is a client again; TERM to the client puts its terminal back and
+ the session runs on; so does a KILL, and a closed terminal (HUP): each a
+ loss, not a close. With none: a Detach refused (nothing could attach),
+ the client on; its terminal closed, the session ends with its last link."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rq-', 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', 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)))
+ terms = []
+
+ def listed():
+ return subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode()
+
+ def drawn(t):
+ wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
+
+ def typed_detach(t, nine, pane):
+ # Its view the live one (it typed last), then the word.
+ os.write(t.master, b'j')
+ time.sleep(.3)
+ nine.write(f'/pane/{pane}/exec', b'Detach\n')
+
+ def started(name, e):
+ t = Term(30, 100)
+ terms.append(t)
+ c = t.spawn([binary, f'--9p={name}', str(notes)], e)
+ wait_for('the socket', (root / f'pardes-9p-{name}.sock').exists)
+ nine = Client(root / f'pardes-9p-{name}.sock')
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ drawn(t)
+ return t, c, nine, session, pane
+
+ try:
+ t, c, nine, session, pane = started('rows', env)
+ typed_detach(t, nine, pane)
+ assert c.wait(timeout=20) == 0, c.returncode
+ wait_for('the detach said', lambda: b"pardes: detached from 'rows', which is still running; come back with `pardes attach rows`" in t.text())
+ assert alive(session) and f'session rows {session} (tty, detached)' in listed()
+ print('pair rows: Detach in the client: said, exit 0; the session runs on, listed')
+ for how in ('TERM', 'KILL', 'HUP'):
+ tt = Term(30, 100)
+ terms.append(tt)
+ a = tt.spawn([binary, 'attach', 'rows'], env)
+ drawn(tt)
+ wait_for('the client listed', lambda: f'client {a.pid} ' in listed())
+ if how == 'HUP':
+ tt.close()
+ terms.remove(tt)
+ else:
+ os.kill(a.pid, getattr(signal, 'SIG' + how))
+ a.wait(timeout=20)
+ if how == 'TERM':
+ wait_for('its terminal put back', lambda: tt.text().rfind(b'\x1b[?1049l') > tt.text().rfind(b'\x1b[?1049h'))
+ wait_for('the client unlisted', lambda: f'client {a.pid} ' not in listed())
+ assert alive(session), how
+ print(f'pair rows: a client ended by {how}: the session runs on')
+ nine.socket.close()
+ assert subprocess.run([binary, 'kill', 'rows'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('the session ended', lambda: not alive(session), timeout=30)
+ t, c, nine, session, pane = started('lone', dict(env, PARDES_DAEMON='off'))
+ typed_detach(t, nine, pane)
+ time.sleep(1)
+ assert c.poll() is None and alive(session), 'a Detach with no daemon is refused'
+ nine.socket.close()
+ t.close()
+ terms.remove(t)
+ c.wait(timeout=20)
+ 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 rows: no daemon: a Detach refused, the client on; its terminal closed, the session ended; nothing left')
+ finally:
+ 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 manage(binary):
"""`pardes --ps`, `--kill=NAME` and `--kill-all`: two detached sessions
and their shells listed, one session killed outright and its shell
@@ -966,10 +1198,10 @@ def window_clients(binary, gui_binary):
wait_for('the window\'s keys after the upgrade', lambda: b'after-upgrade-W' in body(), timeout=30)
wait_for('the window client agrees after the upgrade', lambda: agreed(dcheck, seen), timeout=30)
assert wd.p.poll() is None
- # Detach typed in it: it alone goes, and says why.
+ # Detach typed in it: it alone goes, and says so (exit 0).
wd.keys(b' sD')
wait_for('the window client let go', lambda: wd.p.poll() is not None, timeout=15)
- assert 'let this client go' in wd.said(), wd.said()[-500:]
+ assert wd.p.returncode == 0 and "detached from 'files', which is still running" in wd.said(), wd.said()[-500:]
# A link a line: the first join sent every blob, its rejoins held them.
links = joins(root / 'wd.stats')
assert len(links) == 3 and links[0]['blobs'] > 0 and links[0]['from_memory'] + links[0]['from_disk'] == 0, links
@@ -1521,6 +1753,9 @@ def main(binary, cycles):
clients(binary)
far(binary)
by_hash(binary)
+ launch(binary)
+ pair(binary)
+ pair_rows(binary)
manage(binary)
relink(binary)
shell = terminals(client)[0]
@@ -1557,8 +1792,8 @@ def main(binary, cycles):
terminal closed: it ends; the session and its shell run on."""
if how == 'detach':
client.write(f'/pane/{shell}/exec', b'Detach\n')
- assert c.wait(timeout=10) == 1, c.returncode
- wait_for('the client says it was let go', lambda: b'let this client go' in term.text())
+ assert c.wait(timeout=10) == 0, c.returncode
+ wait_for('the client says it detached', lambda: b"detached from 'work', which is still running" in term.text())
else:
term.close()
c.wait(timeout=10)
@@ -1686,8 +1921,8 @@ def main(binary, cycles):
# The end: the session quits, its shells hang up, its client and
# the daemon go.
exit_session(client, pane)
- assert stub.wait(timeout=10) == 1, stub.returncode
- wait_for('the client says it was let go', lambda: b'let this client go' in term.text())
+ assert stub.wait(timeout=10) == 0, stub.returncode
+ assert b'let this client go' not in term.text(), term.text()[-300:]
client.socket.close()
term.close()
wait_for('the adopted shell hung up', lambda: not alive(shell_pid))
@@ -2231,6 +2466,11 @@ if __name__ == '__main__':
clients(sys.argv[2])
elif sys.argv[1:2] == ['--manage']:
manage(sys.argv[2])
+ elif sys.argv[1:2] == ['--launch']:
+ launch(sys.argv[2])
+ elif sys.argv[1:2] == ['--pair']:
+ pair(sys.argv[2])
+ pair_rows(sys.argv[2])
elif sys.argv[1:2] == ['--relink']:
relink(sys.argv[2])
elif sys.argv[1:2] == ['--games']:
diff --git a/test/process.zig b/test/process.zig
index 8bcbddeb..e2a4f592 100644
--- a/test/process.zig
+++ b/test/process.zig
@@ -916,7 +916,8 @@ pub const Child = struct {
while (environ[i]) |kv| {
const entry = std.mem.span(kv);
const eq = std.mem.indexOfScalar(u8, entry, '=') orelse entry.len;
- if (std.mem.startsWith(u8, entry, "PARDES_") or std.mem.indexOf(u8, entry[0..eq], "PAGER") != null) {
+ // PARDES_PAIR kept: the suite run as pairs (main.zig `pair`).
+ if ((std.mem.startsWith(u8, entry, "PARDES_") and !std.mem.startsWith(u8, entry, "PARDES_PAIR=")) or std.mem.indexOf(u8, entry[0..eq], "PAGER") != null) {
var name: [256]u8 = undefined;
const n = std.fmt.bufPrintSentinel(&name, "{s}", .{entry[0..@min(eq, 255)]}, 0) catch _exit(126);
_ = unsetenv(n);