From 2fadb864051f5afc062606a898d821b702a1692c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 04:16:02 -0300 Subject: launch: `pardes new --detach[=NAME]` forks the session off and returns once it is registered and listening (the last-step design's Z1, 2.2 F's second half): exit 0 and the name on stdout, the session in a session of its own (setsid, stdin /dev/null, its stdout and stderr the launch's until it runs, so a failed start still says why there and its status is the launch's), by the stub's own wait with one word more (`r`, daemon.zig `launch`/`launched`, told from the session loop after its frontend's start); the flag alone (`pardes --detach=NAME`, what every harness and a supervisor runs) is still the session itself; test/daemon.py `launch` (plain and `--launch`) failing first on the base (not returned after 15 s: the launch was the session), then 0.12-0.22 s; help new and docs/typ/command-line.txt say so Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- runtime/session.zig | 2 ++ 1 file changed, 2 insertions(+) (limited to 'runtime/session.zig') diff --git a/runtime/session.zig b/runtime/session.zig index fdd72c2b..6b359eef 100644 --- a/runtime/session.zig +++ b/runtime/session.zig @@ -113,6 +113,8 @@ 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); -- cgit v1.3 From 821509e5cbe47e73ce4f4fcdc5d092f3c5e1c986 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 04:25:37 -0300 Subject: first client: a session takes a client on a socket it was started with BEFORE its first effects, by the join a later client gets (Peers.join, now pub, called from runtime/session.zig between the frontend's open and the first effects when Options.pair is set), and a client's first join is made on its end of the pair with no hello (replica.join reads Options.pair; joinOn's session name optional), so a first client has every terminal from its first byte (P32); two tests through the replica's surface, a session core with a boot shell and real Peers threads over a socket pair, the first effects after the join: screen state (replica.join end to end) and bytes (loaded as the soak's bytes clients): the spawn taped, the shell's first bytes in the client's terminal, the digests equal at the client's check, and under bytes no reload of any byte (the session's one reload at the join is of the boot shell's emulator before anything was written, the client's none; a client after the bytes: every side reloads); core/root.zig's machine-lines count for replica.zig 70 -> 74 (the tests' sockets) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Core.zig | 5 ++ core/replica.zig | 132 +++++++++++++++++++++++++++++++++++++++++++++++++--- core/root.zig | 2 +- runtime/session.zig | 4 ++ 4 files changed, 135 insertions(+), 8 deletions(-) (limited to 'runtime/session.zig') diff --git a/core/Core.zig b/core/Core.zig index 9a542940..c3fa6953 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -2273,6 +2273,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 14757d9a..bf665a50 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -2230,7 +2230,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 { @@ -2576,13 +2579,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 = &.{} }; @@ -2950,7 +2954,8 @@ pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime 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 @@ -2971,7 +2976,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 = &.{}; @@ -4389,6 +4394,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 a57934a6..a58a25b5 100644 --- a/core/root.zig +++ b/core/root.zig @@ -629,7 +629,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", 74, "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/runtime/session.zig b/runtime/session.zig index 6b359eef..d34a8ea9 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. -- cgit v1.3 From 32ac0d9d5f7de60f2045edbd1c15631306bd25d4 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 04:50:25 -0300 Subject: pair: PARDES_PAIR (a working name, one variable) makes `pardes FILE` in a terminal a session and its first client over a socket pair (the last step's design 1.1, Z1): the daemon dialled first as for a stub, the terminal's size read, a fork; the parent is the client (the shell's job, the terminal its own, so WINCH/HUP/TERM reach what draws), its first join on its end of the pair (runtime/main.zig `pair`, tui.runClient unchanged); the child is the session (setsid, 0/1/2 on /dev/null, detached, registered on the dialled connection), its end taken as its first client before its first effects (the previous change); with no daemon too, where a pair's session ends with its last link (runtime/session.zig); without the variable nothing changes (tui core-test 856/1009, shell-test 1049/1052, term 17/17, pane 183/184, kitty 45/45, behaviour 275/275 and --replay, process-test 0 of 144 but pagercolor, which passed alone, both soaks diverged 0 unequal 0 corpus 22 of 22, the bytes soak's one unlisted stop now:1 the base's; daemon.py plain, far, games, upgrade both ways pass); test/daemon.py `pair` (and --pair): the job, the session its child in a session of its own, listed with its client, drawn, typed, digests agreed, Exit ends both, with no daemon a client killed outright ends its session, nothing left; process-test with the variable: 17 of 144 fail as pairs (the harness dials the launched pid's socket, its goldens are an own frontend's frames, a Restore lets the client go with no daemon to rejoin through, its signal and no-terminal cases are the own path's), and one daemon-on case leaves its pair session running (a killed client is a loss: Z4's harness), test/process.zig passes PARDES_PAIR through for that run Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- runtime/main.zig | 53 ++++++++++++++++++++++++++++++++++++++ runtime/session.zig | 3 +++ test/daemon.py | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++++ test/process.zig | 3 ++- 4 files changed, 132 insertions(+), 1 deletion(-) (limited to 'runtime/session.zig') diff --git a/runtime/main.zig b/runtime/main.zig index 24ed1456..0feb0d53 100644 --- a/runtime/main.zig +++ b/runtime/main.zig @@ -1573,6 +1573,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); @@ -1709,6 +1714,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 d34a8ea9..0ef0a8ab 100644 --- a/runtime/session.zig +++ b/runtime/session.zig @@ -125,6 +125,9 @@ pub fn Loop(comptime Frontend: type) type { 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 diff --git a/test/daemon.py b/test/daemon.py index 5214bb00..5a53f149 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -27,6 +27,8 @@ private HOME and runtime directory: the replica clients alone python3 -B test/daemon.py --launch `pardes new --detach` returns once its session runs + python3 -B test/daemon.py --pair + PARDES_PAIR: a terminal's session and its first client python3 -B test/daemon.py --relink the daemon killed: its sessions register again with the next python3 -B test/daemon.py --far @@ -595,6 +597,75 @@ def launch(binary): 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=20) + wait_for('the session gone', lambda: not alive(session), timeout=20) + 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 manage(binary): """`pardes --ps`, `--kill=NAME` and `--kill-all`: two detached sessions and their shells listed, one session killed outright and its shell @@ -1591,6 +1662,7 @@ def main(binary, cycles): far(binary) by_hash(binary) launch(binary) + pair(binary) manage(binary) relink(binary) shell = terminals(client)[0] @@ -2303,6 +2375,8 @@ if __name__ == '__main__': manage(sys.argv[2]) elif sys.argv[1:2] == ['--launch']: launch(sys.argv[2]) + elif sys.argv[1:2] == ['--pair']: + pair(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); -- cgit v1.3 From ae3b9e9d19492c827f257da8a224a19d77de51c1 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 05:58:08 -0300 Subject: last word: a session's last frame on a link says which of two things happened (wire `ended CODE` 0x0b and `left NAME` 0x0c, working names): a Detach typed in a client queues `left` and lets its writer end after it (Peers.detach, Peer.last), a session's end tells every client `ended` with its code before the links are let go (Peers.ended, from runtime/session.zig after the loop; refuseAll and it share the 200 ms flush); a client that typed Detach prints "pardes: detached from 'NAME', which is still running; come back with `pardes attach NAME`" and exits 0 again (the attach's regression to exit 1 and "let this client go" undone, for every client, no variable), a client whose session ended exits with the session's code quietly, a pair's client after reaping its session (EDITOR=pardes waits for the session's end); client.Ended a union (left, ended CODE); a Detach with no daemon is refused in a client too (tui.zig `detach`: the daemon checked first), since a pair with none ends with its last link; test/daemon.py: the client Detach expectations (0 and the line), a session's Exit (0, no let-go line), `pair` Exit 0 and the session reaped, `pair_rows` the rows of the design's tables 1.1 and 2.2 B (Detach said, exit 0, the session listed; a client ended by TERM with its terminal put back, by KILL and by its terminal's HUP: the session runs on; no daemon: Detach refused, the terminal closed ends the session; nothing left); docs/next-run.md and core/CHANGELOG.md say so (the CHANGELOG's `new --detach` line is the first change's); `kept` NOT built: no terminal behaviour turns on it while a hangup and a killed client are losses and Exit ends the session (see the report) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- abi/wire.zig | 10 +++++ core/CHANGELOG.md | 9 ++++- core/replica.zig | 64 +++++++++++++++++++++-------- core/root.zig | 2 +- dev/gui/gui.zig | 8 +++- dev/tui/tui.zig | 26 +++++++++--- docs/next-run.md | 13 +++--- runtime/client.zig | 9 +++-- runtime/session.zig | 2 + test/daemon.py | 114 +++++++++++++++++++++++++++++++++++++++++++++++----- 10 files changed, 211 insertions(+), 46 deletions(-) (limited to 'runtime/session.zig') diff --git a/abi/wire.zig b/abi/wire.zig index 1f7d02d2..7ef5da90 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -191,6 +191,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) { @@ -208,6 +212,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 @@ -243,6 +249,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; @@ -267,6 +275,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 fe9adec8..1d4541c9 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/replica.zig b/core/replica.zig index bf665a50..e1eacf6c 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); @@ -2404,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| { @@ -2421,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. @@ -2445,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); @@ -2919,7 +2937,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 @@ -2934,13 +2952,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); @@ -3078,6 +3099,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, @@ -3196,6 +3220,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; } diff --git a/core/root.zig b/core/root.zig index a58a25b5..3e804bb4 100644 --- a/core/root.zig +++ b/core/root.zig @@ -629,7 +629,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", 74, "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 543be3aa..d752c627 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()}); @@ -1264,10 +1280,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(); } @@ -1608,10 +1624,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/runtime/client.zig b/runtime/client.zig index 544be588..8eb01241 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/session.zig b/runtime/session.zig index 0ef0a8ab..5d7eff78 100644 --- a/runtime/session.zig +++ b/runtime/session.zig @@ -141,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 5a53f149..7dc1b4bd 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -483,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') @@ -639,8 +639,8 @@ def pair(binary): 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=20) - wait_for('the session gone', lambda: not alive(session), timeout=20) + 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() @@ -666,6 +666,98 @@ def pair(binary): 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 @@ -1106,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 @@ -1663,6 +1755,7 @@ def main(binary, cycles): by_hash(binary) launch(binary) pair(binary) + pair_rows(binary) manage(binary) relink(binary) shell = terminals(client)[0] @@ -1699,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) @@ -1828,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)) @@ -2377,6 +2470,7 @@ if __name__ == '__main__': 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']: -- cgit v1.3