From 0957cd7ad097c83a591e315f2e261996e72ea856 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 15:13:48 -0300 Subject: tui: a pardes whose terminal hangs up (no daemon) or that is sent SIGTERM kills its language servers' groups as an exit does: Killed.handle dies by raise, so the language client's atexit group kill (lsp_client.zig killAllAtExit) never ran and a server busy in a build (zls at a cold start, its children) lived on after the editor; the handler calls it now (kill(2) only, async-signal-safe); test "tty editing: lsp-hangup" (the mock, LSPMOCK_MODE=busy, leaves a child in its group at the handshake and says its pid; the case hangs up the pty and wants the child gone in 5 s): ServerChildLivesOn on the base, passes now; a user could hit it: closing the terminal of a daemon-less pardes, or kill (TERM) of any pardes, with a language server busy; tui process-test 1 of 145 failed once in the whole run (the SIGTERM flags case, "the terminal left raw", load 8-15; 3 of 3 alone) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- dev/lsp/lsp_client.zig | 5 ++-- dev/tui/tui.zig | 4 +++- test/lspmock.zig | 26 ++++++++++++++++++++- test/process/tty_editing.zig | 55 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 86 insertions(+), 4 deletions(-) diff --git a/dev/lsp/lsp_client.zig b/dev/lsp/lsp_client.zig index 4ad8dace..fdd4af55 100644 --- a/dev/lsp/lsp_client.zig +++ b/dev/lsp/lsp_client.zig @@ -2244,8 +2244,9 @@ fn reap(pid: libc.pid_t) void { /// At this process's exit, every server's group is killed: a server busy /// in a build (zls at a cold start) would not notice its socket close, and /// lived on with its children after the editor. Registered once, at the -/// first spawn; signals only, no locks (other threads may hold them). -fn killAllAtExit() callconv(.c) void { +/// first spawn; signals only, no locks (other threads may hold them): a +/// signal's handler calls it too (tui.zig `Killed`). +pub fn killAllAtExit() callconv(.c) void { for (&conns) |*c| if (c.pid > 0) { _ = libc.kill(-c.pid, .KILL); }; diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index 72028b04..638f1400 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -906,7 +906,7 @@ const Screen = struct { /// the main screen, no mouse, paste or keyboard modes, the cursor shown, /// cooked termios -- and then the signal's own death. A nested editor /// killed in a pane must not leave that pane's terminal wedged. -/// Async-signal-safe: write, tcsetattr, sigaction, raise. +/// Async-signal-safe: write, tcsetattr, kill, sigaction, raise. const Killed = struct { var fd: posix.fd_t = -1; var cooked: posix.termios = undefined; @@ -937,6 +937,8 @@ const Killed = struct { ninep_io.unlinkOwnSocket(); host_io.Shell.unlinkOwnedRcs(); daemon.hangUp(); + // No exit hook runs: the language servers' groups go here. + @import("../lsp/lsp_client.zig").killAllAtExit(); // SA_RESETHAND put the default back: the same signal, now fatal. _ = std.c.raise(sig); } diff --git a/test/lspmock.zig b/test/lspmock.zig index 001c3488..8b5c73a8 100644 --- a/test/lspmock.zig +++ b/test/lspmock.zig @@ -15,12 +15,17 @@ //! mute handshake, then never answer another request (timeout path) //! die exit right after the handshake (dead-server path) //! utf16 refuse the utf-8 negotiation (column-conversion path) +//! busy at the handshake, leave a child running in the server's +//! group, as a build a server started does; its pid said in +//! `lspmock-busy.pid` in the server's directory (its root) const std = @import("std"); const libc = std.c; extern "c" fn getenv(name: [*:0]const u8) ?[*:0]const u8; +extern "c" fn fork() libc.pid_t; +extern "c" fn pause() c_int; -var mode: enum { normal, mute, die, utf16 } = .normal; +var mode: enum { normal, mute, die, utf16, busy } = .normal; /// stdout, written with plain libc write(2): the transport is a socketpair /// and the frames are small, so partial writes are retried and nothing else @@ -118,6 +123,7 @@ pub fn main(init: std.process.Init) !void { if (std.mem.eql(u8, s, "mute")) mode = .mute; if (std.mem.eql(u8, s, "die")) mode = .die; if (std.mem.eql(u8, s, "utf16")) mode = .utf16; + if (std.mem.eql(u8, s, "busy")) mode = .busy; } const gpa = std.heap.page_allocator; @@ -164,6 +170,23 @@ pub fn main(init: std.process.Init) !void { } } +/// A child that runs on in this server's group, its socket closed, and +/// says its pid. +fn leaveChild() void { + const pid = fork(); + if (pid != 0) return; + _ = libc.close(0); + _ = libc.close(1); + var buf: [16]u8 = undefined; + const said = std.fmt.bufPrint(&buf, "{d}\n", .{libc.getpid()}) catch unreachable; + const fd = libc.open("lspmock-busy.pid", .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o600)); + if (fd >= 0) { + _ = libc.write(fd, said.ptr, said.len); + _ = libc.close(fd); + } + while (true) _ = pause(); +} + fn handle(a: std.mem.Allocator, raw: []const u8) void { const v = std.json.parseFromSliceLeaky(std.json.Value, a, raw, .{}) catch return; const method = str(get(v, "method")) orelse ""; @@ -195,6 +218,7 @@ fn handle(a: std.mem.Allocator, raw: []const u8) void { } if (std.mem.eql(u8, method, "initialized")) { if (mode == .die) std.process.exit(0); + if (mode == .busy) leaveChild(); // the progress trio, so the status pipeline has something to narrate notify(a, "$/progress", "{{\"token\":\"t1\",\"value\":{{\"kind\":\"begin\",\"title\":\"mocking\"}}}}", .{}); notify(a, "$/progress", "{{\"token\":\"t1\",\"value\":{{\"kind\":\"report\",\"percentage\":50,\"message\":\"halfway\"}}}}", .{}); diff --git a/test/process/tty_editing.zig b/test/process/tty_editing.zig index 63c75512..53e1da1e 100644 --- a/test/process/tty_editing.zig +++ b/test/process/tty_editing.zig @@ -27,6 +27,7 @@ pub const cases = .{ .{ "tty editing: lsp", lsp }, .{ "tty editing: lsp-client", lsp_client }, .{ "tty editing: lsp-client-edit", lsp_client_edit }, + .{ "tty editing: lsp-hangup", lsp_hangup }, .{ "tty editing: lspcomplete", lspcomplete }, .{ "tty editing: lspcompletemoved", lspcompletemoved }, .{ "tty editing: lspdebug", lspdebug }, @@ -1511,6 +1512,60 @@ fn lsp_client(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try t.done(); } +// A pardes with no daemon whose terminal hangs up dies by the signal, and +// no exit hook runs: its language servers' groups go with it all the same. +// The mock, busy (LSPMOCK_MODE=busy), leaves a child in its group, as zls +// in a build does, which its socket's end does not stop. +fn lsp_hangup(gpa: std.mem.Allocator, exe: [:0]const u8) !void { + var t = try Tty.init(gpa, exe, "lsp-hangup"); + defer t.deinit(); + _ = setenv("LSPMOCK_MODE", "busy", 1); + // The server's root, where it says its child's pid. + try t.file("Cargo.toml", ""); + try t.file("main.rs", "fn main() {}\n"); + try t.start(25, 100, &.{"main.rs"}); + try t.wait(8000, "fn main()"); + // A request starts the server (goto-definition). + try t.key("g"); + try t.key("d"); + var buf: [32]u8 = undefined; + const child: std.c.pid_t = for (0..1000) |_| { + const fd = std.c.open("lspmock-busy.pid", .{}); + if (fd >= 0) { + const n = std.c.read(fd, &buf, buf.len); + _ = std.c.close(fd); + if (n > 0) if (std.fmt.parseInt(std.c.pid_t, std.mem.trim(u8, buf[0..@intCast(n)], " \n"), 10)) |pid| break pid else |_| {}; + } + try t.settle(10); + } else return error.NoServerChild; + // Whatever the test's end, the child it made goes. + defer _ = std.c.kill(child, .KILL); + t.h.?.deinit(); // the terminal hangs up + t.h = null; + for (0..500) |_| { + if (!alive(child)) return; + var none: [0]std.posix.pollfd = .{}; + _ = std.posix.poll(&none, 10) catch 0; + } + return error.ServerChildLivesOn; +} + +/// Whether `pid` runs (a zombie waiting for its reaper does not). +fn alive(pid: std.c.pid_t) bool { + var path: [32]u8 = undefined; + const p = std.fmt.bufPrintSentinel(&path, "/proc/{d}/stat", .{pid}, 0) catch return false; + const fd = std.c.open(p, .{}); + if (fd < 0) return false; + defer _ = std.c.close(fd); + var stat: [256]u8 = undefined; + const n = std.c.read(fd, &stat, stat.len); + if (n <= 0) return false; + const close_paren = std.mem.lastIndexOfScalar(u8, stat[0..@intCast(n)], ')') orelse return false; + return close_paren + 2 < n and stat[close_paren + 2] != 'Z'; +} + +extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; + // The protocol client's MUTATING answers, through the @put record path: a // server TextEdit response becomes one atomic buffer edit with one undo step. // = applies the mock's formatting edit (a header line) and narrates -- cgit v1.3 From fb7e632248c599a70689cd0451392c8a890044ee Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 15:13:48 -0300 Subject: daemon: the reader hands no note to a session loop that ended: it took the loop's address once, at its start, and ran on until main's daemon.quit joined it, after Loop.run returned, so a client connecting (or a shell adopted, or a daemon relinked) while a session ended was handed to the loop's dead frame (l.peers, l.inbox, deinit'ed); now the reader hands each note under a lock to where notesTo says (daemon.give), the session loop sets it after its frontend opened and clears it (notesTo(null)) before its peers, frontend and queue go, and a note with nowhere to go is let go, its connections closed; test "a client's connection the daemon hands on after the session's loop ended reaches no loop: it is closed" (a fake daemon on a socketpair link): "expected 0, found 1" (the ended loop handed it) on the base, passes now; a user could hit it: a pardes attach (or Adopt's answer) in the moment its session exits: a write into a dead stack frame (a crash or a corrupted teardown) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- runtime/daemon.zig | 83 +++++++++++++++++++++++++++++++++++++++++++++-------- runtime/session.zig | 5 +++- 2 files changed, 75 insertions(+), 13 deletions(-) diff --git a/runtime/daemon.zig b/runtime/daemon.zig index 9b566e60..453ee101 100644 --- a/runtime/daemon.zig +++ b/runtime/daemon.zig @@ -307,8 +307,11 @@ var detached_now = std.atomic.Value(bool).init(false); var name_buf: [128]u8 = undefined; var name_len: usize = 0; var reader: ?std.Thread = null; -/// Where the reader hands each note (`notesTo`). -var notes: ?struct { ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void } = null; +/// Where the reader hands each note (`notesTo`), the lock a hand-over and +/// a change of it take. +var notes: ?Notes = null; +var notes_lock: std.Io.Mutex = .init; +pub const Notes = struct { ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void }; pub fn name() []const u8 { return name_buf[0..name_len]; @@ -452,20 +455,39 @@ pub const Note = union(enum) { pub const Joining = struct { fd: c_int, view: ?u8 = null }; /// Where every note the daemon sends goes, once `watch` has started the -/// reader: the session's, before its first step. -pub fn notesTo(ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void { - notes = .{ .ctx = ctx, .deliver = deliver }; +/// reader: the session loop's, before its first step, until its state +/// goes (null): once this returns, no note reaches the one before. +pub fn notesTo(to: ?Notes) void { + const io = std.Io.Threaded.global_single_threaded.io(); + notes_lock.lockUncancelable(io); + defer notes_lock.unlock(io); + notes = to; +} + +/// A note handed on (`notesTo`); with nowhere to go (the loop ended, the +/// link not yet), let go: its connections closed. +fn give(note: Note) void { + const io = std.Io.Threaded.global_single_threaded.io(); + notes_lock.lockUncancelable(io); + defer notes_lock.unlock(io); + if (notes) |n| return n.deliver(n.ctx, note); + switch (note) { + .relinked => {}, + .adopted => |a| for (a.fds[0..a.n]) |f| { + _ = libc.close(f); + }, + .replica => |j| _ = libc.close(j.fd), + } } /// Hands every note the daemon sends on (`notesTo`), on a thread of its /// own, until the link ends (`quit`). Called each loop: started once. pub fn watch() void { - const n = notes orelse return; - if (link < 0 or reader != null) return; - reader = std.Thread.spawn(.{}, readNotes, .{ link, n.ctx, n.deliver }) catch null; + if (notes == null or link < 0 or reader != null) return; + reader = std.Thread.spawn(.{}, readNotes, .{link}) catch null; } -fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void { +fn readNotes(fd: c_int) void { var buf: [msg_max]u8 = undefined; while (true) { while (recv(fd, &buf)) |got| { @@ -475,7 +497,7 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no .ok => settle(.up), .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 } }); + if (got.nfds >= 1) give(.{ .replica = .{ .fd = got.fds[0], .view = view } }); for (got.fds[@min(got.nfds, 1)..got.nfds]) |f| _ = libc.close(f); }, .adopted => { @@ -490,7 +512,7 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no a.fds[a.n] = f; a.n += 1; } - deliver(ctx, note); + give(note); }, } else for (got.fds[0..got.nfds]) |f| { _ = libc.close(f); @@ -504,7 +526,7 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no // an end begun while it dialled finds the new link (`quit`). if (answer.swap(.asked, .acq_rel) != .up or quitting.load(.acquire) or !redial(fd) or quitting.load(.acquire)) break; retell.store(true, .release); - deliver(ctx, .relinked); + give(.relinked); } // Not kept, until the session's end. settle(.gone); @@ -1204,6 +1226,43 @@ pub fn serve(state: ?[]const u8) noreturn { libc._exit(0); } +test "a client's connection the daemon hands on after the session's loop ended reaches no loop: it is closed" { + if (comptime !supported) return error.SkipZigTest; + var pair: [2]c_int = undefined; + try std.testing.expectEqual(@as(c_int, 0), libc.socketpair(libc.AF.UNIX, libc.SOCK.SEQPACKET | libc.SOCK.CLOEXEC, 0, &pair)); + defer _ = libc.close(pair[1]); + // The session's link, its daemon this test's end. + link = pair[0]; + defer { + quit(); + quitting.store(false, .release); + answer.store(.asked, .release); + } + const Loop = struct { + var notes_taken: u32 = 0; + fn note(_: *anyopaque, n: Note) void { + notes_taken += 1; + if (n == .replica) _ = libc.close(n.replica.fd); + } + }; + var loop: u8 = 0; + notesTo(.{ .ctx = &loop, .deliver = Loop.note }); + watch(); + try std.testing.expect(send(pair[1], "ok", &.{})); + // The loop ends (runtime/session.zig `run`); the link outlives it + // until main's `quit`. + notesTo(null); + var conn: [2]c_int = undefined; + try std.testing.expectEqual(@as(c_int, 0), libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &conn)); + defer _ = libc.close(conn[0]); + try std.testing.expect(send(pair[1], "replica 0", &.{conn[1]})); + _ = libc.close(conn[1]); + // Closed by the reader: the client sees its link end. + var fds = [_]posix.pollfd{.{ .fd = conn[0], .events = posix.POLL.IN, .revents = 0 }}; + try std.testing.expectEqual(@as(usize, 1), try posix.poll(&fds, 5000)); + try std.testing.expectEqual(@as(u32, 0), Loop.notes_taken); +} + test "a message carries its words and its fds, and the peer's end is null" { if (comptime !supported) return error.SkipZigTest; var pair: [2]c_int = undefined; diff --git a/runtime/session.zig b/runtime/session.zig index 9c8446e3..a0c27799 100644 --- a/runtime/session.zig +++ b/runtime/session.zig @@ -101,10 +101,13 @@ pub fn Loop(comptime Frontend: type) type { l.host = try fe.open(&l); defer fe.close(&l); - daemon.notesTo(&l, note); defer l.peers.deinit(); // Before the core goes: each client sees its link end. defer l.peers.dropAll(l.core); + // The daemon's notes, to the loop until its state goes (the + // reader runs on until main's `daemon.quit`). + daemon.notesTo(.{ .ctx = &l, .deliver = note }); + defer daemon.notesTo(null); // A first client on the socket it was started with, before its // first effects: it has every terminal from its first byte, and // no reload (Core.openView). -- cgit v1.3 From d720cf44d458e3986d371f4b8b768a97ba489c9c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 15:13:48 -0300 Subject: ninep: a retry of a held Edit write is answered by the listener from its hold, no step: serveFsInner's first lines read fs.edit_hold, which the session's listener sets between steps (9p_io), so a retried write was the session's step that answered it and every replica's step that ran the Edit again (the tape's divergence, and a client's second pipe); the check is EditHold.retried, which the listener calls before serveFs, and the step never reads the hold (fs.edit_hold stays the listener's, as the namespace's doc now says); test "a client runs an Edit a script's write started once, as its session does, when the held write is asked again" (core/replica.zig, a client joined, the write held as the listener holds it, its command answered, the retry as the listener serves it): diverged on the base ("the core called clock where the tape has a done (0), in serve_fs"), passes now; edit_cmd's held-write test retries through EditHold.retried; a user could hit it: a script's Edit with a | < or > command whose write's park is retried (a 9P client's retry while the command runs) under a far or window client: the client diverged and joined again Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Core.zig | 6 ------ core/edit_cmd.zig | 4 ++-- core/fs.zig | 17 +++++++++++++---- core/replica.zig | 25 +++++++++++++++++++++++++ runtime/9p_io.zig | 2 +- 5 files changed, 41 insertions(+), 13 deletions(-) diff --git a/core/Core.zig b/core/Core.zig index ff704bc6..98e2e407 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -1571,12 +1571,6 @@ fn stepInner(p: *Pardes) void { /// local socket costs microseconds and not a vsync. pub const serveFs = pardes.tape.taped(serveFsInner); fn serveFsInner(p: *Pardes, req: ctlfs.Req) ctlfs.Reply { - // The held write of an Edit whose commands run, asked again by a - // retry of its park: still waiting, or its answer, never run twice. - if (p.fs.edit_hold) |*h| if (h.names(req)) { - if (!h.done) return .{ .tag = req.tag, .status = .again }; - return filesystem.EditHold.answer(&p.fs); - }; defer pardes.panes.File.syncTwins(p); if (!ctlfs.changesPane(p, req)) return ctlfs.handle(p, req); // An address, a limit or the mark flag is nothing drawn: a script's diff --git a/core/edit_cmd.zig b/core/edit_cmd.zig index 9a5c6865..ab4f2b5d 100644 --- a/core/edit_cmd.zig +++ b/core/edit_cmd.zig @@ -533,11 +533,11 @@ test "the held write asked again is parked again, then answered once, and a flus // As 9p_io holds it. p.fs.edit_hold = .{ .asker = @ptrCast(p), .slot = 0, .seq = 1, .tag = 7, .node = ctl, .handle = 0, .written = @intCast(req.data.len) }; // A retry of its park: still waiting, never run a second time. - try testing.expectEqual(tree.Status.again, p.serveFs(req).status); + try testing.expectEqual(tree.Status.again, filesystem.EditHold.retried(&p.fs, req).?.status); try testing.expect(p.pipe.edit_run != null); answer(p, &.{"a\nb\n"}); try testing.expect(p.fs.edit_hold.?.done); - const done = p.serveFs(req); + const done = filesystem.EditHold.retried(&p.fs, req).?; try testing.expectEqual(tree.Status.ok, done.status); try testing.expectEqual(@as(u32, @intCast(req.data.len)), done.written); try testing.expect(p.fs.edit_hold == null); diff --git a/core/fs.zig b/core/fs.zig index eadb7c19..a64487d6 100644 --- a/core/fs.zig +++ b/core/fs.zig @@ -830,6 +830,16 @@ pub const EditHold = struct { return req.op == .write and req.tag == h.tag and req.node == h.node and req.handle == h.handle; } + /// The held write asked again by a retry of its park, as the listener + /// answers it, never a step (no replica holds it): still waiting, or + /// its answer; null for any other request. + pub fn retried(ns: *Namespace, req: tree.Req) ?tree.Reply { + const h = if (ns.edit_hold) |*held| held else return null; + if (!h.names(req)) return null; + if (!h.done) return .{ .tag = req.tag, .status = .again }; + return answer(ns); + } + /// Its answer, the held record let go: the words copied out first. pub fn answer(ns: *Namespace) tree.Reply { const h = ns.edit_hold.?; @@ -852,9 +862,8 @@ pub const Namespace = struct { /// the server's (core/walk.zig): its sockets and the mounts (dumped /// on their own), the log and what a reader or a listener is answered /// with, and the request being served's own flags, set and read in - /// its step. ponytail: `edit_hold`, set by the session's listener - /// between steps and read by the retried write's step, is no - /// replica's (reports/pardes-faults-4.md). + /// its step, and `edit_hold`: the listener's, which answers a retry + /// of the held write from it, no step (`EditHold.retried`). pub const replica = .{ .authority = .{ "socket_path", "tcp_address", "mounts", "node_name", "os_paths", "out", @@ -932,7 +941,7 @@ pub const Namespace = struct { /// commands run off the loop (edit_cmd.zig): the listener holds it. edit_started: bool = false, /// That write, held: answered once `done` (9p_io answerHeld), or - /// asked again by a retry of its park (Pardes.serveFs); a flush or a + /// asked again by a retry of its park (`EditHold.retried`); a flush or a /// hang-up stops the Edit (9p_io watchEdit). edit_hold: ?EditHold = null, /// The words a held Edit write was refused with, kept for its answer. diff --git a/core/replica.zig b/core/replica.zig index ff1e138e..f3269c84 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -7364,6 +7364,31 @@ test "a client joined while a script's writes to a body are held to go in as one try n.agree(); } +test "a client runs an Edit a script's write started once, as its session does, when the held write is asked again" { + var n = try NinepJoin.init("b\na\n", TestHost.host()); + defer n.deinit(); + try n.join(); + const ctl = n.node(.ctl); + const req: pardes.ctlfs.Req = .{ .tag = 7, .op = .write, .node = ctl, .data = "Edit , | sort\n" }; + // The step alone: its loop's pass would run the command (here, with no + // host to run it, fail it). + const first = try n.serve(req, false); + try std.testing.expectEqual(pardes.ctlfs.Status.ok, first.status); + // The write held as the session's listener holds it (runtime/9p_io.zig). + n.a.core.fs.edit_hold = .{ .asker = @ptrCast(n.a.core), .slot = 0, .seq = 1, .tag = req.tag, .node = ctl, .handle = 0, .written = first.written }; + // Its command answers: the Edit is done. + n.a.apply(.{ .pipe_resp = .{ .id = n.a.core.pipe.edit_run.?.id, .success = true, .outputs = &.{"a\nb\n"} } }); + n.a.seq += 1; + try n.send(try n.a.unit(0, n.a.seq)); + try n.agree(); + // A retry of the held write's park, as the listener serves it: its + // answer from the hold, no step, the Edit not run again by anyone. + const again = pardes.filesystem.EditHold.retried(&n.a.core.fs, req) orelse try n.serve(req, true); + try std.testing.expectEqual(pardes.ctlfs.Status.ok, again.status); + try std.testing.expect(n.a.core.pipe.edit_run == null); + try n.agree(); +} + /// A session with a shell, for a run's 9P state across a join: a host /// whose pty takes the line and whose tty nobody else holds. const RunJoin = struct { diff --git a/runtime/9p_io.zig b/runtime/9p_io.zig index aaca377d..1079b102 100644 --- a/runtime/9p_io.zig +++ b/runtime/9p_io.zig @@ -203,7 +203,7 @@ pub const Listener = struct { // Asked first: a release that runs a held line has none after. const changes = pardes.ctlfs.changesPane(core, req); const fills = pardes.ctlfs.handsOff(core, req); - const reply = core.serveFs(req); + const reply = pardes.filesystem.EditHold.retried(&core.fs, req) orelse core.serveFs(req); const edit_started = core.fs.edit_started; core.fs.edit_started = false; // The held Edit write asked again by a retry, its Edit still -- cgit v1.3 From df0fe00d35c1a01a852d7518ef884ec7aab7ace6 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 15:50:20 -0300 Subject: test: the tty harness sends an Esc read alone: `key` waits, before an esc and after it, until the app has read every byte typed (Harness.unread: FIONREAD on the pty's own end, opened by ptsname for the look and closed; the master's FIONREAD counts only what the app wrote); ttytaken typed "@`echo ..`", Esc, then h 100 ms later: the backquote and the Esc read together end a read, readInput waits 50 ms for more, a busy app overran it and read h after it, and ESC h is Alt-h by its bytes (reports/pardes-faults-5.md 4b), a TEST fault, not the product's (a terminal cannot tell the two apart); ttytaken pinned to one CPU (taskset -c 5, no made load), on the tip with this and the cursor change: 0 of 100 failed (load 4-13); the base's failure was round 2's, 4 of 17 under a made load, never pinned Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- test/e2e_harness.zig | 16 ++++++++++++++++ test/tty.zig | 23 ++++++++++++++++++++--- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/test/e2e_harness.zig b/test/e2e_harness.zig index 26e942e7..f9ed44c0 100644 --- a/test/e2e_harness.zig +++ b/test/e2e_harness.zig @@ -20,6 +20,7 @@ extern "c" fn openpty( winp: ?*const posix.winsize, ) c_int; extern "c" fn ttyname(fd: c_int) ?[*:0]const u8; +extern "c" fn ptsname(fd: c_int) ?[*:0]const u8; extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; extern "c" fn _exit(status: c_int) noreturn; extern "c" fn unsetenv(name: [*:0]const u8) c_int; @@ -251,6 +252,21 @@ pub const Harness = struct { return if (n > 0) @intCast(n) else 0; } + /// Bytes typed that the app has not read yet: its end's input queue + /// (the master's FIONREAD counts only what the app wrote). + pub fn unread(self: *Harness) usize { + const FIONREAD: c_int = switch (@import("builtin").os.tag) { + .linux => posix.T.FIONREAD, + else => 0x4004667f, + }; + const fd = libc.open(ptsname(self.master) orelse return 0, .{ .ACCMODE = .RDWR, .NOCTTY = true, .CLOEXEC = true }); + if (fd < 0) return 0; + defer _ = libc.close(fd); + var n: c_int = 0; + if (posix.system.ioctl(fd, FIONREAD, @intFromPtr(&n)) != 0) return 0; + return if (n > 0) @intCast(n) else 0; + } + /// Resize both the pty (SIGWINCH to the app) and our terminal (grid reflows /// to the new size). Harness terminal first so it's ready for the app's /// re-render at the new size. diff --git a/test/tty.zig b/test/tty.zig index a6e37c6c..47fca229 100644 --- a/test/tty.zig +++ b/test/tty.zig @@ -263,11 +263,28 @@ pub const Tty = struct { } /// Keys by name, space-separated: enter esc tab bs space up down left - /// right home end pgup pgdn, a character, c- and a-. After esc, - /// settle: vaxis reads the next byte in the same batch as alt-. + /// right home end pgup pgdn, a character, c- and a-. An esc is + /// read alone: sent once the app has read what came before it, and + /// read before anything after it is sent (a read that ends in ESC waits + /// for more, and `ESC h` is alt-h). pub fn key(t: *Tty, names: []const u8) !void { var it = std.mem.tokenizeScalar(u8, names, ' '); - while (it.next()) |name| try t.live().send(keyBytes(name) orelse return error.BadKey); + while (it.next()) |name| { + const esc = std.mem.eql(u8, name, "esc"); + if (esc) try t.allRead(); + try t.live().send(keyBytes(name) orelse return error.BadKey); + if (esc) try t.allRead(); + } + } + + /// Pump until the app has read every byte typed (10 s at most). + fn allRead(t: *Tty) !void { + const h = t.live(); + const until = eh.nowMs() + 10_000; + while (h.unread() > 0) { + if (eh.nowMs() > until) return error.InputNeverRead; + _ = try h.pumpOnce(2); + } } /// An SGR mouse press, release or drag (motion with it held) of -- cgit v1.3 From 8953e01fba330404ded0e5b87bf4f4bb1cfddbb8 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 15:52:03 -0300 Subject: tui: a frame with no caret hides the terminal's cursor: the frontend called showCursor for a frame with a caret and nothing for one without (dev/tui/tui.zig, the frame's end), vaxis keeps cursor_vis, so the block cursor stayed visible where the last caret was (hscroll: on the first text column of a view wheeled sideways past the caret; a +Search or a pane whose caret is off screen; a terminal pane's spawn); now win.hideCursor; the tty harness records a hidden cursor as `cursor=hidden` (where a hidden cursor was left is no one's: test/e2e_harness.zig `cursor` says `shown`, test/tty.zig's snap and stable key read it): with the harness alone no golden moved (0 of 145), with the fix ten moved, each only in snap headers from cursor=X,Y to cursor=hidden (checked line by line, golden_diff.py): collapse 2, follow 1, hscroll 1, images 2, jumps 1, lspcomplete 1, shrinktag 2, ttytaken 1, wheeldrift 4, wrap 1, re-recorded; a user saw it: a stale block cursor on the text in every frame with no caret Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- dev/tui/tui.zig | 4 +++- test/e2e_harness.zig | 6 ++++-- test/snapshots/collapse.golden | 4 ++-- test/snapshots/follow.golden | 2 +- test/snapshots/hscroll.golden | 2 +- test/snapshots/images.golden | 4 ++-- test/snapshots/jumps.golden | 2 +- test/snapshots/lspcomplete.golden | 2 +- test/snapshots/shrinktag.golden | 4 ++-- test/snapshots/ttytaken.golden | 2 +- test/snapshots/wheeldrift.golden | 8 ++++---- test/snapshots/wrap.golden | 2 +- test/tty.zig | 10 +++++----- 13 files changed, 28 insertions(+), 24 deletions(-) diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index 638f1400..30b334b3 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -1785,10 +1785,12 @@ const Shell = struct { vx.freeImage(sc.tty.writer(), removed.value.id); if (stale_len < stale.len) break; } + // A frame with no caret hides the terminal's cursor: shown, it + // would stay where the last caret was. if (shown.cursor) |cur| { win.showCursor(cur.x, cur.y); win.setCursorShape(if (cur.bar) .beam else .default); - } + } else win.hideCursor(); const tz_render = tracy.zone(@src(), "vx.render"); const before = sc.tty.tty_writer.pos + sc.tty.writer().end; vx.render(sc.tty.writer()) catch {}; diff --git a/test/e2e_harness.zig b/test/e2e_harness.zig index f9ed44c0..9481166e 100644 --- a/test/e2e_harness.zig +++ b/test/e2e_harness.zig @@ -349,11 +349,13 @@ pub const Harness = struct { }; } - /// The visual cursor position (viewport coords): { x, y }. - pub fn cursor(self: *Harness) struct { x: u16, y: u16 } { + /// The visual cursor position (viewport coords): { x, y }, and whether + /// the app shows it (DECTCEM). + pub fn cursor(self: *Harness) struct { x: u16, y: u16, shown: bool } { return .{ .x = self.term.screens.active.cursor.x, .y = self.term.screens.active.cursor.y, + .shown = self.term.modes.get(.cursor_visible), }; } diff --git a/test/snapshots/collapse.golden b/test/snapshots/collapse.golden index 241bc057..3f73e051 100644 --- a/test/snapshots/collapse.golden +++ b/test/snapshots/collapse.golden @@ -5,7 +5,7 @@ | 1 KEEP-FIRST | 2 KEEP-SECOND | 3 KEEP-THIRD -== snap middle-collapsed grid=160x25 cursor=7,3 +== snap middle-collapsed grid=160x25 cursor=hidden |3: |4: |5: @@ -64,7 +64,7 @@ |3: 1 KEEP-FIRST Collapse |4: 2 KEEP-SECOND |5: 3 KEEP-THIRD -== snap tab-collapsed grid=160x25 cursor=51,2 +== snap tab-collapsed grid=160x25 cursor=hidden |3: |4: |5: diff --git a/test/snapshots/follow.golden b/test/snapshots/follow.golden index c02ea08f..69749b42 100644 --- a/test/snapshots/follow.golden +++ b/test/snapshots/follow.golden @@ -31,7 +31,7 @@ | 27 line 27 52 line 52 77 line 77 == snap hop grid=150x30 cursor=82,5 |3: 1 line 1 Save Term Collapse Follow Del Unfoll Save Term Collapse Follow Del Unfo -== snap wheel grid=150x30 cursor=82,5 +== snap wheel grid=150x30 cursor=hidden |3: 2 line 2 Save Term Collapse Follow Del Unfoll Save Term Collapse Follow Del Unfo |4: 3 line 3 ow llow |5: 4 line 4 29 line 29 54 line 54 diff --git a/test/snapshots/hscroll.golden b/test/snapshots/hscroll.golden index 5f930ddf..4799b3b5 100644 --- a/test/snapshots/hscroll.golden +++ b/test/snapshots/hscroll.golden @@ -20,7 +20,7 @@ | Mode Filter Collapse Del | ls | wide.txt -== snap wheeled grid=90x31 cursor=7,9 +== snap wheeled grid=90x31 cursor=hidden |9: 1 ND_A_MARKER_WAY_OUT_RIGHT_padpadpadpad == snap clamped grid=90x31 cursor=7,9 |9: 1 short1 END_A_MARKER_WAY_OUT_RIGHT_padp diff --git a/test/snapshots/images.golden b/test/snapshots/images.golden index 6a06f55b..04797da3 100644 --- a/test/snapshots/images.golden +++ b/test/snapshots/images.golden @@ -1,4 +1,4 @@ -== snap img-open grid=150x31 cursor=11,8 +== snap img-open grid=150x31 cursor=hidden | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config History Debug Exit | New Term Find Grep Joincol Delcol New Term Find Grep Joincol Delcol | /tmp/pardes-snap/images/cwd Term+bash Save Mode Filter Collapse Del /tmp/pardes-snap/images/cwd Term+bash Save Mode Filter Collapse Del @@ -63,7 +63,7 @@ |14: 0-0 d,#152019, 1-29 d,#0d1410, 30-32 p8,p4, 33-33 p4,p8, 34-34 p8,p12, 35-35 p12,p8, 36-45 p12,p12, 46-74 p12,#0d1410, 75-75 p12,#608269, 76-149 p12,#0d1410, |15: 0-0 d,#152019, 1-29 d,#0d1410, 30-30 p4,p8, 31-31 p8,p4, 32-32 p8,p12, 33-33 p12,p8, 34-45 p12,p12, 46-74 p12,#0d1410, 75-75 p12,#608269, 76-149 p12,#0d1410, |16: 0-0 d,#152019, 1-29 d,#0d1410, 30-30 p8,p12, 31-31 p12,p8, 32-45 p12,p12, 46-74 p12,#0d1410, 75-75 p12,#608269, 76-149 p12,#0d1410, -== snap no-ascii grid=150x31 cursor=11,8 +== snap no-ascii grid=150x31 cursor=hidden |6: img petscii:on palette:terminal ascii:off /tmp/pardes-snap/images/cwd/pic |8: Ascii |9: ██████████████🬝🬹 diff --git a/test/snapshots/jumps.golden b/test/snapshots/jumps.golden index 6cb8a45f..34712e6e 100644 --- a/test/snapshots/jumps.golden +++ b/test/snapshots/jumps.golden @@ -130,7 +130,7 @@ |3: 86 line 86 Last ls == snap last-back grid=150x31 cursor=7,17 |3: 86 line 86 ls Last -== snap jumplist grid=150x31 cursor=7,17 +== snap jumplist grid=150x31 cursor=hidden |3: 86 line 86 Jumplist ls |16: /tmp/pardes-snap/jumps/cwd/+Jumps Save Term Collapse Follow LocationsConf |17: ig Del diff --git a/test/snapshots/lspcomplete.golden b/test/snapshots/lspcomplete.golden index 48dac907..72b413cf 100644 --- a/test/snapshots/lspcomplete.golden +++ b/test/snapshots/lspcomplete.golden @@ -54,7 +54,7 @@ | 1 c.zig:7:23 verdigris Shade | 2 c.zig:7:23 cinnabar Shade | ~ -== snap nobrace grid=100x19 cursor=16,10 +== snap nobrace grid=100x19 cursor=hidden | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config History Debug Exit | New Term Find Grep Joincol Delcol |^*/tmp/pardes-snap/lspcomplete/cwd/d.zig Save Term Collapse Follow TreeContext Def Refs Del diff --git a/test/snapshots/shrinktag.golden b/test/snapshots/shrinktag.golden index bfca20e3..c8ef1a13 100644 --- a/test/snapshots/shrinktag.golden +++ b/test/snapshots/shrinktag.golden @@ -20,7 +20,7 @@ | de Filter Collapse Del | ls | w.txt -== snap shrunk grid=100x31 cursor=4,9 +== snap shrunk grid=100x31 cursor=hidden |4: w.txt ls |5: w.txt |6: /tmp/pardes-snap/shrinktag/cwd Term+bash Save Mo @@ -31,7 +31,7 @@ |18: |19: |20: -== snap move-preview grid=100x31 cursor=4,9 +== snap move-preview grid=100x31 cursor=hidden == snap restored grid=100x31 cursor=4,9 |4: ls ls |5: w.txt w.txt diff --git a/test/snapshots/ttytaken.golden b/test/snapshots/ttytaken.golden index 765dc734..ee72ccc2 100644 --- a/test/snapshots/ttytaken.golden +++ b/test/snapshots/ttytaken.golden @@ -38,7 +38,7 @@ |28: line 26 |29: line 27 |30: big.txt -== snap spawned grid=210x31 cursor=109,2 +== snap spawned grid=210x31 cursor=hidden |2: /tmp/pardes-snap/ttytaken/cwd Term+bash Save Mode Filter Collapse Del @`echo TAKEN''ONE` @`echo TAKEN''TWO` |3: line 1 Exec |16: : diff --git a/test/snapshots/wheeldrift.golden b/test/snapshots/wheeldrift.golden index 2474411c..393a57e1 100644 --- a/test/snapshots/wheeldrift.golden +++ b/test/snapshots/wheeldrift.golden @@ -16,7 +16,7 @@ | 11 line 11_0123456789_abcdefghij_ZEND | 12 line 12_0123456789_abcdefghij_ZEND | 13 line 13_0123456789_abcdefghij_ZEND -== snap drifted grid=70x17 cursor=7,4 +== snap drifted grid=70x17 cursor=hidden |4: 6 line 6_0123456789_abcdefghij_ZEND |5: 7 line 7_0123456789_abcdefghij_ZEND |6: 8 line 8_0123456789_abcdefghij_ZEND @@ -30,8 +30,8 @@ |14: 16 line 16_0123456789_abcdefghij_ZEND |15: 17 line 17_0123456789_abcdefghij_ZEND |16: 18 line 18_0123456789_abcdefghij_ZEND -== snap paying grid=70x17 cursor=7,4 -== snap moved grid=70x17 cursor=7,4 +== snap paying grid=70x17 cursor=hidden +== snap moved grid=70x17 cursor=hidden |4: 6 123456789_abcdefghij_ZEND |5: 7 123456789_abcdefghij_ZEND |6: 8 123456789_abcdefghij_ZEND @@ -45,7 +45,7 @@ |14: 16 0123456789_abcdefghij_ZEND |15: 17 0123456789_abcdefghij_ZEND |16: 18 0123456789_abcdefghij_ZEND -== snap rearmed grid=70x17 cursor=7,4 +== snap rearmed grid=70x17 cursor=hidden |4: 5 123456789_abcdefghij_ZEND |5: 6 123456789_abcdefghij_ZEND |6: 7 123456789_abcdefghij_ZEND diff --git a/test/snapshots/wrap.golden b/test/snapshots/wrap.golden index 431664ee..ba115b3f 100644 --- a/test/snapshots/wrap.golden +++ b/test/snapshots/wrap.golden @@ -17,7 +17,7 @@ == snap visual-gj-again grid=48x15 cursor=10,6 == snap visual-gk grid=48x15 cursor=10,5 == snap visual-count-gj grid=48x15 cursor=10,7 -== snap off grid=48x15 cursor=10,7 +== snap off grid=48x15 cursor=hidden |4: 1 0---------1---------2---------3---- Wrap |5: 2 second line |6: 3 third line diff --git a/test/tty.zig b/test/tty.zig index 47fca229..f26328ca 100644 --- a/test/tty.zig +++ b/test/tty.zig @@ -584,7 +584,7 @@ fn stateKey(h: *eh.Harness) ![]u8 { styles.update("\x00"); } } - return std.fmt.allocPrint(h.gpa, "{d},{d},{x}\n{s}", .{ c.x, c.y, styles.final(), text }); + return std.fmt.allocPrint(h.gpa, "{d},{d},{},{x}\n{s}", .{ c.x, c.y, c.shown, styles.final(), text }); } /// A mouse column: either a screen column, or `@Word` / `@Word#2` - the column @@ -814,7 +814,8 @@ fn snap9pText(arena: std.mem.Allocator, h: *eh.Harness, label: []const u8, prev: return out.items; } -/// `== snap