diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-20 01:32:33 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-20 01:36:47 -0300 |
| commit | cdff9d3a854aa8fd434b77ad6ac5a9db3efa3707 (patch) | |
| tree | 161bb0f42ec2d0656acc9a024a29dcd6a136c7e7 | |
| parent | 8e04bc6370916ac328f61ad0df6e3babeb9789b4 (diff) | |
| parent | ff74e10d9375a463438684af6572e2bb35b17030 (diff) | |
| download | pardes-cdff9d3a854aa8fd434b77ad6ac5a9db3efa3707.tar.gz pardes-cdff9d3a854aa8fd434b77ad6ac5a9db3efa3707.zip | |
integration: a session's ptys once, on the terminal's bytes and the build's options: pardes-services-1b (dev/Ptys.zig, the session loop's pty table and the one Inbox its readers post to, both frontends' Host tables taking the pty calls from one set; a command's exit told after the reads already taken) and pardes-merge26; one conflict, the terminal's Host table: the services' entries kept, the newer_build line a far-client fix deleted dropped; tui core-test 856/1006 (150 skipped), shell-test 1046/1049, the window builds; the coordinator's gate in the ledger (reorg/merge27)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
| -rw-r--r-- | dev/Ptys.zig | 397 | ||||
| -rw-r--r-- | dev/gui/gui.zig | 435 | ||||
| -rw-r--r-- | dev/host_io.zig | 2 | ||||
| -rw-r--r-- | dev/root.zig | 1 | ||||
| -rw-r--r-- | dev/tui/tui.zig | 369 | ||||
| -rw-r--r-- | runtime/session.zig | 41 | ||||
| -rw-r--r-- | test/replicas.zig | 2 |
7 files changed, 558 insertions, 689 deletions
diff --git a/dev/Ptys.zig b/dev/Ptys.zig new file mode 100644 index 00000000..97c5cfde --- /dev/null +++ b/dev/Ptys.zig @@ -0,0 +1,397 @@ +//! A session's ptys: each terminal pane's shell (forked here, or adopted +//! from a session that died), its master and pid, and the reader that +//! posts what it says to the session's queue (Inbox). One table a session, +//! the session loop's (runtime/session.zig): the Host's pty calls are +//! answered here whatever the frontend (`Calls`), and a frontend draining +//! the queue hands the readers' posts back (`output`, `eof`). +const std = @import("std"); +const posix = std.posix; +const libc = std.c; +const pardes = @import("core"); +const daemon = @import("runtime").daemon; +const upgrade = @import("runtime").upgrade; +const host_io = @import("host_io.zig"); +const Inbox = host_io.Inbox; +const Ptys = @This(); + +const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); + +pub const Pty = struct { + fd: c_int, + pid: libc.pid_t, + /// Its reader, blocked in an Io read: `close` cancels it. + reader: ?std.Io.Future(void) = null, + /// A command pane's child, watched to its exit (host_io.watchExit); + /// the pty stays open until both its end of file and its exit. + cmd: host_io.CommandWatch = .{}, +}; + +slots: [pardes.MAX_PANES]?Pty = @splat(null), +/// Each slot's generation: a post of an older one is passed over. +gens: [pardes.MAX_PANES]u32 = @splat(0), +queue: *Inbox, +prompt_rcs: *const host_io.Shell.PromptFiles, +/// Shells a dead session left (Adopt), each waiting for the spawn of the +/// terminal pane made for it. +adoptions: host_io.Adoptions = .{}, +/// Readers run from the loop's start on (`start`): a shell spawned in the +/// first effects is read from then. +reading: bool = false, + +/// The Host's pty calls, for a host whose `ctx` is a `*Ctx` with the +/// fields `ptys: *Ptys` and `core: *Pardes`. +pub fn Calls(comptime Ctx: type) type { + return struct { + fn of(ctx: ?*anyopaque) *Ctx { + return @ptrCast(@alignCast(ctx.?)); + } + pub fn spawn(ctx: ?*anyopaque, id: pardes.Pane.Id, cwd: []const u8) void { + const s = of(ctx); + s.ptys.spawn(s.core, id, cwd); + } + pub fn write(ctx: ?*anyopaque, id: pardes.Pane.Id, bytes: []const u8) void { + of(ctx).ptys.write(id, bytes); + } + pub fn resize(ctx: ?*anyopaque, id: pardes.Pane.Id, cols: u16, rows: u16) void { + const s = of(ctx); + s.ptys.resize(s.core, id, cols, rows); + } + pub fn signal(ctx: ?*anyopaque, id: pardes.Pane.Id, sig: pardes.PtySignal) void { + of(ctx).ptys.signal(id, sig); + } + pub fn close(ctx: ?*anyopaque, id: pardes.Pane.Id) void { + of(ctx).ptys.close(id); + } + pub fn ttyTaken(ctx: ?*anyopaque, id: pardes.Pane.Id) bool { + const pt = of(ctx).ptys.slots[id.index()] orelse return false; + return host_io.ttyTaken(pt.pid, pt.fd); + } + pub fn fgName(ctx: ?*anyopaque, id: pardes.Pane.Id, buf: []u8) ?[]const u8 { + const pt = of(ctx).ptys.slots[id.index()] orelse return null; + return host_io.foregroundName(pt.pid, pt.fd, buf); + } + pub fn killJob(ctx: ?*anyopaque, id: pardes.Pane.Id) bool { + const pt = of(ctx).ptys.slots[id.index()] orelse return false; + return host_io.killJob(pt.pid, pt.fd); + } + pub fn adopt(ctx: ?*anyopaque, id: pardes.Pane.Id) void { + const s = of(ctx); + s.ptys.adoptions.ask(s.core, id.index()); + } + }; +} + +/// Pane `id`'s shell, in `cwd` (empty: where its pane's directory says), +/// or the adopted one waiting for it. +pub fn spawn(p: *Ptys, core: *pardes.Pardes, id: pardes.Pane.Id, cwd: []const u8) void { + const pane = id.index(); + if (p.adoptions.take(id)) |a| return p.take(core, pane, a); + // The new shell starts before a running one goes: one that cannot + // start leaves the running one be (pty/ctl's exec). + const running = p.slots[pane] != null; + const child = host_io.forkShell(core, pane, p.prompt_rcs, core.shellBin(), cwd, core.view().screen_h, core.view().screen_w) catch |err| { + if (running) return core.restartFailed(id, err); + return core.shellFailed(id, err); + }; + p.close(id); + p.gens[pane] +%= 1; + const command = if (core.panes[pane]) |pn| pn.command != null else false; + p.slots[pane] = .{ .fd = child.file.handle, .pid = child.pid, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } }; + // Only a shell given no directory is asked where it is: one given a + // directory is named by it already (newShell), and the frame's poll + // (`pollCwds`) says where it went from there. + var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + if (cwd.len == 0) if (host_io.shellCwd(child.pid, &lbuf)) |wd| core.setCwd(id, wd); + p.read(core, pane); +} + +/// An adopted shell, running already, as pane `pane`'s: told the size +/// twice (a size it never had, then the pane's), which makes it redraw. +fn take(p: *Ptys, core: *pardes.Pardes, pane: u8, a: host_io.Adoption) void { + p.close(.at(pane)); + p.gens[pane] +%= 1; + p.slots[pane] = .{ .fd = a.fd, .pid = a.pid }; + var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + core.acknowledgeShell(.at(pane), host_io.processExe(a.pid, &exe_buf) orelse "sh", host_io.marksPrompts(a.pid)); + var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + if (host_io.shellCwd(a.pid, &lbuf)) |wd| core.setCwd(.at(pane), wd); + const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 }; + _ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny)); + if (core.panes[pane]) |pn| p.resize(core, .at(pane), @max(pn.cols, 1), @max(pn.rows, 1)); + p.read(core, pane); +} + +/// Pane `pane`'s reader, once readers run: the place of one stopped for +/// an Upgrade let go first. One that cannot start closes the pty and says +/// why in the pane. +fn read(p: *Ptys, core: *pardes.Pardes, pane: u8) void { + if (!p.reading) return; + const pt = &(p.slots[pane] orelse return); + p.queue.cancelReader(.at(pane), p.gens[pane]); + pt.reader = p.queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, .at(pane), p.gens[pane]) catch |err| { + p.close(.at(pane)); + return core.reportError(.at(pane), "terminal reader", err); + }; +} + +/// The loop's start: every shell read from now on. +pub fn start(p: *Ptys, core: *pardes.Pardes) void { + p.reading = true; + for (0..p.slots.len) |pane| p.read(core, @intCast(pane)); +} + +pub fn write(p: *Ptys, id: pardes.Pane.Id, bytes: []const u8) void { + if (p.slots[id.index()]) |pt| _ = host_io.writeFd(pt.fd, bytes); +} + +pub fn resize(p: *Ptys, core: *const pardes.Pardes, id: pardes.Pane.Id, cols: u16, rows: u16) void { + const pt = p.slots[id.index()] orelse return; + const ws = host_io.ptyWinsize(core, cols, rows); + _ = posix.system.ioctl(pt.fd, TIOCSWINSZ, @intFromPtr(&ws)); +} + +pub fn signal(p: *Ptys, id: pardes.Pane.Id, sig: pardes.PtySignal) void { + // A command whose exit is recorded is reaped: its group may be + // another's by now. + if (p.slots[id.index()]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.fd, sig, pt.cmd.watched); +} + +/// The pane is gone, or its shell is: its reader out of the queue first +/// (which lets go one waiting for room there) and canceled; its pty hung +/// up, which the kernel passes on to the shell as SIGHUP; the daemon's +/// copy let go; the shell retired. +pub fn close(p: *Ptys, id: pardes.Pane.Id) void { + const pane = id.index(); + var pt = p.slots[pane] orelse return; + p.slots[pane] = null; + p.queue.cancelReader(id, p.gens[pane]); + if (pt.reader) |*r| r.cancel(p.queue.io); + _ = libc.close(pt.fd); + daemon.closed(pt.pid); + host_io.retireShell(pt.pid); +} + +/// A reader's read, off the queue (freed here). +pub fn output(p: *Ptys, core: *pardes.Pardes, o: @FieldType(Inbox.Msg, "output")) void { + defer p.queue.gpa.free(o.bytes); + if (p.gens[o.pane.index()] == o.gen) core.update(.{ .output = .{ .pane = o.pane, .bytes = o.bytes } }); +} + +/// A reader's end, off the queue: its pty's end of file, or a read that +/// failed. +pub fn eof(p: *Ptys, core: *pardes.Pardes, e: @FieldType(Inbox.Msg, "eof")) void { + const pane = e.pane.index(); + if (p.gens[pane] != e.gen) return; + if (e.failure) |err| { + p.close(e.pane); + return core.readerFailed(e.pane, err); + } + const pt = &(p.slots[pane] orelse return core.update(.{ .eof = .{ .pane = e.pane } })); + // A command's pty stays open until its child has exited: closing it + // would hang up one that runs on without it. Its exit, if it came + // first, is told now its output is in. + if (pt.cmd.watched) return host_io.commandEof(core, &p.slots, pane, p, closeWatched); + // Unwatched, a command's exit is read here, as its end, and a + // shell's, for a run waiting on it and the log. + const command = if (core.panes[pane]) |pn| pn.command != null else false; + const status = host_io.exitStatus(pt.pid, 100); + if (status != null) pt.pid = 0; // reaped: no shell to retire + p.close(e.pane); + if (command or status != null) core.update(.{ .exited = .{ .pane = e.pane, .status = status } }); + core.update(.{ .eof = .{ .pane = e.pane } }); +} + +/// The command panes' exits, told once their output is in (host_io): +/// after an exit's wake and after each batch of output. +pub fn takeExits(p: *Ptys, core: *pardes.Pardes) void { + host_io.takeExits(core, &p.slots, p, closeWatched); +} + +fn closeWatched(p: *Ptys, id: usize) void { + p.close(.at(id)); +} + +/// Where each shell is now: its pane's directory (a frame's poll). +pub fn pollCwds(p: *Ptys, core: *pardes.Pardes) void { + for (p.slots, 0..) |slot, id| if (slot) |pt| { + var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + if (host_io.ttyCwd(pt.pid, pt.fd, core.settings.shell.effective.get(), &lbuf)) |cwd| core.setCwd(.at(id), cwd); + }; +} + +/// An Upgrade's: the readers stopped, the ptys left open. What a reader +/// posted before its cancel is in the queue still, the frontend's to +/// take; one waiting for room has it once the queue is drained. +pub fn pause(p: *Ptys) void { + for (&p.slots) |*slot| if (slot.*) |*pt| if (pt.reader) |*r| { + r.cancel(p.queue.io); + pt.reader = null; + }; +} + +/// After an Upgrade that did not happen: read on. +pub fn readOn(p: *Ptys, core: *pardes.Pardes) void { + for (p.slots, 0..) |slot, pane| if (slot) |pt| if (pt.reader == null) p.read(core, @intCast(pane)); +} + +/// The ptys an Upgrade hands to the next build. +pub fn record(p: *const Ptys, rec: *upgrade.Record) void { + for (p.slots, 0..) |slot, id| if (slot) |pt| rec.addPty(id, pt.pid, pt.fd); +} + +/// An upgraded session's shells, running on: each its pane's pty again, +/// or, when its dump would not load (`fresh`), adopted as new panes. +pub fn resumeFrom(p: *Ptys, core: *pardes.Pardes, rec: *const upgrade.Record) void { + for (rec.ptys[0..rec.nptys]) |k| { + const pane = if (rec.fresh) null else core.panes[k.pane]; + if (pane == null or !pane.?.isTerminal()) { + p.adoptions.adoptShell(core, k.pid, k.fd); + continue; + } + p.slots[k.pane] = .{ .fd = k.fd, .pid = k.pid, .cmd = .{ .watched = pane.?.command != null and host_io.watchExit(k.pid), .fd = k.fd } }; + } +} + +/// Every pty closed and every generation moved on: a Restore's (the new +/// core's panes start shells of their own) and the session's end. +pub fn stop(p: *Ptys) void { + for (0..p.slots.len) |pane| p.close(.at(pane)); + for (&p.gens) |*gen| gen.* +%= 1; +} + +/// The session's end: every shell hung up and seen out (waitRetired), the +/// adopted ones no pane took let go. +pub fn deinit(p: *Ptys) void { + p.stop(); + for (p.adoptions.list[0..p.adoptions.len]) |a| _ = libc.close(a.fd); + p.adoptions.len = 0; + host_io.waitRetired(); +} + +/// A table over `queue` with shells of its own, readers running: the +/// tests' (each slot's generation 1). +fn testing(queue: *Inbox) Ptys { + const none = struct { + const rcs: host_io.Shell.PromptFiles = .{}; + }; + return .{ .queue = queue, .prompt_rcs = &none.rcs, .gens = @splat(1), .reading = true }; +} + +fn testShell(p: *Ptys, pane: u8) !libc.pid_t { + const child = try host_io.forkShell(null, pane, p.prompt_rcs, "/bin/sh", "", 24, 80); + p.slots[pane] = .{ .fd = child.file.handle, .pid = child.pid }; + p.slots[pane].?.reader = try p.queue.startReader(.{ .handle = child.file.handle, .flags = .{ .nonblocking = false } }, .at(pane), p.gens[pane]); + return child.pid; +} + +test "a reader delivers a real shell's tail before its end of file, and closing joins it" { + const gpa = std.testing.allocator; + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + var p = testing(&queue); + defer p.deinit(); + _ = try p.testShell(0); + const fd = p.slots[0].?.fd; + try std.testing.expect(host_io.writeFd(fd, "printf '\\120\\101\\122\\104\\105\\123\\055\\124\\101\\111\\114'; exit\n")); + var bytes: std.ArrayList(u8) = .empty; + defer bytes.deinit(gpa); + var ended = false; + const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000; + while (!ended and std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) { + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + for (batch.slice()) |msg| switch (msg) { + .output => |o| { + try std.testing.expect(!ended); + try bytes.appendSlice(gpa, o.bytes); + }, + .eof => |e| { + try std.testing.expect(e.failure == null); + ended = true; + }, + else => return error.UnexpectedMessage, + }; + if (!ended) try std.testing.io.sleep(.fromMilliseconds(1), .awake); + } + try std.testing.expect(ended); + try std.testing.expect(std.mem.indexOf(u8, bytes.items, "PARDES-TAIL") != null); + p.close(.at(0)); + try std.testing.expect(queue.readers[0] == null); + try std.testing.expect(p.slots[0] == null); + try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(fd, libc.F.GETFD)); +} + +test "a Restore's stop joins a real reader waiting for room in the queue" { + const gpa = std.testing.allocator; + var core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + try pardes.dump.dumpState(core); + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + queue.acceptReader(.at(1), 1); + for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = .at(1), .gen = 1, .bytes = try gpa.dupe(u8, "other pane") } }); + var p = testing(&queue); + defer p.deinit(); + _ = try p.testShell(0); + const fd = p.slots[0].?.fd; + try std.testing.expect(host_io.writeFd(fd, "printf 'after-full'; exit\n")); + try host_io.PtyTests.waitBlocked(&queue); + const old_serial = core.panes[0].?.serial; + const replacement = try pardes.dump.restore(core, core.dump_out.?, "test"); + p.stop(); + core.deinit(); + core = replacement; + // The dump's pane, its serial too; its old shell stopped all the same. + try std.testing.expectEqual(old_serial, core.panes[0].?.serial); + try std.testing.expectEqual(@as(usize, 0), queue.waiting); + try std.testing.expect(queue.readers[0] == null); + try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(fd, libc.F.GETFD)); + queue.cancelReader(.at(1), 1); + queue.acceptReader(.at(0), p.gens[0]); + queue.push(.{ .eof = .{ .pane = .at(0), .gen = 1 } }); + try std.testing.expect(queue.pushOutput(.at(0), p.gens[0], try gpa.dupe(u8, "fresh"))); + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(@as(usize, 1), batch.len); + try std.testing.expectEqualStrings("fresh", batch.items[0].output.bytes); +} + +test "a pane's removal closes its pty, joins its idle reader, and its shell is reaped by the end" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + var p = testing(&queue); + defer p.deinit(); + while (core.nextEffect()) |_| {} + const pid = try p.testShell(0); + const fd = p.slots[0].?.fd; + try core.removePane(0, null); + // The core asks it closed (panes.retirePane): no pane outlives its pty. + while (core.nextEffect()) |e| if (e == .close_pty) p.close(e.close_pty.pane); + try std.testing.expect(p.slots[0] == null); + try std.testing.expect(queue.readers[0] == null); + try std.testing.expectEqual(@as(usize, 0), queue.waiting); + try std.testing.expectEqual(@as(usize, 0), queue.take().len); + try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(fd, libc.F.GETFD)); + p.deinit(); + try std.testing.expectEqual(@as(libc.pid_t, -1), libc.waitpid(pid, null, libc.W.NOHANG)); + try std.testing.expectEqual(libc.E.CHILD, libc.errno(-1)); +} + +test "a post of an older generation is passed over" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer core.deinit(); + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + var p: Ptys = .{ .queue = &queue, .prompt_rcs = undefined }; + p.gens[0] = 2; + p.output(core, .{ .pane = .at(0), .gen = 1, .bytes = try gpa.dupe(u8, "old session\n") }); + p.output(core, .{ .pane = .at(0), .gen = 2, .bytes = try gpa.dupe(u8, "current session\n") }); + const text = try pardes.Term.scrollback(core.panes[0].?.terminal, gpa); + defer gpa.free(text); + try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null); + try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null); +} diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index 9695bf83..c3272957 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -370,17 +370,6 @@ fn emitTouchClick(g: *const Gui, in: *Input, point: TouchNormPoint, button: pard in.post(.{ .mouse = .{ .button = button, .kind = .release, .col = cell.col, .row = cell.row, .tag_hit = cell.tag_hit, .body_hit = cell.body_hit } }); } -const Pty = struct { - fd: c_int, - pid: libc.pid_t, - serial: u32, - /// Its reader, blocked in an Io read: `closePty` cancels it. - reader: ?std.Io.Future(void) = null, - /// A command pane's child, watched to its exit (host_io.watchExit); - /// the pty stays open until both its end of file and its exit. - cmd: host_io.CommandWatch = .{}, -}; - const Queue = host_io.Inbox; /// Wakes a blocking SDL_WaitEventTimeout from another thread: a push to @@ -1027,9 +1016,6 @@ const Own = struct { g: *Gui, test_mode: bool, detached: bool, - ptys: [pardes.MAX_PANES]?Pty = @splat(null), - gens: [pardes.MAX_PANES]u32 = @splat(0), - queue: Queue = undefined, pipe_tasks: PipeTasks = .{}, inotify_fd: c_int = -1, watch_reader: ?std.Thread = null, @@ -1058,12 +1044,7 @@ const Own = struct { core.view().frontend.native_image_patches = true; observeGuiFont(g, core); syncTaglineFont(g, core); - o.queue = .{ - .io = l.io, - .gpa = l.gpa, - .lsp_allocator = l.allocs.lsp, - .wake_fn = sdlWake, - }; + l.inbox.wake_fn = sdlWake; o.inotify_fd = file_watch.init(true); o.shell = .{ .core = core, @@ -1071,10 +1052,8 @@ const Own = struct { .io = l.io, .gpa = l.gpa, .lsp_allocator = l.allocs.lsp, - .prompt_rcs = &l.prompt_rcs, - .ptys = &o.ptys, - .gens = &o.gens, - .queue = &o.queue, + .ptys = &l.ptys, + .queue = &l.inbox, .pipe_tasks = &o.pipe_tasks, .inotify_fd = o.inotify_fd, .watches = &o.watches, @@ -1102,7 +1081,6 @@ const Own = struct { host_io.setExitWake(null, null); pardes.lsp.setStatusSink(null, null); pardes.Kind.drawer = null; - o.shell.shutdownPtys(); o.shell.job_tasks.cancelAll(io); if (o.inotify_fd >= 0) { if (o.watch_reader) |thread| { @@ -1117,26 +1095,18 @@ const Own = struct { o.inotify_fd = -1; } o.pipe_tasks.cancelAll(io); - if (o.queue.lsp_task) |*task| task.future.cancel(io); + if (l.inbox.lsp_task) |*task| task.future.cancel(io); // Its worker may be waiting on the queue for room. l.core.stream.cancelTask(); - o.queue.deinit(); o.g.hit_core = null; } - pub fn resumePtys(o: *Own, rec: *const upgrade.Record) void { - o.shell.resumePtys(rec); - } - pub fn start(o: *Own, l: *Session) !void { - for (&o.ptys, 0..) |*slot, id| if (slot.*) |*pt| { - pt.reader = try o.queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, .at(id), o.gens[id]); - }; if (o.inotify_fd >= 0) { o.watch_stop = try stopPipe(); - o.watch_reader = try std.Thread.spawn(.{}, watchThread, .{ o.inotify_fd, o.watch_stop[0], &o.queue }); + o.watch_reader = try std.Thread.spawn(.{}, watchThread, .{ o.inotify_fd, o.watch_stop[0], &l.inbox }); } - if (l.fs) |f| try f.watch(&o.queue, wakeFs); + if (l.fs) |f| try f.watch(&l.inbox, wakeFs); _ = c.SDL_StartTextInput(o.g.window); // An upgraded session's window, its view's again. @@ -1144,8 +1114,8 @@ const Own = struct { if (o.test_mode) setStdinRaw() catch {}; o.shell.threads_ok = true; - pardes.lsp.setStatusSink(&o.queue, Queue.lspStatus); - host_io.setExitWake(&o.queue, Queue.wakeForExit); + pardes.lsp.setStatusSink(&l.inbox, Queue.lspStatus); + host_io.setExitWake(&l.inbox, Queue.wakeForExit); if (o.detached) { o.shell.closeTheWindow(); // Nothing else may wake the first wait. @@ -1169,10 +1139,9 @@ const Own = struct { pub fn restoring(o: *Own, nc: *pardes.Pardes) void { o.pipe_tasks.cancelAll(o.shell.io); - o.queue.discardCompletions(); + o.shell.queue.discardCompletions(); // One view, the window's (host_io.restoreCore). o.shell.gview = 0; - o.shell.stopPtys(); o.g.cells.clearImages(); o.g.prepared_images.clearRetainingCapacity(); nc.view().frontend.native_images = true; @@ -1498,13 +1467,11 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ window.loop = &loop; // A client spawns, watches and serves nothing: the Shell's tables are // empty ones, there for what draws. - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(0); var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = start.allocs.lsp, .wake_fn = sdlWake }; defer queue.deinit(); + var ptys: host_io.Ptys = .{ .queue = &queue, .prompt_rcs = undefined }; var pipe_tasks: PipeTasks = .{}; var watches: file_watch.Table = @splat(null); - const prompt_rcs: host_io.Shell.PromptFiles = .{}; var no_peers: replica.Peers = .{}; var shell: Shell = .{ .core = start.r.core(), @@ -1512,9 +1479,7 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ .io = io, .gpa = gpa, .lsp_allocator = start.allocs.lsp, - .prompt_rcs = &prompt_rcs, .ptys = &ptys, - .gens = &gens, .queue = &queue, .pipe_tasks = &pipe_tasks, .inotify_fd = -1, @@ -2434,16 +2399,13 @@ const Shell = struct { /// it). gui: ?*Gui = null, detached: ?*Gui = null, - /// Shells a dead session left (Adopt), each waiting for the spawn of - /// the terminal pane made for it. - adoptions: host_io.Adoptions = .{}, io: std.Io, gpa: std.mem.Allocator, fs: ?*ninep_io.Listener = null, lsp_allocator: std.mem.Allocator, - prompt_rcs: *const host_io.Shell.PromptFiles, - ptys: *[pardes.MAX_PANES]?Pty, - gens: *[pardes.MAX_PANES]u32, + /// The session's ptys (runtime/session.zig's), reading into `queue`; + /// a client's, an empty table. + ptys: *host_io.Ptys, queue: *Queue, /// What drainQueue takes each wakeup, kept rather than rebuilt. batch: Queue.Batch = .{}, @@ -2485,44 +2447,6 @@ const Shell = struct { took_input: bool = false, held: ?c.SDL_Event = null, - fn closePaneShell(ctx: ?*anyopaque, id: pardes.Pane.Id) void { - const pane = id.index(); - shellOf(ctx).closePty(pane); - } - - fn closePty(s: *Shell, pane: u8) void { - const pt = if (s.ptys[pane]) |*pt| pt else return; - // Out of the queue first, which lets go a reader waiting for room - // in it; then its read is canceled (or, at its end, it is joined). - s.queue.cancelReader(.at(pane), s.gens[pane]); - if (pt.reader) |*reader| { - reader.cancel(s.queue.io); // the Io it was started on (startReader) - pt.reader = null; - } - _ = libc.close(pt.fd); - daemon.closed(pt.pid); - host_io.retireShell(pt.pid); - s.ptys[pane] = null; - } - - fn stopPtys(s: *Shell) void { - for (0..s.ptys.len) |pane| s.closePty(@intCast(pane)); - for (s.gens) |*gen| gen.* +%= 1; - } - - fn shutdownPtys(s: *Shell) void { - s.stopPtys(); - host_io.waitRetired(); - } - - fn reconcilePtys(s: *Shell) void { - for (s.ptys, 0..) |slot, pane| if (slot) |pt| { - const current = s.core.panes[pane]; - if (current == null or current.?.serial != pt.serial or !current.?.isTerminal()) - s.closePty(@intCast(pane)); - }; - } - fn host(s: *Shell) pardes.Host { return .{ .ctx = s, .vtable = &vtable }; } @@ -2604,12 +2528,6 @@ const Shell = struct { return shellOf(ctx).gui != null; } - fn adopt(ctx: ?*anyopaque, id: pardes.Pane.Id) void { - const pane = id.index(); - const s = shellOf(ctx); - s.adoptions.ask(s.core, pane); - } - fn upgradeAsked(ctx: ?*anyopaque, id: pardes.Pane.Id) void { const pane = id.index(); const s = shellOf(ctx); @@ -2644,39 +2562,21 @@ const Shell = struct { // the readers stopped (a reader waiting for room has it then), and // what they pushed meanwhile drained. s.drainQueue(); - for (s.ptys) |*slot| if (slot.*) |*pt| if (pt.reader) |*r| { - r.cancel(s.queue.io); - pt.reader = null; - }; + s.ptys.pause(); s.drainQueue(); core.settle(); // Its replica clients told, their views gone before the dump: each // dials the session again once it is back. s.peers.refuseAll(core, "the session is upgrading to another build of pardes"); var rec: upgrade.Record = .{ .link = daemon.link, .window = s.gui != null, .exe = path }; - for (s.ptys, 0..) |slot, id| if (slot) |pt| if (pt.fd >= 0) rec.addPty(id, pt.pid, pt.fd); + s.ptys.record(&rec); var at_buf: [1024:0]u8 = undefined; const failed = upgrade.dumpInto(core, &rec, &at_buf, &why) orelse upgrade.execAs(s.gpa, path, &rec, &at_buf, s.fs, &why); // As it was: its ptys read on. - for (s.ptys, 0..) |*slot, id| if (slot.*) |*pt| if (pt.fd >= 0 and pt.reader == null) { - pt.reader = s.queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, .at(id), s.gens[id]) catch null; - }; + s.ptys.readOn(core); core.reportFailure(pane, failed); } - /// An upgraded session's shells, running on: each its pane's pty again, - /// or, when its dump would not load (`fresh`), adopted as new panes. - fn resumePtys(s: *Shell, rec: *const upgrade.Record) void { - for (rec.ptys[0..rec.nptys]) |k| { - const pane = if (rec.fresh) null else s.core.panes[k.pane]; - if (pane == null or !pane.?.isTerminal()) { - s.adoptions.adoptShell(s.core, k.pid, k.fd); - continue; - } - s.ptys[k.pane] = .{ .fd = k.fd, .pid = k.pid, .serial = pane.?.serial, .cmd = .{ .watched = pane.?.command != null and host_io.watchExit(k.pid), .fd = k.fd } }; - } - } - /// An upgraded session's window, its view's again; every other view /// but a replica client's, kept for its rejoin (views.away), closes. fn resumeWindow(s: *Shell) void { @@ -2695,16 +2595,16 @@ const Shell = struct { .poll_frame = pollFrame, .watched = watched, .detach = detachWindow, - .adopt = adopt, + .adopt = PtyCalls.adopt, .upgrade = upgradeAsked, - .spawn = spawnPane, - .pty_write = ptyWrite, - .pty_resize = ptyResize, - .pty_signal = ptySignal, - .close_pty = closePaneShell, - .tty_taken = ttyTaken, - .fg_name = fgName, - .kill_job = killJob, + .spawn = PtyCalls.spawn, + .pty_write = PtyCalls.write, + .pty_resize = PtyCalls.resize, + .pty_signal = PtyCalls.signal, + .close_pty = PtyCalls.close, + .tty_taken = PtyCalls.ttyTaken, + .fg_name = PtyCalls.fgName, + .kill_job = PtyCalls.killJob, .write_file = writeFile, .write_dump = writeDump, .watch_file = watchFile, @@ -2721,13 +2621,11 @@ const Shell = struct { .job = kindJob, }; + const PtyCalls = host_io.Ptys.Calls(Shell); + /// The command panes' exits, told once their output is in (host_io). fn takeExits(s: *Shell) void { - host_io.takeExits(s.core, s.ptys, s, closeWatched); - } - - fn closeWatched(s: *Shell, id: usize) void { - s.closePty(@intCast(id)); + s.ptys.takeExits(s.core); } /// A client's queue holds its draws alone: each landed for its pane's @@ -2745,7 +2643,6 @@ const Shell = struct { } fn drainQueue(s: *Shell) void { - s.reconcilePtys(); // After this batch's output, which an exit is told behind. defer s.takeExits(); s.queue.takeInto(&s.batch); @@ -2753,39 +2650,8 @@ const Shell = struct { if (msgs.len > 0) s.mail_only = false; var check_files = false; for (msgs.slice()) |m| switch (m) { - .output => |o| { - if (s.gens[o.pane.index()] == o.gen) - s.core.update(.{ .output = .{ .pane = o.pane, .bytes = o.bytes } }); - s.gpa.free(o.bytes); - }, - .eof => |e| { - if (s.gens[e.pane.index()] == e.gen) eof: { - if (e.failure) |err| { - s.closePty(e.pane.index()); - s.core.readerFailed(e.pane, err); - break :eof; - } - const pt = if (s.ptys[e.pane.index()]) |*pt| pt else { - s.core.update(.{ .eof = .{ .pane = e.pane } }); - break :eof; - }; - // A command's pty stays open until its child has exited: - // closing it would hang up one that runs on without it. - // Its exit, if it came first, is told now its output is in. - if (pt.cmd.watched) { - host_io.commandEof(s.core, s.ptys, e.pane.index(), s, closeWatched); - break :eof; - } - // Unwatched, a command's exit is read here, as its end, - // and a shell's, for a run waiting on it and the log. - const unwatched = if (s.core.panes[e.pane.index()]) |pane| pane.command != null else false; - const status = host_io.exitStatus(pt.pid, 100); - if (status != null) pt.pid = 0; // reaped: no shell to retire - s.closePty(e.pane.index()); - if (unwatched or status != null) s.core.update(.{ .exited = .{ .pane = e.pane, .status = status } }); - s.core.update(.{ .eof = .{ .pane = e.pane } }); - } - }, + .output => |o| s.ptys.output(s.core, o), + .eof => |e| s.ptys.eof(s.core, e), .lsp => |l| { s.core.update(.{ .lsp_resp = .{ .id = l.id, .rows = l.rows } }); if (l.rows) |rows| s.lsp_allocator.free(rows); @@ -2821,7 +2687,7 @@ const Shell = struct { .files_changed => check_files = true, .fs_ready => {}, .window => if (s.gui == null) s.openTheWindow(), - .adopted => |a| s.adoptions.adoptShell(s.core, a.pid, a.fd), + .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)) s.queue.push(.files_changed); @@ -3026,11 +2892,10 @@ fn waitDetached(core: *pardes.Pardes, timeout_ms: u32) void { fn pollFrame(ctx: ?*anyopaque) void { const s = shellOf(ctx); - s.reconcilePtys(); const core = s.core; if (s.fs) |f| if (f.tick().pending) s.queue.push(.fs_ready); // The authority owns its terminals even with its window closed. - pollCwds(core, s.ptys); + s.ptys.pollCwds(core); const g = s.gui orelse { if (core.settings.window_opacity_pending) { var unchanged_opacity: u8 = 100; @@ -3330,56 +3195,6 @@ fn guiNow(ctx: ?*anyopaque) u64 { return s.test_clock orelse s.paced_ns orelse c.SDL_GetTicksNS(); } -fn spawnPane(ctx: ?*anyopaque, id: pardes.Pane.Id, cwd: []const u8) void { - const pane = id.index(); - const s = shellOf(ctx); - if (s.adoptions.take(id)) |a| return takeShell(s, pane, a); - // The new shell starts before a running one goes: one that cannot - // start leaves the running one be (pty/ctl's exec). - const running = s.ptys[pane] != null; - const child = host_io.forkShell(s.core, pane, s.prompt_rcs, s.core.shellBin(), cwd, s.core.view().screen_h, s.core.view().screen_w) catch |err| { - if (running) return s.core.restartFailed(id, err); - return s.core.shellFailed(id, err); - }; - s.closePty(pane); - if (s.ptys[pane] != null) { - _ = libc.close(child.file.handle); - host_io.retireShell(child.pid); - return s.core.reportError(id, "shell", error.WorkersBusy); - } - s.gens[pane] +%= 1; - const command = s.core.panes[pane].?.command != null; - const pt: Pty = .{ .fd = child.file.handle, .pid = child.pid, .serial = s.core.panes[pane].?.serial, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } }; - s.ptys[pane] = pt; - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.shellCwd(pt.pid, &lbuf)) |wd| s.core.setCwd(id, wd); - if (!s.threads_ok) return; - s.ptys[pane].?.reader = s.queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, id, s.gens[pane]) catch |err| { - s.closePty(pane); - return s.core.reportError(id, "terminal reader", err); - }; -} - -/// An adopted shell, running already, as pane `pane`'s: told the size twice -/// (one it never had, then the pane's), which makes it redraw. -fn takeShell(s: *Shell, pane: u8, a: host_io.Adoption) void { - s.closePty(pane); - s.gens[pane] +%= 1; - s.ptys[pane] = .{ .fd = a.fd, .pid = a.pid, .serial = s.core.panes[pane].?.serial, .cmd = .{} }; - var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - s.core.acknowledgeShell(.at(pane), host_io.processExe(a.pid, &exe_buf) orelse "sh", host_io.marksPrompts(a.pid)); - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.shellCwd(a.pid, &lbuf)) |wd| s.core.setCwd(.at(pane), wd); - const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 }; - _ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny)); - if (s.core.panes[pane]) |pn| ptyResize(s, .at(pane), @max(pn.cols, 1), @max(pn.rows, 1)); - if (!s.threads_ok) return; - s.ptys[pane].?.reader = s.queue.startReader(.{ .handle = a.fd, .flags = .{ .nonblocking = false } }, .at(pane), s.gens[pane]) catch |err| { - s.closePty(pane); - return s.core.reportError(.at(pane), "terminal reader", err); - }; -} - /// The daemon's thread: what it says, onto the queue (drainQueue). fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { const s: *Shell = @ptrCast(@alignCast(ctx)); @@ -3401,49 +3216,6 @@ fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { } } -fn ptyWrite(ctx: ?*anyopaque, id: pardes.Pane.Id, bytes: []const u8) void { - const pane = id.index(); - const s = shellOf(ctx); - if (s.ptys[pane]) |pt| _ = host_io.writeFd(pt.fd, bytes); -} - -fn ptyResize(ctx: ?*anyopaque, id: pardes.Pane.Id, cols: u16, rows: u16) void { - const pane = id.index(); - const s = shellOf(ctx); - if (s.ptys[pane]) |pt| { - const ws = host_io.ptyWinsize(s.core, cols, rows); - _ = posix.system.ioctl(pt.fd, TIOCSWINSZ, @intFromPtr(&ws)); - } -} - -fn ptySignal(ctx: ?*anyopaque, id: pardes.Pane.Id, sig: pardes.PtySignal) void { - const pane = id.index(); - const s = shellOf(ctx); - // A command whose exit is recorded is reaped: its group may be another's. - if (s.ptys[pane]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.fd, sig, pt.cmd.watched); -} - -fn ttyTaken(ctx: ?*anyopaque, id: pardes.Pane.Id) bool { - const pane = id.index(); - const s = shellOf(ctx); - const pt = s.ptys[pane] orelse return false; - return host_io.ttyTaken(pt.pid, pt.fd); -} - -fn fgName(ctx: ?*anyopaque, id: pardes.Pane.Id, buf: []u8) ?[]const u8 { - const pane = id.index(); - const s = shellOf(ctx); - const pt = s.ptys[pane] orelse return null; - return host_io.foregroundName(pt.pid, pt.fd, buf); -} - -fn killJob(ctx: ?*anyopaque, id: pardes.Pane.Id) bool { - const pane = id.index(); - const s = shellOf(ctx); - const pt = s.ptys[pane] orelse return false; - return host_io.killJob(pt.pid, pt.fd); -} - fn writeFile(ctx: ?*anyopaque, id: pardes.Pane.Id, path: []const u8, bytes: []const u8) void { const pane = id.index(); const s = shellOf(ctx); @@ -3590,13 +3362,6 @@ fn handOver(ctx: ?*anyopaque, seq: u32, bytes: []const u8) void { }; } -fn pollCwds(core: *pardes.Pardes, ptys: *[pardes.MAX_PANES]?Pty) void { - for (ptys, 0..) |slot, id| if (slot) |pt| { - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.ttyCwd(pt.pid, pt.fd, core.settings.shell.effective.get(), &lbuf)) |cwd| core.setCwd(.at(id), cwd); - }; -} - fn accumulateWheelDelta(pending: f32, raw_y: f32) f32 { if (!std.math.isFinite(raw_y)) return pending; const next = pending - raw_y; @@ -6276,129 +6041,6 @@ test "installed Nerd Symbols fallback covers Yazi directory icons" { try std.testing.expect(atlas.glyphForCodepoint(0xe5ff).glyph != 0); } -test "GUI PTY reader delivers a real shell tail before EOF and joins on close" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(1); - var shell: Shell = undefined; - shell.core = core; - shell.gpa = gpa; - shell.ptys = &ptys; - shell.gens = &gens; - shell.queue = &queue; - defer shell.shutdownPtys(); - const rcs: host_io.Shell.PromptFiles = .{}; - const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); - ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; - ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, .at(0), 1); - try std.testing.expect(host_io.writeFd(child.file.handle, "printf '\\120\\101\\122\\104\\105\\123\\055\\124\\101\\111\\114'; exit\n")); - var bytes: std.ArrayList(u8) = .empty; - defer bytes.deinit(gpa); - var eof = false; - const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000; - while (!eof and std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) { - var batch = queue.take(); - defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); - for (batch.slice()) |msg| switch (msg) { - .output => |o| { - try std.testing.expect(!eof); - try bytes.appendSlice(gpa, o.bytes); - }, - .eof => |e| { - try std.testing.expect(e.failure == null); - eof = true; - }, - else => return error.UnexpectedMessage, - }; - if (!eof) try std.testing.io.sleep(.fromMilliseconds(1), .awake); - } - try std.testing.expect(eof); - try std.testing.expect(std.mem.indexOf(u8, bytes.items, "PARDES-TAIL") != null); - shell.closePty(0); - try std.testing.expect(queue.readers[0] == null); - try std.testing.expect(ptys[0] == null or ptys[0].?.reader == null); - try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD)); -} - -test "GUI PTY Restore joins a real reader waiting for queue space" { - const gpa = std.testing.allocator; - var core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - try dump.dumpState(core); - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - queue.acceptReader(.at(1), 1); - for (0..output_capacity) |_| queue.push(.{ .output = .{ .pane = .at(1), .gen = 1, .bytes = try gpa.dupe(u8, "other pane") } }); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(1); - var shell: Shell = undefined; - shell.core = core; - shell.gpa = gpa; - shell.ptys = &ptys; - shell.gens = &gens; - shell.queue = &queue; - defer shell.shutdownPtys(); - const rcs: host_io.Shell.PromptFiles = .{}; - const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); - ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; - ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, .at(0), 1); - try std.testing.expect(host_io.writeFd(child.file.handle, "printf 'after-full'; exit\n")); - try host_io.PtyTests.waitBlocked(&queue); - const old_serial = core.panes[0].?.serial; - const replacement = try dump.restore(core, core.dump_out.?, "test"); - shell.stopPtys(); - core.deinit(); - core = replacement; - shell.core = replacement; - // The dump's pane, its serial too; its old shell stopped all the same. - try std.testing.expectEqual(old_serial, core.panes[0].?.serial); - try std.testing.expectEqual(@as(usize, 0), queue.waiting); - try std.testing.expect(queue.readers[0] == null); - try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD)); - queue.cancelReader(.at(1), 1); - queue.acceptReader(.at(0), gens[0]); - queue.push(.{ .eof = .{ .pane = .at(0), .gen = 1 } }); - try std.testing.expect(queue.pushOutput(.at(0), gens[0], try gpa.dupe(u8, "fresh"))); - var batch = queue.take(); - defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); - try std.testing.expectEqual(@as(usize, 1), batch.len); - try std.testing.expectEqualStrings("fresh", batch.items[0].output.bytes); -} - -test "GUI PTY deletion joins an idle reader and its shell is reaped by exit" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(1); - var shell: Shell = undefined; - shell.core = core; - shell.gpa = gpa; - shell.ptys = &ptys; - shell.gens = &gens; - shell.queue = &queue; - defer shell.shutdownPtys(); - const rcs: host_io.Shell.PromptFiles = .{}; - const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); - ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; - ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, .at(0), 1); - try core.removePane(0, null); - shell.reconcilePtys(); - try std.testing.expect(queue.readers[0] == null); - try std.testing.expectEqual(@as(usize, 0), queue.waiting); - try std.testing.expectEqual(@as(usize, 0), queue.take().len); - try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD)); - shell.shutdownPtys(); - try std.testing.expectEqual(@as(libc.pid_t, -1), libc.waitpid(child.pid, null, libc.W.NOHANG)); - try std.testing.expectEqual(libc.E.CHILD, libc.errno(-1)); -} - test "GUI PTY file watcher stops and joins without closing its watched descriptor" { if (!file_watch.supported) return error.SkipZigTest; const gpa = std.testing.allocator; @@ -6435,14 +6077,12 @@ test "GUI completion failure survives backlog and leaves the document unchanged" .bytes = try gpa.dupe(u8, "output"), } }); queue.push(.{ .lsp = .{ .id = id, .rows = null } }); - var gens: [pardes.MAX_PANES]u32 = @splat(1); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); + var ptys: host_io.Ptys = .{ .queue = &queue, .prompt_rcs = undefined, .gens = @splat(1) }; var shell: Shell = undefined; shell.core = core; shell.queue = &queue; shell.gpa = gpa; shell.lsp_allocator = gpa; - shell.gens = &gens; shell.ptys = &ptys; shell.drainQueue(); try std.testing.expect(core.lsp_ask.wait == null); @@ -8165,16 +7805,15 @@ test "a detached GUI authority follows terminal directory changes with no window _ = core.settings.shell.effective.set("/bin/sh"); var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = gpa }; defer queue.deinit(); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(1); const rcs: host_io.Shell.PromptFiles = .{}; + var ptys: host_io.Ptys = .{ .queue = &queue, .prompt_rcs = &rcs, .gens = @splat(1) }; + defer ptys.deinit(); var pipes: PipeTasks = .{}; var watches: file_watch.Table = @splat(null); var no_peers: replica.Peers = .{}; - var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .prompt_rcs = &rcs, .ptys = &ptys, .gens = &gens, .queue = &queue, .pipe_tasks = &pipes, .inotify_fd = -1, .watches = &watches, .peers = &no_peers }; - defer shell.shutdownPtys(); + var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .ptys = &ptys, .queue = &queue, .pipe_tasks = &pipes, .inotify_fd = -1, .watches = &watches, .peers = &no_peers }; const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); - ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; + ptys.slots[0] = .{ .fd = child.file.handle, .pid = child.pid }; try std.testing.expect(host_io.writeFd(child.file.handle, "cd child\n")); const until = std.Io.Clock.awake.now(io).toMilliseconds() + 2_000; var actual: [4096]u8 = undefined; diff --git a/dev/host_io.zig b/dev/host_io.zig index f86c3250..5465fc7a 100644 --- a/dev/host_io.zig +++ b/dev/host_io.zig @@ -197,6 +197,8 @@ pub const Fallback = struct { /// a language query since superseded, are dropped here. pub const Inbox = @import("Inbox.zig"); +pub const Ptys = @import("Ptys.zig"); + pub const Lsp = @import("Lsp.zig"); pub const Shell = @import("Shell.zig"); diff --git a/dev/root.zig b/dev/root.zig index fc3ccfa8..fb1d1ad9 100644 --- a/dev/root.zig +++ b/dev/root.zig @@ -30,5 +30,6 @@ test { if (comptime @import("pardes_options").platform == .tui) _ = tui; if (comptime @import("pardes_options").platform == .gui) _ = gui; _ = vaxis_input; + _ = host_io.Ptys; } } diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index d7ea8ed6..5c1945e6 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -116,8 +116,6 @@ const Msg = union(enum) { /// A SIGHUP: the session's own terminal hung up. hangup, key_press: vaxis.Key, - pty_read: struct { id: usize, gen: u32, bytes: []u8 }, - pty_eof: struct { id: usize, gen: u32 }, winsize: vaxis.Winsize, mouse: vaxis.Mouse, focus_in, @@ -379,15 +377,6 @@ const TestReader = struct { const PipeTasks = selection_pipe.Tasks; -const Pty = struct { - file: std.Io.File, - pid: posix.pid_t, - reader: std.Io.Future(error{OutOfMemory}!void), - /// A command pane's child, watched to its exit (host_io.watchExit); - /// the pty stays open until both its end of file and its exit. - cmd: host_io.CommandWatch = .{}, -}; - /// A watched child exited: wake the loop, which takes it (`takeExits`). fn wakeForExit(ctx: ?*anyopaque) void { const loop: *Loop = @ptrCast(@alignCast(ctx.?)); @@ -776,15 +765,18 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, var tty: Tty = undefined; var c = try Client.init(&tty, &start); defer c.link.deinit(gpa); - // A client has no clients of its own. + // A client has no clients of its own, and spawns nothing: its pty + // table an empty one over an empty queue. var no_peers: replica.Peers = .{}; + var no_inbox: host_io.Inbox = .{ .io = io, .gpa = gpa, .lsp_allocator = start.allocs.lsp }; + defer no_inbox.deinit(); + var no_ptys: host_io.Ptys = .{ .queue = &no_inbox, .prompt_rcs = undefined }; var sh: Shell = .{ .io = io, .gpa = gpa, .lsp_gpa = start.allocs.lsp, .core = start.r.core(), .frames = &start.frames, - .prompt_rcs = undefined, .loop = &loop, .frame = &frame_arena, .paste_buf = &paste_buf, @@ -793,6 +785,7 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, .screen = &screen, .client = &c, .peers = &no_peers, + .ptys = &no_ptys, }; tty = .{ .sh = &sh, .screen = &screen, .loop = &loop, .joins = &start }; @@ -961,7 +954,6 @@ const Own = struct { .lsp_gpa = l.allocs.lsp, .core = l.core, .frames = &l.frames, - .prompt_rcs = &l.prompt_rcs, .loop = o.loop, .frame = &o.frame_arena, .paste_buf = o.paste_buf, @@ -969,9 +961,12 @@ const Own = struct { .fs = l.fs, .test_clock = host_io.testClock(), .peers = &l.peers, + .ptys = &l.ptys, }; const sh = &o.sh; sh.screen = o.screen; + l.inbox.wake_fn = Shell.wakeForQueue; + l.inbox.wake_ctx = sh; l.peers.wake_ctx = o.loop; l.peers.wake = wakeForReplica; pardes.lsp.setStatusSink(sh, lspStatusSink); @@ -997,12 +992,6 @@ const Own = struct { pardes.Kind.drawer = null; host_io.setExitWake(null, null); pardes.lsp.setStatusSink(null, null); - for (&sh.ptys) |*slot| if (slot.*) |*pt| { - pt.reader.cancel(io) catch {}; - _ = libc.close(pt.file.handle); - slot.* = null; - }; - for (sh.adoptions.list[0..sh.adoptions.len]) |a| _ = libc.close(a.fd); if (sh.lsp_task) |*t| { t.future.cancel(io); sh.lsp_task = null; @@ -1021,10 +1010,6 @@ const Own = struct { sh.inotify_fd = -1; } while (loop.tryEvent() catch null) |ev| switch (ev) { - .pty_read => |pr| { - tookRead(io, pr.id); - gpa.free(pr.bytes); - }, .paste => |b| gpa.free(@constCast(b)), .lsp_done => |d| if (d.rows) |rows| sh.lsp_gpa.free(rows), .lsp_status => |text| sh.lsp_gpa.free(text), @@ -1046,10 +1031,6 @@ const Own = struct { o.frame_arena.deinit(); } - pub fn resumePtys(o: *Own, rec: *const upgrade.Record) void { - o.sh.resumePtys(rec); - } - pub fn start(o: *Own, l: *Session) !void { const io = l.io; const sh = &o.sh; @@ -1064,9 +1045,6 @@ const Own = struct { if (!screen.on) l.watch(); sh.threads_ok = true; - for (&sh.ptys, 0..) |*slot, id| if (slot.*) |*pt| { - pt.reader = try io.concurrent(readPty, .{ io, l.gpa, pt.file, id, sh.gens[id], loop }); - }; if (sh.inotify_fd >= 0) sh.watch_task = io.concurrent(watchFiles, .{ io, sh.inotify_fd, loop }) catch null; } @@ -1098,8 +1076,6 @@ const Own = struct { sh.lsp_task = null; } sh.pipe_tasks.cancelAll(io); - for (&sh.gens) |*generation| generation.* +%= 1; - for (0..pardes.MAX_PANES) |pane| Shell.closePty(sh, .at(pane)); // One view, the terminal's (host_io.restoreCore). const live = o.screen; stopInput(io, &live.thread); @@ -1167,7 +1143,6 @@ const Shell = struct { /// Its runner's frame timings (Pardes.frames): written as it draws and /// takes input, never through the core. frames: *pardes.FrameStats, - prompt_rcs: *const host_io.Shell.PromptFiles, loop: *Loop, /// The terminal (none in tests), and the view it shows: a second /// terminal on the session is a replica client (`pardes --attach`). @@ -1176,12 +1151,16 @@ const Shell = struct { frame: *std.heap.ArenaAllocator, paste_buf: *std.Io.Writer.Allocating, inotify_fd: c_int, - /// Shells a dead session left (Adopt), each waiting for the spawn of - /// the terminal pane made for it. - adoptions: host_io.Adoptions = .{}, fs: ?*ninep_io.Listener = null, - ptys: [pardes.MAX_PANES]?Pty = @splat(null), - gens: [pardes.MAX_PANES]u32 = @splat(0), + /// The session's ptys (runtime/session.zig's); a client's, an empty + /// table over an empty queue. + ptys: *host_io.Ptys, + /// What `takeQueue` takes off the ptys' queue, and whether the loop + /// was woken for it since it last did (one wake, not one a read ahead + /// of the terminal's keys in the loop's queue). + batch: host_io.Inbox.Batch = .{}, + batch_at: usize = 0, + queue_woken: std.atomic.Value(bool) = .init(false), watches: file_watch.Table = @splat(null), watch_task: ?std.Io.Future(void) = null, lsp_task: ?host_io.Lsp.Task = null, @@ -1207,8 +1186,6 @@ const Shell = struct { focused_ns: u64 = 0, /// Upgrade was asked from this pane, to be done between steps (`upgradeNow`). upgrade_asked: ?u8 = null, - /// Its pty readers stopped for it: their end of file is not a shell's. - upgrading: bool = false, /// The session's replica clients (core/replica.zig), on sockets: the /// session loop's (runtime/session.zig); a client's, none. peers: *replica.Peers, @@ -1272,16 +1249,16 @@ const Shell = struct { .poll_frame = pollFrame, .watched = watched, .detach = detach, - .adopt = adopt, + .adopt = PtyCalls.adopt, .upgrade = upgradeAsked, - .spawn = spawn, - .pty_write = ptyWrite, - .pty_resize = ptyResize, - .pty_signal = ptySignal, - .close_pty = closePty, - .tty_taken = ttyTaken, - .fg_name = fgName, - .kill_job = killJob, + .spawn = PtyCalls.spawn, + .pty_write = PtyCalls.write, + .pty_resize = PtyCalls.resize, + .pty_signal = PtyCalls.signal, + .close_pty = PtyCalls.close, + .tty_taken = PtyCalls.ttyTaken, + .fg_name = PtyCalls.fgName, + .kill_job = PtyCalls.killJob, .write_file = writeFile, .write_dump = writeDump, .watch_file = watchFile, @@ -1385,11 +1362,7 @@ const Shell = struct { if (stub >= 0) daemon.tellStub(stub, "r{s}", .{why}); } - fn adopt(ctx: ?*anyopaque, id: pardes.Pane.Id) void { - const pane = id.index(); - const s = of(ctx); - s.adoptions.ask(s.core, pane); - } + const PtyCalls = host_io.Ptys.Calls(Shell); fn upgradeAsked(ctx: ?*anyopaque, id: pardes.Pane.Id) void { const pane = id.index(); @@ -1418,18 +1391,19 @@ const Shell = struct { .ok => {}, } // Nothing more read from a pty or a terminal, and what was read - // goes in; a reader's cancel posts an end of file, passed over. - s.upgrading = true; - defer s.upgrading = false; - for (&s.ptys) |*slot| if (slot.*) |*pt| pt.reader.cancel(s.io) catch {}; + // goes in: taken, the readers stopped (one waiting for room has it + // then), and what they posted meanwhile taken. + s.takeAll(); + s.ptys.pause(); if (s.screen) |sc| stopInput(s.io, &sc.thread); while (s.loop.tryEvent() catch null) |ev| _ = s.apply(ev); + s.takeAll(); core.settle(); // Its replica clients told, their views gone before the dump: each // dials the session again once it is back. s.peers.refuseAll(core, "the session is upgrading to another build of pardes"); var rec: upgrade.Record = .{ .link = daemon.link, .stub = daemon.stub, .exe = path }; - for (s.ptys, 0..) |slot, id| if (slot) |pt| rec.addPty(id, pt.pid, pt.file.handle); + s.ptys.record(&rec); if (s.screen) |sc| if (sc.on) rec.addTty(.{ .view = s.own, .fd = sc.tty.fd.handle, @@ -1453,9 +1427,7 @@ const Shell = struct { break :failed upgrade.execAs(s.gpa, path, &rec, &at_buf, s.fs, &why); }; // As it was: its ptys read on, its terminals' keys as they were. - for (&s.ptys, 0..) |*slot, id| if (slot.*) |*pt| { - pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, id, s.gens[id], s.loop }) catch pt.reader; - }; + s.ptys.readOn(core); if (s.screen) |sc| if (sc.on) { if (popped) sc.vx.enableDetectedFeatures(sc.tty.writer()) catch {}; startInput(s.loop, sc) catch {}; @@ -1463,20 +1435,6 @@ const Shell = struct { core.reportFailure(pane, failed); } - /// An upgraded session's shells, running on: each its pane's pty again, - /// or, when its dump would not load (`fresh`), adopted as new panes. - fn resumePtys(s: *Shell, rec: *const upgrade.Record) void { - for (rec.ptys[0..rec.nptys]) |k| { - const pane = if (rec.fresh) null else s.core.panes[k.pane]; - if (pane == null or !pane.?.isTerminal()) { - s.adoptions.adoptShell(s.core, k.pid, k.fd); - continue; - } - const file: std.Io.File = .{ .handle = k.fd, .flags = .{ .nonblocking = false } }; - s.ptys[k.pane] = .{ .file = file, .pid = k.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{ .watched = pane.?.command != null and host_io.watchExit(k.pid), .fd = k.fd } }; - } - } - /// An upgraded session's terminal, its view's again (`primary`, run's, /// entered already); every other view but a replica client's, kept for /// its rejoin (views.away), closes. A terminal another build kept for a @@ -1614,9 +1572,16 @@ const Shell = struct { batch += 1; } if (motion) |m| _ = s.apply(m); + // The ptys' output, after the terminal's input of this wait (which + // is never queued behind it; with clients, an input after output + // is held for the next wait: `split`). + s.takeQueue(); // An exit's wake (a .nop) or output an exit waited behind: told - // here, inside the step, so the frame after it shows it. - s.takeExits(); + // here, inside the step, so the frame after it shows it; not while + // reads taken off the queue wait their steps (`takeQueue`): one of + // them may be the command's own last output, which its exit would + // be drawn above (CommandWatch.due cannot see it). + if (s.batch_at == s.batch.len) s.takeExits(); s.reloadWatched(); } @@ -1628,10 +1593,6 @@ const Shell = struct { fn split(s: *Shell, ev: Msg) bool { if (!s.peers.recording) return false; switch (ev) { - .pty_read => { - s.took_output = true; - return false; - }, .key_press => if (s.in_paste) return false, .mouse, .paste, .paste_end, .winsize, .focus_in, .focus_out => {}, else => return false, @@ -1702,7 +1663,7 @@ const Shell = struct { return true; }, .attach => |a| s.attachTerminal(a.tty, a.stub, null), - .adopted => |a| s.adoptions.adoptShell(s.core, a.pid, a.fd), + .adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd), .replica => |j| { s.peers.handed(j.fd, j.view); s.input_seen = true; @@ -1741,38 +1702,6 @@ const Shell = struct { s.feed(.{ .focus = false }); }, .winsize => |ws| if (!s.detached()) s.resized(s.screen, ws), - .pty_read => |pr| { - tookRead(s.io, pr.id); - s.output_seen = true; - if (pr.id == core.view().active) s.focused_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - if (s.gens[pr.id] == pr.gen) - core.update(.{ .output = .{ .pane = .at(pr.id), .bytes = pr.bytes } }); - s.gpa.free(pr.bytes); - // An exit waiting behind this output may be told now. - s.takeExits(); - return true; - }, - .pty_eof => |e| if (s.gens[e.id] == e.gen and !s.upgrading) { - if (s.ptys[e.id]) |*pt| { - pt.reader.await(s.io) catch {}; // reader just finished; join it or its future leaks - // A command's pty stays open until its child has exited: - // closing it would hang up one that runs on without it. - // Its exit, if it came first, is told now its output is in. - if (pt.cmd.watched) { - host_io.commandEof(core, &s.ptys, e.id, s, closeWatched); - return true; - } - _ = libc.close(pt.file.handle); - // Unwatched, a command's exit is read here, as its end, - // and a shell's, for a run waiting on it and the log. - const command = if (core.panes[e.id]) |pn| pn.command != null else false; - const status = host_io.exitStatus(pt.pid, 100); - if (status == null) host_io.retireShell(pt.pid); - s.ptys[e.id] = null; - if (command or status != null) core.update(.{ .exited = .{ .pane = .at(e.id), .status = status } }); - } - core.update(.{ .eof = .{ .pane = .at(e.id) } }); - }, .key_press => |key| if (s.in_paste) { const bytes = vaxis_input.pasteBytes(key); const room = max_paste_bytes -| s.paste_buf.written().len; @@ -1881,10 +1810,7 @@ const Shell = struct { if (s.fs) |f| if (f.tick().pending) { _ = s.loop.tryPostEvent(.fs_ready) catch {}; }; - for (&s.ptys, 0..) |*slot, id| if (slot.*) |pt| { - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.ttyCwd(pt.pid, pt.file.handle, s.core.settings.shell.effective.get(), &lbuf)) |cwd| s.core.setCwd(.at(id), cwd); - }; + s.ptys.pollCwds(s.core); const sc = s.term() orelse return; s.core.view().frontend.native_image_patches = sc.feed.shm.load(.acquire); @@ -2026,120 +1952,59 @@ const Shell = struct { tracy.frameMark(); } - fn spawn(ctx: ?*anyopaque, id: pardes.Pane.Id, cwd: []const u8) void { - const pane = id.index(); - const s = of(ctx); - if (s.adoptions.take(id)) |a| return s.takeShell(pane, a); - // The new shell starts before a running one goes: one that cannot - // start leaves the running one be (pty/ctl's exec). - const running = s.ptys[pane] != null; - const child = host_io.forkShell(s.core, pane, s.prompt_rcs, s.core.shellBin(), cwd, s.core.view().screen_h, s.core.view().screen_w) catch |err| { - if (running) return s.core.restartFailed(id, err); - return s.core.shellFailed(id, err); - }; - closePty(ctx, id); // a shell still in the slot goes, reaped - s.gens[pane] +%= 1; - const command = if (s.core.panes[pane]) |pn| pn.command != null else false; - s.ptys[pane] = .{ .file = child.file, .pid = child.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } }; - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - // Only a shell given no directory is asked where it is: one given a - // directory is named by it already (newShell), and asked now, before - // its chdir, it would answer this process's, a rename to undo. - if (cwd.len == 0) if (host_io.shellCwd(child.pid, &lbuf)) |wd| s.core.setCwd(id, wd); - if (s.threads_ok) { - if (s.ptys[pane]) |*pt| { - pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader; - } - } - } - - /// An adopted shell, running already, as pane `pane`'s: told the size - /// twice (a size it never had, then the pane's), which makes it redraw. - fn takeShell(s: *Shell, pane: u8, a: host_io.Adoption) void { - closePty(s, .at(pane)); - s.gens[pane] +%= 1; - const file: std.Io.File = .{ .handle = a.fd, .flags = .{ .nonblocking = false } }; - s.ptys[pane] = .{ .file = file, .pid = a.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{} }; - var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - s.core.acknowledgeShell(.at(pane), host_io.processExe(a.pid, &exe_buf) orelse "sh", host_io.marksPrompts(a.pid)); - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.shellCwd(a.pid, &lbuf)) |wd| s.core.setCwd(.at(pane), wd); - const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 }; - _ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny)); - if (s.core.panes[pane]) |pn| ptyResize(s, .at(pane), @max(pn.cols, 1), @max(pn.rows, 1)); - if (s.threads_ok) if (s.ptys[pane]) |*pt| { - pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader; - }; + /// The command panes' exits, told once their output is in (host_io). + fn takeExits(s: *Shell) void { + s.ptys.takeExits(s.core); } - fn ptyWrite(ctx: ?*anyopaque, id: pardes.Pane.Id, bytes: []const u8) void { - const pane = id.index(); + /// A post to the session's queue (Inbox.wake, any thread): the loop + /// woken, once until it takes them. + fn wakeForQueue(ctx: ?*anyopaque) void { const s = of(ctx); - if (s.ptys[pane]) |pt| _ = host_io.writeFd(pt.file.handle, bytes); + if (s.queue_woken.swap(true, .acq_rel)) return; + // A full queue is taken soon anyway, and the post with it. + if (!(s.loop.tryPostEvent(.nop) catch false)) s.queue_woken.store(false, .release); } - fn ptyResize(ctx: ?*anyopaque, id: pardes.Pane.Id, cols: u16, rows: u16) void { - const pane = id.index(); - const s = of(ctx); - if (s.ptys[pane]) |pt| { - const ws = host_io.ptyWinsize(s.core, cols, rows); - _ = posix.system.ioctl(pt.file.handle, TIOCSWINSZ, @intFromPtr(&ws)); + /// What the session's queue holds: its ptys' output (`waitInput` + /// paces it; the focused pane's is its echo) and their ends of file. + /// A read a step, as the terminal's own queue gave them: the frame + /// after one shows it before what came after it (a command's last line + /// before its exit scrolls it away), the rest kept for the next wait. + fn takeQueue(s: *Shell) void { + while (true) { + if (s.batch_at == s.batch.len) { + s.queue_woken.store(false, .release); + s.ptys.queue.takeInto(&s.batch); + s.batch_at = 0; + if (s.batch.len == 0) return; + } + const m = s.batch.items[s.batch_at]; + s.batch_at += 1; + switch (m) { + .output => |o| { + s.output_seen = true; + s.mail_only = false; + if (s.peers.recording) s.took_output = true; + if (o.pane.index() == s.core.view().active) s.focused_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + s.ptys.output(s.core, o); + // The next wait takes the rest (a wake its own: the + // one a post made may be taken already). + _ = s.loop.tryPostEvent(.nop) catch {}; + return; + }, + .eof => |e| s.ptys.eof(s.core, e), + else => m.deinit(s.gpa, s.lsp_gpa), + } } } - fn ptySignal(ctx: ?*anyopaque, id: pardes.Pane.Id, sig: pardes.PtySignal) void { - const pane = id.index(); - const s = of(ctx); - // A command whose exit is recorded is reaped: its group may be - // another's by now. - if (s.ptys[pane]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.file.handle, sig, pt.cmd.watched); - } - - /// The pane is gone: hang its pty up, which the kernel passes on to the - /// shell as SIGHUP, and retire the shell. Output still in flight - /// carries the old generation and is dropped. - fn closePty(ctx: ?*anyopaque, id: pardes.Pane.Id) void { - const pane = id.index(); - const s = of(ctx); - var pt = s.ptys[pane] orelse return; - s.ptys[pane] = null; - s.gens[pane] +%= 1; - pt.reader.cancel(s.io) catch {}; - _ = libc.close(pt.file.handle); - daemon.closed(pt.pid); - host_io.retireShell(pt.pid); - } - - fn ttyTaken(ctx: ?*anyopaque, id: pardes.Pane.Id) bool { - const pane = id.index(); - const s = of(ctx); - const pt = s.ptys[pane] orelse return false; - return host_io.ttyTaken(pt.pid, pt.file.handle); - } - - fn fgName(ctx: ?*anyopaque, id: pardes.Pane.Id, buf: []u8) ?[]const u8 { - const pane = id.index(); - const s = of(ctx); - const pt = s.ptys[pane] orelse return null; - return host_io.foregroundName(pt.pid, pt.file.handle, buf); - } - - /// The command panes' exits, told once their output is in (host_io). - fn takeExits(s: *@This()) void { - host_io.takeExits(s.core, &s.ptys, s, closeWatched); - } - - fn closeWatched(s: *@This(), id: usize) void { - const pt = &(s.ptys[id] orelse return); - _ = libc.close(pt.file.handle); - s.ptys[id] = null; - } - - fn killJob(ctx: ?*anyopaque, id: pardes.Pane.Id) bool { - const pane = id.index(); - const s = of(ctx); - const pt = s.ptys[pane] orelse return false; - return host_io.killJob(pt.pid, pt.file.handle); + /// Everything queued taken (an Upgrade's). + fn takeAll(s: *Shell) void { + while (true) { + s.takeQueue(); + if (s.batch.len == 0) return; + } } fn writeFile(ctx: ?*anyopaque, id: pardes.Pane.Id, path: []const u8, bytes: []const u8) void { @@ -2351,44 +2216,6 @@ fn wakeFs(ctx: ?*anyopaque) void { _ = loop.tryPostEvent(.fs_ready) catch {}; } -/// Each pane's reads posted and not yet taken in. Two at most: a flood the -/// loop cannot keep up with waits in its pty, not in the queue ahead of a -/// key and its echo (hundreds of 4 KB reads queued were half a second). -var reads_queued: [pardes.MAX_PANES]std.atomic.Value(u32) = @splat(.init(0)); - -/// A read of pane `id` taken in (or dropped): its reader may read on. Never -/// below zero, for an event no reader posted (a test's). -fn tookRead(io: std.Io, id: usize) void { - var queued = reads_queued[id].load(.acquire); - while (queued > 0) queued = reads_queued[id].cmpxchgWeak(queued, queued - 1, .acq_rel, .acquire) orelse { - if (queued == 2) io.futexWake(u32, &reads_queued[id].raw, 1); - return; - }; -} - -fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: u32, loop: *Loop) error{OutOfMemory}!void { - // One buffer, read into directly: a Reader around it only added a second - // (and in a safe build, filled both as `undefined` on every start). - var buf: [0x10000]u8 = undefined; - read: while (true) { - while (true) { - const queued = reads_queued[id].load(.acquire); - if (queued < 2) break; - io.futexWait(u32, &reads_queued[id].raw, queued) catch break :read; - } - const n = pty.readStreaming(io, &.{&buf}) catch break; - if (n == 0) break; - const bytes = try gpa.dupe(u8, buf[0..n]); - _ = reads_queued[id].fetchAdd(1, .acq_rel); - loop.postEvent(.{ .pty_read = .{ .id = id, .gen = gen, .bytes = bytes } }) catch { - tookRead(io, id); - gpa.free(bytes); - break; - }; - } - _ = loop.tryPostEvent(.{ .pty_eof = .{ .id = id, .gen = gen } }) catch {}; -} - const max_paste_bytes: usize = pardes.memory.limits.max_paste_bytes; fn mouseEvent(m: vaxis.Mouse) ?pardes.Event { @@ -2995,7 +2822,7 @@ test "on a terminal with no kitty graphics a program's 64x64 image over 8x4 cell try std.testing.expectEqual(@as(usize, 32), painted); } -test "TTY queued results reject old PTY generations and LSP request IDs" { +test "TTY queued results reject an old LSP request ID" { const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer core.deinit(); @@ -3006,21 +2833,13 @@ test "TTY queued results reject old PTY generations and LSP request IDs" { .lsp_gpa = gpa, .core = core, .frames = core.frames, - .prompt_rcs = undefined, .loop = undefined, .frame = undefined, .paste_buf = undefined, .inotify_fd = -1, .peers = &no_peers, + .ptys = undefined, }; - shell.gens[0] = 2; - _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 1, .bytes = try gpa.dupe(u8, "old session\n") } }); - _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 2, .bytes = try gpa.dupe(u8, "current session\n") } }); - const text = try pardes.Term.scrollback(core.panes[0].?.terminal, gpa); - defer gpa.free(text); - try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null); - try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null); - core.lspRequest(0, .status, ""); const old_id = core.lsp_ask.wait.?.id; core.lspRequest(0, .status, ""); @@ -3054,13 +2873,13 @@ test "TTY worker setup failures finish matching LSP and pipe requests" { .lsp_gpa = failing.allocator(), .core = core, .frames = core.frames, - .prompt_rcs = undefined, .loop = undefined, .frame = undefined, .paste_buf = undefined, .inotify_fd = -1, .threads_ok = true, .peers = &no_peers, + .ptys = undefined, }; core.lspRequest(core.view().active, .status, ""); const req: host_io.Lsp.Request = .{ diff --git a/runtime/session.zig b/runtime/session.zig index f401c85a..3942aa83 100644 --- a/runtime/session.zig +++ b/runtime/session.zig @@ -2,23 +2,24 @@ //! (dev/gui `runNative`) alike, each with a frontend of its own. It holds //! the session's allocators and workers, its core (an upgrade's, a dump's //! or a new one), the prompt files its shells start with, its 9P listener -//! and its replica clients (`Peers`): a step, its unit to the clients and -//! theirs taken in, an Upgrade or a Restore between steps; and the order -//! its parts end in. Its devices (the ptys and their readers, the files -//! watched, the LSP's and the pipes' and addons' jobs, the queue they post -//! to, the session's own input) are still its frontend's (each `Shell`, -//! the services step's to make one). What a frontend does is: +//! its replica clients (`Peers`), its queue (the workers' and readers' +//! posts, `Inbox`) and its ptys (`Ptys`): a step, its unit to the clients +//! and theirs taken in, an Upgrade or a Restore between steps; and the +//! order its parts end in. Its other devices (the files watched, the LSP's +//! and the pipes' and addons' jobs, the session's own input) are still its +//! frontend's (each `Shell`). What a frontend does is: //! //! - `options(o)`: before the core: what it gives the core it starts (a //! window's size, for a dump's layout). //! - `open(l) Host`: its devices made over the session's core and parts, -//! the host the core steps with (the core's, set there); what it does -//! before the core's first effects (an upgraded terminal's panes its -//! own again, whether anyone looks). +//! the host the core steps with (the core's, set there), who wakes it +//! when the queue gets a post (`l.inbox`); what it does before the +//! core's first effects (an upgraded terminal's panes its own again, +//! whether anyone looks). //! - `close(l)`: its devices stopped, after the clients are let go and -//! before the core goes. -//! - `resumePtys(rec)`: an upgraded session's shells, its own again. -//! - `start(l)`: after the first effects: its input, its readers, the +//! before the ptys, the queue and the core go. +//! - `start(l)`: after the first effects, the ptys read: its input, its +//! readers, the //! 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). @@ -32,6 +33,7 @@ const std = @import("std"); const pardes = @import("core"); const replica = pardes.replica; const host_io = @import("dev").host_io; +const Ptys = host_io.Ptys; const file_watch = @import("dev").file_watch; const daemon = @import("daemon.zig"); const upgrade = @import("upgrade.zig"); @@ -52,6 +54,10 @@ pub fn Loop(comptime Frontend: type) type { frames: pardes.FrameStats = .{}, core: *pardes.Pardes = undefined, prompt_rcs: host_io.Shell.PromptFiles = undefined, + /// What the session's workers and readers post, for the frontend + /// to take in its wait. + inbox: host_io.Inbox = undefined, + ptys: Ptys = undefined, fs: ?*ninep_io.Listener = null, peers: replica.Peers = .{}, host: pardes.Host = undefined, @@ -83,6 +89,10 @@ pub fn Loop(comptime Frontend: type) type { l.fs = ninep_io.start(l.io, l.gpa, l.core); defer if (l.fs) |f| f.deinit(l.gpa); l.peers = .{ .gpa = l.gpa, .io = l.io, .name = daemon.name() }; + l.inbox = .{ .io = l.io, .gpa = l.gpa, .lsp_allocator = l.allocs.lsp }; + defer l.inbox.deinit(); + l.ptys = .{ .queue = &l.inbox, .prompt_rcs = &l.prompt_rcs }; + defer l.ptys.deinit(); l.host = try fe.open(&l); defer fe.close(&l); @@ -93,9 +103,10 @@ pub fn Loop(comptime Frontend: type) type { // ...and its shells, once a fresh session's own has a directory // to adopt them in. if (upgrade.resumed) |*rec| { - fe.resumePtys(rec); + l.ptys.resumeFrom(l.core, rec); l.effects(); } + l.ptys.start(l.core); try fe.start(&l); while (!l.core.quit) { @@ -140,11 +151,13 @@ pub fn Loop(comptime Frontend: type) type { } /// A Restore: the core its dump makes replaces this one, its clients - /// let go (host_io.restoreCore); the frontend's devices with it. + /// let go (host_io.restoreCore); its shells and the frontend's + /// devices with it. fn restore(l: *L, path: []const u8) void { const w = l.fe.watched(); const nc = host_io.restoreCore(l.gpa, l.core, path, &l.peers, w.fd, w.table) orelse return; l.fe.restoring(nc); + l.ptys.stop(); nc.host = l.host; if (l.fs) |f| f.reset(nc); l.core.deinit(); diff --git a/test/replicas.zig b/test/replicas.zig index 70edea75..ffe82790 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -914,8 +914,6 @@ const Soak = struct { s.sending.deinit(s.l.peers.gpa); } - pub fn resumePtys(_: *Soak, _: anytype) void {} - /// The tty's own boot (a raw shell, a text pane under it), then three /// files looked at, and the picture and the PDF in a column of their /// own (plain kinds' panes every client joins with, loaded from its |
