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/main.zig | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) (limited to 'runtime/main.zig') diff --git a/runtime/main.zig b/runtime/main.zig index a791ffec..24ed1456 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 => { @@ -1537,6 +1542,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; -- 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/main.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