diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-20 01:46:17 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-20 04:00:32 -0300 |
| commit | 969369d4b84fa1847dc3dee0e737dcd58e56c5e7 (patch) | |
| tree | e866b74b33701005eb2009ce573aef8dd4ab420f | |
| parent | 11f55f018a5eb0699d58627a4f2ea39c2b7f5e89 (diff) | |
| download | pardes-969369d4b84fa1847dc3dee0e737dcd58e56c5e7.tar.gz pardes-969369d4b84fa1847dc3dee0e737dcd58e56c5e7.zip | |
attach: `pardes attach [NAME]` is a client always, from a terminal a terminal's and from `pardes-gui` a window's, whatever the session was born with (the ruling of 2026-11-17: a session's own frontend is only the one it was born with), and the in-place attach deleted with what only it used (305 lines deleted, 94 added): the daemon's `attach` request and its `find` that chose (runtime/daemon.zig), `daemon.attach` and its `Answer`, `Note.attach`, the stub's second use (`stubWait`'s `child` and its `r`/`x` words, `tellStubExit`), `attachTo`'s two hand-offs and `crossAttach` (runtime/main.zig: a named attach goes straight to the replica socket, where the daemon refuses a name nobody has; a bare one takes the one detached session, else the one session, from the daemon's `list`, else names them: `bareAttach`, with a test), the terminal handed to a session (`attachTerminal`, `refuse`, the `.attach` message and its three arms: dev/tui/tui.zig), the window opened again in place (`openTheWindow`, `Shell.detached`, the queue's `.window` and its arms: dev/gui/gui.zig, dev/Inbox.zig, runtime/macos.zig), and `setState(false)`, which nothing says now (`setDetached`); test/daemon.py's attach cases expect a client (a Detach in its own terminal once, then each attach a client in `--ps`, the session detached still, its Detach exit 1 "let this client go"; the window cycles as window clients, offscreen); tui shell-test 1046/1049 (3 skipped, as the base), core-test 855/1005 (the base's less the deleted `find` test), daemon.py plain passing (gated with the next change)
Co-Authored-By: Claude Opus <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
| -rw-r--r-- | dev/Inbox.zig | 4 | ||||
| -rw-r--r-- | dev/gui/gui.zig | 37 | ||||
| -rw-r--r-- | dev/tui/tui.zig | 59 | ||||
| -rw-r--r-- | runtime/daemon.zig | 206 | ||||
| -rw-r--r-- | runtime/macos.zig | 2 | ||||
| -rw-r--r-- | runtime/main.zig | 89 | ||||
| -rw-r--r-- | runtime/session.zig | 7 | ||||
| -rw-r--r-- | test/daemon.py | 220 |
8 files changed, 221 insertions, 403 deletions
diff --git a/dev/Inbox.zig b/dev/Inbox.zig index ed3a9835..4df02013 100644 --- a/dev/Inbox.zig +++ b/dev/Inbox.zig @@ -23,8 +23,6 @@ pub const Msg = union(enum) { kind_job: *KindJob, files_changed, fs_ready, - /// The daemon asks for the window again (`pardes-gui --attach`). - window, /// A shell a dead session left, its pty's master (Adopt); pid 0 is /// the last of them told. adopted: struct { pid: libc.pid_t, fd: c_int }, @@ -44,7 +42,7 @@ pub const Msg = union(enum) { .adopted => |a| if (a.fd >= 0) { _ = libc.close(a.fd); }, - .eof, .files_changed, .fs_ready, .window => {}, + .eof, .files_changed, .fs_ready => {}, } } }; diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index c3272957..81d58137 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -990,8 +990,9 @@ fn closeWindow(g: *Gui) void { }; } -/// `pardes-gui --attach`: a window again, as the first was made, at the -/// size the last one had. False when the display will not give one. +/// A window again, as the first was made, at the size the last one had +/// (a transparent one: syncWindowOpacity). False when the display will not +/// give one. fn reopenWindow(g: *Gui) bool { const window = c.SDL_CreateWindow("pardes", g.window_w, g.window_h, g.win_flags) orelse return false; if (comptime builtin.os.tag == .macos) c.ui_macos_trackpad_attach(window); @@ -2395,10 +2396,8 @@ fn pollGamepad(g: *Gui, in: *Input) void { const Shell = struct { core: *pardes.Pardes, - /// The window's, while one is open; null while detached (`detached` has - /// it). + /// The window's, while one is open; null once detached. gui: ?*Gui = null, - detached: ?*Gui = null, io: std.Io, gpa: std.mem.Allocator, fs: ?*ninep_io.Listener = null, @@ -2452,7 +2451,7 @@ const Shell = struct { } /// Detach: the window closed, the session left running with no - /// window, for `pardes-gui --attach` to open one again. + /// window, detached for good: an attach shows it as a client. fn detachWindow(ctx: ?*anyopaque) void { const s = shellOf(ctx); // A replica client's: its link ends. @@ -2499,29 +2498,13 @@ const Shell = struct { fn closeTheWindow(s: *Shell) void { const g = s.gui orelse return; closeWindow(g); - s.detached = g; s.gui = null; s.presented = false; s.surface = null; // Its clients look at it still (Peers keeps it attended). s.peers.detached = true; s.core.unattended = s.peers.count() == 0; - daemon.setState(true); - } - - fn openTheWindow(s: *Shell) void { - const g = s.detached orelse return; - if (!reopenWindow(g)) { - log.err("--attach: no window: {s}", .{c.SDL_GetError()}); - return daemon.setState(true); - } - s.gui = g; - s.detached = null; - s.peers.detached = false; - s.core.unattended = false; - s.core.needs_frame = true; - resetScroll(g); - daemon.setState(false); + daemon.setDetached(); } fn watched(ctx: ?*anyopaque) bool { @@ -2686,7 +2669,6 @@ const Shell = struct { }, .files_changed => check_files = true, .fs_ready => {}, - .window => if (s.gui == null) s.openTheWindow(), .adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd), }; if (check_files and file_watch.reloadChanged(s.core, s.io, s.gpa, s.watches)) @@ -3200,13 +3182,6 @@ fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { const s: *Shell = @ptrCast(@alignCast(ctx)); const q = s.queue; switch (note) { - .attach => |a| { - // A terminal for a window session: the daemon refuses that kind - // before it is sent, so only an old one's would be here. - if (a.tty >= 0) _ = libc.close(a.tty); - if (a.stub >= 0) daemon.tellStub(a.stub, "r{s}", .{"a window session takes no terminal"}); - if (a.tty < 0) q.push(.window); - }, .adopted => |a| { for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| q.push(.{ .adopted = .{ .pid = pid, .fd = fd } }); q.push(.{ .adopted = .{ .pid = 0, .fd = -1 } }); diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index 5c1945e6..42f73559 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -104,9 +104,6 @@ const Msg = union(enum) { /// The terminal's input ended: its end of file, a hangup. A session /// a daemon keeps carries on detached; any other ends. quit, - /// A terminal for this detached session, and its stub's pipe - /// (daemon.Note.attach). - attach: struct { tty: posix.fd_t, stub: posix.fd_t }, /// A shell a dead session left, its pty's master (daemon.Note.adopted). adopted: struct { pid: posix.pid_t, fd: posix.fd_t }, /// A timed wait ran out: the core's next wake has come. @@ -573,7 +570,7 @@ fn surfaceHasKittyKey(surface: *const pardes.Surface, key: u64) bool { /// Where a session's terminal comes from: /dev/tty, as a plain `pardes` /// opens it; one open already (a session forked off its stub, -/// daemon.forkSession); or none, detached until one is attached (`--detach`). +/// daemon.forkSession); or none, detached from the start (`--detach`). /// The terminal a session starts on: /dev/tty, one its stub opened (an /// upgraded session's is raw already, `termios` the cooked one), or none. pub const Term = union(enum) { open, fd: struct { fd: posix.fd_t, termios: ?posix.termios = null }, detached }; @@ -811,9 +808,9 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, /// A terminal a session draws on, while it has one: entered (raw, the /// alternate screen, mouse and paste reports) and left (all of it put back, -/// the terminal closed) at the session's start and end, and at a detach and -/// a reattach in between (daemon.zig), its stub `daemon.stub`. One a -/// process: a second terminal on a session is a replica client of it. +/// the terminal closed) at the session's start and end, or at a detach +/// (daemon.zig), its stub `daemon.stub`. One a process, the one the session +/// was born with: an attach is a replica client of it. const Screen = struct { io: std.Io, gpa: std.mem.Allocator, @@ -1019,10 +1016,6 @@ const Own = struct { }, .search_rows => |b| b.deinit(gpa), .kind_job => |j| j.drop(), - .attach => |a| { - _ = libc.close(a.tty); - if (a.stub >= 0) _ = libc.close(a.stub); - }, .adopted => |a| _ = libc.close(a.fd), else => {}, }; @@ -1108,12 +1101,6 @@ fn clearNativeImages( fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { const loop: *Loop = @ptrCast(@alignCast(ctx)); switch (note) { - .attach => |a| if (a.tty < 0) { - if (a.stub >= 0) daemon.tellStub(a.stub, "r{s}", .{"a terminal session takes a terminal"}); - } else loop.postEvent(.{ .attach = .{ .tty = a.tty, .stub = a.stub } }) catch { - _ = libc.close(a.tty); - _ = libc.close(a.stub); - }, .adopted => |a| { for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| loop.postEvent(.{ .adopted = .{ .pid = pid, .fd = fd } }) catch { _ = libc.close(fd); @@ -1324,42 +1311,7 @@ const Shell = struct { if (null_fd > 2) _ = libc.close(null_fd); } daemon.tellStubDetached(); - daemon.setState(true); - } - - /// `pardes --attach`'s terminal, for a detached session: its own again, - /// entered as the first one was, sized, asked what it can do, and drawn - /// whole. One attached already takes no other (the daemon makes a second - /// a replica client). - fn attachTerminal(s: *Shell, fd: posix.fd_t, stub: posix.fd_t, cooked: ?posix.termios) void { - const screen = s.screen orelse { - _ = libc.close(fd); - return refuse(stub, "that session has no terminal of its own to attach to"); - }; - if (screen.on) { - _ = libc.close(fd); - return refuse(stub, "that session has a terminal: join it as a client, `pardes --attach=<socket>:<name>`"); - } - const tty = Screen.ttyOn(s.io, screen.buf, fd, cooked) catch { - _ = libc.close(fd); - daemon.setState(true); - return refuse(stub, "that terminal would not go raw"); - }; - screen.enter(tty) catch { - daemon.setState(true); - return refuse(stub, "that terminal would not take the screen"); - }; - daemon.stub = stub; - s.setAttended(true); - startInput(s.loop, screen) catch {}; - screen.vx.queryTerminalSend(screen.tty.writer()) catch {}; - s.core.needs_frame = true; - daemon.setState(false); - } - - /// A terminal refused: its stub told why (a test's has none). - fn refuse(stub: posix.fd_t, why: []const u8) void { - if (stub >= 0) daemon.tellStub(stub, "r{s}", .{why}); + daemon.setDetached(); } const PtyCalls = host_io.Ptys.Calls(Shell); @@ -1662,7 +1614,6 @@ const Shell = struct { core.quit = true; return true; }, - .attach => |a| s.attachTerminal(a.tty, a.stub, null), .adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd), .replica => |j| { s.peers.handed(j.fd, j.view); diff --git a/runtime/daemon.zig b/runtime/daemon.zig index 0d860918..1b9149b6 100644 --- a/runtime/daemon.zig +++ b/runtime/daemon.zig @@ -10,9 +10,9 @@ //! - a dup of every pty master it forks (`pty`), so a session killed //! outright never hangs its shells up, and which ones it closed; //! - whether a terminal or a window shows it (`state`). -//! It hands a terminal (`pardes --attach`) or a window request -//! (`pardes-gui --attach`) to a detached session, and a crashed session's -//! masters to the one that asks for them (Adopt). +//! It lists the sessions (`pardes ps`), hands a crashed session's masters +//! to the one that asks for them (Adopt), and a client's connection to the +//! session it names (below). //! //! Messages are SOCK_SEQPACKET datagrams: a line of words, and the fds it //! carries (SCM_RIGHTS). @@ -359,8 +359,10 @@ pub fn closed(pid: libc.pid_t) void { tell(std.fmt.bufPrint(&buf, "close {d}", .{pid}) catch unreachable, &.{}); // a pid fits 32 } -pub fn setState(detached: bool) void { - tell(if (detached) "state detached" else "state attached", &.{}); +/// Its own frontend let go (Detach, its terminal's end): detached for +/// good, an attach after it a client. +pub fn setDetached() void { + tell("state detached", &.{}); } /// This session's replica clients now, each its process's pid (0 when its @@ -398,9 +400,6 @@ pub fn resumeLink(fd: c_int, stub_fd: c_int, k: Kind, named: []const u8, detache } pub const Note = union(enum) { - /// A terminal for a detached tui session (`pardes --attach`), and the - /// stub's pipe; for a window session, both -1: open a window. - attach: struct { tty: c_int, stub: c_int }, adopted: struct { pids: [max_fds]libc.pid_t, fds: [max_fds]c_int, n: usize }, /// A replica's connection, its hello taken (core/replica.zig `Peers`), /// and the view it joins again for, if it does. @@ -426,15 +425,8 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no while (recv(fd, &buf)) |got| { var words = std.mem.tokenizeScalar(u8, got.words, ' '); const verb = words.next() orelse ""; - if (std.meta.stringToEnum(enum { ok, attach, replica, adopted }, verb)) |v| switch (v) { + if (std.meta.stringToEnum(enum { ok, replica, adopted }, verb)) |v| switch (v) { .ok => up.store(true, .release), - .attach => { - deliver(ctx, .{ .attach = .{ - .tty = if (got.nfds >= 2) got.fds[0] else -1, - .stub = if (got.nfds >= 2) got.fds[1] else -1, - } }); - for (got.fds[@min(got.nfds, 2)..got.nfds]) |f| _ = libc.close(f); - }, .replica => { const view = std.fmt.parseInt(u8, words.next() orelse "", 10) catch null; if (got.nfds >= 1) deliver(ctx, .{ .replica = .{ .fd = got.fds[0], .view = view } }); @@ -501,37 +493,13 @@ pub fn quit() void { link = -1; } -// ---- `pardes --attach`: a terminal, or a window, for a detached session ---- - -/// `other`: the session is the other kind (a window's for a terminal, or a -/// terminal's for a window), named so: joined as a replica client instead -/// (`replicaSocket`). -pub const Answer = union(enum) { ok: libc.pid_t, no: []const u8, other: []const u8 }; +// ---- `pardes attach`: a client, by the replica socket ---- /// This machine's replica socket, which joins a session of either kind. pub fn replicaSocket(buf: *[sun_path_len:0]u8) ?[:0]const u8 { return place(buf, "pardes-replica.sock"); } -/// Asks the daemon to hand `fds` (a terminal and a stub's pipe, or none for -/// a window) to the detached session `named` (any one, when empty), and -/// answers how it went; the words are `buf`'s. -pub fn attach(k: Kind, named: []const u8, fds: []const c_int, buf: []u8) Answer { - const fd = connect(false) orelse return .{ .no = "no detached session is running" }; - defer _ = libc.close(fd); - var line: [256]u8 = undefined; - const words = std.fmt.bufPrint(&line, "attach {t} {s}", .{ k, named }) catch return .{ .no = "that name is too long" }; - if (!send(fd, words, fds) or !readable(fd, 2000)) return .{ .no = "the daemon does not answer" }; - const got = recv(fd, buf) orelse return .{ .no = "the daemon hung up" }; - for (got.fds[0..got.nfds]) |f| _ = libc.close(f); - if (std.mem.startsWith(u8, got.words, "ok ")) { - const pid = std.fmt.parseInt(libc.pid_t, got.words[3..], 10) catch return .{ .no = "the daemon answered nonsense" }; - return .{ .ok = pid }; - } - if (std.mem.startsWith(u8, got.words, "other ")) return .{ .other = got.words["other ".len..] }; - return .{ .no = if (std.mem.startsWith(u8, got.words, "no ")) got.words[3..] else got.words }; -} - /// The daemon's answer to `words` (`list`, `kill <name>`, `killall`), in /// `buf`; null with no daemon running, or none answering. pub fn ask(words: []const u8, buf: []u8) ?[]const u8 { @@ -558,13 +526,11 @@ fn forward(sig: posix.SIG) callconv(.c) void { } } -/// The job the shell waits on, for a session that is not its child any -/// more (`pardes --attach`) or that it forked (`child`, reaped here): what -/// a terminal sends the job goes on to the session (its size, an end +/// The job the shell waits on, for the session it forked (reaped here): +/// what a terminal sends the job goes on to the session (its size, an end /// asked for), and it ends when the session is gone from the terminal -- -/// detached (`d<name>`), exited (`x<code>`, or the pipe's end and the -/// child's status), or refused (`r<why>`). -pub fn stubWait(session: libc.pid_t, child: bool, pipe: c_int) noreturn { +/// detached (`d<name>`), or exited (the pipe's end and the child's status). +fn stubWait(session: libc.pid_t, pipe: c_int) noreturn { stub_child = session; const on: posix.Sigaction = .{ .handler = .{ .handler = forward }, .mask = posix.sigemptyset(), .flags = posix.SA.RESTART }; for ([_]posix.SIG{ .WINCH, .TERM, .INT, .QUIT, .HUP }) |sig| posix.sigaction(sig, &on, null); @@ -587,31 +553,21 @@ pub fn stubWait(session: libc.pid_t, child: bool, pipe: c_int) noreturn { if (said.len > 0 and said[0] == 'd') { var text: [700]u8 = undefined; const who = said[1..]; - out.writeStreamingAll(io, std.fmt.bufPrint(&text, "pardes: detached from '{s}', which is still running; come back with `pardes --attach={s}`\n", .{ who, who }) catch "pardes: detached\n") catch {}; + out.writeStreamingAll(io, std.fmt.bufPrint(&text, "pardes: detached from '{s}', which is still running; come back with `pardes attach {s}`\n", .{ who, who }) catch "pardes: detached\n") catch {}; libc._exit(0); } - if (said.len > 0 and said[0] == 'r') { - var text: [700]u8 = undefined; - out.writeStreamingAll(io, std.fmt.bufPrint(&text, "pardes: --attach: {s}\n", .{said[1..]}) catch "pardes: --attach refused\n") catch {}; - libc._exit(1); + var status: c_int = 0; + while (libc.waitpid(session, &status, 0) < 0) { + if (libc.errno(-1) != .INTR) libc._exit(1); } - if (child) { - var status: c_int = 0; - while (libc.waitpid(session, &status, 0) < 0) { - if (libc.errno(-1) != .INTR) libc._exit(1); - } - const s: u32 = @bitCast(status); - if (libc.W.IFEXITED(s)) libc._exit(@intCast(libc.W.EXITSTATUS(s))); - if (libc.W.IFSIGNALED(s)) { - const sig = libc.W.TERMSIG(s); - const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 }; - posix.sigaction(sig, &default, null); - _ = libc.raise(sig); - } - libc._exit(1); + const s: u32 = @bitCast(status); + if (libc.W.IFEXITED(s)) libc._exit(@intCast(libc.W.EXITSTATUS(s))); + if (libc.W.IFSIGNALED(s)) { + const sig = libc.W.TERMSIG(s); + const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 }; + posix.sigaction(sig, &default, null); + _ = libc.raise(sig); } - if (said.len > 0 and said[0] == 'x') libc._exit(std.fmt.parseInt(u8, said[1..], 10) catch 1); - out.writeStreamingAll(io, "pardes: the session ended without a word\n") catch {}; libc._exit(1); } @@ -642,16 +598,8 @@ pub fn tellStubDetached() void { stub = -1; } -/// The session's end, `code` its exit status: the stub is told (and goes). -pub fn tellStubExit(code: u8) void { - tellStub(stub, "x{d}", .{code}); - stub = -1; -} - -/// The stub on `fd` told how its terminal's session went, what stubWait -/// reads, and its pipe let go: `d<name>` detached (one of a session's -/// several terminals, views.zig), `x<code>` exited, `r<why>` refused (an -/// attach that came too late). +/// The stub on `fd` told that its terminal's session detached +/// (`d<name>`), what stubWait reads, and its pipe let go. pub fn tellStub(fd: c_int, comptime fmt: []const u8, args: anytype) void { if (fd < 0) return; var buf: [256]u8 = undefined; @@ -694,7 +642,7 @@ pub fn forkSession(conn: c_int) ?void { _ = libc.close(conn); // Off the session's way: it is drawing already, its hello queued. startPending(true); - stubWait(pid, true, pipe[0]); + stubWait(pid, pipe[0]); } // ---- the daemon ---- @@ -815,7 +763,7 @@ const Daemon = struct { }; const c = &d.conns[i]; var words = std.mem.tokenizeScalar(u8, got.words, ' '); - const Verb = enum { hello, state, clients, pty, close, quit, upgrade, list, kill, killall, adopt, attach }; + const Verb = enum { hello, state, clients, pty, close, quit, upgrade, list, kill, killall, adopt }; switch (std.meta.stringToEnum(Verb, words.next() orelse return) orelse return) { .hello => { const v = std.fmt.parseInt(u32, words.next() orelse "", 10) catch 0; @@ -880,95 +828,7 @@ const Daemon = struct { if (!send(c.fd, w.buffered(), fds[0..n])) return d.hangUp(i); for (given[0..n]) |h| h.owner = i; }, - .attach => { - const k = std.meta.stringToEnum(Kind, words.next() orelse "") orelse return d.reply(i, "no bad attach", &.{}); - const wanted_name = std.mem.trim(u8, words.rest(), " "); - var why: [512]u8 = undefined; - // "other <name>": the client joins it through the replica socket. - const target = d.find(k, wanted_name, &why) orelse return d.reply(i, std.mem.sliceTo(&why, 0), &.{}); - const t = &d.conns[target]; - if (!send(t.fd, "attach", got.fds[0..got.nfds])) { - d.hangUp(target); - return d.reply(i, "no that session does not answer", &.{}); - } - t.detached = false; - var line: [32]u8 = undefined; - return d.reply(i, std.fmt.bufPrint(&line, "ok {d}", .{t.pid}) catch unreachable, &.{}); // a pid fits 32 - }, - } - } - - /// The detached session of kind `k` called `wanted_name`, or the one - /// there is when it is empty; else null, and why not in `why` - /// (0-terminated): "other <its name>" for one to join as a replica - /// client (of the other kind, or attached already: a session shows one - /// frontend of its own). - fn find(d: *Daemon, k: Kind, wanted_name: []const u8, why: *[512]u8) ?u8 { - @memset(why, 0); - const other: []const u8 = switch (k) { - .tty => "a window: attach it with `pardes-gui --attach", - .gui => "a terminal session: attach it with `pardes --attach", - }; - if (wanted_name.len != 0) { - for (&d.conns, 0..) |*s, i| if (s.fd >= 0 and s.kind != null and std.mem.eql(u8, s.named(), wanted_name)) { - if (s.kind.? != k or !s.detached) { - _ = std.fmt.bufPrint(why, "other {s}", .{wanted_name}) catch {}; - return null; - } - return @as(u8, @intCast(i)); - }; - _ = std.fmt.bufPrint(why, "no no session called '{s}'", .{wanted_name}) catch {}; - return null; } - var found: ?u8 = null; - var count: usize = 0; - var others: usize = 0; - var w: std.Io.Writer = .fixed(why[0 .. why.len - 1]); - for (&d.conns, 0..) |*s, i| if (s.fd >= 0 and s.detached and s.kind != null) { - if (s.kind.? != k) { - others += 1; - continue; - } - count += 1; - found = @intCast(i); - }; - if (count == 1) return found.?; - // None detached: the one session there is, joined as a client. - if (count == 0) { - for (&d.conns, 0..) |*s, i| if (s.fd >= 0 and s.kind == k) { - count += 1; - found = @intCast(i); - }; - if (count == 1) { - _ = std.fmt.bufPrint(why, "other {s}", .{d.conns[found.?].named()}) catch unreachable; // a [128]u8 field's name fits 512 - return null; - } - count = 0; - // None of this kind at all: the one session there is, the other kind's. - var only: ?*Conn = null; - var sessions: usize = 0; - for (&d.conns) |*s| if (s.fd >= 0 and s.kind != null) { - sessions += 1; - only = s; - }; - if (found == null and sessions == 1) { - _ = std.fmt.bufPrint(why, "other {s}", .{only.?.named()}) catch unreachable; // a [128]u8 field's name fits 512 - return null; - } - } - if (count == 0 and others == 0) { - w.writeAll("no no detached session is running") catch unreachable; // a literal fits 511 - return null; - } - if (count == 0) { - w.print("no the detached session{s} running {s} {s}=<name>`", .{ if (others == 1) " is" else "s are", if (others == 1) "is" else "are each", other }) catch {}; // cut short, still 0-terminated - return null; - } - w.print("no {d} detached sessions are running; say which with --attach=<name>:", .{count}) catch unreachable; // a usize fits 511 - for (&d.conns) |*s| if (s.fd >= 0 and s.detached and s.kind == k) { - w.print(" {s}", .{s.named()}) catch {}; - }; - return null; } /// More of a replica's hello; once it is whole, the connection refused @@ -1239,13 +1099,3 @@ test "a message carries its words and its fds, and the peer's end is null" { _ = libc.close(pair[1]); try std.testing.expect(recv(pair[0], &buf) == null); } - -test "an attach by a name longer than any session's is refused in words, never an empty reason" { - var d: Daemon = .{}; - var why: [512]u8 = undefined; - const long: []const u8 = &@as([600]u8, @splat('n')); - try std.testing.expect(d.find(.tty, long, &why) == null); - const said = std.mem.sliceTo(&why, 0); - try std.testing.expect(std.mem.startsWith(u8, said, "no ")); - try std.testing.expect(said.len > "no ".len); -} diff --git a/runtime/macos.zig b/runtime/macos.zig index dc12a6fb..cfe93b13 100644 --- a/runtime/macos.zig +++ b/runtime/macos.zig @@ -835,7 +835,7 @@ fn drainInbox(st: *State) bool { // No daemon on macOS (daemon.supported): neither ever comes. // ponytail: no `job` host entry here either: a kind's jobs run // on the loop (host_io.KindJob.runHere), so none comes. - .files_changed, .fs_ready, .handed, .window, .adopted, .kind_job => {}, + .files_changed, .fs_ready, .handed, .adopted, .kind_job => {}, } } for (0..pardes.MAX_PANES) |pane| { diff --git a/runtime/main.zig b/runtime/main.zig index 448dfa57..563461ed 100644 --- a/runtime/main.zig +++ b/runtime/main.zig @@ -1595,7 +1595,6 @@ fn nativeMain(std_init: std.process.Init) !void { } } defer daemon.quit(); - errdefer daemon.tellStubExit(1); switch (pardes.platform) { .tui => @import("dev").tui.run(init, opts, term) catch |err| switch (err) { // No controlling terminal (a detached pty, a daemon): said, not @@ -1609,7 +1608,6 @@ fn nativeMain(std_init: std.process.Init) !void { .gui => try @import("dev").gui.run(init, opts, detached), .macos => unreachable, } - daemon.tellStubExit(0); } extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; @@ -1803,50 +1801,61 @@ fn attachClient(init: std.process.Init, opts: pardes.Options, where: []const u8, std.process.exit(0); } -/// `pardes --attach[=name]` in a terminal: this terminal handed (through -/// the daemon) to the detached session of that name, or the only one, and -/// this process its stub until the session leaves it. `pardes-gui -/// --attach`: the session asked to open its window again, and done. A -/// session attached already, or of the other kind, is joined as a replica -/// client, through this machine's replica socket. +/// `pardes attach [NAME]` (`pardes-gui` too): a client of the session of +/// that name on this machine, through its replica socket (the daemon +/// refuses a name no session has); bare, of the one `bareAttach` finds. fn attachTo(init: std.process.Init, opts: pardes.Options, name: []const u8) noreturn { const io = init.io; - var words: [600]u8 = undefined; if (comptime !daemon.supported) die(io, "--attach: this system has no pardes daemon to attach through", .{}); - if (pardes.platform == .gui) switch (daemon.attach(.gui, name, &.{}, &words)) { - .ok => std.process.exit(0), - .no => |why| die(io, "--attach: {s}", .{why}), - .other => |named| crossAttach(init, opts, named), - }; - const fd = std.c.open("/dev/tty", .{ .ACCMODE = .RDWR, .CLOEXEC = true, .NOCTTY = true }, @as(std.c.mode_t, 0)); - if (fd < 0) die(io, "--attach: no terminal to attach: /dev/tty will not open", .{}); - if (std.posix.tcgetattr(fd)) |tio| std.posix.tcsetattr(fd, .NOW, tio) catch {} else |_| {} - var pipe: [2]std.c.fd_t = undefined; - if (std.c.pipe(&pipe) != 0) die(io, "--attach: no pipe for the session to say when it leaves", .{}); - ninep_io.setCloexec(pipe[0]); - ninep_io.setCloexec(pipe[1]); - switch (daemon.attach(.tty, name, &.{ fd, pipe[1] }, &words)) { - .ok => |pid| { - _ = std.c.close(fd); - _ = std.c.close(pipe[1]); - daemon.stubWait(pid, false, pipe[0]); - }, - .no => |why| die(io, "--attach: {s}", .{why}), - .other => |named| { - _ = std.c.close(fd); - _ = std.c.close(pipe[0]); - _ = std.c.close(pipe[1]); - crossAttach(init, opts, named); - }, + var list: [4096]u8 = undefined; + var names_buf: [600]u8 = undefined; + var names: std.Io.Writer = .fixed(&names_buf); + const said = daemon.ask("list", &list) orelse die(io, "--attach: no pardes daemon is running", .{}); + const named = if (name.len != 0) name else bareAttach(said, &names) orelse if (names.end == 0) + die(io, "--attach: no session is running", .{}) + else + die(io, "--attach: say which session:{s}", .{names.buffered()}); + var sock_buf: [ninep_io.sun_path_len:0]u8 = undefined; + const sock = daemon.replicaSocket(&sock_buf) orelse die(io, "--attach: no runtime directory for the replica socket", .{}); + attachClient(init, opts, sock, named); +} + +/// The session a bare attach takes, from the daemon's `list`: the one +/// detached, else the one there is; null with none or several, every +/// session's name in `names`. +fn bareAttach(list: []const u8, names: *std.Io.Writer) ?[]const u8 { + var one: ?[]const u8 = null; + var detached: ?[]const u8 = null; + var n: usize = 0; + var n_detached: usize = 0; + var lines = std.mem.tokenizeScalar(u8, list, '\n'); + while (lines.next()) |line| { + var words = std.mem.tokenizeScalar(u8, line, ' '); + if (!std.mem.eql(u8, words.next() orelse "", "session")) continue; + _ = words.next(); // its pid + _ = words.next(); // its kind + const state = words.next() orelse continue; + one = std.mem.trim(u8, words.rest(), " "); + n += 1; + names.print(" {s}", .{one.?}) catch {}; // cut short + if (!std.mem.eql(u8, state, "detached")) continue; + detached = one; + n_detached += 1; } + if (n_detached == 1) return detached; + return if (n == 1) one else null; } -/// A session attached already or of the other kind (`--attach`'s): a -/// replica client of it here. -fn crossAttach(init: std.process.Init, opts: pardes.Options, name: []const u8) noreturn { - var sock_buf: [ninep_io.sun_path_len:0]u8 = undefined; - const sock = daemon.replicaSocket(&sock_buf) orelse die(init.io, "--attach: no runtime directory for the replica socket", .{}); - attachClient(init, opts, sock, name); +test "a bare attach takes the one detached session, else the one there is, else names them" { + var buf: [600]u8 = undefined; + var names: std.Io.Writer = .fixed(&buf); + try std.testing.expectEqualStrings("b", bareAttach("daemon 1\nsession 2 tty attached a\nshell 9\nsession 3 gui detached b\n", &names).?); + try std.testing.expectEqualStrings("a", bareAttach("daemon 1\nsession 2 tty attached a\n", &names).?); + names = .fixed(&buf); + try std.testing.expect(bareAttach("daemon 1\norphan 4\n", &names) == null); + try std.testing.expectEqual(@as(usize, 0), names.end); + try std.testing.expect(bareAttach("session 2 tty detached a\nsession 3 tty detached b c\n", &names) == null); + try std.testing.expectEqualStrings(" a b c", names.buffered()); } /// Where Recent's file (0.24) and the store before it were kept: diff --git a/runtime/session.zig b/runtime/session.zig index 3942aa83..55b42b60 100644 --- a/runtime/session.zig +++ b/runtime/session.zig @@ -23,8 +23,8 @@ //! listener's wake, a detached session's first wait (`l.watch`). //! - `sent()`: after each step's unit went to the clients. //! - `upgradeAsked()`: an Upgrade asked in the step, done (it execs). -//! - `note(n)`: what the daemon says (a terminal, an adopted shell, a -//! client's connection), onto its queue. +//! - `note(n)`: what the daemon says (an adopted shell, a client's +//! connection), onto its queue. //! - `watched()`: the files it watches (a Restore stops watching them). //! - `restoring(nc)`, `restored(l)`: a Restore's new core, before it //! replaces the old one (its devices let go, what it is told of the @@ -119,8 +119,7 @@ pub fn Loop(comptime Frontend: type) type { // Asked in the step (the word), done between steps: the // session whole. fe.upgradeAsked(); - // A terminal (`pardes --attach`), a window asked for again, - // an adopted shell or a client's connection, handed on by + // An adopted shell or a client's connection, handed on by // the daemon's thread; started after the first frame, off a // start's way. l.watch(); diff --git a/test/daemon.py b/test/daemon.py index e600beb7..31806863 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -2,8 +2,8 @@ """The per-user daemon end to end (docs/next-daemon.md, phase 3), under a private HOME and runtime directory: -- a terminal's session detached (the stub ends, exit 0) and attached again - from another terminal, N times; +- a terminal's session detached (the stub ends, exit 0), then attached + from another terminal N times, each a client (an attach is always one); - a session killed outright: its shells live on, held by the daemon, and another session adopts them as terminal panes; - a replica's hello on the daemon's stream socket (phase 5): one of this @@ -16,8 +16,8 @@ private HOME and runtime directory: - nothing left behind: no session, shell, daemon or socket. python3 -B test/daemon.py <pardes> [cycles] - python3 -B test/daemon.py --gui <pardes-gui> [cycles] (a hidden window; - needs a Wayland display, and a pardes beside it for the refusal) + python3 -B test/daemon.py --gui <pardes-gui> [cycles] (hidden windows, + offscreen, and a pardes beside it for the terminal's client) python3 -B test/daemon.py --ping <socket> <session> <pardes> [n] a hello of <pardes>'s build and n pings on a replica socket (one `ssh -L` forwards, say), timed @@ -428,8 +428,8 @@ def clients(binary): wait_for('both clients out of insert mode', lambda: normal_again(ta) and normal_again(tb)) wait_for('client A agrees once quiet', lambda: agreed(root / 'a.check', 0)) wait_for('client B agrees once quiet', lambda: agreed(root / 'b.check', 0)) - # A terminal attached while a client's view is live (its input the - # last): it takes the session's own and is drawn. + # A terminal attached by the session's name alone while a client's + # view is live (its input the last): a client too, drawn. tt = Term(24, 80) terms.append(tt) stub = tt.spawn([binary, '--attach=files'], env) @@ -1395,70 +1395,90 @@ def main(binary, cycles): shell = terminals(client)[0] shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1]) started.append(shell_pid) + # Detach in the terminal it was born with: the stub ends (exit 0, + # its words), the terminal put back; the session runs on detached, + # for good: every attach after it is a client. + client.write(f'/pane/{shell}/exec', b'Detach\n') + assert stub.wait(timeout=10) == 0, stub.returncode + # The stub's last words are in its terminal before it ends, but + # this side's reader may not have them yet. + wait_for('the stub says it detached', lambda: b'detached from \'work\', which is still running; come back with `pardes attach work`' in term.text()) + assert b'\x1b[?1049l' in term.text(), 'the terminal is put back' + term.close() + assert alive(session) and alive(shell_pid) + assert run(client, shell, b'echo still\n').startswith(b'exit 0\nstill'), 'the shell runs on, detached' + + def attach(term, argv, typed): + """A client: its own process, drawn, listed by --ps under the + session, detached still, and its keys in the shell.""" + c = term.spawn(argv, env) + started.append(c.pid) + wait_for('the client\'s first frame', lambda: b'\x1b[?1049h' in term.text()) + listed = wait_for('the client in --ps', lambda: (lambda out: f'client {c.pid} ' in out and out)( + subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())) + assert f'session work {session} (tty, detached)' in listed, listed + os.write(term.master, f'echo {typed}\r'.encode()) + wait_for('its keys in the shell', lambda: typed.encode() in client.read(f'/pane/{shell}/body')) + return c + + def let_go(how, c, term): + """Detach in it (its view the live one: it typed last), or its + 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()) + else: + term.close() + c.wait(timeout=10) + if how == 'detach': + term.close() + assert alive(session) and alive(shell_pid) + baseline = None for cycle in range(cycles): - client.write(f'/pane/{shell}/exec', b'Detach\n') - assert stub.wait(timeout=10) == 0, stub.returncode - # The stub's last words are in its terminal before it ends, but - # this side's reader may not have them yet. - wait_for('the stub says it detached', lambda: b'detached from \'work\'' in term.text()) - said = term.text() - assert b'\x1b[?1049l' in said, 'the terminal is put back' - term.close() - assert alive(session) and alive(shell_pid) - assert run(client, shell, b'echo still\n').startswith(b'exit 0\nstill'), 'the shell runs on, detached' term = Term(30, 100) - stub = term.spawn([binary, '--attach=work'], env) - wait_for('the attached terminal\'s first frame', lambda: b'\x1b[?1049h' in term.text()) - wait_for('the session sized to its new terminal', - lambda: client.screen()['cols'] == 100 and client.screen()['rows'] == 30) + c = attach(term, [binary, '--attach=work'] if cycle % 2 else [binary, 'attach'], f'cycle-{cycle}') now = (fds(session), fds(daemon), len(list(root.iterdir())), len(processes(root))) if baseline is None: baseline = now assert now == baseline, (cycle, now, baseline) - print(f'daemon: {cycles} detach/attach cycles, fds/sockets/processes level: {baseline}') + let_go('detach' if cycle % 2 else 'close', c, term) + print(f'daemon: a Detach in its own terminal, then {cycles} attaches as clients (Detach in each, or its terminal closed), ' + f'fds/sockets/processes level: {baseline}') - # Another terminal while one is attached: a replica client of the - # session (a session shows one frontend of its own), listed under - # it by --ps, drawn beside the first, typed into as the first is. - # Detached from inside, it ends and the first draws on; closed - # outright, the same. + # Two clients at once, both listed by --ps, both typed into and + # drawn; the second let go by a Detach in it, or its terminal + # closed, and the first draws on. + term = Term(30, 100) + first = attach(term, [binary, 'attach', 'work'], 'first-in') for how in ('detach', 'close'): - # Bigger than the first: the shell, sized for the first (its - # last typist), shows whole in it. term2 = Term(40, 120) - stub2 = term2.spawn([binary, '--attach=work'], env) - started.append(stub2.pid) - wait_for('the second terminal\'s first frame', lambda: b'\x1b[?1049h' in term2.text()) - wait_for('the second terminal\'s view live', lambda: client.screen()['cols'] == 120) - listed = subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode() - assert f'client {stub2.pid} ' in listed, listed + second = attach(term2, [binary, 'attach', 'work'], f'two-typed-{how}') os.write(term.master, f'echo one-typed-{how}\r'.encode()) wait_for('the first terminal\'s keys in the shell', lambda: f'one-typed-{how}'.encode() in client.read(f'/pane/{shell}/body')) - os.write(term2.master, f'echo two-typed-{how}\r'.encode()) - wait_for('the second terminal\'s keys in the shell', lambda: f'two-typed-{how}'.encode() in client.read(f'/pane/{shell}/body')) + # (Words no line before has a letter of in the same place: a + # terminal is sent the cells that changed.) + drawn = f'{how.upper()}BOTHDRAWN' seen = len(term.text()) - run(client, shell, f'echo both-drawn-{how}\n'.encode()) - wait_for('the first terminal drawn', lambda: f'both-drawn-{how}'.encode() in term.text()[seen:]) - wait_for('the second terminal drawn', lambda: f'both-drawn-{how}'.encode() in term2.text()) - assert stub.poll() is None and stub2.poll() is None - if how == 'detach': - # Its view is the live one (its terminal spoke last). - client.write(f'/pane/{shell}/exec', b'Detach\n') - stub2.wait(timeout=10) - term2.close() - else: - term2.close() - stub2.wait(timeout=10) - wait_for('the first terminal\'s view live again', lambda: client.screen()['cols'] == 100) - wait_for('the client gone from --ps', lambda: 'client ' not in subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode()) + run(client, shell, f'echo {drawn}\n'.encode()) + wait_for('the first terminal drawn', lambda: drawn.encode() in term.text()[seen:]) + wait_for('the second terminal drawn', lambda: drawn.encode() in term2.text()) + assert first.poll() is None and second.poll() is None + # Its view the live one: it typed last. + os.write(term2.master, f'echo two-last-{how}\r'.encode()) + wait_for('the second terminal\'s keys in the shell', lambda: f'two-last-{how}'.encode() in client.read(f'/pane/{shell}/body')) + let_go(how, second, term2) + wait_for('the client gone from --ps', lambda: f'client {second.pid} ' not in subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode()) + drawn = f'{how.upper()}FIRSTON' seen = len(term.text()) - run(client, shell, f'echo first-on-{how}\n'.encode()) - wait_for('the first terminal drawn on', lambda: f'first-on-{how}'.encode() in term.text()[seen:]) - assert stub.poll() is None, 'the first terminal stays attached' + run(client, shell, f'echo {drawn}\n'.encode()) + wait_for('the first terminal drawn on', lambda: drawn.encode() in term.text()[seen:]) + assert first.poll() is None, 'the first client stays' now = (fds(session), fds(daemon), len(list(root.iterdir())), len([p for p in processes(root) if alive(p)])) assert now[:3] == baseline[:3], (how, now, baseline) - print('daemon: a second terminal on an attached session a client of it (in --ps), both typed into and drawn, then detached and closed; the first drew on') + print('daemon: two clients at once, each in --ps, both typed into and drawn; the second detached, then closed; the first drew on') + stub = first # Killed outright: its shells live on, their masters the daemon's, # and a replica client of it hears so at once, in words (one froze @@ -1507,22 +1527,33 @@ def main(binary, cycles): shell.kill() shell.wait(timeout=10) term.close() - term = Term() - stub = term.spawn([binary, '--attach=fresh'], env) - wait_for('the attached terminal\'s first frame', lambda: b'\x1b[?1049h' in term.text()) - wait_for('the session sized to its new terminal', lambda: not sized(client)) - print('daemon: a session whose stub was killed outright detached, and was attached again') before = set(terminals(client)) client.write(f'/pane/{min(before)}/exec', b'Adopt\n') adopted = wait_for('the adopted pane', lambda: set(terminals(client)) - before) pane = adopted.pop() + # Sized twice (Ptys.take): a run into a prompt redrawn under it + # reads as not run (core/ninep/pty.zig). + wait_for('the adopted shell answers', lambda: run(client, pane, b'true\n') == b'exit 0\n') said = run(client, pane, b'echo $$\n') assert said.split(b'\n')[1] == str(shell_pid).encode(), said print(f'daemon: shell {shell_pid} outlived kill -9 of its session and was adopted') + # Attached again: a client. (After the runs: a pty/run under a + # client puts it off the session's state, and it joins again; one + # that tries as the session ends says it could not.) + term = Term() + stub = term.spawn([binary, 'attach', 'fresh'], env) + started.append(stub.pid) + wait_for('the client\'s first frame', lambda: b'\x1b[?1049h' in term.text()) + listed = wait_for('the client in --ps', lambda: (lambda out: f'client {stub.pid} ' in out and out)( + subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())) + assert f'session fresh {session} (tty, detached)' in listed, listed + print('daemon: a session whose stub was killed outright detached, and was attached again, as a client') - # The end: the session quits, its shells hang up, the daemon goes. - client.write(f'/pane/{pane}/exec', b'Exit\n') - stub.wait(timeout=10) + # 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()) client.socket.close() term.close() wait_for('the adopted shell hung up', lambda: not alive(shell_pid)) @@ -1551,62 +1582,67 @@ def sized(client): def gui(binary, cycles): - """A window's Detach closes it and keeps the process; `pardes-gui - --attach` opens it again. Test mode: a hidden window, its stdin the - test feed.""" + """A window's Detach closes it and keeps the process, detached for good: + `pardes-gui attach` is a window client of it, a process of its own, + and so is a terminal's `pardes attach`. Test mode: hidden windows, + offscreen, the session's stdin the test feed.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rtg-', dir=scratch)) env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} - display = Path(os.environ.get('WAYLAND_DISPLAY', 'wayland-0')) - if not display.is_absolute(): - display = Path(os.environ.get('XDG_RUNTIME_DIR', f'/run/user/{os.getuid()}')) / display (root / 'caps').mkdir() env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_TEST='1', PARDES_TEST_CAPTURE_DIR=str(root / 'caps'), - SDL_VIDEODRIVER='wayland', WAYLAND_DISPLAY=str(display), PARDES_DAEMON='on') + SDL_VIDEO_DRIVER='offscreen', PARDES_DAEMON='on', TERM='xterm-256color') (root / 'config' / 'pardes').mkdir(parents=True) (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') feed_r, feed_w = os.pipe() proc = subprocess.Popen([binary, '--9p=win'], env=env, cwd=root, stdin=feed_r, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) os.close(feed_r) + + def listed(): + return subprocess.run([binary, '--ps'], env=env, cwd=root, capture_output=True, timeout=30).stdout.decode() + try: sock = root / 'pardes-9p-win.sock' wait_for('the window session', sock.exists, timeout=20) client = Client(sock) shell = terminals(client)[0] assert not sized(client), 'a window owns the size' - baseline = None - for cycle in range(cycles): - client.write(f'/pane/{shell}/exec', b'Detach\n') - wait_for('the window closed', lambda: sized(client)) - assert proc.poll() is None, 'the process carries on with no window' - attach = subprocess.run([binary, '--attach=win'], env=env, cwd=root, timeout=10, - stdout=subprocess.PIPE, stderr=subprocess.PIPE) - assert attach.returncode == 0, attach.stderr - wait_for('the window open again', lambda: not sized(client)) - now = (fds(proc.pid), len(processes(root))) - baseline = baseline or now - assert now == baseline, (cycle, now, baseline) - print(f'daemon: {cycles} window detach/attach cycles, fds/processes level: {baseline}') - # Attached already: another window is a replica client of the - # session (its own process, its captures its own), listed by --ps; - # closed, it ends alone. + # With its window: another window is a client of the session (its + # own process, its captures its own), listed by --ps; closed, it + # ends alone. second = Window(root, 'second', [binary, '--attach=win'], env) wait_for('the second window drawn', lambda: (root / 'second' / 'latest.ppm').exists(), timeout=20) - listed = subprocess.run([binary, '--ps'], env=env, cwd=root, capture_output=True, timeout=30).stdout.decode() - assert f'client {second.pid} ' in listed, listed + assert f'client {second.pid} ' in listed(), listed() second.close() - wait_for('the client gone from --ps', lambda: 'client ' not in subprocess.run([binary, '--ps'], env=env, cwd=root, capture_output=True, timeout=30).stdout.decode()) + wait_for('the client gone from --ps', lambda: 'client ' not in listed()) assert not sized(client), 'the first window stays' assert proc.poll() is None - print('daemon: a second window on an attached window session a client of it (in --ps), closed alone') - # Another kind joins as a replica client: a terminal of the window's - # session, by its name alone. A name nobody has is refused in words. + print('daemon: a second window on a window session a client of it (in --ps), closed alone') + # Detached: the window closed, the process on; every attach after it + # a window client, the session detached still. client.write(f'/pane/{shell}/exec', b'Detach\n') wait_for('the window closed', lambda: sized(client)) + assert proc.poll() is None, 'the process carries on with no window' + assert f'session win {proc.pid} (gui, detached)' in listed(), listed() + baseline = None + for cycle in range(cycles): + w = Window(root, f'w{cycle}', [binary, 'attach'] if cycle % 2 else [binary, '--attach=win'], env) + wait_for('the client window drawn', lambda: (root / f'w{cycle}' / 'latest.ppm').exists(), timeout=20) + wait_for('the client in --ps', lambda: f'client {w.pid} ' in listed()) + assert f'session win {proc.pid} (gui, detached)' in listed(), listed() + now = (fds(proc.pid), len(processes(root))) + baseline = baseline or now + assert now == baseline, (cycle, now, baseline) + w.close() + wait_for('the client gone from --ps', lambda: 'client ' not in listed()) + print(f'daemon: a window Detach, then {cycles} window attaches as clients, fds/processes level: {baseline}') + # A terminal's client of the window's session, by its name alone. A + # name nobody has is refused in words. term = Term() - tty_attach = term.spawn([binary.replace('pardes-gui', 'pardes'), '--attach=win'], env) + tty_attach = term.spawn([binary.replace('pardes-gui', 'pardes'), 'attach', 'win'], env) wait_for('the window session drawn in the terminal', lambda: b'\x1b[?1049h' in term.text()) time.sleep(1) assert tty_attach.poll() is None, term.text()[-400:] |
