diff options
37 files changed, 625 insertions, 168 deletions
diff --git a/build/tools.zig b/build/tools.zig index da77958a..e573b16d 100644 --- a/build/tools.zig +++ b/build/tools.zig @@ -229,8 +229,8 @@ pub fn add(b: *std.Build, c: struct { const fs_bench_step = b.step("fs-bench", "9P filesystem request cost and allocation count (-- [--json] [--reps N])"); fs_bench_step.dependOn(&run_fs_bench.step); - // The syntax module's own tests and snapshots, on the core without - // a terminal: its tests reach the editor's modes (modal.zig). + // The syntax module's snapshots, on the core without a terminal (its + // tests are core-test's, those named "syntax ..."). var syntax_cfg = c.lean; syntax_cfg.root = "core/syntax.zig"; const syntax_module = core.module(b, c.parts, syntax_cfg).root; @@ -239,15 +239,6 @@ pub fn add(b: *std.Build, c: struct { run_syntax.addPassthruArgs(); run_syntax.has_side_effects = true; b.step("syntax", "emit deterministic syntax snapshots (-- --bench: highlighting latency and allocations)").dependOn(&run_syntax.step); - const syntax_test = b.addTest(.{ - .root_module = syntax_module, - .filters = if (c.test_filters.len == 0) &.{"syntax "} else c.test_filters, - }); - const run_syntax_test = b.addRunArtifact(syntax_test); - run_syntax_test.has_side_effects = true; - const syntax_test_step = b.step("syntax-test", "test syntax correctness without building the editor"); - syntax_test_step.dependOn(&run_syntax_test.step); - if (testMatch(b, c.unit_profile, c.test_filters, syntax_test_step)) |check| check.addArtifactArg(syntax_test); // The library as a package that depends on pardes is given it // (`library`): test/consumer's own `zig build test`, over the packages diff --git a/core/CHANGELOG.md b/core/CHANGELOG.md index b12d6988..49bc105f 100644 --- a/core/CHANGELOG.md +++ b/core/CHANGELOG.md @@ -2,6 +2,17 @@ ## Unreleased +- An experiment, behind `PARDES_PAIR=1` until it is the default: `pardes + FILE` in a terminal and `pardes-gui FILE` fork a session with no + frontend of its own and are its first client. Such a session is kept + (started with `new --detach`, or a Detach typed in any client since) or + not: closing a client's window or terminal, or a TERM to it, ends a + session not kept when that was its last client; a client killed outright + leaves it running. `pardes ps` says `(tty, kept)` or `(tty)` of it. + Without the variable nothing changes, but a terminal client (`pardes + attach`) ended by a TERM now says goodbye and exits 0, its terminal put + back, where it died of the signal. + - `pardes new --detach[=NAME]` returns once the session runs (registered and listening), printing its name, exit 0; the session runs on in a session of its own. `pardes --detach=NAME` without `new` is still the diff --git a/core/Core.zig b/core/Core.zig index 7c20c252..55b3682f 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/File.zig b/core/File.zig index ceb6d03b..8a8c05de 100644 --- a/core/File.zig +++ b/core/File.zig @@ -2312,6 +2312,7 @@ test "a pager's text is a diff when it holds a diff header or a unified hunk" { } test "a long line is painted only around the caret" { + if (comptime !syntax.full_grammars) return error.SkipZigTest; // JSON's const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const line = try std.testing.allocator.alloc(u8, 600 << 10); diff --git a/core/Query.zig b/core/Query.zig index 95322cc1..3a5aa5f8 100644 --- a/core/Query.zig +++ b/core/Query.zig @@ -2390,6 +2390,7 @@ test "Grep: lines of the files under the owner's directory, under their file; Al } test "* seeds line 1 and keeps the keyboard; SPC b b picks a pane, SPC s s a declaration" { + if (comptime !syntax.minimal_grammars) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); defer p.deinit(); const pane = try p.setTestFile("const alpha = 1;\nfn beta() void {\n _ = alpha;\n}\nfn gamma() void {}\n"); @@ -2624,6 +2625,7 @@ test "a query row's place is its text: the match tinted after it, B3 on it opens } test "the +Preview: the query's hits in its file are its places, the row's one current and selected, coloured as the file is" { + if (comptime !syntax.minimal_grammars) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const text = "const needle = 1;\nconst hay = 2;\nfn f() void {\n _ = needle;\n}\npub const needle_too = needle;\n"; diff --git a/core/Stream.zig b/core/Stream.zig index 1f4a7405..a04cad46 100644 --- a/core/Stream.zig +++ b/core/Stream.zig @@ -1266,6 +1266,7 @@ test "Stream: the listing of files for Find on a worker, a cap of hits stops the } test "Stream: a big text's declarations are parsed on a worker, never the loop, and the rows of its / regroup under them" { + if (comptime !syntax.minimal_grammars) return error.SkipZigTest; const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); defer p.deinit(); var text: std.ArrayList(u8) = .empty; @@ -1304,6 +1305,7 @@ test "Stream: a big text's declarations are parsed on a worker, never the loop, } test "Stream: a scroll's colours are painted ahead on a worker, so PageDown after PageDown parses nothing on the frame" { + if (comptime !syntax.minimal_grammars) return error.SkipZigTest; const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); defer p.deinit(); var text: std.ArrayList(u8) = .empty; 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 1a127ad4..de58da94 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -2059,10 +2059,10 @@ pub const Peers = struct { /// No frontend of its own (the host says): with no client either, the /// session is unattended. detached: bool = false, - /// Its last client left by closing its window, and no Detach was typed - /// in any (`kept`): a pair's session ends there (runtime/session.zig). + /// Its last client left with a close (its window closed, its terminal + /// hung up) and the session is a pair's not kept (daemon.sessionState): it + /// ends there (runtime/session.zig). closed: bool = false, - kept: bool = false, /// The worst a join cost the session's step, and the last one's dump. join_ns: u64 = 0, each_join: std.ArrayListUnmanaged(u64) = .empty, @@ -2362,7 +2362,7 @@ pub const Peers = struct { core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view.index())); ps.closeViewOf(core, peer, peer.again); if (ps.count() == 0) core.unattended = ps.detached; - if (ps.count() == 0 and peer.close and !ps.kept) ps.closed = true; + if (ps.count() == 0 and peer.close and daemon.sessionState() == .pair) ps.closed = true; ps.seq += 1; ps.unit(0, ps.seq); ps.letGo(peer); @@ -2467,7 +2467,7 @@ pub const Peers = struct { /// (`left`), its last word; the client goes, and its reader says so. pub fn detach(ps: *Peers, k: u8) bool { for (ps.list) |slot| if (slot) |peer| if (peer.view.index() == k) { - ps.kept = true; + daemon.keepSession(); var out: [wire.max_name + 8]u8 = undefined; peer.last(wire.encodeServer(&out, .{ .left = ps.name[0..@min(ps.name.len, wire.max_name)] }) catch unreachable); return true; @@ -7364,6 +7364,42 @@ 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(); +} + +test "an Edit's stop token is each process's own (selection_pipe.next_token): a client's differs from its session's, and they agree" { + var n = try NinepJoin.init("b\na\n", TestHost.host()); + defer n.deinit(); + try n.join(); + _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.ctl), .data = "Edit , | sort\n" }, false); + const session = n.a.core.pipe.edit_run.?.request.token; + const client = n.late.?.core().pipe.edit_run.?.request.token; + try std.testing.expect(session != client); + 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/core/syntax.zig b/core/syntax.zig index 19831ec2..00ee497f 100644 --- a/core/syntax.zig +++ b/core/syntax.zig @@ -7,8 +7,10 @@ const regexp = @import("regexp.zig"); const c_heap = @import("c_heap"); const diff = @import("diff.zig"); -const minimal_grammars = config.grammars != .none; -const full_grammars = config.grammars == .full; +/// The grammar sets built (`-Dgrammars`): a test that needs a grammar +/// not built skips. +pub const minimal_grammars = config.grammars != .none; +pub const full_grammars = config.grammars == .full; pub const ts = @import("tree-sitter"); const ts_queries = @import("ts_queries"); @@ -1260,6 +1262,7 @@ test "every vendored textobject and indent query compiles against its grammar" { } test "syntax context nested Zig containers and multiline function signatures" { + if (comptime !minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1291,7 +1294,7 @@ test "syntax context nested Zig containers and multiline function signatures" { } test "syntax context Python class and function body excludes first statement" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1304,6 +1307,7 @@ test "syntax context Python class and function body excludes first statement" { } test "syntax context multiline bindings and C++ namespaces preserve declaration starts" { + if (comptime !minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1313,7 +1317,7 @@ test "syntax context multiline bindings and C++ namespaces preserve declaration try std.testing.expectEqual(@as(usize, 1), zig_declarations.len); try std.testing.expectEqual(@as(usize, 0), zig_declarations[0].start_line); try std.testing.expectEqual(@as(usize, 1), zig_declarations[0].header_end_line); - if (!minimal_grammars) return; + if (!minimal_grammars) return error.SkipZigTest; const cpp_source = "namespace example {\nstruct Outer {\n int run() {\n return 1;\n }\n};\n}\n"; const cpp_declarations = try contextDeclarations(gpa, "nested.cpp", cpp_source); defer gpa.free(cpp_declarations); @@ -1325,7 +1329,7 @@ test "syntax context multiline bindings and C++ namespaces preserve declaration } test "syntax context Rust modules impls and methods remain nested" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1341,7 +1345,7 @@ test "syntax context Rust modules impls and methods remain nested" { } test "syntax formatted locations color hidden context and preserve multiline source" { - if (!minimal_grammars) return; + if (!minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1366,7 +1370,7 @@ test "syntax formatted locations color hidden context and preserve multiline sou } test "syntax formatted locations separate alignment from Markdown indentation" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1382,6 +1386,7 @@ test "syntax formatted locations separate alignment from Markdown indentation" { } test "syntax a results row is coloured by the file its location names" { + if (comptime !minimal_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); const gpa = std.testing.allocator; @@ -1431,7 +1436,7 @@ test "syntax codeAfterLocation takes whole-token locations and nothing else" { } test "syntax default full grammar set highlights Typst source" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); @@ -1454,7 +1459,7 @@ test "syntax default full grammar set highlights Typst source" { } test "syntax Typst markup constructs paint and raw blocks inject their language" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); @@ -1498,7 +1503,7 @@ test "syntax Typst markup constructs paint and raw blocks inject their language" } test "syntax markdown highlights markup, injects inline spans and fenced code blocks" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); @@ -1530,7 +1535,7 @@ test "syntax markdown highlights markup, injects inline spans and fenced code bl } test "syntax inline fast path agrees with full Markdown query" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); const selected = (try forLang("markdown_inline")).?; @@ -1577,7 +1582,7 @@ test "syntax inline fast path agrees with full Markdown query" { } test "syntax plain Markdown keeps block styles without starting the inline parser" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); const source = "# Heading\n\nPlain prose.\n\n indented code\n"; @@ -1619,6 +1624,7 @@ test "syntax highlightDiff colors unified diff lines by prefix" { } test "syntax a Zig hunk is coloured as Zig, each side parsed whole" { + if (comptime !minimal_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); const diff_text = @@ -1659,7 +1665,7 @@ test "syntax a Zig hunk is coloured as Zig, each side parsed whole" { } test "syntax a Python hunk is coloured as Python" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); const diff_text = @@ -1680,6 +1686,7 @@ test "syntax a Python hunk is coloured as Python" { } test "syntax a deleted file's lines are coloured in its language" { + if (comptime !minimal_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); const diff_text = @@ -1715,6 +1722,7 @@ test "syntax a hunk in no known language keeps the line colours" { } test "syntax git diff output in a command pane is told and coloured by its rows" { + if (comptime !minimal_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); // A command pane's rows: its command line, then git's output, with one @@ -1747,6 +1755,7 @@ test "syntax git diff output in a command pane is told and coloured by its rows" } test "syntax a section's small hunks share one parse" { + if (comptime !minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1768,6 +1777,7 @@ test "syntax a section's small hunks share one parse" { } test "syntax a hunk painted once is kept, and a long one is parsed in pieces" { + if (comptime !minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1856,6 +1866,7 @@ test "syntax query filtering preserves upstream colors" { } test "syntax Zig keyword captures cover both bytes beyond line ten thousand" { + if (comptime !minimal_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); const code = "pub fn main() void {\n if (true) return;\n}\n"; @@ -1873,6 +1884,7 @@ test "syntax Zig keyword captures cover both bytes beyond line ten thousand" { } test "syntax allocator switching clears default-runtime caches" { + if (comptime !minimal_grammars) return error.SkipZigTest; const source = "fn main() void {}"; const initial = try highlightFileRange(std.testing.allocator, "a.zig", source, 0, source.len); std.testing.allocator.free(initial); @@ -1888,7 +1900,7 @@ test "syntax allocator switching clears default-runtime caches" { } test "syntax location context snapshots retain omitted multiline comment scope" { - if (!minimal_grammars) return; + if (!minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1914,6 +1926,7 @@ test "syntax location context snapshots retain omitted multiline comment scope" } test "syntax declaration locations clear snapshots without muting ordinary context" { + if (comptime !minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1933,7 +1946,7 @@ test "syntax declaration locations clear snapshots without muting ordinary conte } test "syntax stacked addresses do not split multiline source groups" { - if (!minimal_grammars) return; + if (!minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -2018,7 +2031,7 @@ test "syntax source analysis preserves declarations and injected colors" { } test "tables are the pipe_tables tree-sitter finds" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); const Tables = @import("Tables.zig"); @@ -2087,6 +2100,7 @@ test "tables are the pipe_tables tree-sitter finds" { } test "a kept tree told its edits parses to the fresh parse's tree, places and all" { + if (comptime !minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; const a = "const std = @import(\"std\");\n\nfn f(x: u32) u32 {\n return x;\n}\n\ntest \"t\" {\n _ = f(1);\n}\n"; const old_tree = parseTree("a.zig", a, null) orelse return error.NoTree; @@ -2126,6 +2140,7 @@ test "a kept tree told its edits parses to the fresh parse's tree, places and al } test "syntax: a grammar handed in at run time colours and walks as the one compiled in" { + if (comptime !minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); 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..e441df92 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -721,19 +721,22 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, std.process.exit(1); } }; - var start: client_loop.Start = undefined; - if (!start.open(init, opts, .{ .path = path, .session = session, .far = far_link })) Said.no(io, "{s}", .{start.said()}); - defer start.close(); - + // Blocked before its join makes a thread, so that winchWatch alone + // takes them: a hangup (its terminal closed) or a TERM ends it the + // normal way (`quit`), its goodbye a close (a pair's session not kept + // ends at its last client's), what it made kept on disk (`Have.keep`) + // and its ssh forward's socket unlinked (main.zig). var winch_set = posix.sigemptyset(); posix.sigaddset(&winch_set, posix.SIG.WINCH); - // A hangup ends it the normal way (`quit`), what it made kept on disk - // (`Have.keep`) and its ssh forward's socket unlinked (main.zig). posix.sigaddset(&winch_set, posix.SIG.HUP); + posix.sigaddset(&winch_set, posix.SIG.TERM); hangup_quits = true; if (comptime builtin.os.tag == .freebsd) posix.sigaction(.WINCH, &.{ .handler = .{ .handler = keepSignal }, .mask = posix.sigemptyset(), .flags = 0 }, null); posix.sigprocmask(posix.SIG.BLOCK, &winch_set, null); + var start: client_loop.Start = undefined; + if (!start.open(init, opts, .{ .path = path, .session = session, .far = far_link })) Said.no(io, "{s}", .{start.said()}); + defer start.close(); var tty_buf: [0x10000]u8 = undefined; var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf, .kitty = .init(gpa) }; defer screen.kitty.deinit(); @@ -906,7 +909,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 +940,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); } @@ -1544,7 +1549,10 @@ const Shell = struct { virtual.* = @max(virtual.*, s.wake_to); }, .quit => { + // A client's terminal went (a hangup, its input's end) or it + // took a TERM: a close, as a window's close button. if (s.client) |c| { + c.link.close = true; c.link.quit = true; return true; } @@ -1783,10 +1791,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 {}; @@ -1939,19 +1949,20 @@ const Shell = struct { fn keepSignal(_: posix.SIG) callconv(.c) void {} -/// A replica client's (`runClient`): a hangup is its end, whoever sent it. +/// A replica client's (`runClient`): a hangup or a TERM is its end. var hangup_quits = false; fn winchWatch(loop: *Loop) void { var set = posix.sigemptyset(); posix.sigaddset(&set, posix.SIG.WINCH); if (daemon.link >= 0 or hangup_quits) posix.sigaddset(&set, posix.SIG.HUP); + if (hangup_quits) posix.sigaddset(&set, posix.SIG.TERM); while (true) { var sig: c_int = 0; if (libc.sigwait(&set, &sig) != 0) continue; // The terminals are the loop's: it asks each its size, and takes a // hangup as the end of the one that hung up. - const ev: Msg = if (sig != @backingInt(posix.SIG.HUP)) .winched else if (hangup_quits) .quit else .hangup; + const ev: Msg = if (sig == @backingInt(posix.SIG.WINCH)) .winched else if (hangup_quits) .quit else .hangup; loop.postEvent(ev) catch {}; } } diff --git a/docs/next-run.md b/docs/next-run.md index c2d3488b..00890ef1 100644 --- a/docs/next-run.md +++ b/docs/next-run.md @@ -178,6 +178,33 @@ it). For the window's build the fork comes before SDL starts. Then `pardes --detach=work` returns at once, `&` is not needed, and every session in `ps` is either its stub's child or a process of its own. +## `PARDES_PAIR`: every frontend a client (an experiment, built) + +With `PARDES_PAIR=1` in its environment (`export PARDES_PAIR=1` in a +shell's rc; unset, nothing below happens), `pardes FILE` in a terminal and +`pardes-gui FILE` start the way the last step's design has every frontend +start: the process you started forks a session with no terminal or window +of its own (`setsid`, `/dev/null`; a window's child execs the `pardes` +beside it) and is its first client over a socket pair, the job your shell +waits on (`runtime/main.zig` `pair`). A session is `kept` or not: kept from +birth when started with `new --detach[=NAME]` or `--detach`, kept once a +Detach is typed in any of its clients, never unkept, and an Upgrade +carries it (`runtime/daemon.zig` `State`, the upgrade record's `state`). +`pardes ps` says `(tty, kept)` of a kept session and `(tty)` of one that +is not; a session with a frontend of its own still says `(tty, has a +frontend)` and a detached one `(tty, detached)`. Its lifetime +(`core/replica.zig` `Peers.leave`, `runtime/session.zig`): + +| What happens | Not kept | Kept | +|---|---|---| +| Detach typed in a client | it becomes kept; the client says "detached from 'NAME', which is still running" and exits 0 | the same | +| a window closed, a terminal closed (its hangup), a TERM to a client | the client says goodbye with a close and exits 0, its terminal put back; the session ends if that was its last client | it runs on | +| a client killed outright (KILL) or crashed | the link ends with no goodbye: it runs on, listed by `pardes ps`, attachable | it runs on | +| no daemon | it ends when its last client's link ends, goodbye or not | cannot be: Detach refuses | + +Tested by `test/daemon.py --pair` (`pair`, `pair_rows`) and `--gui` +(`gui_pair`). + ## Rex beside pardes From Rex's own help (captured under diff --git a/docs/typ/building.typ b/docs/typ/building.typ index 6ef27ef8..94939452 100644 --- a/docs/typ/building.typ +++ b/docs/typ/building.typ @@ -197,7 +197,6 @@ zig build kitty-test kitty graphics conformance of terminal panes, at the zig build kitty-harness kitty graphics through a pane end to end (a fake kitty terminal outside on the tui, the GPU capture on the gui; kitten icat and chafa too when installed) -zig build syntax-test tree-sitter tests without building the editor zig build syntax deterministic per-byte highlighting snapshots zig build consumer-test the library, from a package that depends on pardes (test/consumer); unit-test runs it too diff --git a/docs/typ/command-line.txt b/docs/typ/command-line.txt index 0ced145f..2f7753e4 100644 --- a/docs/typ/command-line.txt +++ b/docs/typ/command-line.txt @@ -39,10 +39,12 @@ The old spellings --ps, --attach[=NAME], --kill=NAME, --kill-all, -h and == pardes help ps What the per-user daemon lists: each session with its name, pid, kind -(tty or gui) and whether it has a frontend of its own or is detached; -under it its clients and its shells; then the shells no session holds, -which Adopt takes. /sessions is the same list, read from inside a -session (where a session with a frontend says attached). +(tty or gui) and whether it has a frontend of its own or is detached +(under PARDES_PAIR: kept, or nothing when its last client's close +ends it); under it its clients and its shells; then the shells no +session holds, which Adopt takes. /sessions is the same list, read +from inside a session (where a session with a frontend says +attached, and a pair's not kept says pair). Usage: pardes ps diff --git a/docs/typ/running.typ b/docs/typ/running.typ index 74eb8cbd..320b3130 100644 --- a/docs/typ/running.typ +++ b/docs/typ/running.typ @@ -205,6 +205,37 @@ daemon died is not: it starts the next one itself (#link(<run-survives>)[below]) `pardes-gui` built for a Mac has no daemon either, but can still be a far client. += An experiment: `PARDES_PAIR` <run-pair> + +// runtime/main.zig pair (the fork); runtime/daemon.zig State, keepSession; +// core/replica.zig Peers.leave, Peers.detach; runtime/session.zig (the +// end); dev/tui/tui.zig runClient and winchWatch (HUP and TERM a close); +// dev/gui/gui.zig Input.close; runtime/upgrade.zig Record.state. +With `PARDES_PAIR=1` in its environment (`export PARDES_PAIR=1`; unset, +none of this happens), `pardes FILE` in a terminal and `pardes-gui FILE` +start the way every frontend will: the process you started forks a +session with no terminal or window of its own and is its first client, +the job your shell waits on. A session is _kept_ or not: kept from birth +when started with `pardes new --detach` (or `--detach`), and once a +#word("Detach") is typed in any of its clients; an #word("Upgrade") keeps +which. `pardes ps` says `(tty, kept)` of a kept session and `(tty)` of +one that is not. + +#{ + set text(size: 0.85em) + set par(justify: false) + table( + columns: (1.2fr, 1.6fr, 0.9fr), + stroke: (x, y) => if y == 0 { (bottom: 0.8pt) } else { (bottom: 0.3pt) }, + inset: (x: 4pt, y: 4pt), + table.header([*what happens*], [*not kept*], [*kept*]), + [#word("Detach") typed in a client], [it becomes kept; the client says so and exits 0], [the same], + [a window closed, a terminal closed, a TERM to a client], [the client says goodbye and exits 0, its terminal put back; the session ends if that was its last client], [it runs on], + [a client killed outright (KILL) or crashed], [it runs on, listed by `pardes ps`], [it runs on], + [no daemon], [it ends with its last client, whatever ended it], [cannot be: #word("Detach") refuses], + ) +} + = At a glance <run-glance> // The rows' sources are the sections above; `ps`: 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 diff --git a/runtime/client.zig b/runtime/client.zig index 329bdab3..7941889e 100644 --- a/runtime/client.zig +++ b/runtime/client.zig @@ -149,6 +149,11 @@ pub fn execAgain(s: *Start, view: u8) []const u8 { k += 1; } envp[k] = null; + // The mask goes across an exec: the signals a terminal client blocks + // for its own sigwait (HUP, TERM) would stay blocked under a build that + // waits on fewer, a TERM never delivered. + const none = std.posix.sigemptyset(); + std.posix.sigprocmask(std.posix.SIG.SETMASK, &none, null); _ = libc.execve(path, &argv, envp.ptr); return "Upgrade: the build at this client's start path would not start"; } diff --git a/runtime/daemon.zig b/runtime/daemon.zig index 9b566e60..7ae0d8b5 100644 --- a/runtime/daemon.zig +++ b/runtime/daemon.zig @@ -279,9 +279,9 @@ fn spawn(listener: c_int, lock: c_int) bool { /// Says who this session is. Its answer is not waited for: a daemon just /// started is still being exec'd, and no startup waits on it. The reader /// (`watch`) takes the `ok`, and only then is the session kept (`kept`). -fn hello(fd: c_int, k: Kind, pid: libc.pid_t, named: []const u8, detached: bool) bool { +fn hello(fd: c_int, k: Kind, pid: libc.pid_t, named: []const u8, s: State) bool { var buf: [256]u8 = undefined; - const words = std.fmt.bufPrint(&buf, "hello {d} {t} {d} {s} {x} {s}", .{ version, k, pid, if (detached) "detached" else "attached", wire.semantics, named }) catch return false; + const words = std.fmt.bufPrint(&buf, "hello {d} {t} {d} {t} {x} {s}", .{ version, k, pid, s, wire.semantics, named }) catch return false; return send(fd, words, &.{}); } @@ -300,15 +300,32 @@ var quitting = std.atomic.Value(bool).init(false); /// A new daemon took the hello since the last one died: the rest of what /// the dead one was told is to be told again (`relinked`). var retell = std.atomic.Value(bool).init(false); -/// What the hello says besides the name: the kind, and whether detached. +/// What a session's hello says of it besides its kind and name: a frontend +/// of its own (`attached`) or none (`detached`); a pair's (PARDES_PAIR), +/// whether its last client's close ends it (`pair`) or it is `kept` +/// (started --detach, or a Detach typed in a client since): `ps` says it. +/// Numbered as the daemon's record said a bool before (`reexec`). +pub const State = enum(u8) { attached, detached, pair, kept }; var kind: Kind = .tty; -var detached_now = std.atomic.Value(bool).init(false); +var state_now = std.atomic.Value(State).init(.detached); + +pub fn sessionState() State { + return state_now.load(.acquire); +} + +/// A Detach typed in a client: a pair's session is kept from now on. +pub fn keepSession() void { + if (state_now.cmpxchgStrong(.pair, .kept, .acq_rel, .acquire) == null) tell("state kept", &.{}); +} /// What it is called (its 9P name). 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]; @@ -347,14 +364,14 @@ fn setName(named: []const u8) void { /// Registers this session on `fd` (connected already, as a terminal's /// stub does before it forks), or on a new connection when `fd` is null. -pub fn register(fd: ?c_int, k: Kind, named: []const u8, detached: bool) bool { +pub fn register(fd: ?c_int, k: Kind, named: []const u8, s: State) bool { if (comptime !supported) return false; setName(named); kind = k; - detached_now.store(detached, .release); + state_now.store(s, .release); const c = fd orelse connect(true) orelse return false; startPending(true); - if (!hello(c, k, libc.getpid(), name(), detached)) { + if (!hello(c, k, libc.getpid(), name(), s)) { _ = libc.close(c); return false; } @@ -386,7 +403,7 @@ pub fn closed(pid: libc.pid_t) void { /// Its own frontend let go (Detach, its terminal's end): detached for /// good, an attach after it a client. pub fn setDetached() void { - detached_now.store(true, .release); + state_now.store(.detached, .release); tell("state detached", &.{}); } @@ -429,14 +446,14 @@ pub fn upgraded() void { /// An upgraded session's link and stub as its old process left them: its /// build's hello said again on the link (the daemon keeps its masters as /// they were), and the stub's death a HUP again. -pub fn resumeLink(fd: c_int, stub_fd: c_int, k: Kind, named: []const u8, detached: bool) void { +pub fn resumeLink(fd: c_int, stub_fd: c_int, k: Kind, named: []const u8, s: State) void { if (comptime !supported) return; stub = stub_fd; if (stub >= 0) hupOnStubDeath(true); setName(named); kind = k; - detached_now.store(detached, .release); - if (fd >= 0 and hello(fd, k, libc.getpid(), name(), detached)) link = fd else if (fd >= 0) _ = libc.close(fd); + state_now.store(s, .release); + if (fd >= 0 and hello(fd, k, libc.getpid(), name(), s)) link = fd else if (fd >= 0) _ = libc.close(fd); } pub const Note = union(enum) { @@ -452,20 +469,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 +511,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 +526,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 +540,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); @@ -518,7 +554,7 @@ fn redial(fd: c_int) bool { startPending(true); defer _ = libc.close(c); return libc.dup3(c, fd, @bitCast(@as(u32, @bitCast(libc.O{ .CLOEXEC = true })))) >= 0 and - hello(fd, kind, libc.getpid(), name(), detached_now.load(.acquire)); + hello(fd, kind, libc.getpid(), name(), sessionState()); } /// `bytes` sent whole on a socket, never raising SIGPIPE: false when the @@ -778,7 +814,7 @@ const Conn = struct { fd: c_int = -1, kind: ?Kind = null, pid: libc.pid_t = 0, - detached: bool = false, + state: State = .attached, /// Its build's wire.semantics: a replica's must be the same. semantics: u64 = 0, /// `pardes --kill` asked its end: its shells go with it, not kept. @@ -871,7 +907,7 @@ const Daemon = struct { var w: std.Io.Writer = .fixed(&line); w.print("daemon {d}\n", .{libc.getpid()}) catch unreachable; // a pid fits msg_max for (&d.conns, 0..) |*s, k| if (s.fd >= 0 and s.kind != null) { - w.print("session {d} {t} {s} {s}\n", .{ s.pid, s.kind.?, if (s.detached) "detached" else "attached", s.named() }) catch break; + w.print("session {d} {t} {t} {s}\n", .{ s.pid, s.kind.?, s.state, s.named() }) catch break; for (s.clients[0..s.nclients]) |pid| w.print("client {d}\n", .{pid}) catch break; for (d.held) |h| if (h.fd >= 0 and h.owner == @as(u8, @intCast(k))) w.print("shell {d}\n", .{h.pid}) catch break; }; @@ -896,7 +932,7 @@ const Daemon = struct { const v = std.fmt.parseInt(u32, words.next() orelse "", 10) catch 0; const k = std.meta.stringToEnum(Kind, words.next() orelse ""); const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch 0; - const state = words.next() orelse ""; + const said = words.next() orelse ""; const semantics = std.fmt.parseInt(u64, words.next() orelse "", 16) catch 0; const rest = std.mem.trim(u8, words.rest(), " "); if (v != version or k == null or pid <= 0) { @@ -906,14 +942,14 @@ const Daemon = struct { } c.kind = k; c.pid = pid; - c.detached = std.mem.eql(u8, state, "detached"); + c.state = std.meta.stringToEnum(State, said) orelse .attached; c.semantics = semantics; c.nclients = 0; c.name_len = @min(rest.len, c.name.len); @memcpy(c.name[0..c.name_len], rest[0..c.name_len]); return d.reply(i, "ok", &.{}); }, - .state => c.detached = std.mem.eql(u8, words.next() orelse "", "detached"), + .state => c.state = std.meta.stringToEnum(State, words.next() orelse "") orelse .attached, .clients => { c.nclients = 0; while (words.next()) |w| if (c.nclients < max_clients) { @@ -1026,7 +1062,7 @@ const Daemon = struct { w.print("{s}replicas {d}\n", .{ upgrade.flag, replicas }) catch return; for (&d.conns, 0..) |*c, i| if (c.fd >= 0) { const k: []const u8 = if (c.kind) |k| @tagName(k) else "-"; - w.print("c {d} {d} {s} {d} {d} {x} {s}\n", .{ i, c.fd, k, c.pid, @intFromBool(c.detached), c.semantics, c.named() }) catch return; + w.print("c {d} {d} {s} {d} {d} {x} {s}\n", .{ i, c.fd, k, c.pid, @intFromEnum(c.state), c.semantics, c.named() }) catch return; }; for (&d.held) |*h| if (h.fd >= 0) { w.print("h {d} {d} {d}\n", .{ h.fd, h.pid, h.owner orelse 255 }) catch return; @@ -1076,12 +1112,12 @@ const Daemon = struct { if (i >= max_conns) continue; const k = std.meta.stringToEnum(Kind, words.next() orelse ""); const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch 0; - const detached = std.mem.eql(u8, words.next() orelse "", "1"); + const s = std.enums.fromInt(State, std.fmt.parseInt(u8, words.next() orelse "", 10) catch 0) orelse .attached; const semantics = std.fmt.parseInt(u64, words.next() orelse "", 16) catch 0; const rest = std.mem.trim(u8, words.rest(), " "); ninep_io.setCloexec(fd); const c = &d.conns[i]; - c.* = .{ .fd = fd, .kind = k, .pid = pid, .detached = detached, .semantics = semantics }; + c.* = .{ .fd = fd, .kind = k, .pid = pid, .state = s, .semantics = semantics }; c.nclients = 0; c.name_len = @min(rest.len, c.name.len); @memcpy(c.name[0..c.name_len], rest[0..c.name_len]); @@ -1204,6 +1240,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/main.zig b/runtime/main.zig index a21eb83f..dc351c30 100644 --- a/runtime/main.zig +++ b/runtime/main.zig @@ -269,10 +269,12 @@ const cmds = std.EnumArray(Cmd, Doc).init(.{ .line = "the daemon's sessions, their clients and shells", .doc = \\What the per-user daemon lists: each session with its name, pid, kind - \\(tty or gui) and whether it has a frontend of its own or is detached; - \\under it its clients and its shells; then the shells no session holds, - \\which Adopt takes. /sessions is the same list, read from inside a - \\session (where a session with a frontend says attached). + \\(tty or gui) and whether it has a frontend of its own or is detached + \\(under PARDES_PAIR: kept, or nothing when its last client's close + \\ends it); under it its clients and its shells; then the shells no + \\session holds, which Adopt takes. /sessions is the same list, read + \\from inside a session (where a session with a frontend says + \\attached, and a pair's not kept says pair). , .examples = &.{.{ "pardes ps", "every session, client and shell" }}, .see = "attach, kill, /sessions", @@ -1570,14 +1572,14 @@ fn nativeMain(std_init: std.process.Init) !void { term = .{ .fd = .{ .fd = t.fd, .termios = t.termios } }; }; detached = if (pardes.platform == .gui) !rec.window else rec.nttys == 0; - daemon.resumeLink(rec.link, rec.stub, kind, opts.ninep_name, detached); + daemon.resumeLink(rec.link, rec.stub, kind, opts.ninep_name, rec.state orelse if (detached) .detached else .attached); } else if (paired) |fd| { // A window's pair's session: its first client on `fd`, the daemon // its own to dial (and to start, when none runs). opts.pair = fd; term = .detached; detached = true; - if (daemon.wanted()) _ = daemon.register(null, kind, opts.ninep_name, true); + if (daemon.wanted()) _ = daemon.register(null, kind, opts.ninep_name, .pair); } else if (detach == null and std.c.getenv("PARDES_PAIR") != null) { // The last step's way, behind its variable until it is the default: // this terminal or window a client of a session forked off for it @@ -1586,7 +1588,9 @@ fn nativeMain(std_init: std.process.Init) !void { term = .detached; } else if (daemon.wanted()) { if (detach != null or pardes.platform == .gui) { - _ = daemon.register(null, kind, opts.ninep_name, detach != null); + // A session started detached is kept from birth: a pair's word. + const s: daemon.State = if (detach == null) .attached else if (std.c.getenv("PARDES_PAIR") != null) .kept else .detached; + _ = daemon.register(null, kind, opts.ninep_name, s); } else if (pardes.platform == .tui) fork: { // A terminal's session is forked off its stub, which stays the // job the shell waits on: Detach (or the terminal's end) ends @@ -1610,7 +1614,7 @@ fn nativeMain(std_init: std.process.Init) !void { _ = std.c.close(conn); break :fork; }; - _ = daemon.register(conn, .tty, opts.ninep_name, false); + _ = daemon.register(conn, .tty, opts.ninep_name, .attached); term = .{ .fd = .{ .fd = fd } }; } } @@ -1662,7 +1666,12 @@ fn manage(io: std.Io, verb: enum { list, kill, killall }, name: []const u8) nore .session => { const kind = it.next() orelse ""; const state = it.next() orelse ""; - w.print(" session {s} {s} ({s}, {s})\n", .{ std.mem.trim(u8, it.rest(), " "), pid, kind, if (std.mem.eql(u8, state, "attached")) "has a frontend" else state }) catch break; + const named = std.mem.trim(u8, it.rest(), " "); + // A pair's not kept: its clients are all there is to it. + if (std.mem.eql(u8, state, "pair")) + w.print(" session {s} {s} ({s})\n", .{ named, pid, kind }) catch break + else + w.print(" session {s} {s} ({s}, {s})\n", .{ named, pid, kind, if (std.mem.eql(u8, state, "attached")) "has a frontend" else state }) catch break; }, .client => w.print(" client {s} {s}\n", .{ pid, comm }) catch break, .shell => w.print(" shell {s} {s}\n", .{ pid, comm }) catch break, @@ -1784,7 +1793,7 @@ fn pair(init: std.process.Init, opts: *pardes.Options, args: []const [:0]const u opts.pair = fds[0]; // The daemon is the client's to start; the hello is this one's. daemon.startPending(false); - if (conn) |c| _ = daemon.register(c, .tty, opts.ninep_name, true); + if (conn) |c| _ = daemon.register(c, .tty, opts.ninep_name, .pair); return; } _ = std.c.close(fds[0]); @@ -1941,7 +1950,7 @@ fn bareAttach(list: []const u8, names: *std.Io.Writer) ?[]const u8 { one = std.mem.trim(u8, words.rest(), " "); n += 1; names.print(" {s}", .{one.?}) catch {}; // cut short - if (!std.mem.eql(u8, state, "detached")) continue; + if (std.mem.eql(u8, state, "attached")) continue; detached = one; n_detached += 1; } @@ -1954,6 +1963,8 @@ test "a bare attach takes the one detached session, else the one there is, else var names: std.Io.Writer = .fixed(&buf); try std.testing.expectEqualStrings("b", bareAttach("daemon 1\nsession 2 tty attached a\nshell 9\nsession 3 gui detached b\n", &names).?); try std.testing.expectEqualStrings("a", bareAttach("daemon 1\nsession 2 tty attached a\n", &names).?); + // A pair's, kept or not, has no frontend of its own either. + try std.testing.expectEqualStrings("c", bareAttach("session 2 tty attached a\nsession 3 tty pair c\n", &names).?); names = .fixed(&buf); try std.testing.expect(bareAttach("daemon 1\norphan 4\n", &names) == null); try std.testing.expectEqual(@as(usize, 0), names.end); diff --git a/runtime/session.zig b/runtime/session.zig index 9c8446e3..60644aa6 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). @@ -129,9 +132,8 @@ pub fn Loop(comptime Frontend: type) type { l.peers.boundary(l.core); // A pair's session with no daemon ends with its last link: // nothing could attach to it again; with one, when its last - // client closed its window (a close, not a loss), no Detach - // typed in any. - if (o.pair != null and l.peers.count() == 0 and (daemon.link < 0 or l.peers.closed)) break; + // client left with a close (not a loss) and it is not kept. + if (l.peers.count() == 0 and (l.peers.closed or (o.pair != null and daemon.link < 0))) break; fe.sent(); upgrade.locate(); // Asked in the step (the word), done between steps: the diff --git a/runtime/upgrade.zig b/runtime/upgrade.zig index 37d4890b..f59117ee 100644 --- a/runtime/upgrade.zig +++ b/runtime/upgrade.zig @@ -19,6 +19,7 @@ const builtin = @import("builtin"); const libc = std.c; const posix = std.posix; const pardes = @import("core"); +const daemon = @import("daemon.zig"); pub const supported = builtin.os.tag == .linux or builtin.os.tag == .freebsd; pub const flag = "--upgraded="; @@ -140,6 +141,9 @@ pub const Record = struct { /// This process's own: its dump would not load, so it started afresh /// and adopts the shells. fresh: bool = false, + /// A pair's session's state (daemon.State): whether it is kept, which + /// the dump does not say. None: as its frontend says (attached or not). + state: ?daemon.State = null, pub fn addPty(rec: *Record, pane: usize, pid: libc.pid_t, fd: c_int) void { if (rec.nptys == rec.ptys.len or fd < 0) return; @@ -177,6 +181,7 @@ pub const Record = struct { for (rec.ttys[0..rec.nttys]) |t| try w.print("tty {d} {d} {d} {d} {x}\n", .{ t.view, t.fd, t.stub, @intFromBool(t.primary), std.mem.asBytes(&t.termios) }); if (rec.refused.len > 0) try w.print("refused {s}\n", .{rec.refused}); if (rec.label.len > 0) try w.print("label {s}\n", .{rec.label}); + if (rec.state) |s| try w.print("state {t}\n", .{s}); try w.print("exe {s}\ndump {s}\n", .{ rec.exe, rec.dump }); } @@ -191,7 +196,7 @@ pub const Record = struct { const rest = line[sp + 1 ..]; var it = std.mem.tokenizeScalar(u8, rest, ' '); // A word of a later build's record is passed over. - switch (std.meta.stringToEnum(enum { link, stub, old, window, pty, tty, refused, label, exe, dump }, word) orelse continue) { + switch (std.meta.stringToEnum(enum { link, stub, old, window, pty, tty, refused, label, state, exe, dump }, word) orelse continue) { .link => rec.link = try std.fmt.parseInt(c_int, rest, 10), .stub => rec.stub = try std.fmt.parseInt(c_int, rest, 10), .old => rec.old = try std.fmt.parseInt(c_int, rest, 10), @@ -225,6 +230,7 @@ pub const Record = struct { }, .refused => rec.refused = rest, .label => rec.label = rest, + .state => rec.state = std.meta.stringToEnum(daemon.State, rest), .exe => rec.exe = rest, .dump => rec.dump = rest, } @@ -383,9 +389,14 @@ pub fn dumpInto(core: *pardes.Pardes, rec: *Record, at: *[1024:0]u8, why: []u8) /// dump stays, a dump among the state file's): why, in words (`why`'s). pub fn execAs(gpa: std.mem.Allocator, path: [:0]const u8, rec: *const Record, at: [*:0]const u8, fs: ?*@import("9p_io.zig").Listener, why: []u8) []const u8 { _ = at; - @import("daemon.zig").upgraded(); + daemon.upgraded(); if (fs) |f| f.flushOut(); - const err_words = exec(gpa, path, -1, rec); + var with = rec.*; + with.state = switch (daemon.sessionState()) { + .pair, .kept => |s| s, + .attached, .detached => null, + }; + const err_words = exec(gpa, path, -1, &with); // Still here: the exec failed. if (rec.old >= 0) _ = libc.close(rec.old); return std.fmt.bufPrint(why, "Upgrade: {s} would not start: {s}; this session stays as it is", .{ path[0..@min(path.len, 600)], err_words }) catch "Upgrade: the new pardes would not start"; @@ -453,7 +464,7 @@ pub fn load(gpa: std.mem.Allocator, core_gpa: std.mem.Allocator, opts: pardes.Op } test "an upgrade's record reads back as it was written, and refuses one cut short" { - var rec: Record = .{ .link = 5, .stub = 7, .old = 9, .window = true, .exe = "/a b/pardes", .dump = "/home/u/.local/share/pardes/pardes.xitdb", .label = "upgrade-1" }; + var rec: Record = .{ .link = 5, .stub = 7, .old = 9, .window = true, .exe = "/a b/pardes", .dump = "/home/u/.local/share/pardes/pardes.xitdb", .label = "upgrade-1", .state = .kept }; rec.addPty(3, 1234, 11); rec.addPty(0, 99, 12); var tio: posix.termios = std.mem.zeroes(posix.termios); @@ -474,10 +485,12 @@ test "an upgrade's record reads back as it was written, and refuses one cut shor try std.testing.expectEqualStrings("/a b/pardes", back.exe); try std.testing.expectEqualStrings("/home/u/.local/share/pardes/pardes.xitdb", back.dump); try std.testing.expectEqualStrings("upgrade-1", back.label); - // An older build's: its dump a file, no label. + try std.testing.expectEqual(daemon.State.kept, back.state.?); + // An older build's: its dump a file, no label, no state. const older = try Record.decode("link 5\nexe /a\ndump /run/u/pardes-upgrade-1.dump\n"); try std.testing.expectEqualStrings("/run/u/pardes-upgrade-1.dump", older.dump); try std.testing.expectEqualStrings("", older.label); + try std.testing.expect(older.state == null); try std.testing.expectError(error.BadRecord, Record.decode("link 5\n")); try std.testing.expectError(error.BadRecord, Record.decode("tty 0 1 2 1 abc\ndump x\n")); } diff --git a/test/daemon.py b/test/daemon.py index 2325f721..c1e0d54a 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -635,7 +635,7 @@ def pair(binary): assert session != c.pid and ppid(session) == c.pid and os.getsid(session) == session, (session, c.pid) wait_for('the file drawn on the terminal', lambda: b'line 3 of the notes' in t.text(), timeout=30) listed = lambda: subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode() - wait_for('the client listed', lambda: f'session pair {session} (tty, detached)' in listed() + wait_for('the client listed', lambda: f'session pair {session} (tty)' in listed() and f'client {c.pid} ' in listed()) pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') os.write(t.master, b'Ofrom-the-pair\x1b') @@ -676,12 +676,13 @@ def pair(binary): def pair_rows(binary): """PARDES_PAIR, the shell's view (the last step's design, 1.1) and a - session's lifetime (2.2 B), one row a step. With a daemon: a Detach in - the pair's client says so and exits 0, the session runs on (listed); an - attach is a client again; TERM to the client puts its terminal back and - the session runs on; so does a KILL, and a closed terminal (HUP): each a - loss, not a close. With none: a Detach refused (nothing could attach), - the client on; its terminal closed, the session ends with its last link.""" + session's lifetime (2.2 B), one row a step. `ps` says a pair's session + `kept` (started --detach, or a Detach typed in any client since), or + nothing after its kind; an Upgrade carries which. Kept: a client ended + by TERM, KILL or a closed terminal (HUP) leaves it running, as does a + Detach typed in one (said, exit 0). With no daemon: a Detach refused + (nothing could attach), the client on; its terminal closed, the session + ends with its last link.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rq-', dir=scratch)) @@ -697,6 +698,12 @@ def pair_rows(binary): def listed(): return subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode() + def state_of(name): + """What `ps` says of session `name` after its pid: `(tty)`, `(tty, kept)`.""" + for line in listed().splitlines(): + if line.split()[:2] == ['session', name]: + return line[line.index('('):] + def drawn(t): wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30) @@ -717,30 +724,112 @@ def pair_rows(binary): drawn(t) return t, c, nine, session, pane + def attached(name): + tt = Term(30, 100) + terms.append(tt) + a = tt.spawn([binary, 'attach', name], env) + drawn(tt) + wait_for('the client listed', lambda: f'client {a.pid} ' in listed()) + return tt, a + + def ended_by(how, tt, a): + """Client `a` on terminal `tt` ended: TERM, KILL, or HUP (its terminal + closed); its exit status, once it is unlisted.""" + if how == 'HUP': + tt.close() + terms.remove(tt) + else: + os.kill(a.pid, getattr(signal, 'SIG' + how)) + code = a.wait(timeout=20) + if how == 'TERM': + wait_for('its terminal put back', lambda: tt.text().rfind(b'\x1b[?1049l') > tt.text().rfind(b'\x1b[?1049h')) + wait_for('the client unlisted', lambda: f'client {a.pid} ' not in listed()) + return code + + def upgraded(name, nine, session): + """An Upgrade to the same build: the session exec'd under its pid, its + 9P again.""" + nine.write('/ctl', b'Upgrade\n') + wait_for('the session exec\'d', lambda: any(a.startswith(b'--upgraded=') for a in cmdline(session)), timeout=60) + nine.socket.close() + again = reconnect(root / f'pardes-9p-{name}.sock') + assert alive(session) + return again + try: + # Kept from birth: `new --detach`. Its clients end and it runs on. + out = subprocess.run([binary, 'new', '--detach=kd', str(notes)], env=env, cwd=root, capture_output=True, + timeout=30, stdin=subprocess.DEVNULL) + assert out.returncode == 0, out + with Client(root / 'pardes-9p-kd.sock') as kn: + kd = int(dict(line.split(maxsplit=1) for line in kn.read('/status').decode().splitlines())['pid']) + assert state_of('kd') == '(tty, kept)', listed() + for how in ('HUP', 'TERM'): + ended_by(how, *attached('kd')) + assert alive(kd) and state_of('kd') == '(tty, kept)', (how, listed()) + assert subprocess.run([binary, 'kill', 'kd'], env=env, capture_output=True, timeout=30).returncode == 0 + wait_for('kd ended', lambda: not alive(kd), timeout=30) + print('pair rows: `new --detach` kept from birth (ps: (tty, kept)); its client ended by HUP, by TERM: it runs on') + # Not kept: a client's close (its terminal closed, a TERM) ends the + # session when it was the last; a KILL is a loss, it runs on. + t, c, nine, session, pane = started('nk', env) + assert ended_by('HUP', *attached('nk')) == 0 + assert alive(session) and state_of('nk') == '(tty)', ('not its last client', listed()) + os.kill(c.pid, signal.SIGKILL) + c.wait(timeout=10) + wait_for('the client unlisted', lambda: f'client {c.pid} ' not in listed()) + assert alive(session) and state_of('nk') == '(tty)', ('a loss', listed()) + assert ended_by('TERM', *attached('nk')) == 0 + wait_for('the session ended at its last client\'s close', lambda: not alive(session), timeout=20) + assert state_of('nk') is None, listed() + nine.socket.close() + print('pair rows: not kept: a client\'s terminal closed (not the last): it runs on; its own killed -9: it runs on, ' + 'listed; the last client TERMed (exit 0, its terminal put back): the session ended') + # The pair's own terminal closed after an Upgrade: its last client's + # close, which the Upgrade did not make kept. + t, c, nine, session, pane = started('nk2', env) + nine = upgraded('nk2', nine, session) + wait_for('the client joined again', lambda: b'joined again' in t.text(), timeout=30) + nine.socket.close() + t.close() + terms.remove(t) + assert c.wait(timeout=20) == 0, c.returncode + wait_for('the session ended with its terminal', lambda: not alive(session), timeout=20) + print('pair rows: not kept, upgraded: its terminal closed (exit 0): the session ended') + # Without the variable nothing changes: an attach client's TERM + # leaves the session running, and its own terminal closed detaches it. + own_env = {k: v for k, v in env.items() if k != 'PARDES_PAIR'} + t, c, nine, session, pane = started('own', own_env) + assert state_of('own') == '(tty, has a frontend)', listed() + assert ended_by('TERM', *attached('own')) == 0 + assert alive(session) and state_of('own') == '(tty, has a frontend)', listed() + nine.socket.close() + t.close() + terms.remove(t) + c.wait(timeout=20) + wait_for('the own session detached', lambda: state_of('own') == '(tty, detached)') + assert alive(session) + assert subprocess.run([binary, 'kill', 'own'], env=env, capture_output=True, timeout=30).returncode == 0 + wait_for('the own session ended', lambda: not alive(session), timeout=30) + print('pair rows: without the variable: an attach client TERMed, the session on; its terminal closed, it detached (ps: (tty, detached))') + # A pair: not kept, and not across an Upgrade either; a Detach typed + # in its client keeps it, across an Upgrade too. t, c, nine, session, pane = started('rows', env) + assert state_of('rows') == '(tty)', listed() + nine = upgraded('rows', nine, session) + wait_for('ps after the Upgrade', lambda: state_of('rows') == '(tty)') + wait_for('the client joined again', lambda: b'joined again' in t.text(), timeout=30) typed_detach(t, nine, pane) assert c.wait(timeout=20) == 0, c.returncode wait_for('the detach said', lambda: b"pardes: detached from 'rows', which is still running; come back with `pardes attach rows`" in t.text()) - assert alive(session) and f'session rows {session} (tty, detached)' in listed() - print('pair rows: Detach in the client: said, exit 0; the session runs on, listed') + assert alive(session) and state_of('rows') == '(tty, kept)', listed() + nine = upgraded('rows', nine, session) + wait_for('ps after the Upgrade', lambda: state_of('rows') == '(tty, kept)') + print('pair rows: a pair (ps: (tty)), so after an Upgrade; Detach in its client: said, exit 0, it runs on, kept, so after an Upgrade') for how in ('TERM', 'KILL', 'HUP'): - tt = Term(30, 100) - terms.append(tt) - a = tt.spawn([binary, 'attach', 'rows'], env) - drawn(tt) - wait_for('the client listed', lambda: f'client {a.pid} ' in listed()) - if how == 'HUP': - tt.close() - terms.remove(tt) - else: - os.kill(a.pid, getattr(signal, 'SIG' + how)) - a.wait(timeout=20) - if how == 'TERM': - wait_for('its terminal put back', lambda: tt.text().rfind(b'\x1b[?1049l') > tt.text().rfind(b'\x1b[?1049h')) - wait_for('the client unlisted', lambda: f'client {a.pid} ' not in listed()) - assert alive(session), how - print(f'pair rows: a client ended by {how}: the session runs on') + ended_by(how, *attached('rows')) + assert alive(session) and state_of('rows') == '(tty, kept)', (how, listed()) + print(f'pair rows: kept: a client ended by {how}: the session runs on') nine.socket.close() assert subprocess.run([binary, 'kill', 'rows'], env=env, capture_output=True, timeout=30).returncode == 0 wait_for('the session ended', lambda: not alive(session), timeout=30) @@ -2298,7 +2387,7 @@ def gui_pair(gui_binary): try: w, nine, session, pane = started('gp', env) - wait_for('the window listed its client', lambda: f'session gp {session} (tty, detached)' in listed() + wait_for('the window listed its client', lambda: f'session gp {session} (tty)' in listed() and f'client {w.pid} ' in listed()) w.keys(b'Ofrom-the-window\x1b') wait_for('its keys in the session\'s text', lambda: b'from-the-window' in nine.read(f'/pane/{pane}/body')) @@ -2316,11 +2405,29 @@ def gui_pair(gui_binary): os.kill(w.pid, signal.SIGKILL) w.p.wait(timeout=10) wait_for('the client unlisted', lambda: f'client {w.pid} ' not in listed()) - assert alive(session) and f'session gl {session} (tty, detached)' in listed(), listed() + assert alive(session) and f'session gl {session} (tty)' in listed(), listed() nine.socket.close() assert subprocess.run([binary, 'kill', 'gl'], env=env, capture_output=True, timeout=30).returncode == 0 wait_for('the session ended', lambda: not alive(session), timeout=30) print('pair window: the window killed: the session runs on, listed (a loss); killed by name') + # Kept from birth (`new --detach`): its window client's close leaves it. + out = subprocess.run([binary, 'new', '--detach=gk', str(notes)], env=env, cwd=root, capture_output=True, + timeout=30, stdin=subprocess.DEVNULL) + assert out.returncode == 0, out + with Client(root / 'pardes-9p-gk.sock') as kn: + gk = int(dict(line.split(maxsplit=1) for line in kn.read('/status').decode().splitlines())['pid']) + assert f'session gk {gk} (tty, kept)' in listed(), listed() + w = Window(root, 'gkw', [gui_binary, 'attach', 'gk'], env) + windows.append(w) + wait_for('the window client listed', lambda: f'client {w.pid} ' in listed(), timeout=30) + w.p.stdin.write(b'\x1b]777;close\x07') + w.p.stdin.flush() + assert w.p.wait(timeout=30) == 0, (w.p.returncode, w.said()[-400:]) + wait_for('the client unlisted', lambda: f'client {w.pid} ' not in listed()) + assert alive(gk) and f'session gk {gk} (tty, kept)' in listed(), listed() + assert subprocess.run([binary, 'kill', 'gk'], env=env, capture_output=True, timeout=30).returncode == 0 + wait_for('the session ended', lambda: not alive(gk), timeout=30) + print('pair window: a `new --detach` session (kept): its window client closed, it runs on') w, nine, session, pane = started('gn', dict(env, PARDES_DAEMON='off')) nine.socket.close() os.kill(w.pid, signal.SIGKILL) diff --git a/test/e2e_harness.zig b/test/e2e_harness.zig index 26e942e7..9481166e 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. @@ -333,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/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 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 a6e37c6c..f26328ca 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-<ch> and a-<ch>. After esc, - /// settle: vaxis reads the next byte in the same batch as alt-<ch>. + /// right home end pgup pgdn, a character, c-<ch> and a-<ch>. 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 @@ -567,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 @@ -797,7 +814,8 @@ fn snap9pText(arena: std.mem.Allocator, h: *eh.Harness, label: []const u8, prev: return out.items; } -/// `== snap <label> grid=CxR cursor=X,Y` then either the whole screen as +/// `== snap <label> grid=CxR cursor=X,Y` (`cursor=hidden` when the app +/// hides it: where a hidden cursor was left is no one's) then either the whole screen as /// `|<row text>` (first capture of a case, or after a resize) or just the /// rows that changed as `|<n>: <row text>`. An indexed row is a patch against /// the previous capture; an unindexed one is a frame. @@ -810,9 +828,8 @@ fn snapText(arena: std.mem.Allocator, h: *eh.Harness, label: []const u8, prev: * for (rows) |*r| r.* = try arena.dupe(u8, std.mem.trimEnd(u8, it.next() orelse "", " ")); var out: std.ArrayList(u8) = .empty; - try out.appendSlice(arena, try std.fmt.allocPrint(arena, "== snap {s} grid={d}x{d} cursor={d},{d}\n", .{ - label, h.cols, h.rows, c.x, c.y, - })); + try out.appendSlice(arena, try std.fmt.allocPrint(arena, "== snap {s} grid={d}x{d} cursor=", .{ label, h.cols, h.rows })); + try out.appendSlice(arena, if (c.shown) try std.fmt.allocPrint(arena, "{d},{d}\n", .{ c.x, c.y }) else "hidden\n"); if (prev.snap.len == rows.len and prev.snap_cols == h.cols) { for (rows, prev.snap, 0..) |now, was, i| { if (std.mem.eql(u8, now, was)) continue; |
