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/root.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'core/root.zig') 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" }, -- 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 'core/root.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