From a22129c343d9236277dcc0353c48cb53bc3417ce Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 18:32:37 -0300 Subject: pardes --wait (-w) in a pane returns only once the pane its file landed in is deleted, so it can be $EDITOR A launch inside a pane forwards its file to the session's look and returned at once, so fish's Ctrl-O (edit_command_buffer), git commit and crontab -e read their still-unedited file back and went on. With --wait, as acme's E against B and read the way plan9port's E reads acme's log, it finds the pane /index names the file by (the one already showing it, if open), follows /log on one connection with 'follow new', reads /index once more to catch a Del that came first, and then blocks with no deadline until that pane's del record: exit 0, or 1 when the connection ends with the session. The 9P client's one-shot requests keep their 2 s deadline; its new follow takes it for the setup only. Outside pardes nothing changes. --help, docs/fs.md, the README and the 9P skill say to set EDITOR='pardes --wait', which GIT_EDITOR follows. Tested in fs.py (it returns within 50 ms of the Del, a second -w waits on the same pane, one whose session is killed exits 1) and end to end: fish 4.8 in a detached session, echo hi, Ctrl-O, the waiting launch idle in poll, the line edited over 9P, Save, Del, and fish ran echo edited. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/pardes-9p/SKILL.md | 4 ++ README.md | 6 +++ docs/fs.md | 9 ++++ src/9p_io.zig | 86 +++++++++++++++++++++++++++++++-------- src/main.zig | 85 ++++++++++++++++++++++++++++++++++++++ test/fs.py | 41 +++++++++++++++++++ 6 files changed, 213 insertions(+), 18 deletions(-) diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index 18700589..1d32ce7a 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -34,6 +34,10 @@ cat "$m/pane/$PARDES_PANE/body" From there the editor is files: `cat`, `echo >`, `ls` and shell scripts are the whole interface, and nothing below needs more than they do. +`pardes FILE` run in a pane opens FILE in that session and returns at once; +`pardes --wait FILE` returns when that pane is deleted (1 if the session goes +away), which is what `EDITOR='pardes --wait'` needs (`GIT_EDITOR` follows it). + Entries for dead sessions stay listed and answer `Input/output error` on any access, so name the session you mean rather than globbing or taking the newest. `cat "$m/index"` is the cheapest liveness check, and `cat "$m/status"` reports diff --git a/README.md b/README.md index f60b0ed7..14803aef 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,12 @@ serves the layout: `/layout` lists the columns, their places and panes, and `/tag` and `/col//tag` are the workspace and column tags, editable like a window's ([the tree](docs/fs.md#the-served-tree)). +`pardes FILE` in a pane opens FILE in that session and returns at once. As +`$EDITOR`, use `EDITOR='pardes --wait'` (`GIT_EDITOR` follows it): `--wait` +returns when that pane is deleted, so fish's Ctrl-O, `git commit` and +`crontab -e` read the file after you edit it +([forwarding](docs/fs.md#filesystem)). + plan9port's `9p write` always opens with OTRUNC, so `echo x | 9p write pardes//body` replaces the whole body where acme would append. To append, write through a mount with `>>` (`echo x >> $PARDES_MOUNT//body`). diff --git a/docs/fs.md b/docs/fs.md index 52f991c2..ca02082b 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -15,6 +15,15 @@ separate editor and withholds `PARDES_PID` from its pane shells, so a pardes started in one of them runs a session of its own; its 9P service stays available. +A forwarded launch returns at once, as acme's `B` does. `--wait` (`-w`) +returns only once the pane the file landed in -- the one already showing +it, if any -- is deleted (exit 0), or the session goes away (exit 1), as +acme's `E` does: what an `$EDITOR` must do, since fish's Ctrl-O +(`edit_command_buffer`), `git commit` and `crontab -e` read the file back +when the editor exits. Set `EDITOR='pardes --wait'`; `GIT_EDITOR` follows +`EDITOR` when unset. Outside pardes `--wait` changes nothing, a session +blocking anyway. + Look resolves the OS filesystem first, then the editor's virtual filesystem. Explicit paths bypass that search: diff --git a/src/9p_io.zig b/src/9p_io.zig index 6f05e3ab..78ff5d59 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -1947,14 +1947,8 @@ pub const Client = struct { } }; - fn transact( - s: *Session, - names: []const []const u8, - out: *std.Io.Writer.Allocating, - remote: *RemoteError, - write_bytes: ?[]const u8, - read_limit: usize, - ) !void { + /// Version, attach and a walk to `names`: the fid there and its qid. + fn walkTo(s: *Session, names: []const []const u8, remote: *RemoteError) !struct { fid: u32, qid: ninep.Qid } { _ = try s.ask(.{ .version = .{} }, remote); if (s.cl.msize == 0) return Error.Botch; @@ -1978,6 +1972,20 @@ pub const Client = struct { next = if (next == 1) 2 else 1; i += n; } + return .{ .fid = cur, .qid = here }; + } + + fn transact( + s: *Session, + names: []const []const u8, + out: *std.Io.Writer.Allocating, + remote: *RemoteError, + write_bytes: ?[]const u8, + read_limit: usize, + ) !void { + const at = try walkTo(s, names, remote); + const cur = at.fid; + const here = at.qid; defer s.dropNoWait(cur); const directory = here.type & ninep.qtdir != 0; @@ -2036,15 +2044,20 @@ pub const Client = struct { read_limit: usize, ) ![]u8 { if (comptime !supported) return Error.Dial; + const s = try startSession(gpa, sock, display_path); + defer endSession(gpa, s); + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + try transact(s, names, &out, remote, write_bytes, read_limit); + return out.toOwnedSlice(); + } + + /// A connected session whose requests have the usual deadline. + fn startSession(gpa: std.mem.Allocator, sock: Dial, display_path: []const u8) !*Session { const deadline = nowMs() +| budget_ms; const s = try gpa.create(Session); s.* = .{ .fd = -1, .deadline = deadline, .display_path = display_path }; - defer { - if (quic_enabled and s.quic != null) { - s.quic.?.deinit(); - } else if (s.fd >= 0) _ = libc.close(s.fd); - gpa.destroy(s); - } + errdefer endSession(gpa, s); if (sock == .quic) { if (comptime quic_enabled) { s.quic = quic.Connection.dial(sock.quic) catch return Error.Dial; @@ -2052,11 +2065,48 @@ pub const Client = struct { } else return Error.QuicUnavailable; } else s.fd = try connect(sock, deadline); s.cl = .init(.{ .in = &s.in, .out = &s.out }); + return s; + } - var out: std.Io.Writer.Allocating = .init(gpa); - errdefer out.deinit(); - try transact(s, names, &out, remote, write_bytes, read_limit); - return out.toOwnedSlice(); + fn endSession(gpa: std.mem.Allocator, s: *Session) void { + if (quic_enabled and s.quic != null) { + s.quic.?.deinit(); + } else if (s.fd >= 0) _ = libc.close(s.fd); + gpa.destroy(s); + } + + /// Opens `path` on one connection and writes `first` to it (/log's + /// `follow new`), all with the usual deadline; then, once `ready(ctx)` + /// has said it is not done already, reads it with no deadline, a read at + /// a time, until `record(ctx, bytes)` says done. An end of file or a + /// dropped connection is Hangup. What `pardes --wait` blocks on. + pub fn follow( + gpa: std.mem.Allocator, + dial: []const u8, + path: []const u8, + first: []const u8, + ctx: anytype, + comptime ready: fn (@TypeOf(ctx)) bool, + comptime record: fn (@TypeOf(ctx), []const u8) bool, + ) !void { + if (comptime !supported) return error.Unsupported; + var names: [max_depth][]const u8 = undefined; + const n = try elements(path, &names); + var sock_buf: [sun_path_len]u8 = undefined; + const sock = try resolve(&sock_buf, dial); + var remote: RemoteError = .{}; + const s = try startSession(gpa, sock, path); + defer endSession(gpa, s); + const fid = (try walkTo(s, names[0..n], &remote)).fid; + _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); + _ = try s.ask(.{ .write = .{ .fid = fid, .offset = 0, .data = first } }, &remote); + if (ready(ctx)) return; + s.deadline = std.math.maxInt(i64); + while (true) { + const data = (try s.ask(.{ .read = .{ .fid = fid, .offset = 0, .count = s.cl.maxRead() } }, &remote)).read; + if (data.len == 0) return Error.Hangup; + if (record(ctx, data)) return; + } } fn connect(sock: Dial, deadline: i64) Error!c_int { diff --git a/src/main.zig b/src/main.zig index aaa237f6..ec2472d7 100644 --- a/src/main.zig +++ b/src/main.zig @@ -58,6 +58,12 @@ const help_text = \\ A FILE argument boots just that file instead. \\ --tty-toggle use Ctrl- to toggle tty/editor mode \\ -l load a dump of another instance (see Dump) + \\ -w, --wait inside a pardes pane, hand FILE to the outer + \\ session and return only once the pane it opened + \\ (or already had) is deleted: 0 then, 1 if the + \\ session goes away. For $EDITOR (acme's E): + \\ EDITOR='pardes --wait', which GIT_EDITOR follows. + \\ Outside pardes a session blocks anyway. \\ --nested run a full session even inside another pardes. \\ Without it, a pardes started inside a pardes \\ hands its FILE argument to the outer one. This @@ -92,6 +98,81 @@ const help_text = \\ ; +/// `--wait` after a forwarded look, as plan9port's E reads acme's log: the +/// pane `path` landed in (the one it already had, if open), then /log +/// followed on one connection until that pane's `del` -- exit 0 -- or the +/// connection ends with the session -- exit 1. +fn waitForDel(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, path: []const u8) noreturn { + const first = ninep_io.Client.read(gpa, dial, "/index", "/index") catch std.process.exit(1); + const serial = paneShowing(first, path) orelse { + std.Io.File.stderr().writeStreamingAll(io, "pardes: --wait: no pane shows that file\n") catch {}; + std.process.exit(1); + }; + gpa.free(first); + const Wait = struct { + gpa: std.mem.Allocator, + dial: []const u8, + serial: u32, + /// Deleted between the look and the follow: /index, read once the + /// follow stands, says so, and a `del` after it is followed. + fn gone(w: *const @This()) bool { + const index = ninep_io.Client.read(w.gpa, w.dial, "/index", "/index") catch return false; + defer w.gpa.free(index); + return !hasPane(index, w.serial); + } + fn deleted(w: *const @This(), bytes: []const u8) bool { + return isDel(bytes, w.serial); + } + }; + const w: Wait = .{ .gpa = gpa, .dial = dial, .serial = serial }; + ninep_io.Client.follow(gpa, dial, "/log", "follow new", &w, Wait.gone, Wait.deleted) catch std.process.exit(1); + std.process.exit(0); +} + +/// Whether log records `bytes` hold `del ...`. +fn isDel(bytes: []const u8, serial: u32) bool { + var records = std.mem.splitScalar(u8, bytes, '\n'); + while (records.next()) |rec| { + if (!std.mem.startsWith(u8, rec, "del ")) continue; + const word = rec[4 .. std.mem.indexOfScalarPos(u8, rec, 4, ' ') orelse rec.len]; + if ((std.fmt.parseInt(u32, word, 10) catch continue) == serial) return true; + } + return false; +} + +/// The serial of /index's first row named `path` (`serial kind dirty name col`). +fn paneShowing(index: []const u8, path: []const u8) ?u32 { + var rows = std.mem.splitScalar(u8, index, '\n'); + while (rows.next()) |row| { + var words = std.mem.splitScalar(u8, row, ' '); + const serial = std.fmt.parseInt(u32, words.first(), 10) catch continue; + _ = words.next() orelse continue; // kind + _ = words.next() orelse continue; // dirty + const rest = words.rest(); + const end = std.mem.lastIndexOfScalar(u8, rest, ' ') orelse continue; + if (std.mem.eql(u8, rest[0..end], path)) return serial; + } + return null; +} + +fn hasPane(index: []const u8, serial: u32) bool { + var rows = std.mem.splitScalar(u8, index, '\n'); + while (rows.next()) |row| { + const first = row[0 .. std.mem.indexOfScalar(u8, row, ' ') orelse row.len]; + if ((std.fmt.parseInt(u32, first, 10) catch continue) == serial) return true; + } + return false; +} + +test "--wait finds the pane /index names a file by, spaces and all, and sees it gone" { + const index = "1 term 0 /home/u 1\n4 text 1 /tmp/a b.txt 2\n"; + try std.testing.expectEqual(@as(?u32, 4), paneShowing(index, "/tmp/a b.txt")); + try std.testing.expectEqual(@as(?u32, null), paneShowing(index, "/tmp/a")); + try std.testing.expect(hasPane(index, 4) and !hasPane(index, 2)); + try std.testing.expect(isDel("new 5 /x\ndel 4 /tmp/a b.txt\n", 4)); + try std.testing.expect(!isDel("del 41 /x\n", 4) and !isDel("undel 4\n", 4)); +} + fn badArgs(io: std.Io, comptime fmt: []const u8, args: anytype) noreturn { var buf: [1024]u8 = undefined; const line = std.fmt.bufPrint(&buf, "pardes: " ++ fmt ++ "\nTry 'pardes --help'.\n", args) catch @@ -159,6 +240,7 @@ fn nativeMain(init: std.process.Init) !void { var detach: ?[]const u8 = null; var attach: ?[]const u8 = null; var positional: ?[:0]const u8 = null; + var wait = false; var i: usize = 1; while (i < args.len) : (i += 1) { const a = args[i]; @@ -239,6 +321,8 @@ fn nativeMain(init: std.process.Init) !void { mounts_len += 1; } else if (std.mem.eql(u8, a, "--nested")) { opts.nested = true; + } else if (std.mem.eql(u8, a, "-w") or std.mem.eql(u8, a, "--wait")) { + wait = true; } else if (std.mem.eql(u8, a, "--detach")) { detach = ""; } else if (std.mem.startsWith(u8, a, "--detach=")) { @@ -328,6 +412,7 @@ fn nativeMain(init: std.process.Init) !void { var command_buf: [8192]u8 = undefined; const command = std.fmt.bufPrint(&command_buf, "{s}{s}\n", .{ path, word[target.path.len..] }) catch break :forwarding; ninep_io.Client.write(arena, parent.dial, look, command) catch break :forwarding; + if (wait) waitForDel(init.io, arena, parent.dial, path); return; } if (positional) |a| { diff --git a/test/fs.py b/test/fs.py index 7401861b..db10f32d 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1224,6 +1224,47 @@ def test(binary, quic=False): cell[0] for cell in local.screen()['cells']) assert client.read('/index') == before + # --wait (acme's E): a launch inside a pane lasts until the pane it + # opened is deleted, as an $EDITOR must; one on a file already open + # waits on that pane; a session that goes away ends it with 1. + with session(binary, root, 'wait') as (client, address): + status = dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines()) + env = {k: v for k, v in os.environ.items() if k != 'PARDES_FORWARD_LOOK'} + env.update(PARDES_9P=str(address), PARDES_PANE='1', PARDES_PID=status['pid']) + edited = root / 'wait edit.txt' + edited.write_bytes(b'edit me\n') + + def serials(): + return {int(row.split()[0]) for row in client.read('/index').splitlines()} + + def launch(flag): + before = serials() + child = subprocess.Popen([binary, flag, str(edited)], cwd=root, env=env, + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + deadline = time.monotonic() + 3 + while child.poll() is None and not serials() - before and time.monotonic() < deadline: + time.sleep(.01) + return child + + first = launch('--wait') + opened, = serials() - {1} + second = launch('-w') + time.sleep(.5) + assert first.poll() is None and second.poll() is None, (first.stderr.read(), second.stderr.read()) + assert serials() == {1, opened} + client.write(f'/pane/{opened}/body', b'edited\n', truncate=True) + execute(client, opened, 'Save') + client.remove(f'/pane/{opened}') + deleted = time.monotonic() + assert first.wait(timeout=5) == 0 + # Woken by the `del` record, not a poll. + assert time.monotonic() - deleted < .05, time.monotonic() - deleted + assert second.wait(timeout=5) == 0 + assert edited.read_bytes() == b'edited\n' + orphan = launch('--wait') + assert orphan.poll() is None + assert orphan.wait(timeout=5) == 1 + for tty in [False, True]: name = 'lsp-tty' if tty else 'lsp-detached' with session(binary, root, name, tty=tty) as (client, _): -- cgit v1.3