From 3eb6c09bc97c2e60a17e1663108f4b22e3d1308c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 01:45:46 -0300 Subject: dev, runtime: a session's file watches once (file_watch.Watches, a working name), the session loop's beside its ptys and queue: the kernel's descriptor, the table (each pane's mark and the theme's slot), the reader that posts `files_changed` to the one queue (the Inbox) and the Host's three file calls (Watches.Calls fills both frontends' write_file, watch_file, watch_theme); the terminal's reader (an Io task posting to vaxis's queue, its files_changed message) and the window's (a thread with a stop pipe, polling a non-blocking descriptor) are deleted for one Io task on a blocking descriptor ended by its cancel, as the ptys' readers are; a Restore lets go of the loop's table, so the frontend call `watched` is gone (ten calls to nine); what a user sees: nothing (the queue keeps one change flag however many reads posted it; a reader that cannot start leaves the session running unwatched, as the terminal's did, where the window's start failed); tui core-test 857/1007 (150 skipped; +1, the device's test), shell-test 1047/1050, term 17/17, pane 183/184, kitty 45/45, behaviour-test and --replay 275/275, process-test 0 of 144 failed (ttytaken once in the run, passed on its retry), soaks --clients 5 and --bytes --clients 5 diverged 0, unequal 0, quiet checks 597/0 673/0 779/0 and 920/0 723/0 755/0, unlisted 0, corpus scene 22 of 22, no leak; gui unit-test 1643/1647 with only the perf check's BaselineHarnessMismatch; daemon.py plain, --far, --games, --window-clients, --upgrade both ways pass; the macOS library (Linux, aarch64-macos) and FreeBSD build (load 9-18) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- dev/file_watch.zig | 122 +++++++++++++++++++++++++++++++++++++++++++++++++++++ dev/gui/gui.zig | 121 ++++++---------------------------------------------- dev/tui/tui.zig | 77 ++++++--------------------------- 3 files changed, 148 insertions(+), 172 deletions(-) (limited to 'dev') diff --git a/dev/file_watch.zig b/dev/file_watch.zig index 84f37c81..58229d90 100644 --- a/dev/file_watch.zig +++ b/dev/file_watch.zig @@ -664,6 +664,88 @@ pub fn reloadTheme( return false; } +/// A session's file watches: the kernel's descriptor, the table (each +/// pane's mark and the theme's slot) and the reader that posts a change +/// to the session's queue (Inbox) as `files_changed`. One a session, the +/// session loop's (runtime/session.zig): the Host's three file calls are +/// answered here whatever the frontend (`Calls`), and a frontend taking +/// `files_changed` off the queue hands it back (`reload`). +pub const Watches = struct { + fd: c_int = -1, + table: Table = @splat(null), + io: std.Io, + gpa: std.mem.Allocator, + queue: *Inbox, + reader: ?std.Io.Future(void) = null, + + const Inbox = @import("Inbox.zig"); + + pub fn open(io: std.Io, gpa: std.mem.Allocator, queue: *Inbox) Watches { + return .{ .fd = init(false), .io = io, .gpa = gpa, .queue = queue }; + } + + /// The reader, from the loop's start on (none: nothing is watched for + /// a change, the marks still made). + pub fn start(w: *Watches) void { + if (w.fd >= 0) w.reader = w.io.concurrent(read, .{ w.io, w.fd, w.queue }) catch null; + } + + pub fn deinit(w: *Watches) void { + stop(w.fd); + if (w.reader) |*r| r.cancel(w.io); + w.reader = null; + if (w.fd >= 0) _ = libc.close(w.fd); + w.fd = -1; + } + + /// The marks reconciled after a wake; a second pass asked of the + /// queue when one wants it (`reloadPane`). + pub fn reload(w: *Watches, core: *pardes.Pardes) void { + if (reloadChanged(core, w.io, w.gpa, &w.table)) w.queue.push(.files_changed); + } + + /// Blocked in a read of the descriptor (a kqueue's `wait`, where there + /// is nothing to read): a change posted, whatever it was (`reload` + /// reads every mark); canceled (`deinit`), it ends. + fn read(io: std.Io, fd: c_int, queue: *Inbox) void { + if (comptime builtin.os.tag != .linux and builtin.os.tag != .freebsd) { + while (wait(fd)) queue.push(.files_changed); + return; + } + const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; + var buf: [4096]u8 = undefined; + while (true) { + const n = file.readStreaming(io, &.{&buf}) catch return; + if (n == 0) return; + queue.push(.files_changed); + } + } + + /// The Host's file calls, for a host whose `ctx` is a `*Ctx` with the + /// fields `watches: *Watches` and `core: *Pardes`. + pub fn Calls(comptime Ctx: type) type { + return struct { + fn of(ctx: ?*anyopaque) *Ctx { + return @ptrCast(@alignCast(ctx.?)); + } + pub fn writeFile(ctx: ?*anyopaque, id: pardes.Pane.Id, path: []const u8, bytes: []const u8) void { + const s = of(ctx); + @import("host_io.zig").writeFile(s.core, &s.watches.table, id.index(), path, bytes); + } + pub fn watchFile(ctx: ?*anyopaque, id: pardes.Pane.Id, _: []const u8, on: bool, mode: pardes.WatchMode) void { + const s = of(ctx); + const w = s.watches; + if (applyEffect(s.core, w.io, w.fd, &w.table, id.index(), on, mode)) w.queue.push(.files_changed); + } + pub fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void { + const s = of(ctx); + const w = s.watches; + if (applyThemeEffect(s.core, w.gpa, w.fd, &w.table, generation, on)) w.queue.push(.files_changed); + } + }; + } +}; + pub fn identify(io: std.Io, path: []const u8) !Identity { const native = filesystem.localPath(path) orelse return error.NonLocalPath; pardes.turn.yield(); @@ -961,3 +1043,43 @@ test "a watched file deleted wakes the watch at once, and its pane says so" { _ = reloadChanged(core, io, gpa, &watches); try std.testing.expect(pane.file.?.disk_gone); } + +test "a session's watches: a marked file's change posted to the queue, the reader ended at the end" { + if (comptime !supported or !filesystem.platform_has_fs) return; + const io = std.testing.io; + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "before\n" }); + var path_buf: [256]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/watched", .{tmp.sub_path}); + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + while (core.nextEffect()) |_| {} + const id: u8 = @intCast(core.freeSlot().?); + const pane = try pardes.panes.File.open(core, id, path, 0); + var queue: Watches.Inbox = .{ .io = io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + var w: Watches = .open(io, gpa, &queue); + defer w.deinit(); + if (w.fd < 0) return error.NoWatcher; + defer unwatchAll(w.fd, &w.table); + while (core.nextEffect()) |effect| switch (effect) { + .watch => |watch| if (watch.pane.index() == id and watch.on) { + _ = applyEffect(core, io, w.fd, &w.table, id, watch.on, watch.mode); + }, + else => {}, + }; + w.start(); + try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "after\n" }); + var batch: Watches.Inbox.Batch = .{}; + for (0..500) |_| { + queue.takeInto(&batch); + if (batch.len > 0) break; + try io.sleep(.fromMilliseconds(10), .awake); + } + try std.testing.expectEqual(@as(usize, 1), batch.len); + try std.testing.expect(batch.items[0] == .files_changed); + w.reload(core); + try std.testing.expectEqualStrings("after\n", pane.file.?.content); +} diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index c3272957..59e0516a 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -382,32 +382,6 @@ fn sdlWake(_: ?*anyopaque) void { const PipeTasks = selection_pipe.Tasks; const output_capacity = Queue.output_capacity; -fn stopPipe() ![2]c_int { - var fds: [2]c_int = undefined; - if (libc.pipe(&fds) != 0) return error.PipeFailed; - errdefer for (fds) |fd| { - _ = libc.close(fd); - }; - for (fds) |fd| if (libc.fcntl(fd, libc.F.SETFD, @as(c_int, 1)) < 0) return error.PipeFailed; - return fds; -} - -fn watchThread(fd: c_int, stop: c_int, q: *Queue) void { - while (true) { - var fds = [_]libc.pollfd{ - .{ .fd = stop, .events = libc.POLL.IN, .revents = 0 }, - .{ .fd = fd, .events = libc.POLL.IN, .revents = 0 }, - }; - if (libc.poll(&fds, fds.len, -1) < 0) { - if (libc.errno(-1) == .INTR) continue; - return; - } - if (fds[0].revents != 0) return; - if ((fds[1].revents & (libc.POLL.ERR | libc.POLL.HUP | libc.POLL.NVAL)) != 0) return; - if (fds[1].revents != 0 and file_watch.drain(fd)) q.push(.files_changed); - } -} - const Gui = struct { addon_gpu: ?SketchGpu = null, addon_hash: [pardes.MAX_PANES]u64 = @splat(0), @@ -1017,10 +991,6 @@ const Own = struct { test_mode: bool, detached: bool, pipe_tasks: PipeTasks = .{}, - inotify_fd: c_int = -1, - watch_reader: ?std.Thread = null, - watch_stop: [2]c_int = .{ -1, -1 }, - watches: file_watch.Table = @splat(null), shell: Shell = undefined, const Session = session_loop.Loop(Own); @@ -1045,7 +1015,6 @@ const Own = struct { observeGuiFont(g, core); syncTaglineFont(g, core); l.inbox.wake_fn = sdlWake; - o.inotify_fd = file_watch.init(true); o.shell = .{ .core = core, .gui = g, @@ -1055,8 +1024,7 @@ const Own = struct { .ptys = &l.ptys, .queue = &l.inbox, .pipe_tasks = &o.pipe_tasks, - .inotify_fd = o.inotify_fd, - .watches = &o.watches, + .watches = &l.watches, .fs = l.fs, .test_mode = o.test_mode, .test_clock = if (o.test_mode) host_io.testClock() else null, @@ -1082,18 +1050,6 @@ const Own = struct { pardes.lsp.setStatusSink(null, null); pardes.Kind.drawer = null; o.shell.job_tasks.cancelAll(io); - if (o.inotify_fd >= 0) { - if (o.watch_reader) |thread| { - _ = host_io.writeFd(o.watch_stop[1], "x"); - thread.join(); - } - for (o.watch_stop) |fd| if (fd >= 0) { - _ = libc.close(fd); - }; - file_watch.stop(o.inotify_fd); - _ = libc.close(o.inotify_fd); - o.inotify_fd = -1; - } o.pipe_tasks.cancelAll(io); if (l.inbox.lsp_task) |*task| task.future.cancel(io); // Its worker may be waiting on the queue for room. @@ -1102,10 +1058,6 @@ const Own = struct { } pub fn start(o: *Own, l: *Session) !void { - 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], &l.inbox }); - } if (l.fs) |f| try f.watch(&l.inbox, wakeFs); _ = c.SDL_StartTextInput(o.g.window); @@ -1133,10 +1085,6 @@ const Own = struct { deliverNote(&o.shell, n); } - pub fn watched(o: *Own) session_loop.Watched { - return .{ .fd = o.inotify_fd, .table = &o.watches }; - } - pub fn restoring(o: *Own, nc: *pardes.Pardes) void { o.pipe_tasks.cancelAll(o.shell.io); o.shell.queue.discardCompletions(); @@ -1471,7 +1419,7 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ defer queue.deinit(); var ptys: host_io.Ptys = .{ .queue = &queue, .prompt_rcs = undefined }; var pipe_tasks: PipeTasks = .{}; - var watches: file_watch.Table = @splat(null); + var no_watches: file_watch.Watches = .{ .io = io, .gpa = gpa, .queue = &queue }; var no_peers: replica.Peers = .{}; var shell: Shell = .{ .core = start.r.core(), @@ -1482,8 +1430,7 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ .ptys = &ptys, .queue = &queue, .pipe_tasks = &pipe_tasks, - .inotify_fd = -1, - .watches = &watches, + .watches = &no_watches, .test_mode = test_mode, .client = &window, .peers = &no_peers, @@ -2411,8 +2358,9 @@ const Shell = struct { batch: Queue.Batch = .{}, pipe_tasks: *PipeTasks, job_tasks: PipeTasks = .{}, - inotify_fd: c_int, - watches: *file_watch.Table, + /// The session's file watches (runtime/session.zig's); a client's, + /// none. + watches: *file_watch.Watches, threads_ok: bool = false, test_mode: bool = false, feed: StdinFeed = .{}, @@ -2605,10 +2553,10 @@ const Shell = struct { .tty_taken = PtyCalls.ttyTaken, .fg_name = PtyCalls.fgName, .kill_job = PtyCalls.killJob, - .write_file = writeFile, + .write_file = WatchCalls.writeFile, .write_dump = writeDump, - .watch_file = watchFile, - .watch_theme = watchTheme, + .watch_file = WatchCalls.watchFile, + .watch_theme = WatchCalls.watchTheme, .dump_themes = dumpThemes, .set_clipboard = setClipboard, .read_clipboard = readClipboard, @@ -2622,6 +2570,7 @@ const Shell = struct { }; const PtyCalls = host_io.Ptys.Calls(Shell); + const WatchCalls = file_watch.Watches.Calls(Shell); /// The command panes' exits, told once their output is in (host_io). fn takeExits(s: *Shell) void { @@ -2689,8 +2638,7 @@ const Shell = struct { .window => if (s.gui == null) s.openTheWindow(), .adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd), }; - if (check_files and file_watch.reloadChanged(s.core, s.io, s.gpa, s.watches)) - s.queue.push(.files_changed); + if (check_files) s.watches.reload(s.core); } }; @@ -3216,35 +3164,10 @@ fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { } } -fn writeFile(ctx: ?*anyopaque, id: pardes.Pane.Id, path: []const u8, bytes: []const u8) void { - const pane = id.index(); - const s = shellOf(ctx); - host_io.writeFile(s.core, s.watches, pane, path, bytes); -} - fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { host_io.writeDump(shellOf(ctx).core, bytes); } -fn watchFile(ctx: ?*anyopaque, id: pardes.Pane.Id, _: []const u8, on: bool, mode: pardes.WatchMode) void { - const pane = id.index(); - const s = shellOf(ctx); - if (file_watch.applyEffect(s.core, s.io, s.inotify_fd, s.watches, pane, on, mode)) - s.queue.push(.files_changed); -} - -fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void { - const s = shellOf(ctx); - if (file_watch.applyThemeEffect( - s.core, - s.gpa, - s.inotify_fd, - s.watches, - generation, - on, - )) s.queue.push(.files_changed); -} - fn dumpThemes(ctx: ?*anyopaque, id: pardes.Pane.Id) void { const pane = id.index(); const s = shellOf(ctx); @@ -6041,25 +5964,6 @@ test "installed Nerd Symbols fallback covers Yazi directory icons" { try std.testing.expect(atlas.glyphForCodepoint(0xe5ff).glyph != 0); } -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; - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - const fd = file_watch.init(true); - if (fd < 0) return error.WatchInitFailed; - defer _ = libc.close(fd); - const stop = try stopPipe(); - defer for (stop) |pipe_fd| { - _ = libc.close(pipe_fd); - }; - const thread = try std.Thread.spawn(.{}, watchThread, .{ fd, stop[0], &queue }); - _ = host_io.writeFd(stop[1], "x"); - thread.join(); - try std.testing.expect(libc.fcntl(fd, libc.F.GETFD) >= 0); - try std.testing.expectEqual(@as(usize, 0), queue.take().len); -} - test "GUI completion failure survives backlog and leaves the document unchanged" { const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); @@ -7809,9 +7713,8 @@ test "a detached GUI authority follows terminal directory changes with no window 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, .ptys = &ptys, .queue = &queue, .pipe_tasks = &pipes, .inotify_fd = -1, .watches = &watches, .peers = &no_peers }; + var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .ptys = &ptys, .queue = &queue, .pipe_tasks = &pipes, .watches = undefined, .peers = &no_peers }; const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); ptys.slots[0] = .{ .fd = child.file.handle, .pid = child.pid }; try std.testing.expect(host_io.writeFd(child.file.handle, "cd child\n")); diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index 5c1945e6..b20c15a0 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -130,7 +130,6 @@ const Msg = union(enum) { search_rows: pardes.Stream.Batch, /// A kind's job done on a worker (host_io.KindJob). kind_job: *host_io.KindJob, - files_changed, fs_ready, /// A replica's connection, handed over by the daemon (Peers). replica: daemon.Joining, @@ -771,6 +770,7 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, 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 no_watches: file_watch.Watches = .{ .io = io, .gpa = gpa, .queue = &no_inbox }; var sh: Shell = .{ .io = io, .gpa = gpa, @@ -780,7 +780,7 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, .loop = &loop, .frame = &frame_arena, .paste_buf = &paste_buf, - .inotify_fd = -1, + .watches = &no_watches, .own = start.joined.view, .screen = &screen, .client = &c, @@ -957,7 +957,7 @@ const Own = struct { .loop = o.loop, .frame = &o.frame_arena, .paste_buf = o.paste_buf, - .inotify_fd = file_watch.init(false), + .watches = &l.watches, .fs = l.fs, .test_clock = host_io.testClock(), .peers = &l.peers, @@ -1000,15 +1000,6 @@ const Own = struct { sh.job_tasks.cancelAll(io); // Its worker may be waiting on the loop's queue for room. sh.core.stream.cancelTask(); - file_watch.stop(sh.inotify_fd); - if (sh.watch_task) |*t| { - t.cancel(io); - sh.watch_task = null; - } - if (sh.inotify_fd >= 0) { - _ = libc.close(sh.inotify_fd); - sh.inotify_fd = -1; - } while (loop.tryEvent() catch null) |ev| switch (ev) { .paste => |b| gpa.free(@constCast(b)), .lsp_done => |d| if (d.rows) |rows| sh.lsp_gpa.free(rows), @@ -1045,7 +1036,6 @@ const Own = struct { if (!screen.on) l.watch(); sh.threads_ok = true; - if (sh.inotify_fd >= 0) sh.watch_task = io.concurrent(watchFiles, .{ io, sh.inotify_fd, loop }) catch null; } /// Detached, the unit is its clients' frame: its output is paced to it @@ -1064,10 +1054,6 @@ const Own = struct { deliverNote(o.loop, n); } - pub fn watched(o: *Own) session_loop.Watched { - return .{ .fd = o.sh.inotify_fd, .table = &o.sh.watches }; - } - pub fn restoring(o: *Own, nc: *pardes.Pardes) void { const sh = &o.sh; const io = sh.io; @@ -1150,7 +1136,9 @@ const Shell = struct { own: u8 = 0, frame: *std.heap.ArenaAllocator, paste_buf: *std.Io.Writer.Allocating, - inotify_fd: c_int, + /// The session's file watches (runtime/session.zig's); a client's, + /// none. + watches: *file_watch.Watches, fs: ?*ninep_io.Listener = null, /// The session's ptys (runtime/session.zig's); a client's, an empty /// table over an empty queue. @@ -1161,8 +1149,6 @@ const Shell = struct { 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, pipe_tasks: PipeTasks = .{}, job_tasks: PipeTasks = .{}, @@ -1259,10 +1245,10 @@ const Shell = struct { .tty_taken = PtyCalls.ttyTaken, .fg_name = PtyCalls.fgName, .kill_job = PtyCalls.killJob, - .write_file = writeFile, + .write_file = WatchCalls.writeFile, .write_dump = writeDump, - .watch_file = watchFile, - .watch_theme = watchTheme, + .watch_file = WatchCalls.watchFile, + .watch_theme = WatchCalls.watchTheme, .dump_themes = dumpThemes, .set_clipboard = setClipboard, .read_clipboard = readClipboard, @@ -1363,6 +1349,7 @@ const Shell = struct { } const PtyCalls = host_io.Ptys.Calls(Shell); + const WatchCalls = file_watch.Watches.Calls(Shell); fn upgradeAsked(ctx: ?*anyopaque, id: pardes.Pane.Id) void { const pane = id.index(); @@ -1722,7 +1709,6 @@ const Shell = struct { if (pasted.len > 0) s.feed(.{ .paste = pasted }); s.paste_buf.clearRetainingCapacity(); }, - .files_changed => s.check_files = true, .fs_ready => {}, .lsp_done => |d| { core.update(.{ .lsp_resp = .{ .id = d.id, .rows = d.rows } }); @@ -1785,8 +1771,7 @@ const Shell = struct { fn reloadWatched(s: *Shell) void { if (!s.check_files) return; s.check_files = false; - if (file_watch.reloadChanged(s.core, s.io, s.gpa, &s.watches)) - s.loop.postEvent(.files_changed) catch {}; + s.watches.reload(s.core); } /// The tty's own motions (its glide, a jump's trail) are under way. @@ -1994,6 +1979,7 @@ const Shell = struct { return; }, .eof => |e| s.ptys.eof(s.core, e), + .files_changed => s.check_files = true, else => m.deinit(s.gpa, s.lsp_gpa), } } @@ -2007,29 +1993,10 @@ const Shell = struct { } } - fn writeFile(ctx: ?*anyopaque, id: pardes.Pane.Id, path: []const u8, bytes: []const u8) void { - const pane = id.index(); - const s = of(ctx); - host_io.writeFile(s.core, &s.watches, pane, path, bytes); - } - fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { host_io.writeDump(of(ctx).core, bytes); } - fn watchFile(ctx: ?*anyopaque, id: pardes.Pane.Id, _: []const u8, on: bool, mode: pardes.WatchMode) void { - const pane = id.index(); - const s = of(ctx); - if (file_watch.applyEffect(s.core, s.io, s.inotify_fd, &s.watches, pane, on, mode)) - s.loop.postEvent(.files_changed) catch {}; - } - - fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void { - const s = of(ctx); - if (file_watch.applyThemeEffect(s.core, s.gpa, s.inotify_fd, &s.watches, generation, on)) - s.loop.postEvent(.files_changed) catch {}; - } - fn dumpThemes(ctx: ?*anyopaque, id: pardes.Pane.Id) void { const pane = id.index(); const s = of(ctx); @@ -2129,22 +2096,6 @@ fn lspStatusSink(ctx: ?*anyopaque, text: []const u8) void { if (!posted) s.lsp_gpa.free(copy); } -fn watchFiles(io: std.Io, fd: c_int, loop: *Loop) void { - if (comptime builtin.os.tag != .linux and builtin.os.tag != .freebsd) { - while (file_watch.wait(fd)) loop.postEvent(.files_changed) catch break; - return; - } - const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; - // 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: [4096]u8 = undefined; - while (true) { - const n = file.readStreaming(io, &.{&buf}) catch break; - if (n == 0) break; - loop.postEvent(.files_changed) catch break; - } -} - fn keepSignal(_: posix.SIG) callconv(.c) void {} /// A replica client's (`runClient`): a hangup is its end, whoever sent it. @@ -2836,7 +2787,7 @@ test "TTY queued results reject an old LSP request ID" { .loop = undefined, .frame = undefined, .paste_buf = undefined, - .inotify_fd = -1, + .watches = undefined, .peers = &no_peers, .ptys = undefined, }; @@ -2876,7 +2827,7 @@ test "TTY worker setup failures finish matching LSP and pipe requests" { .loop = undefined, .frame = undefined, .paste_buf = undefined, - .inotify_fd = -1, + .watches = undefined, .threads_ok = true, .peers = &no_peers, .ptys = undefined, -- cgit v1.3 From 680cfe1fa5a15be3770d310153258ba9ded13dd8 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 02:35:56 -0300 Subject: dev, runtime: the language servers' client once, through the session's one queue: both frontends start a query with Inbox.startLsp (its task and its id in the Inbox, an older answer turned away at the push and an older one still queued discarded) and land an answer or a status line with Inbox.landLsp; the session loop sets the language client's status sink on its queue from before the first effects and unsets it before the queue goes, a Restore turns the old core's answer away (discardCompletions, the window's way) and the queue's end cancels the query in flight; the terminal's own copy is deleted (its lsp_task, deliverLspRows posting lsp_done to vaxis's queue, a post that BLOCKED the language worker while that queue was full, lspStatusSink, the lsp_done and lsp_status messages and arms, the cancels in close and restoring) and with it its test of a stale answer at apply (the Inbox's rejection is pinned by gui.zig's worker-setup test); what a user sees: a window now shows an LSP status said during the session's first effects (its sink was set only after them), nothing else; the loop's frontend calls stay nine (close and restoring shrank); tui core-test 857/1007 (150 skipped), shell-test 1046/1049 (-1, the deleted test), term 17/17, pane 183/184, kitty 45/45, behaviour-test and --replay 275/275, process-test 0 of 144 failed (hscroll once in the run, passed on its retry), soaks --clients 5 and --bytes --clients 5 diverged 0, unequal 0, quiet checks 651/0 673/0 779/0 and 920/0 723/0 755/0, unlisted 0, corpus scene 22 of 22, no leak; gui unit-test 1643/1647 with only the perf check's BaselineHarnessMismatch; daemon.py plain, --far, --games, --window-clients, --upgrade both ways pass (load 11-16) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- dev/Inbox.zig | 20 ++++++++++++ dev/gui/gui.zig | 14 +-------- dev/tui/tui.zig | 88 ++++++----------------------------------------------- runtime/session.zig | 8 ++++- 4 files changed, 37 insertions(+), 93 deletions(-) (limited to 'dev') diff --git a/dev/Inbox.zig b/dev/Inbox.zig index ed3a9835..1dd30adf 100644 --- a/dev/Inbox.zig +++ b/dev/Inbox.zig @@ -264,6 +264,9 @@ pub fn close(q: *Inbox) void { } pub fn deinit(q: *Inbox) void { + // The query in flight ends first: what it still delivers is dropped. + if (q.lsp_task) |*t| t.future.cancel(q.io); + q.lsp_task = null; q.close(); std.debug.assert(q.waiting == 0); } @@ -310,6 +313,23 @@ pub fn startLsp(q: *Inbox, core: *pardes.Pardes, e: Lsp.Request) void { Lsp.start(q.io, q.lsp_allocator, core, &q.lsp_task, e, q, pushLspRows); } +/// A language server's answer or status line taken off the queue, to the +/// core (whichever frontend took it). +pub fn landLsp(q: *Inbox, core: *pardes.Pardes, m: Msg) void { + switch (m) { + .lsp => |l| { + core.update(.{ .lsp_resp = .{ .id = l.id, .rows = l.rows } }); + if (l.rows) |rows| q.lsp_allocator.free(rows); + }, + .lsp_status => |text| { + var mbuf: [256]u8 = undefined; + core.setStatus(.at(core.view().active), pardes.Messages.Message.stamp(&mbuf, "lsp", text)); + q.lsp_allocator.free(text); + }, + else => unreachable, + } +} + fn pushLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { const q: *Inbox = @ptrCast(@alignCast(ctx orelse return)); q.push(.{ .lsp = .{ .id = id, .rows = rows } }); diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index 59e0516a..df3d2f2b 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -1047,11 +1047,9 @@ const Own = struct { const io = l.io; o.shell.fs = null; host_io.setExitWake(null, null); - pardes.lsp.setStatusSink(null, null); pardes.Kind.drawer = null; o.shell.job_tasks.cancelAll(io); o.pipe_tasks.cancelAll(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.g.hit_core = null; @@ -1066,7 +1064,6 @@ const Own = struct { if (o.test_mode) setStdinRaw() catch {}; o.shell.threads_ok = true; - pardes.lsp.setStatusSink(&l.inbox, Queue.lspStatus); host_io.setExitWake(&l.inbox, Queue.wakeForExit); if (o.detached) { o.shell.closeTheWindow(); @@ -1087,7 +1084,6 @@ const Own = struct { pub fn restoring(o: *Own, nc: *pardes.Pardes) void { o.pipe_tasks.cancelAll(o.shell.io); - o.shell.queue.discardCompletions(); // One view, the window's (host_io.restoreCore). o.shell.gview = 0; o.g.cells.clearImages(); @@ -2601,15 +2597,7 @@ const Shell = struct { for (msgs.slice()) |m| switch (m) { .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); - }, - .lsp_status => |text| { - var mbuf: [256]u8 = undefined; - s.core.setStatus(.at(s.core.view().active), message.stamp(&mbuf, "lsp", text)); - s.lsp_allocator.free(text); - }, + .lsp, .lsp_status => s.queue.landLsp(s.core, m), .pipe => |response_value| { var response = response_value; s.core.update(.{ .pipe_resp = .{ diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index b20c15a0..1c59a8be 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -123,8 +123,6 @@ const Msg = union(enum) { paste: []const u8, paste_start, paste_end, - lsp_done: struct { id: u32, rows: ?[]u8 }, - lsp_status: []u8, pipe_done: selection_pipe.Response, /// A streaming search's rows (pardes.Stream). search_rows: pardes.Stream.Batch, @@ -969,7 +967,6 @@ const Own = struct { l.inbox.wake_ctx = sh; l.peers.wake_ctx = o.loop; l.peers.wake = wakeForReplica; - pardes.lsp.setStatusSink(sh, lspStatusSink); host_io.setExitWake(o.loop, wakeForExit); const host = sh.host(); l.core.host = host; @@ -991,19 +988,12 @@ const Own = struct { stopInput(io, &o.screen.thread); pardes.Kind.drawer = null; host_io.setExitWake(null, null); - pardes.lsp.setStatusSink(null, null); - if (sh.lsp_task) |*t| { - t.future.cancel(io); - sh.lsp_task = null; - } sh.pipe_tasks.cancelAll(io); sh.job_tasks.cancelAll(io); // Its worker may be waiting on the loop's queue for room. sh.core.stream.cancelTask(); while (loop.tryEvent() catch null) |ev| switch (ev) { .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), .pipe_done => |response_value| { var response = response_value; response.deinit(gpa); @@ -1057,10 +1047,6 @@ const Own = struct { pub fn restoring(o: *Own, nc: *pardes.Pardes) void { const sh = &o.sh; const io = sh.io; - if (sh.lsp_task) |*task| { - task.future.cancel(io); - sh.lsp_task = null; - } sh.pipe_tasks.cancelAll(io); // One view, the terminal's (host_io.restoreCore). const live = o.screen; @@ -1149,7 +1135,6 @@ const Shell = struct { batch: host_io.Inbox.Batch = .{}, batch_at: usize = 0, queue_woken: std.atomic.Value(bool) = .init(false), - lsp_task: ?host_io.Lsp.Task = null, pipe_tasks: PipeTasks = .{}, job_tasks: PipeTasks = .{}, threads_ok: bool = false, @@ -1710,19 +1695,6 @@ const Shell = struct { s.paste_buf.clearRetainingCapacity(); }, .fs_ready => {}, - .lsp_done => |d| { - core.update(.{ .lsp_resp = .{ .id = d.id, .rows = d.rows } }); - if (d.rows) |rows| s.lsp_gpa.free(rows); - if (s.lsp_task) |*t| if (t.id == d.id) { - t.future.await(s.io); - s.lsp_task = null; - }; - }, - .lsp_status => |text| { - var mbuf: [256]u8 = undefined; - core.setStatus(.at(core.view().active), message.stamp(&mbuf, "lsp", text)); - s.lsp_gpa.free(text); - }, .pipe_done => |response_value| { var response = response_value; core.update(.{ .pipe_resp = .{ @@ -1980,6 +1952,7 @@ const Shell = struct { }, .eof => |e| s.ptys.eof(s.core, e), .files_changed => s.check_files = true, + .lsp, .lsp_status => s.ptys.queue.landLsp(s.core, m), else => m.deinit(s.gpa, s.lsp_gpa), } } @@ -2024,16 +1997,9 @@ const Shell = struct { fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { const s = of(ctx); - if (!s.threads_ok) { - s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); - return s.core.reportError(req.pane, "lsp", error.WorkersUnavailable); - } - host_io.Lsp.start(s.io, s.lsp_gpa, s.core, &s.lsp_task, req, s, deliverLspRows); - } - - fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { - const s = of(ctx); - s.loop.postEvent(.{ .lsp_done = .{ .id = id, .rows = rows } }) catch if (rows) |owned| s.lsp_gpa.free(owned); + if (s.threads_ok) return s.ptys.queue.startLsp(s.core, req); + s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); + s.core.reportError(req.pane, "lsp", error.WorkersUnavailable); } fn pipe(ctx: ?*anyopaque, id: u32) void { @@ -2089,13 +2055,6 @@ const Shell = struct { } }; -fn lspStatusSink(ctx: ?*anyopaque, text: []const u8) void { - const s: *Shell = @ptrCast(@alignCast(ctx orelse return)); - const copy = s.lsp_gpa.dupe(u8, text) catch return; - const posted = s.loop.tryPostEvent(.{ .lsp_status = copy }) catch false; - if (!posted) s.lsp_gpa.free(copy); -} - fn keepSignal(_: posix.SIG) callconv(.c) void {} /// A replica client's (`runClient`): a hangup is its end, whoever sent it. @@ -2773,38 +2732,6 @@ 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 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(); - var no_peers: replica.Peers = .{}; - var shell: Shell = .{ - .io = std.testing.io, - .gpa = gpa, - .lsp_gpa = gpa, - .core = core, - .frames = core.frames, - .loop = undefined, - .frame = undefined, - .paste_buf = undefined, - .watches = undefined, - .peers = &no_peers, - .ptys = undefined, - }; - core.lspRequest(0, .status, ""); - const old_id = core.lsp_ask.wait.?.id; - core.lspRequest(0, .status, ""); - const current_id = core.lsp_ask.wait.?.id; - shell.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } }; - _ = shell.apply(.{ .lsp_done = .{ .id = old_id, .rows = try gpa.dupe(u8, "stale result\n") } }); - try std.testing.expect(shell.lsp_task != null); - try std.testing.expectEqual(current_id, shell.lsp_task.?.id); - try std.testing.expectEqual(current_id, core.lsp_ask.wait.?.id); - _ = shell.apply(.{ .lsp_done = .{ .id = current_id, .rows = try gpa.dupe(u8, "") } }); - try std.testing.expect(shell.lsp_task == null); - try std.testing.expect(core.lsp_ask.wait == null); -} - test "TTY worker setup failures finish matching LSP and pipe requests" { const gpa = std.testing.allocator; var failing_vtable = std.testing.io.vtable.*; @@ -2818,6 +2745,9 @@ test "TTY worker setup failures finish matching LSP and pipe requests" { .fail_index = if (failure == 0) 0 else std.math.maxInt(usize), }); var no_peers: replica.Peers = .{}; + var queue: host_io.Inbox = .{ .io = failing_io, .gpa = gpa, .lsp_allocator = failing.allocator() }; + defer queue.deinit(); + var ptys: host_io.Ptys = .{ .queue = &queue, .prompt_rcs = undefined }; var shell: Shell = .{ .io = failing_io, .gpa = failing.allocator(), @@ -2830,7 +2760,7 @@ test "TTY worker setup failures finish matching LSP and pipe requests" { .watches = undefined, .threads_ok = true, .peers = &no_peers, - .ptys = undefined, + .ptys = &ptys, }; core.lspRequest(core.view().active, .status, ""); const req: host_io.Lsp.Request = .{ @@ -2853,7 +2783,7 @@ test "TTY worker setup failures finish matching LSP and pipe requests" { Shell.pipe(&shell, pipe_id); try std.testing.expect(core.pipe.wait == null); try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expect(shell.lsp_task == null); + try std.testing.expect(queue.lsp_task == null); try std.testing.expectEqual(@as(usize, 0), shell.pipe_tasks.len); } } diff --git a/runtime/session.zig b/runtime/session.zig index 6f8ab4a3..c8b8dc25 100644 --- a/runtime/session.zig +++ b/runtime/session.zig @@ -7,7 +7,8 @@ //! (`file_watch.Watches`): 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 LSP's and the pipes' and addons' -//! jobs, the session's own input) are still its frontend's (each `Shell`). +//! jobs, the session's own input) are still its frontend's (each `Shell`); +//! the language servers' answers come through its queue (`Inbox.startLsp`). //! What a frontend does is: //! //! - `options(o)`: before the core: what it gives the core it starts (a @@ -89,6 +90,9 @@ pub fn Loop(comptime Frontend: type) type { 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(); + // The language servers' status lines, from the first effects on. + pardes.lsp.setStatusSink(&l.inbox, host_io.Inbox.lspStatus); + defer pardes.lsp.setStatusSink(null, null); l.ptys = .{ .queue = &l.inbox, .prompt_rcs = &l.prompt_rcs }; defer l.ptys.deinit(); l.watches = .open(l.io, l.gpa, &l.inbox); @@ -157,6 +161,8 @@ pub fn Loop(comptime Frontend: type) type { fn restore(l: *L, path: []const u8) void { const nc = host_io.restoreCore(l.gpa, l.core, path, &l.peers, l.watches.fd, &l.watches.table) orelse return; l.fe.restoring(nc); + // An answer to the old core's query is turned away. + l.inbox.discardCompletions(); l.ptys.stop(); nc.host = l.host; if (l.fs) |f| f.reset(nc); -- cgit v1.3