summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--abi/pardes.h2
-rw-r--r--abi/wire.zig25
-rw-r--r--build.zig2
-rw-r--r--build/patches.zig5
-rw-r--r--build/tests.zig2
-rw-r--r--build/tools.zig29
-rw-r--r--core/CHANGELOG.md17
-rw-r--r--core/Core.zig37
-rw-r--r--core/File.zig15
-rw-r--r--core/Handover.zig14
-rw-r--r--core/Names.zig20
-rw-r--r--core/Pipe.zig36
-rw-r--r--core/Places.zig21
-rw-r--r--core/Plumb.zig4
-rw-r--r--core/Query.zig20
-rw-r--r--core/Store.zig8
-rw-r--r--core/Stream.zig2
-rw-r--r--core/Turn.zig10
-rw-r--r--core/body_layer.zig5
-rw-r--r--core/builtins.zig4
-rw-r--r--core/colors.zig7
-rw-r--r--core/dump.zig12
-rw-r--r--core/echo.zig2
-rw-r--r--core/edit_cmd.zig4
-rw-r--r--core/exec.zig2
-rw-r--r--core/fs.zig78
-rw-r--r--core/layout.zig90
-rw-r--r--core/lsp/Ask.zig39
-rw-r--r--core/ninep/events.zig4
-rw-r--r--core/ninep/pane.zig22
-rw-r--r--core/ninep/pty.zig1
-rw-r--r--core/ninep/tree.zig94
-rw-r--r--core/panes.zig13
-rw-r--r--core/replica.zig570
-rw-r--r--core/rollback.zig16
-rw-r--r--core/syntax.zig47
-rw-r--r--core/tape.zig128
-rw-r--r--core/walk.zig6
-rw-r--r--dev/Inbox.zig75
-rw-r--r--dev/Ptys.zig34
-rw-r--r--dev/file_watch.zig6
-rw-r--r--dev/gui/gui.zig100
-rw-r--r--dev/host_io.zig55
-rw-r--r--dev/lsp/lsp_client.zig5
-rw-r--r--dev/macos/Sources/AppDelegate.swift4
-rw-r--r--dev/tui/tui.zig202
-rw-r--r--docs/next-daemon.md9
-rw-r--r--docs/next-drag.md6
-rw-r--r--docs/next-run.md27
-rw-r--r--docs/search-proto-converge.md8
-rw-r--r--docs/typ/building.typ5
-rw-r--r--docs/typ/command-line.txt10
-rw-r--r--docs/typ/running.typ31
-rw-r--r--runtime/9p_io.zig8
-rw-r--r--runtime/client.zig59
-rw-r--r--runtime/daemon.zig171
-rw-r--r--runtime/macos.zig51
-rw-r--r--runtime/main.zig146
-rw-r--r--runtime/session.zig45
-rw-r--r--runtime/upgrade.zig35
-rw-r--r--test/consumer/build.zig2
-rw-r--r--test/daemon.py629
-rw-r--r--test/delay_relay.py10
-rw-r--r--test/e2e_harness.zig40
-rw-r--r--test/lspmock.zig26
-rw-r--r--test/macos_e2e.swift4
-rw-r--r--test/panes.zig4
-rw-r--r--test/perf-baseline-gui-debug.json2
-rw-r--r--test/perf-baseline-tui-debug.json2
-rw-r--r--test/perf-baseline-tui-fast.json2
-rw-r--r--test/perf.zig138
-rw-r--r--test/process/tty_editing.zig55
-rw-r--r--test/replicas.zig7
-rw-r--r--test/session.zig15
-rw-r--r--test/snapshots/collapse.golden4
-rw-r--r--test/snapshots/follow.golden2
-rw-r--r--test/snapshots/hscroll.golden2
-rw-r--r--test/snapshots/images.golden4
-rw-r--r--test/snapshots/jumps.golden2
-rw-r--r--test/snapshots/lspcomplete.golden2
-rw-r--r--test/snapshots/shrinktag.golden4
-rw-r--r--test/snapshots/ttytaken.golden2
-rw-r--r--test/snapshots/wheeldrift.golden8
-rw-r--r--test/snapshots/wrap.golden2
-rw-r--r--test/tty.zig33
85 files changed, 2692 insertions, 814 deletions
diff --git a/abi/pardes.h b/abi/pardes.h
index ca65b8f3..24eb6701 100644
--- a/abi/pardes.h
+++ b/abi/pardes.h
@@ -223,7 +223,7 @@ typedef struct {
// core defers each shell's greeting until it has seen one), and the first
// forkpty takes its winsize straight off the core — boot at 80x24 and the
// shell draws its first prompt to a width the window never had.
-int pardes_init(const pardes_callbacks_s *runtime, uint16_t cols, uint16_t rows);
+int pardes_init(const pardes_callbacks_s *callbacks, uint16_t cols, uint16_t rows);
void pardes_deinit(void);
// Drain pty output into the core and perform the effects it queued. Call after
diff --git a/abi/wire.zig b/abi/wire.zig
index ff1d1bf2..5f8e1f97 100644
--- a/abi/wire.zig
+++ b/abi/wire.zig
@@ -10,8 +10,13 @@ const pardes = @import("core");
const config = @import("pardes_options");
const build_info = @import("build_info");
-/// 24: a view kept for its client's rejoin says when it went away
+/// 26: a view kept for its client's rejoin says when it went away
/// (View.away_ns), and is that client's for Views.away_kept_ns;
+/// 25: the 9P state a session's requests made (its open records, each
+/// pane's, the panes the last look or exec touched, a header's
+/// truncation) is in its join's dump and its digest (core/fs.zig Namespace);
+/// 24: a bye's byte says the client's window was closed (2), which ends a
+/// pair's session at its last client;
/// 23: a pane of a kind's frame names its rasters by key, their pixels
/// crossing before it as strips of 4 MiB at most over the rows it shows
/// (screen kind 5), and a replica lacking one asks for its pane again
@@ -38,7 +43,7 @@ const build_info = @import("build_info");
/// part B); 14: the hello names a session and
/// carries the semantics hash, and a ping is answered (phase 5's
/// groundwork); 13: the frames went (phase 3).
-pub const version: u16 = 24;
+pub const version: u16 = 26;
/// The terminal's build and the window's step alike (`semantics`).
const family = switch (config.platform) {
@@ -298,8 +303,9 @@ pub fn helloVersion(payload: []const u8) Error!u16 {
/// one call and no longer.
pub const ClientMsg = union(enum) {
hello: Hello,
- /// The client's end: `again`, it joins again for its view at once.
- bye: struct { again: bool = false },
+ /// The client's end: `again`, it joins again for its view at once;
+ /// `close`, its window was closed (a pair's session ends at its last).
+ bye: struct { again: bool = false, close: bool = false },
/// A round trip's probe, answered `pong` with the same value.
ping: u64,
screen_ack: []const u8,
@@ -516,7 +522,8 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 {
try putSlice16(&w, h.session);
try w.writeByte(h.view orelse 0xff);
},
- .bye => |b| try w.writeByte(@intFromBool(b.again)),
+ // 0 it leaves, 1 it joins again, 2 its window was closed.
+ .bye => |b| try w.writeByte(if (b.close) 2 else @intFromBool(b.again)),
.ping => |v| try w.writeInt(u64, v, .little),
.screen_ack, .want => |bytes| try w.writeAll(bytes),
.check => {},
@@ -586,7 +593,12 @@ pub fn decodeClient(tag: u8, payload: []const u8) Error!ClientMsg {
else => |k| k,
},
} },
- .bye => .{ .bye = .{ .again = try getBool(&r) } },
+ .bye => .{ .bye = switch (try r.takeByte()) {
+ 0 => .{},
+ 1 => .{ .again = true },
+ 2 => .{ .close = true },
+ else => return error.BadValue,
+ } },
.ping => .{ .ping = try r.takeInt(u64, .little) },
.screen_ack => return .{ .screen_ack = payload },
.check => .check,
@@ -701,6 +713,7 @@ test "detached wire: every Event variant round-trips" {
try testing.expectEqualStrings("work", got.hello.session);
}
try testing.expect((try roundClient(&buf, .{ .bye = .{ .again = true } })).bye.again);
+ try testing.expect((try roundClient(&buf, .{ .bye = .{ .close = true } })).bye.close);
try testing.expectEqual(@as(?u8, 2), (try roundClient(&buf, .{ .hello = .{ .session = "work", .view = 2 } })).hello.view);
try testing.expectEqual(@as(u64, 0xfeed_beef_0000_0001), (try roundClient(&buf, .{ .ping = 0xfeed_beef_0000_0001 })).ping);
{
diff --git a/build.zig b/build.zig
index 125f4dcc..470d8600 100644
--- a/build.zig
+++ b/build.zig
@@ -33,7 +33,7 @@
//! such a package fetches what it asked for and nothing else.
//! `pardes-editor` has `pardes-syntax` in it as `.syntax`: a file belongs
//! to one module, so a package imports one of the two. `test/consumer` is
-//! such a package, with both shapes; `lib-test`, which `unit-test` runs,
+//! such a package, with both shapes; `consumer-test`, which `unit-test` runs,
//! builds and runs it.
const std = @import("std");
const builtin = @import("builtin");
diff --git a/build/patches.zig b/build/patches.zig
index 7c7b2d60..7d87b9f1 100644
--- a/build/patches.zig
+++ b/build/patches.zig
@@ -34,7 +34,8 @@ fn apply(b: *std.Build, patch: *std.Build.Step.Compile, dep: *std.Build.Dependen
/// startup width queries' `CSI 1;1R` arrived as two F3s, which a shell
/// pane took for text (build/patches/vaxis_parser.zig).
/// - ESC before a CSI or SS3 key (rxvt's Alt+arrow) is Alt on that key,
-/// not Alt+Escape followed by `[A` as text.
+/// not Alt+Escape followed by `[A` as text; before anything else (a
+/// mouse report: Alt is in its button) it is the Escape key.
/// - An X10 mouse report and a kitty graphics reply cut short by a read
/// wait for their rest: the first became three bytes of text, the
/// second sliced past its input.
@@ -56,7 +57,7 @@ const vaxis_parser = [_]Edit{
\\ if (inner.n == 0) return inner;
\\ if (inner.event) |*event| switch (event.*) {
\\ .key_press, .key_release => |*key| key.mods.alt = true,
- \\ else => {},
+ \\ else => return .{ .event = .{ .key_press = .{ .codepoint = Key.escape } }, .n = 1 },
\\ };
\\ inner.n += 1;
\\ return inner;
diff --git a/build/tests.zig b/build/tests.zig
index 741eb24a..e0b33911 100644
--- a/build/tests.zig
+++ b/build/tests.zig
@@ -62,7 +62,7 @@ pub fn add(b: *std.Build, c: struct {
// The perf gate runs with every unit-test (a regression like a
// contrast search per grapheme costs 100x, far past the gate).
unit_step.dependOn(c.tools.perf_gate_step);
- unit_step.dependOn(c.tools.lib_test_step);
+ unit_step.dependOn(c.tools.consumer_test_step);
const units: Units = .{ .nonce = c.test_nonce, .build = c.test_build, .unit = unit_step, .match = testMatch(b, c.unit_profile, c.test_filters, unit_step), .profiler = c.unit_profile, .filters = c.test_filters, .target = c.target, .optimize = c.optimize };
// The perf and fs bench programs' own tests: they compile no editor.
_ = units.add(b, units.root(b, "test/perf.zig", true, &.{.{ .name = "perf_options", .module = c.tools.perf_options.createModule() }}), null);
diff --git a/build/tools.zig b/build/tools.zig
index a4b41dd7..e573b16d 100644
--- a/build/tools.zig
+++ b/build/tools.zig
@@ -16,7 +16,7 @@ pub const Tools = struct {
perf_gate_step: *std.Build.Step,
/// The perf program's build identity, which its own tests read too.
perf_options: *std.Build.Step.Options,
- lib_test_step: *std.Build.Step,
+ consumer_test_step: *std.Build.Step,
};
/// The harnesses, the helix comparisons, the benches and the perf gate, the
@@ -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,25 +239,16 @@ 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
// this checkout has fetched.
- const lib_test = b.addSystemCommand(&.{ b.graph.zig_exe, "build", "test", "--pkg-dir", "../../zig-pkg" });
- lib_test.setName("zig build test in test/consumer, a package that depends on pardes");
- lib_test.setCwd(b.path("test/consumer"));
- lib_test.has_side_effects = true;
- const lib_test_step = b.step("lib-test", "build and test the library from a package that depends on pardes (test/consumer)");
- lib_test_step.dependOn(&lib_test.step);
+ const consumer_test = b.addSystemCommand(&.{ b.graph.zig_exe, "build", "test", "--pkg-dir", "../../zig-pkg" });
+ consumer_test.setName("zig build test in test/consumer, a package that depends on pardes");
+ consumer_test.setCwd(b.path("test/consumer"));
+ consumer_test.has_side_effects = true;
+ const consumer_test_step = b.step("consumer-test", "build and test the library from a package that depends on pardes (test/consumer)");
+ consumer_test_step.dependOn(&consumer_test.step);
const history = b.addExecutable(.{
.name = "pardes-history",
@@ -271,7 +262,7 @@ pub fn add(b: *std.Build, c: struct {
run_history.addPassthruArgs();
run_history.has_side_effects = true;
b.step("history", "compare command output and test/build runtime across jj revisions").dependOn(&run_history.step);
- return .{ .perf_gate_step = perf_gate_step, .perf_options = perf_options, .lib_test_step = lib_test_step };
+ return .{ .perf_gate_step = perf_gate_step, .perf_options = perf_options, .consumer_test_step = consumer_test_step };
}
/// The PDF benches: the core over the pdf addon, a pane of it.
diff --git a/core/CHANGELOG.md b/core/CHANGELOG.md
index faa02ade..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
@@ -238,9 +249,9 @@
editor has them, for a program that draws source text itself. Every
dependency but tree-sitter's runtime is lazy in the manifest, so such a
package fetches the runtime and the grammars of its `grammars` set
- and nothing else; `zig build lib-test`, which `unit-test` runs, builds
- one (`test/consumer`). The markdown grammar is pinned by its commit: its
- branch has moved, and a fresh checkout could not fetch it.
+ and nothing else; `zig build consumer-test`, which `unit-test` runs,
+ builds one (`test/consumer`). The markdown grammar is pinned by its
+ commit: its branch has moved, and a fresh checkout could not fetch it.
- Enter, `o` and `O` give the new line helix's indent where the file's
grammar has an indent query (bash, C, C#, C++, Clojure, CSS, Elixir,
diff --git a/core/Core.zig b/core/Core.zig
index de911469..d2cfadfc 100644
--- a/core/Core.zig
+++ b/core/Core.zig
@@ -303,7 +303,7 @@ theme_file_path: config.Settings.Text(limits.host_path_cap) = .{},
/// what a failed ThemeFile goes back to (colors.revertThemeFile).
theme_file_loaded: config.Settings.Text(limits.host_path_cap) = .{},
theme_file_generation: u32 = 0,
-theme_file_pane: u8 = 0,
+theme_file_pane: Pane.Id = .at(0),
chrome: colors.ChromeTheme = colors.initial_chrome,
/// Every drawn frame's timings (FrameStats: the Debug box, PARDES_FRAMES):
/// its runner's (`Options.frames`), which its frontend writes as it draws
@@ -472,11 +472,11 @@ pub const replica = .{
"tape",
},
.derived = .{ "shell_rows", "diff_output", "locations_cache", "retired_panes", "tty_filter_palette", "body_chrome" },
- // The host's handles, the 9P server's fids and log, the state file
- // every session of the user shares (and Recent read from it), this
- // session's closed panes, and the files of a host with no file
- // system of its own.
- .authority = .{ "host", "fs", "store", "recent", "db", "fallback" },
+ // The host's handles, the state file every session of the user
+ // shares (and Recent read from it), this session's closed panes, and
+ // the files of a host with no file system of its own. (The 9P
+ // server's own part of `fs` says so in fs.Namespace.)
+ .authority = .{ "host", "store", "recent", "db", "fallback" },
.len = .{ .{ "look_src", "n_look_src" }, .{ "session_dir", "session_dir_len" }, .{ "session_home", "session_home_len" }, .{ "session_shell", "session_shell_len" } },
};
@@ -531,9 +531,9 @@ pub const perform = @import("Effect.zig").perform;
/// second copy of this drifted once, leaving restored tags without an
/// allocator and every 9P mtime 0.
pub fn create(gpa: std.mem.Allocator, opts: Options) !*Pardes {
- // The global still set beside the field (P20): a core made while
- // a tape records (PARDES_RECORD, a replica's step) is its.
- const tape = opts.tape orelse pardes.tape.on orelse &pardes.tape.none;
+ // Its options' (a recording session's, an authority's, a replay's), or
+ // the one nobody records.
+ const tape = opts.tape orelse &pardes.tape.none;
const p = try gpa.create(Pardes);
p.* = .{
.gpa = gpa,
@@ -564,10 +564,9 @@ pub fn create(gpa: std.mem.Allocator, opts: Options) !*Pardes {
return p;
}
-/// A new session, its tape written from here when PARDES_RECORD asks.
+/// A new session, recorded from here on its options' tape.
pub fn init(gpa: std.mem.Allocator, opts: Options) !*Pardes {
// By hand, not `taped`: no core yet to enter on; the tape adopts the one made.
- pardes.tape.startFromEnv();
const taped = pardes.tape.enter(null, .{ .init = opts });
// The tape adopts the core made, none on a failure.
var made: ?*Pardes = null;
@@ -824,8 +823,8 @@ fn recentFound(p: *Pardes, hash: u64) ?recent_files.Entry {
pub fn deinit(p: *Pardes) void {
// By hand, not `taped`: what it records is no argument (`current`), and it leaves on no core.
- const taped = pardes.tape.enter(p, .{ .deinit = pardes.tape.current(p) });
- pardes.tape.forget(p);
+ const taped = pardes.tape.enter(p, .{ .deinit = p.tape.current(p) });
+ p.tape.forget(p);
defer pardes.tape.leave(null, taped);
if (std.c.getenv("PARDES_FRAMES")) |path| p.frames.dump(std.mem.span(path));
// Every file open now is closed with its dot, and the list kept.
@@ -1581,12 +1580,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
@@ -2293,6 +2286,10 @@ pub const Options = struct {
/// first effects (runtime/session.zig); a client's session is on it,
/// its first join made there with no hello (replica.join).
pair: ?c_int = null,
+ /// A client exec'd at an Upgrade (runtime/client.zig `execAgain`,
+ /// PARDES_JOIN_VIEW): the view it had, which the session kept for it
+ /// (views.away), joined again for as a rejoin dials (replica.join).
+ join_view: ?u8 = null,
mounts: []const filesystem.Mount = &.{},
config_dir: ?[]const u8 = null,
/// Where what outlives the session is kept (Db.zig): the user's state
@@ -2308,7 +2305,7 @@ pub const Options = struct {
/// A client's: the kinds it caught breaking PA_PLAIN, its frontend's
/// list, which outlives each core it joins with. In no tape and no dump.
distrusted: ?*pardes.Addon.Distrusted = null,
- /// The core's tape (`Pardes.tape`); null: `tape.on`'s, or `tape.none`.
+ /// The core's tape (`Pardes.tape`); null: `tape.none`.
tape: ?*pardes.tape.Tape = null,
/// What the host's scan of the addon directories found (Addon.scan).
addons: []const pardes.Kind.Loaded = &.{},
diff --git a/core/File.zig b/core/File.zig
index 51773c89..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);
@@ -2356,6 +2357,20 @@ test "a caret deep in a long line scrolls the view sideways to it, measured from
try std.testing.expectEqual(@as(i32, 0), pane.hscroll);
}
+test "a caret left of a view scrolled sideways is not drawn in the gutter" {
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
+ defer p.deinit();
+ p.settings.wrap = false;
+ const pane = try p.setTestFile("short1 END_A_MARKER_WAY_OUT_RIGHT_padpadpadpadpadpadpadpadpadpadpad_TAIL\n");
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ try std.testing.expect((try p.render(arena.allocator())).cursor != null);
+ // One wheel notch (4 columns) of the 7 the gutter is: the caret, at
+ // column 0, was drawn 3 columns into the gutter.
+ pane.hscroll = 4;
+ try std.testing.expect((try p.render(arena.allocator())).cursor == null);
+}
+
test "undo and redo walk back and forth through every step of random edits, joined entries and all" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
diff --git a/core/Handover.zig b/core/Handover.zig
index dde31f8b..6f7340b2 100644
--- a/core/Handover.zig
+++ b/core/Handover.zig
@@ -33,7 +33,7 @@ const MAX_PANES = pardes.MAX_PANES;
/// libc: fork and exec of a window, and file calls in the cancelable carry task that must not see its cancel (its defer's unlink).
const libc = std.c;
-/// What a grip carries out of its window: one pane with the panes attached
+/// What a grip carries out of its window: one pane with the panes docked
/// to it, or a whole column.
pub const Kind = enum { pane, column };
@@ -46,7 +46,7 @@ const Carried = struct {
/// Each pane as dump.savePane makes it, top to bottom.
panes: []const []const u8,
weights: []const f32,
- /// Which of them each one is attached to (layout.zig, "Attached panes").
+ /// Which of them each one is docked to (layout.zig, "Docked panes").
owners: []const ?u32,
};
pub const carried_magic = "pardes-carried\n";
@@ -84,8 +84,8 @@ pub fn deinit(h: *Handover, gpa: std.mem.Allocator) void {
h.bytes = null;
}
-/// Pane slot `at` (with what is attached to it, or alone when it is itself
-/// an attachment), or column `at`, released past the window's edge: dumped,
+/// Pane slot `at` (with what is docked to it, or alone when it is itself
+/// a docked pane), or column `at`, released past the window's edge: dumped,
/// and the host asked to carry it. Only text panes travel: a terminal's
/// shell is this process's child and would die with the pane here.
pub fn begin(h: *Handover, p: *Pardes, carried: Kind, at: usize) void {
@@ -273,7 +273,7 @@ pub fn adopt(p: *Pardes, bytes: []const u8) !usize {
n += 1;
if (pane.file == null) return error.NotText;
}
- // An attachment names its owner by its place in the dump.
+ // A docked pane names its owner by its place in the dump.
for (st.owners, 0..) |owner, k| {
const at = owner orelse continue;
if (at >= n) continue;
@@ -299,7 +299,7 @@ pub fn adopt(p: *Pardes, bytes: []const u8) !usize {
for (0..p.view().ncol) |c| for (p.view().cols[c].panes[0..p.view().cols[c].n]) |id| {
heights[id] = p.view().rects[id].h;
};
- // The group under the pointer (a pane with what is attached to it): the
+ // The group under the pointer (a pane with what is docked to it): the
// new panes go under all of it, out of its owner's rows.
var after: usize = p.view().cols[tc].n;
var root: ?usize = null;
@@ -315,7 +315,7 @@ pub fn adopt(p: *Pardes, bytes: []const u8) !usize {
}
if (root) |owner| {
const r = p.view().rects[owner];
- // Down to the pointer's row; let go over one of its attachments,
+ // Down to the pointer's row; let go over one of its docked panes,
// half of it.
const keeps = @max(layout.minRows(p, owner), if (y >= r.y and y < r.y + r.h) (y - r.y) + 1 else r.h / 2);
const give = heights[owner] -| keeps;
diff --git a/core/Names.zig b/core/Names.zig
index fff2c84f..2fbbec37 100644
--- a/core/Names.zig
+++ b/core/Names.zig
@@ -2,7 +2,7 @@
//! directory (listed by the disk engine, Stream.zig), the recent files, the open panes,
//! a file's declarations. Each keystroke scores them again with a small
//! fzf-style scorer (subsequence, Smith-Waterman with affine gaps, bonuses
-//! at the starts of words and path segments), a frame's budget at a time,
+//! at the starts of words and path segments), a frame's count at a time,
//! the best kept first. Lifted from the pick prototype (Pick.zig), whose
//! scorer took ~1 ms for 20k paths in a release build. Embedded in a
//! Query; the rows it shows are the Query's to make.
@@ -56,8 +56,12 @@ pub const max_query = 64;
/// A candidate is scored over its first this many bytes.
const max_text = 512;
const max_cands = 200_000;
-/// A keystroke's scoring, and a frame's: what is left waits a frame.
-const score_budget_ns = 4 * std.time.ns_per_ms;
+/// A keystroke's scoring, and a frame's: at most this many of the
+/// scorer's cells (a key's bytes times the query's and one: what `match`
+/// can visit of a candidate); what is left waits a frame. A count, not the
+/// clock: a client's guess of a key scores as far as the session's step
+/// (P27, P30). About 4 ms in a release build (`pardes-perf --search`).
+const score_cells = 3_000_000;
pub fn deinit(n: *Names, gpa: std.mem.Allocator) void {
n.bytes.deinit(gpa);
@@ -136,12 +140,12 @@ pub fn typed(n: *Names, gpa: std.mem.Allocator, text: []const u8) void {
}
/// Scores the pending candidates, then `cands[scored..]`, into `hits`, and
-/// sorts them: at most `score_budget_ns` of it a call, the rest on the
-/// next frames while the best so far is shown.
+/// sorts them: at most `score_cells` of it a call, the rest on the next
+/// frames while the best so far is shown.
pub fn rescore(n: *Names, gpa: std.mem.Allocator) void {
const q = n.queryText();
const empty = std.mem.trim(u8, q, " ").len == 0;
- const started = pardes.FrameStats.nowNs();
+ var left: usize = score_cells;
const had = n.hits.items.len;
const was_scored = n.scored;
var count: usize = 0;
@@ -157,8 +161,8 @@ pub fn rescore(n: *Names, gpa: std.mem.Allocator) void {
const key = n.bytes.items[c.start + c.key ..][0..c.key_len];
const s = if (empty) 0 else match(q, key, n.lower.items[c.start + c.key ..][0..c.key_len], c.base, null, null);
if (s) |score| n.hits.append(gpa, .{ .cand = i, .score = score }) catch break;
- // The clock every 256 candidates: reading it is not free either.
- if (!empty and count % 256 == 255 and pardes.tape.over(started, score_budget_ns)) break;
+ left -|= @as(usize, @min(c.key_len, max_text)) * (q.len + 1);
+ if (!empty and left == 0) break;
}
// An empty query keeps the source's order (the walk's, recency): no
// row moves as the walk goes on, it only grows at the foot.
diff --git a/core/Pipe.zig b/core/Pipe.zig
index cf61b78f..012ce689 100644
--- a/core/Pipe.zig
+++ b/core/Pipe.zig
@@ -52,7 +52,7 @@ pub const PendingPipe = struct {
/// The digest's walk (core/walk.zig) of the ranges, as far as they go.
pub const replica = .{ .len = .{.{ "ranges", "nranges" }} };
id: u32,
- pane: usize,
+ pane: Pane.Id,
serial: u32,
/// The text piped: the pane's body or tag, or a header (`column`
/// names which).
@@ -133,7 +133,7 @@ pub fn submitPipe(p: *Pardes, id: usize) void {
if (p.pipe.wait) |*old| old.deinit();
p.pipe.wait = .{
.id = p.pipe.seq,
- .pane = id,
+ .pane = .at(id),
.serial = pane.serial,
.what = t.what,
.column = p.headerColumn() orelse 0,
@@ -166,16 +166,16 @@ fn pipeFailed(p: *Pardes, wait: *const PendingPipe, failure: ?selection_pipe.Fai
var out: std.Io.Writer.Allocating = .init(p.gpa);
defer out.deinit();
const w = &out.writer;
- w.print("| {s}\n\n", .{wait.command}) catch |err| return p.reportError(.at(wait.pane), "pipe", err);
+ w.print("| {s}\n\n", .{wait.command}) catch |err| return p.reportError(wait.pane, "pipe", err);
if (wait.inputs.len > 1) if (failure) |fail|
- w.print("selection {d} of {d}: ", .{ fail.index + 1, wait.inputs.len }) catch |err| return p.reportError(.at(wait.pane), "pipe", err);
- writeFailure(w, failure) catch |err| return p.reportError(.at(wait.pane), "pipe", err);
- const content = out.toOwnedSlice() catch |err| return p.reportError(.at(wait.pane), "pipe", err);
+ w.print("selection {d} of {d}: ", .{ fail.index + 1, wait.inputs.len }) catch |err| return p.reportError(wait.pane, "pipe", err);
+ writeFailure(w, failure) catch |err| return p.reportError(wait.pane, "pipe", err);
+ const content = out.toOwnedSlice() catch |err| return p.reportError(wait.pane, "pipe", err);
const was = p.view().active;
- panes.Output.openErrors(p, wait.pane, content) catch |err| {
+ panes.Output.openErrors(p, wait.pane.index(), content) catch |err| {
p.gpa.free(content);
// Nowhere to put the report is itself worth one line.
- p.reportError(.at(wait.pane), "pipe", err);
+ p.reportError(wait.pane, "pipe", err);
return;
};
if (p.panes[was] != null) p.view().active = was;
@@ -250,7 +250,7 @@ pub fn pipeResponse(
if (!success or outputs.len != wait.inputs.len) return pipeFailed(p, &wait, failure);
- const pane = p.panes[wait.pane] orelse return;
+ const pane = p.panes[wait.pane.index()] orelse return;
if (pane.serial != wait.serial) return;
const t: *Text = switch (wait.what) {
.body => &pane.body,
@@ -259,13 +259,13 @@ pub fn pipeResponse(
.workspace => &p.global_tag,
.input => return,
};
- const content = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(.at(wait.pane), "pipe", err);
+ const content = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(wait.pane, "pipe", err);
const changed = if (t.what == .body) changed: {
const f = pane.file orelse return;
if (!panes.Output.fileTraits(f.output).saves) return;
break :changed f.revision != wait.revision;
} else std.hash.Wyhash.hash(0, content) != wait.sum;
- if (changed) return p.reportError(.at(wait.pane), "pipe", error.FileChangedWhileFiltering);
+ if (changed) return p.reportError(wait.pane, "pipe", error.FileChangedWhileFiltering);
if (wait.how == .ignore) return;
if (wait.how == .keep) {
@@ -296,14 +296,14 @@ pub fn pipeResponse(
const cut = pipeCut(&wait, content, i) orelse return;
const output = pipeOutput(&wait, outputs, content, i);
if (output.len > selection_pipe.max_stdout_bytes)
- return p.setMessage(.at(wait.pane), std.fmt.bufPrint(&said, "pipe: an output of {d} bytes, past {d}: the text is left as it was", .{ output.len, selection_pipe.max_stdout_bytes }) catch unreachable); // two numbers fit 128
+ return p.setMessage(wait.pane, std.fmt.bufPrint(&said, "pipe: an output of {d} bytes, past {d}: the text is left as it was", .{ output.len, selection_pipe.max_stdout_bytes }) catch unreachable); // two numbers fit 128
total_output += output.len; // each under 1 MiB, at most max_selections of them
if (total_output > selection_pipe.max_total_stdout_bytes)
- return p.setMessage(.at(wait.pane), std.fmt.bufPrint(&said, "pipe: {d} bytes of output in all, past {d}: the text is left as it was", .{ total_output, selection_pipe.max_total_stdout_bytes }) catch unreachable); // two numbers fit 128
- if (i > 0 and cut.lo < ops[i - 1].q1) return p.setMessage(.at(wait.pane), "pipe: the selections overlap: the text is left as it was");
+ return p.setMessage(wait.pane, std.fmt.bufPrint(&said, "pipe: {d} bytes of output in all, past {d}: the text is left as it was", .{ total_output, selection_pipe.max_total_stdout_bytes }) catch unreachable); // two numbers fit 128
+ if (i > 0 and cut.lo < ops[i - 1].q1) return p.setMessage(wait.pane, "pipe: the selections overlap: the text is left as it was");
ops[i] = .{ .q0 = @intCast(cut.lo), .q1 = @intCast(cut.hi), .text = output };
}
- const replacement = sam.apply(p.gpa, content, ops[0..n]) catch |err| return p.reportError(.at(wait.pane), "pipe", err);
+ const replacement = sam.apply(p.gpa, content, ops[0..n]) catch |err| return p.reportError(wait.pane, "pipe", err);
var new_ranges: [panes.Text.max_selections]modal.Selection = undefined;
var delta: isize = 0;
for (ops[0..n], wait.ranges[0..n], new_ranges[0..n]) |op, range, *moved| {
@@ -316,10 +316,10 @@ pub fn pipeResponse(
// One async request is one history transaction, even at 64 cursors.
edit.pushUndo(p.editor(), t) catch |err| {
p.gpa.free(replacement);
- return p.reportError(.at(wait.pane), "pipe", err);
+ return p.reportError(wait.pane, "pipe", err);
};
- edit.setEditText(p.editor(), t, replacement) catch |err| return p.reportError(.at(wait.pane), "pipe", err);
- const now = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(.at(wait.pane), "pipe", err);
+ edit.setEditText(p.editor(), t, replacement) catch |err| return p.reportError(wait.pane, "pipe", err);
+ const now = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(wait.pane, "pipe", err);
t.setRanges(p.settings.tab, now, new_ranges[0..n], &.{}, wait.primary, wait.explicit);
t.select = false;
t.show(p.settings.tab);
diff --git a/core/Places.zig b/core/Places.zig
index 9ffbff88..35b79805 100644
--- a/core/Places.zig
+++ b/core/Places.zig
@@ -46,13 +46,14 @@ pub const Provenance = enum { typed, search, list };
/// Places past this many are not kept. ponytail: 16 bytes a place, 16 MB
/// at the cap; a sparse count past it if a million is ever too few.
pub const max_hits = 1 << 20;
-/// What one frame spends finding places: about 4 ms on the clock, checked
-/// between pieces of the text; mvzr's steps (Regex.budget is about 300 ms
-/// of them, so this is about 5 ms), which bound one slow piece; and bytes
-/// read, the bound where there is no clock.
-pub const frame_ns: u64 = 4 * std.time.ns_per_ms;
+/// What one frame spends finding places: bytes of the text read (and the
+/// places an insert above the view moves, as many bytes), about 4 ms in a
+/// release build (`pardes-perf --search`); and mvzr's steps (Regex.budget
+/// is about 300 ms of them, so this is about 5 ms), which bound one slow
+/// piece. Counts, not the clock: a replica finds as many places a frame as
+/// its session (P27, P30).
pub const frame_steps: u64 = regexp.Regex.budget / 64;
-pub const frame_bytes: usize = 8 << 20;
+pub const frame_bytes: usize = 512 << 10;
/// The text is searched in pieces of about this much, each ending at a
/// line's end, so that a budget runs out between pieces, not inside one.
/// A folding set lowers its copy of the text a piece at a time too.
@@ -405,7 +406,6 @@ fn restart(set: *Places, p: *Pardes, f: *File.State) void {
/// been searched, make it current. Run after every step (with no budget:
/// the view only) and every tick (a frame's).
pub fn fill(set: *Places, p: *Pardes, pane: *Pane, bytes: usize, steps: u64) void {
- const started_ns = pardes.FrameStats.nowNs();
if (!set.started) return;
set.derive(p.gpa);
const f = if (pane.file) |*file| file else return set.clear(p.gpa);
@@ -490,17 +490,14 @@ pub fn fill(set: *Places, p: *Pardes, pane: *Pane, bytes: usize, steps: u64) voi
}
if (forward) set.hi = at else {
set.hits.insertSlice(gpa, set.nhead, head.items) catch return;
+ // With many places below, moving them is most of the work.
+ left -|= (set.hits.items.len - set.nhead - head.items.len) * @sizeOf(Hit);
if (set.current) |*c| c.* += head.items.len;
set.nhead += head.items.len;
set.head_to = at;
}
left -|= at - from;
if (short) break;
- // A frame's time spent (a whole search's for n and N, whose steps
- // are mvzr's whole budget).
- // The clock's verdict is the session's (core/tape.zig): a replica
- // finds as many places a frame as this did.
- if (started_ns != 0 and bytes != std.math.maxInt(usize) and pardes.tape.over(started_ns, frame_ns)) break;
}
if (set.hits.items.len != found_before) {
set.gen +%= 1;
diff --git a/core/Plumb.zig b/core/Plumb.zig
index f51ddace..e1b09e69 100644
--- a/core/Plumb.zig
+++ b/core/Plumb.zig
@@ -593,7 +593,7 @@ pub fn portName(p: *const Pardes, index: u8) ?[]const u8 {
/// Whether a program reads port `index` (an open of its file): the
/// authority's 9P state, asked through the tape.
fn portRead(p: *Pardes, index: u8) bool {
- for (&p.fs.opens) |*o| if (o.node != 0 and o.what == .port and o.what.port.index == index) return true;
+ for (p.fs.opens[0..p.fs.opens_len]) |*o| if (o.node != 0 and o.what == .port and o.what.port.index == index) return true;
return false;
}
@@ -611,7 +611,7 @@ fn enqueue(p: *Pardes, q: *events.Queue, lead: []const u8, m: *const Msg) bool {
/// A copy of `m` to every reader of port `index` (plumber(4)'s queuesend:
/// every fid open when it was sent), each read held for one answered.
fn fanOut(p: *Pardes, index: u8, m: *const Msg) void {
- for (&p.fs.opens) |*o| if (o.node != 0 and o.what == .port and o.what.port.index == index) {
+ for (p.fs.opens[0..p.fs.opens_len]) |*o| if (o.node != 0 and o.what == .port and o.what.port.index == index) {
if (!enqueue(p, &o.what.port.queue, "", m)) {
var said: Kind.Buf(160) = .{};
events.notePath(p, "err -", said.print("plumb/{s}: a message of {d} bytes is over a reader's {d} KiB, not sent to it", .{ portName(p, index).?, m.data.len, events.queue_cap / 1024 }));
diff --git a/core/Query.zig b/core/Query.zig
index f0e9ee1a..e2f59028 100644
--- a/core/Query.zig
+++ b/core/Query.zig
@@ -1,5 +1,5 @@
-//! The query pane: the one pane search is. A +Search attached under the
-//! pane that asked (its owner, layout.zig "Attached panes"), born at a
+//! The query pane: the one pane search is. A +Search docked under the
+//! pane that asked (its owner, layout.zig "Docked panes"), born at a
//! fixed height, whose body's line 1 is the query, editable text, and
//! whose rows below are made live from a source, read-only while live.
//! Line 1's first word names the source: `/pat` the owner's text (smart-
@@ -18,7 +18,7 @@
//! text: B3 on one looks, B2 on line 1 runs it again. Wherever a row points into
//! an open pane's text, that pane's places (Places.zig) show the set:
//! tints, rail ticks, the current one selected. A row pointing at a file
-//! no pane shows is shown in the +Preview attached under this pane; Enter
+//! no pane shows is shown in the +Preview docked under this pane; Enter
//! promotes the preview to the file's pane where it stands.
//!
//! Nothing moves while you type: the pane never closes, resizes or
@@ -319,7 +319,7 @@ fn create(p: *Pardes, owner_id: usize, line: []const u8, source: Source) ?usize
preview_rows = spare -| want;
}
}
- if (!layout.attachFrom(p, owner_id, free, want, owner_id)) {
+ if (!layout.dockFrom(p, owner_id, free, want, owner_id)) {
// An owner too short to give a query pane its rows: placed as any
// new pane is, the one place a search moves another pane.
layout.placeNew(p, owner_id, owner_id, free, .doc);
@@ -1644,7 +1644,7 @@ fn makePreview(p: *Pardes, qid: usize, rows: u16, giver: usize) ?usize {
return null;
};
layout.compute(p);
- if (!layout.attachFrom(p, qid, free, rows, giver)) {
+ if (!layout.dockFrom(p, qid, free, rows, giver)) {
p.removePane(free, qid) catch |err| p.reportError(.at(qid), "query", err);
return null;
}
@@ -1732,7 +1732,7 @@ fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void
/// The +Preview becomes the file's pane where it stands: same slot, same
/// serial, same rect, its scroll and selection as the preview left them.
/// It is a file pane from here: an empty undo history, the Recent entry,
-/// the watch, a file's tag; and a pane of its own, no longer attached (it
+/// the watch, a file's tag; and a pane of its own, no longer docked (it
/// stays when its query pane goes).
fn promote(p: *Pardes, qid: usize, id: usize) void {
const pane = p.panes[id] orelse return;
@@ -1911,10 +1911,10 @@ pub fn cancel(p: *Pardes, id: usize) void {
if (owner_id) |oid| p.view().active = oid;
return;
}
- // Attached, its rows go back to its owner; else to its own column's.
- const attached = layout.ownerOf(p, id) != null;
+ // Docked, its rows go back to its owner; else to its own column's.
+ const docked = layout.ownerOf(p, id) != null;
if (owner_id) |oid| {
- p.removePane(id, if (attached) oid else null) catch |err| p.reportError(.at(id), "query", err);
+ p.removePane(id, if (docked) oid else null) catch |err| p.reportError(.at(id), "query", err);
p.view().active = oid;
if (layout.findPane(p, oid)) |at| p.setActiveColumn(at.col);
} else p.removePane(id, null) catch |err| p.reportError(.at(id), "query", err);
@@ -2399,6 +2399,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");
@@ -2633,6 +2634,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/Store.zig b/core/Store.zig
index 82e3c5bf..ac9387cb 100644
--- a/core/Store.zig
+++ b/core/Store.zig
@@ -28,7 +28,7 @@ pub const Closed = struct {
/// brought back, it takes them from that pane alone.
gainer: u32,
below: bool,
- /// The pane it was attached to, by serial (0 none).
+ /// The pane it was docked to, by serial (0 none).
owner: u32,
rows: u16,
/// What its Panes row shows: its file, command or directory.
@@ -78,7 +78,7 @@ pub fn clone(s: *const Store, gpa: std.mem.Allocator) Store {
// ---- the closed panes ----
/// Pane `id`, about to close, kept: what it was (a one-pane Dump) and
-/// where (its column, its rows, what it was attached to). Null for a pane
+/// where (its column, its rows, what it was docked to). Null for a pane
/// that is no pane of the user's: a query pane, a preview, one carried to
/// another window (`away`), one made and refused in the same step (never
/// announced), or one whose dump fails or is too big. `close` finishes it
@@ -186,7 +186,7 @@ pub fn closedBySerial(s: *const Store, serial: u32) ?*Closed {
}
/// Closed pane `serial` of this session made again, where it was: beside
-/// the pane its rows went to, taking them from that pane alone (attached
+/// the pane its rows went to, taking them from that pane alone (docked
/// again to its owner when that is still open), else placed as a new pane
/// from `from`. False when it is not this session's, or its dump will not
/// load; the keyboard on it otherwise.
@@ -204,7 +204,7 @@ pub fn reopen(s: *Store, p: *Pardes, serial: u32, from: usize) bool {
const owner = if (place.owner != 0) p.paneBySerial(place.owner) else null;
const gainer = if (place.gainer != 0) p.paneBySerial(place.gainer) else null;
const placed = if (owner) |o|
- layout.attachFrom(p, o, free, place.rows, o)
+ layout.dockFrom(p, o, free, place.rows, o)
else if (gainer) |g|
layout.giveBack(p, free, g, place.below, place.rows)
else
diff --git a/core/Stream.zig b/core/Stream.zig
index 78f6ef41..f65d0683 100644
--- a/core/Stream.zig
+++ b/core/Stream.zig
@@ -1269,6 +1269,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;
@@ -1307,6 +1308,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/Turn.zig b/core/Turn.zig
index 687e287f..249c6795 100644
--- a/core/Turn.zig
+++ b/core/Turn.zig
@@ -17,7 +17,6 @@
//! come from a shell performing a save between steps -- so a parked request
//! is never the syscall's own.
const std = @import("std");
-const tape = @import("tape.zig");
const Turn = @This();
@@ -46,6 +45,10 @@ restores: u64 = 0,
lsp_answers: u64 = 0,
/// All of the above, and `out` reaching zero.
settled: std.Io.Condition = .init,
+/// Every `yield`, ever: a replica's step makes none (each syscall of its
+/// core is a tape site), which its tape checks by this count across a
+/// speculation and a replayed input (core/tape.zig `stray`).
+yields: u64 = 0,
/// The editor's thread takes the turn for good; it has it until `stop`.
pub fn start(t: *Turn, io: std.Io) void {
@@ -79,10 +82,7 @@ pub fn wake(t: *Turn) void {
/// a step. Nests: a directory listing that resolves each entry yields
/// inside a yield, and only the outermost one lets go.
pub fn yield(t: *Turn) void {
- // A replica makes no syscall: each is a site of the tape's. One that
- // is none stops a speculation and diverges a replay (it joins
- // again), never the process (a window client's `Term fish`, H17).
- if (tape.replaying()) tape.stray();
+ t.yields +%= 1;
const io = t.io orelse return;
yield_depth += 1;
if (yield_depth != 1) return;
diff --git a/core/body_layer.zig b/core/body_layer.zig
index 7dc097ad..1582136c 100644
--- a/core/body_layer.zig
+++ b/core/body_layer.zig
@@ -512,7 +512,10 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane
)
else
ccol;
- if (prow >= pane.tag_rows and cx >= 0 and prow < body_bottom and cx < tw)
+ // Left of a view scrolled sideways it is off the view, not
+ // in the gutter.
+ const left: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0;
+ if (prow >= pane.tag_rows and cx >= left and prow < body_bottom and cx < tw)
s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - pane.tag_rows)), .bar = pane.body.mode == .insert };
}
} else if (pane.terminal != null) visible: {
diff --git a/core/builtins.zig b/core/builtins.zig
index 894478fd..7ad70e7c 100644
--- a/core/builtins.zig
+++ b/core/builtins.zig
@@ -1017,11 +1017,11 @@ pub const Del = struct {
// acme's Del asks winclean first (exec.c del): unsaved text is warned
// about once, and the same Del again, nothing edited since, closes.
if (warnModifiedIn(c, .Del, .{ .pane = c.id })) return;
- // An attachment's rows go back to its owner: nothing to ask.
+ // A docked pane's rows go back to its owner: nothing to ask.
if (layout.ownerOf(c.p, c.id)) |owner| return c.p.removePane(c.id, owner) catch |err| c.p.reportError(.at(c.id), "close", err);
const at = layout.findPane(c.p, c.id);
const above = if (at) |f| layout.expandedNeighbor(c.p, f.col, f.idx, .above) else null;
- // An owner's attachments close with it: below is past them.
+ // An owner's docked panes close with it: below is past them.
const below = if (at) |f| layout.expandedNeighbor(c.p, f.col, layout.groupEnd(c.p, f.col, f.idx) - 1, .below) else null;
const to: ?usize = if (std.mem.eql(u8, side, "k"))
above orelse below
diff --git a/core/colors.zig b/core/colors.zig
index 4825ea3f..7e692fe5 100644
--- a/core/colors.zig
+++ b/core/colors.zig
@@ -8,7 +8,6 @@ const Color = @import("surface.zig").Color;
const FontRole = @import("surface.zig").FontRole;
const config = @import("config.zig");
const platform = pardes.platform;
-const MAX_PANES = pardes.MAX_PANES;
const BOX_H = pardes.BOX_H;
const Pardes = pardes.Pardes;
@@ -630,7 +629,7 @@ pub fn requestThemeFile(p: *Pardes, id: usize, argument: []const u8) void {
p.reportError(.at(id), "theme file", error.PathTooLong);
return;
}
- p.theme_file_pane = @intCast(@min(id, MAX_PANES - 1));
+ p.theme_file_pane = .at(id);
const generation = nextThemeFileGeneration(p);
p.emit(.{ .theme_file = .{ .generation = generation, .on = true } });
}
@@ -645,7 +644,7 @@ pub fn loadedThemeFile(p: *const Pardes) ?[]const u8 {
pub const ThemeFileRequest = struct {
path: []const u8,
- pane: u8,
+ pane: pardes.Pane.Id,
};
/// Borrow the current request while a native host performs its synchronous
@@ -673,7 +672,7 @@ fn themeFileFailure(p: *Pardes, request: ThemeFileRequest, why: []const u8) void
var said: pardes.Kind.Buf(520) = .{};
var cut: [200]u8 = undefined;
const path = @import("ninep/tree.zig").fitErr(request.path, &cut);
- p.reportFailure(request.pane, said.print("theme file {s}: {s}", .{ path, why }));
+ p.reportFailure(request.pane.index(), said.print("theme file {s}: {s}", .{ path, why }));
revertThemeFile(p);
}
diff --git a/core/dump.zig b/core/dump.zig
index c348dec2..4fc7fc4d 100644
--- a/core/dump.zig
+++ b/core/dump.zig
@@ -531,17 +531,20 @@ fn restoreInner(p: *Pardes, bytes: []const u8, from: []const u8) !*Pardes {
var opts = p.opts;
opts.cols = p.view().screen_w;
opts.rows = p.view().screen_h;
+ // Loaded on the session's tape (one with clients has it from no
+ // options), which the replacement's options do not keep.
+ opts.tape = p.tape;
const replacement = try loadAndRevive(p.gpa, opts, bytes, p, null);
+ replacement.opts.tape = p.opts.tape;
replacement.pointRestoreAt(from);
// The tape follows the replacement from here (it is the session).
- pardes.tape.adopt(replacement);
+ p.tape.adopt(replacement);
pardes.ctlfs.events.notePath(replacement, "restore", from);
return replacement;
}
pub fn initFromDump(gpa: std.mem.Allocator, opts: Options, bytes: []const u8) !*Pardes {
// By hand, not `taped`: no core yet to enter on, as `Pardes.init`.
- pardes.tape.startFromEnv();
const taped = pardes.tape.enter(null, .{ .init_from_dump = .{ .opts = opts, .bytes = bytes } });
// The tape adopts the core made, none on a failure.
var made: ?*Pardes = null;
@@ -574,6 +577,10 @@ fn loadAndRevive(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, previ
var on_disk: OnDisk = @splat(false);
const p = try loadKnowing(gpa, opts, bytes, &notes, &on_disk);
errdefer p.deinit();
+ // The 9P state its requests made was its connections', which do not
+ // come with it (a client's join loads alone, and keeps it).
+ p.fs.forget(gpa);
+ for (p.panes) |slot| if (slot) |pane| pane.fs.deinit(gpa);
// Its kinds are this process's, not the dump's: the session's it
// replaces, or what the scan found (a dump of another session's).
p.kinds = if (previous) |old| old.kinds else .started(p.tape, opts.addons);
@@ -750,6 +757,7 @@ pub fn loadPane(p: *Pardes, id: usize, bytes: []const u8) !*pardes.panes.Pane {
pane.command_from = 0;
pane.places.from = 0;
pane.collapsed = false;
+ pane.fs.deinit(p.gpa);
pane.prompt_view = p.live;
try ensureKind(p, pane);
p.installPane(id, pane);
diff --git a/core/echo.zig b/core/echo.zig
index 40200696..f35c9f9d 100644
--- a/core/echo.zig
+++ b/core/echo.zig
@@ -614,7 +614,7 @@ const Rig = struct {
for (msgs.items) |m| gpa.free(m);
msgs.deinit(gpa);
}
- try g.screens.flush(g.a.core, g.peer, g.r.view, &msgs);
+ try g.screens.flush(g.a.core, g.peer, &msgs);
for (msgs.items) |m| if (g.r.screen(m)) |reply| {
_ = try g.screens.take(g.a.core, g.peer, reply);
};
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/exec.zig b/core/exec.zig
index 18b519ff..52f54541 100644
--- a/core/exec.zig
+++ b/core/exec.zig
@@ -799,7 +799,7 @@ pub fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize {
/// Whether an open of a look or exec file holds `serial` from its own write
/// (tree.Open.results): its client is reading that pane.
fn leased(p: *const Pardes, serial: u32) bool {
- for (p.fs.opens) |o| if (o.node != 0 and o.results.wrote) {
+ for (p.fs.opens[0..p.fs.opens_len]) |o| if (o.node != 0 and o.results.wrote) {
if (std.mem.indexOfScalar(u32, o.results.list[0..o.results.len], serial) != null) return true;
};
return false;
diff --git a/core/fs.zig b/core/fs.zig
index 6e5829e1..6b43ba67 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.?;
@@ -841,6 +851,32 @@ pub const EditHold = struct {
};
pub const Namespace = struct {
+ /// What a step reads that 9P requests made (every request an input
+ /// each replica replays) is the core's like any state: the open
+ /// records (a command pane a script reads is not taken again:
+ /// exec.leased), the panes the last look or exec touched (a new open's
+ /// own), the writes held to go in as one edit and a header tag's
+ /// truncation, digested and dumped (a client's join takes them from
+ /// the dump; a session revived from one drops the opens with the
+ /// connections that held them: dump.zig `loadAndRevive`). The rest is
+ /// 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, 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",
+ "listeners", "origin", "no_prompt", "session_write", "unlogged", "capturing",
+ "serving", "refused", "failure", "failure_len", "no_pane_slot", "no_pane_slot_len",
+ "said", "said_len", "said_at", "late_failure", "late_failure_len",
+ "lsp_answer_at", "edit_started", "edit_hold", "edit_said", "lsp_result", "write_room",
+ "write_waits", "log_full_hash", "pages", "closed_lines", "ran_at", "refilled",
+ "failures", "ename", "news", "hanging_up", "log", "plumb_held",
+ "started",
+ },
+ .len = .{ .{ "opens", "opens_len" }, .{ "results", "results_len" } },
+ };
socket_path: []const u8 = "",
tcp_address: ?std.Io.net.IpAddress = null,
mounts: std.ArrayList(Mount) = .empty,
@@ -848,6 +884,11 @@ pub const Namespace = struct {
os_paths: std.ArrayList(OsPath) = .empty,
/// What each open holds between its open and its release.
opens: [tree.open_slots]tree.Open = @splat(.{}),
+ /// The records past it are nothing: a digest, a dump and a replica's
+ /// rollback copy take the opens this far (an idle session's none), and
+ /// nothing reads or frees one past it (a rollback leaves there what
+ /// its epoch freed).
+ opens_len: u8 = 0,
out: std.ArrayList(u8) = .empty,
listeners: u16 = 0,
origin: u8 = 'K',
@@ -902,7 +943,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.
@@ -985,7 +1026,7 @@ pub const Namespace = struct {
st.mounts.deinit(gpa);
for (st.os_paths.items) |entry| gpa.free(entry.path);
st.os_paths.deinit(gpa);
- for (&st.opens) |*o| o.deinit(gpa);
+ for (st.opens[0..st.opens_len]) |*o| o.deinit(gpa);
for (st.pages.items) |*page| page.bytes.deinit(gpa);
st.pages.deinit(gpa);
for (st.closed_lines.items) |*line| line.bytes.deinit(gpa);
@@ -995,6 +1036,39 @@ pub const Namespace = struct {
st.out.deinit(gpa);
}
+ /// Its digest (core/walk.zig): the opens in use, and writes held by
+ /// their length (their bytes are the same writes on every side; a
+ /// stream of 8 KB appends hashed whole cost each its length again;
+ /// none held, the rest of `batch` is nothing a step reads), the panes
+ /// the last look or exec touched, a header's truncation. Nothing at
+ /// all for a session no script holds anything of.
+ pub fn digest(st: *const Namespace, h: *pardes.walk.Hasher) void {
+ comptime if (pardes.walk.fieldNames(Namespace).len != 8) @compileError("Namespace.digest: hash every field the walk does not leave out");
+ for (st.opens[0..st.opens_len]) |*o| pardes.walk.hash(tree.Open, o, h);
+ h.update(std.mem.sliceAsBytes(st.results[0..st.results_len]));
+ if (st.header_rewrite != null or st.header_trunc_pending != null or st.header_held) {
+ const words = [_]u64{ st.header_rewrite orelse std.math.maxInt(u64), st.header_trunc_pending orelse std.math.maxInt(u64), @intFromBool(st.header_held) };
+ h.update(std.mem.asBytes(&words));
+ }
+ const b = &st.batch;
+ if (b.bytes.items.len == 0) return;
+ const words = [_]u64{ b.serial, b.node, b.handle, b.at, b.bytes.items.len, b.last_ns };
+ h.update(std.mem.asBytes(&words));
+ }
+
+ /// What the requests of connections gone made, let go: a session
+ /// revived from a dump has none of the connections that held its opens.
+ pub fn forget(st: *Namespace, gpa: std.mem.Allocator) void {
+ for (st.opens[0..st.opens_len]) |*o| o.deinit(gpa);
+ st.opens_len = 0;
+ st.results_len = 0;
+ st.batch.bytes.deinit(gpa);
+ st.batch = .{};
+ st.header_rewrite = null;
+ st.header_trunc_pending = null;
+ st.header_held = false;
+ }
+
pub fn mount(st: *Namespace, gpa: std.mem.Allocator, name: []const u8, dial: []const u8) !void {
if (!validMountName(name)) return error.BadMountName;
try ninep_io.Client.validateDial(dial);
diff --git a/core/layout.zig b/core/layout.zig
index 9c99dc7d..4c7d6afb 100644
--- a/core/layout.zig
+++ b/core/layout.zig
@@ -249,8 +249,8 @@ fn splitRowFor(y: u16, h: u16, cur_y: u16, least: ?u16) ?u16 {
}
/// Where pane `id` dragged by its grip to (`cur_x`, `cur_y`) lands. An
-/// owner's grip drags its group; an attachment's drags it alone, which
-/// within its group resizes it and anywhere else detaches it (movePane).
+/// owner's grip drags its group; a docked pane's drags it alone, which
+/// within its group resizes it and anywhere else undocks it (movePane).
/// Another group is one place: a pane dropped on it lands under all of it.
pub fn movePlacement(p: *Pardes, id: usize, cur_x: u16, cur_y: u16) ?MovePlacement {
const v = p.view();
@@ -285,8 +285,8 @@ pub fn movePlacement(p: *Pardes, id: usize, cur_x: u16, cur_y: u16) ?MovePlaceme
k += 1;
continue;
}
- // Its own group's panes are places of their own: that is how an
- // attachment's grip resizes it against its owner.
+ // Its own group's panes are places of their own: that is how a
+ // docked pane's grip resizes it against its owner.
const unit_end = if (groupRoot(p, v.cols[tc].panes[k]) == own_root) k + 1 else groupEnd(p, tc, k);
var h: u16 = 0;
for (k..unit_end) |j| {
@@ -313,8 +313,8 @@ pub fn movePlacement(p: *Pardes, id: usize, cur_x: u16, cur_y: u16) ?MovePlaceme
return last;
}
-/// Move pane `id`, and the group it owns, where movePlacement says. An
-/// attachment moved anywhere but within its own group is detached there.
+/// Move pane `id`, and the group it owns, where movePlacement says. A
+/// docked pane moved anywhere but within its own group is undocked there.
pub fn movePane(p: *Pardes, id: usize, cur_x: u16, cur_y: u16) void {
const v = p.view();
const placement = movePlacement(p, id, cur_x, cur_y) orelse return;
@@ -549,7 +549,7 @@ pub fn acmePlace(p: *Pardes, c: usize, origin: ?usize, id: usize) void {
var empty: ?usize = null;
for (p.view().cols[c].panes[0..n]) |k| {
const pane = p.panes[k] orelse continue;
- // An attachment is its owner's: never halved for another pane.
+ // A docked pane is its owner's: never halved for another pane.
if (pane.collapsed or ownerOf(p, k) != null) continue;
// `>=`: at a tie the one nearer the bottom, as acme picks.
if (big == null or bodyRows(p, k) >= bodyRows(p, big.?)) big = k;
@@ -1076,7 +1076,7 @@ pub fn absorbVWeight(p: *Pardes, id: usize, to: ?usize) ?usize {
var k = f.idx;
while (to == null and k > 0) : (k -= 1) {
sib = v.cols[f.col].panes[k - 1];
- // nor to a pane attached to another: rows go to owners
+ // nor to a pane docked to another: rows go to owners
if (p.panes[sib]) |pp| if (if (pp.file) |ff| panes.Output.fileTraits(ff.output).doc else true) if (ownerOf(p, sib) == null) break;
}
const s = p.panes[sib] orelse return null;
@@ -1112,26 +1112,26 @@ pub fn splitBelow(p: *Pardes, src_id: usize, nw: *Pane) void {
};
}
-// ---- Attached panes ----
+// ---- Docked panes ----
//
-// A results pane (+Search, +Callstack, +Diff, +Errors) is ATTACHED to the
+// A results pane (+Search, +Callstack, +Diff, +Errors) is DOCKED to the
// pane it answers for, its owner (Pane.docked_to). The owner and what is
-// attached to it, and what is attached to those (a preview under a
+// docked to it, and what is docked to those (a preview under a
// +Search), are a GROUP: contiguous in one column, the owner first. A group
// is one place to everything else in the layout: an unrelated pane is never
// put inside it (acmePlace, splitAt, splitTallest), a pane dragged onto it
// lands under all of it (movePlacement), and its owner's grip, Collapse and
-// Del take all of it (movePane, toggleCollapse, Pardes.removePane). An
-// attachment's rows come from its owner and go back to it, nobody else's.
+// Del take all of it (movePane, toggleCollapse, Pardes.removePane). A
+// docked pane's rows come from its owner and go back to it, nobody else's.
-/// The slot of `id`'s owner, when `id` is attached to a live pane.
+/// The slot of `id`'s owner, when `id` is docked to a live pane.
pub fn ownerOf(p: *const Pardes, id: usize) ?usize {
const serial = (p.panes[id] orelse return null).docked_to orelse return null;
for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.serial == serial and i != id) return i;
return null;
}
-/// The owner at the top of `id`'s group: `id` itself when it is attached to
+/// The owner at the top of `id`'s group: `id` itself when it is docked to
/// nothing. Bounded: a dump could name a ring of owners.
pub fn groupRoot(p: *const Pardes, id: usize) usize {
var at = id;
@@ -1139,7 +1139,7 @@ pub fn groupRoot(p: *const Pardes, id: usize) usize {
return at;
}
-/// Whether `id` is `root` or attached to it through any number of owners.
+/// Whether `id` is `root` or docked to it through any number of owners.
fn descends(p: *const Pardes, id: usize, root: usize) bool {
var at = id;
for (0..MAX_PANES) |_| {
@@ -1150,7 +1150,7 @@ fn descends(p: *const Pardes, id: usize, root: usize) bool {
}
/// One past the last pane of the group that pane `idx` of column `c` is
-/// in: `idx + 1` for a pane with nothing attached.
+/// in: `idx + 1` for a pane with nothing docked.
pub fn groupEnd(p: *const Pardes, c: usize, idx: usize) usize {
const v = p.view();
const root = groupRoot(p, v.cols[c].panes[idx]);
@@ -1159,11 +1159,11 @@ pub fn groupEnd(p: *const Pardes, c: usize, idx: usize) usize {
return k;
}
-/// The attachments kept where they are attached: one whose owner is gone,
+/// The docked panes kept where they are docked: one whose owner is gone,
/// or that something (a 9P move, a pane split into a column of its own, an
/// owner moved by a route that does not carry its group) left anywhere but
/// right under its owner's group, is an ordinary pane from then on, where
-/// it stands. Nothing moves. Top to bottom, so a nested attachment is
+/// it stands. Nothing moves. Top to bottom, so a nested docked pane is
/// judged after the one it hangs from.
pub fn keepGroups(p: *Pardes) void {
for (0..p.view().ncol) |c| for (p.view().cols[c].panes[0..p.view().cols[c].n], 0..) |id, k| {
@@ -1175,17 +1175,17 @@ pub fn keepGroups(p: *Pardes) void {
};
}
-/// Attach new pane `id`, in no column yet, to `owner`: under the owner's
+/// Dock new pane `id`, in no column yet, to `owner`: under the owner's
/// group, `rows` of the owner's rows (tag included), from the owner and
/// from no other pane. The owner keeps its own minimum, else its tag (acme
-/// lets a window shrink to it), so the attachment may get fewer. A folded
-/// owner is unfolded first. The rows are the attachment's from then on:
+/// lets a window shrink to it), so the docked pane may get fewer. A folded
+/// owner is unfolded first. The rows are the docked pane's from then on:
/// nothing here ever resizes it again; the seam is the user's to drag.
/// False, `id` in no column, when the owner has not the rows for its tag
-/// and the attachment's minimum. The rows are given by `giver`: the owner
+/// and the docked pane's minimum. The rows are given by `giver`: the owner
/// itself or a pane of its group (a +Preview added under a query pane later
/// takes the text's rows, so the query pane, typed into, keeps its own).
-pub fn attachFrom(p: *Pardes, owner: usize, id: usize, rows: u16, giver: usize) bool {
+pub fn dockFrom(p: *Pardes, owner: usize, id: usize, rows: u16, giver: usize) bool {
const v = p.view();
const o = p.panes[owner] orelse return false;
const g = p.panes[giver] orelse return false;
@@ -1238,10 +1238,10 @@ pub fn giveBack(p: *Pardes, id: usize, gainer: usize, below: bool, rows: u16) bo
return true;
}
-/// Collapse on an owner with attachments: the whole group folds to its
+/// Collapse on an owner with docked panes: the whole group folds to its
/// tags, every row it gave up to the one unfolded neighbour outside it,
/// and unfolds again from that neighbour, as one pane's Collapse does.
-/// ponytail: unfolding opens every attachment, one folded alone before
+/// ponytail: unfolding opens every docked pane, one folded alone before
/// included; remembering which were is a bit a pane.
fn collapseGroup(p: *Pardes, c: usize, start: usize, end: usize) void {
const v = p.view();
@@ -1281,7 +1281,7 @@ pub fn toggleCollapse(p: *Pardes, id: usize) void {
const pane = p.panes[id] orelse return;
const at = findPane(p, id) orelse return;
compute(p);
- // An owner folds and unfolds with what is attached to it.
+ // An owner folds and unfolds with what is docked to it.
if (ownerOf(p, id) == null) {
const end = groupEnd(p, at.col, at.idx);
if (end > at.idx + 1) return collapseGroup(p, at.col, at.idx, end);
@@ -1635,8 +1635,8 @@ pub fn reprojectTagHit(p: *const Pardes, tag_hit: TagHit) ?TagHit {
return Layer.tagAgain(tag_hit);
}
-/// A test's attachment: an empty +Search in a new slot, in no column.
-fn testAttachment(p: *Pardes) !usize {
+/// A test's docked pane: an empty +Search in a new slot, in no column.
+fn testDocking(p: *Pardes) !usize {
const free = p.freeSlot().?;
_ = try panes.Output.open(p, free, "/tmp", .search, "", try p.gpa.dupe(u8, "q\n"));
return free;
@@ -1884,7 +1884,7 @@ test "column reorder moves only crossed state and preserves weights" {
try std.testing.expectEqual(@as(i32, 21), p.view().col_tags[1].cur_col);
}
-test "an attachment takes its rows from its owner alone, keeps them, and moves, folds and closes with it" {
+test "a docked pane takes its rows from its owner alone, keeps them, and moves, folds and closes with it" {
const exec = pardes.exec;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 48 });
defer p.deinit();
@@ -1900,8 +1900,8 @@ test "an attachment takes its rows from its owner alone, keeps them, and moves,
const unrelated = [_]usize{ below, other_col };
// Under its owner, the rows asked for, the owner's and nobody else's.
- const s = try testAttachment(p);
- try std.testing.expect(attachFrom(p, 0, s, 9, 0));
+ const s = try testDocking(p);
+ try std.testing.expect(dockFrom(p, 0, s, 9, 0));
try std.testing.expectEqual(@as(?usize, 0), ownerOf(p, s));
try std.testing.expectEqual(s, p.view().cols[0].panes[1]);
for (unrelated) |k| try std.testing.expectEqualDeep(before[k], p.view().rects[k]);
@@ -1909,8 +1909,8 @@ test "an attachment takes its rows from its owner alone, keeps them, and moves,
try std.testing.expectEqual(before[0].y, p.view().rects[0].y);
try std.testing.expectEqual(@as(u16, 9), p.view().rects[s].h);
// A second level (a preview under a query pane): out of the first's rows.
- const pv = try testAttachment(p);
- try std.testing.expect(attachFrom(p, s, pv, 4, s));
+ const pv = try testDocking(p);
+ try std.testing.expect(dockFrom(p, s, pv, 4, s));
try std.testing.expectEqual(pv, p.view().cols[0].panes[2]);
try std.testing.expectEqual(@as(usize, 0), groupRoot(p, pv));
try std.testing.expectEqual(@as(usize, 3), groupEnd(p, 0, 0));
@@ -1925,7 +1925,7 @@ test "an attachment takes its rows from its owner alone, keeps them, and moves,
compute(p);
try std.testing.expectEqual(@as(u16, 5), p.view().rects[s].h);
- // An unrelated New, from the owner or from its attachment, never lands
+ // An unrelated New, from the owner or from its docked pane, never lands
// inside the group.
exec.runBuiltin(p, .New, 0, "", null);
exec.runBuiltin(p, .New, s, "", null);
@@ -1933,7 +1933,7 @@ test "an attachment takes its rows from its owner alone, keeps them, and moves,
try std.testing.expectEqual(s, p.view().cols[at.col].panes[at.idx + 1]);
try std.testing.expectEqual(pv, p.view().cols[at.col].panes[at.idx + 2]);
- // The seam between owner and attachment is the user's: the pair alone.
+ // The seam between owner and docked pane is the user's: the pair alone.
compute(p);
const pre_drag = p.view().rects;
applyRowSplit(p, at.col, at.idx, p.view().rects[s].y - 3);
@@ -1965,7 +1965,7 @@ test "an attachment takes its rows from its owner alone, keeps them, and moves,
try std.testing.expect(p.panes[pv] == null);
compute(p);
try std.testing.expectEqual(pair[s].h + pair[pv].h, p.view().rects[s].h);
- // Del of the attachment gives its rows back to the owner, nobody else.
+ // Del of the docked pane gives its rows back to the owner, nobody else.
pair = p.view().rects;
exec.runBuiltin(p, .Del, s, "", null);
try std.testing.expect(p.panes[s] == null);
@@ -1973,19 +1973,19 @@ test "an attachment takes its rows from its owner alone, keeps them, and moves,
try std.testing.expectEqual(pair[0].h + pair[s].h, p.view().rects[0].h);
for (p.view().cols[1].panes[0..p.view().cols[1].n]) |k| if (k != 0) try std.testing.expectEqualDeep(pair[k], p.view().rects[k]);
- // Del of the owner closes what is attached to it.
- const again = try testAttachment(p);
- try std.testing.expect(attachFrom(p, 0, again, 6, 0));
+ // Del of the owner closes what is docked to it.
+ const again = try testDocking(p);
+ try std.testing.expect(dockFrom(p, 0, again, 6, 0));
exec.runBuiltin(p, .Del, 0, "", null);
try std.testing.expect(p.panes[0] == null and p.panes[again] == null);
}
-test "an attachment survives Dump and Restore, and one left away from its owner is a pane of its own" {
+test "a docked pane survives Dump and Restore, and one left away from its owner is a pane of its own" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 });
defer p.deinit();
_ = try p.setTestFile("alpha\nbeta\nalphabet\n");
- const s = try testAttachment(p);
- try std.testing.expect(attachFrom(p, 0, s, 8, 0));
+ const s = try testDocking(p);
+ try std.testing.expect(dockFrom(p, 0, s, 8, 0));
try std.testing.expectEqual(@as(?usize, 0), ownerOf(p, s));
try dump.dumpState(p);
const restored = try dump.initFromDump(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }, p.dump_out.?);
@@ -1995,8 +1995,8 @@ test "an attachment survives Dump and Restore, and one left away from its owner
pardes.exec.runBuiltin(p, .Undock, s, "", null);
try std.testing.expect(p.panes[s].?.docked_to == null);
// Put above its owner by a route that does not carry groups: detached.
- const t = try testAttachment(p);
- try std.testing.expect(attachFrom(p, 0, t, 8, 0));
+ const t = try testDocking(p);
+ try std.testing.expect(dockFrom(p, 0, t, 8, 0));
try std.testing.expectEqual(@as(?usize, 0), ownerOf(p, t));
removePane(p, t);
insert(p, 0, 0, t);
diff --git a/core/lsp/Ask.zig b/core/lsp/Ask.zig
index 376b093d..500f02b5 100644
--- a/core/lsp/Ask.zig
+++ b/core/lsp/Ask.zig
@@ -29,7 +29,7 @@ last: ?struct { kind: lsp.Kind, arg: Effect.Buf(128), serial: u32, offset: u32 }
wait: ?struct {
id: u32,
kind: lsp.Kind,
- pane: usize,
+ pane: Pane.Id,
serial: u32,
revision: u32,
arg: Effect.Buf(128),
@@ -103,7 +103,7 @@ pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8)
p.lsp_ask.wait = .{
.id = p.lsp_ask.seq,
.kind = kind,
- .pane = id,
+ .pane = .at(id),
.serial = pane.serial,
.revision = if (pane.file) |f| f.revision else 0,
.arg = .from(arg),
@@ -270,24 +270,25 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void {
const w = p.lsp_ask.wait orelse return;
if (w.id != id) return; // superseded by a newer press, or the pane died
p.lsp_ask.wait = null;
- const pane = p.panes[w.pane] orelse return;
+ const asked = w.pane.index();
+ const pane = p.panes[asked] orelse return;
if (pane.serial != w.serial) return;
// Whatever fails from here -- no answer, nothing found, no room for
// its pane -- fails a 9P write that asked it too.
const failures = p.fs.failures;
- defer if (p.fs.failures != failures) p.noteLateFailure(.at(w.pane));
+ defer if (p.fs.failures != failures) p.noteLateFailure(w.pane);
var said: pardes.Kind.Buf(256) = .{};
const rows = response orelse
- return p.reportFailure(w.pane, said.print("{s}: the language server did not answer", .{lspWord(w.kind)}));
+ return p.reportFailure(asked, said.print("{s}: the language server did not answer", .{lspWord(w.kind)}));
// A backend that cannot answer it says why (`@none <why>`).
if (std.mem.startsWith(u8, rows, "@none ")) {
const why = std.mem.trimEnd(u8, rows["@none ".len..], "\n");
- return p.reportFailure(w.pane, said.print("{s}: {s}", .{ lspWord(w.kind), why }));
+ return p.reportFailure(asked, said.print("{s}: {s}", .{ lspWord(w.kind), why }));
}
// Index's answer is its indexer's command line, run in a command
// pane (lsp_client.indexCommand).
if (w.kind == .index) {
- if (std.mem.startsWith(u8, rows, "@run ")) _ = exec.execute(p, w.pane, std.mem.trimEnd(u8, rows["@run ".len..], "\n"));
+ if (std.mem.startsWith(u8, rows, "@run ")) _ = exec.execute(p, asked, std.mem.trimEnd(u8, rows["@run ".len..], "\n"));
return;
}
if (w.kind == .rename or w.kind == .format) {
@@ -296,7 +297,7 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void {
if (applyLspEdits(p, pane, w.revision, edits)) {
var buf: pardes.Kind.Buf(64) = .{};
const verb: []const u8 = if (w.kind == .rename) "renamed" else "formatted";
- p.setMessage(.at(w.pane), buf.print("{s} {d} range(s)", .{ verb, edits.len }));
+ p.setMessage(w.pane, buf.print("{s} {d} range(s)", .{ verb, edits.len }));
}
return;
}
@@ -308,19 +309,19 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void {
}
if (rows.len == 0) {
if (w.kind == .completion and pane.body.mode == .insert and pane.body.nsel == 0 and
- pane.body.cur_row == w.row and pane.body.cur_col == w.col) edit.insertTab(p.editor(), &pane.body) catch |err| return p.reportError(.at(w.pane), "complete", err);
+ pane.body.cur_row == w.row and pane.body.cur_col == w.col) edit.insertTab(p.editor(), &pane.body) catch |err| return p.reportError(w.pane, "complete", err);
// Nothing found fails, but for a file with no diagnostics,
// which is no failure, and a completion's Tab.
const none: ?[]const u8 = switch (w.kind) {
.completion, .format => null,
.rename => "nothing here to rename",
- .diagnostics, .workspace_diagnostics => return p.setMessage(.at(w.pane), said.print("{s}: none", .{lspWord(w.kind)})),
+ .diagnostics, .workspace_diagnostics => return p.setMessage(w.pane, said.print("{s}: none", .{lspWord(w.kind)})),
.incoming_calls => "callers not found",
.outgoing_calls => "callees not found",
.hover => "nothing to show: not found",
else => "not found",
};
- if (none) |text| p.reportFailure(w.pane, said.print("{s}: {s}", .{ lspWord(w.kind), text }));
+ if (none) |text| p.reportFailure(asked, said.print("{s}: {s}", .{ lspWord(w.kind), text }));
return;
}
@@ -330,7 +331,7 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void {
const ln = std.mem.trimEnd(u8, rows, "\n");
const place = ln[0..panes.Output.location(ln).end];
p.look_missed = false;
- look.lookAt(p, w.pane, place);
+ look.lookAt(p, asked, place);
// The one place is the text's places, as a list's would be: tinted,
// and n and N step it.
const spot = look.parsePathLine(place);
@@ -367,16 +368,16 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void {
};
if (listed) |source| if (pane.file != null and pane.query == null and !p.exec_header) {
p.fs.refilled = null;
- panes.Query.fillList(p, w.pane, source, rows);
+ panes.Query.fillList(p, asked, source, rows);
p.fs.lsp_result = if (panes.Query.ofOwner(p, pane.serial)) |qid| p.panes[qid].?.serial else null;
return;
};
const dir = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice();
- const content = p.gpa.dupe(u8, rows) catch |err| return p.reportError(.at(w.pane), lspWord(w.kind), err);
+ const content = p.gpa.dupe(u8, rows) catch |err| return p.reportError(w.pane, lspWord(w.kind), err);
const serial_before = p.next_serial;
p.fs.refilled = null;
- panes.Output.fillResults(p, w.pane, dir, from, w.arg.slice(), content, null) catch |err| {
- p.reportError(.at(w.pane), "language response", err);
+ panes.Output.fillResults(p, asked, dir, from, w.arg.slice(), content, null) catch |err| {
+ p.reportError(w.pane, "language response", err);
return;
};
if (rows.len >= 1 << 20) memory.trim();
@@ -390,7 +391,7 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void {
if (p.next_serial != serial_before) {
const report_rows = std.mem.count(u8, result_pane.file.?.content, "\n");
const wanted: u16 = @intCast(@min(v.screen_h, report_rows + result_pane.tag_rows));
- layout.givePaneRows(p, result_id, wanted, w.pane);
+ layout.givePaneRows(p, result_id, wanted, asked);
}
look.focusPaneLine(p, result_id, .{ .line = 1, .col = 1 }, .keep);
break;
@@ -401,7 +402,7 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void {
// Rows that only name a file the server left alone (lsp_client
// renameEdits) are no edits.
const unrenamed = std.mem.count(u8, rows, ", which the server did not rename\n");
- p.setMessage(.at(w.pane), if (unrenamed > 0)
+ p.setMessage(w.pane, if (unrenamed > 0)
said_buf.print("Rename: previewed, not applied: the server renamed in this file only, and {d} other open file(s) say the name", .{unrenamed})
else
said_buf.print("Rename: {d} edit(s) across files, previewed, not applied", .{nrows}));
@@ -413,7 +414,7 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void {
.line = @as(usize, @intCast(@max(0, w.row))) + 1,
.col = @as(usize, @intCast(@max(0, w.col))) + 1,
});
- _ = look.jumpResult(p, w.pane, row);
+ _ = look.jumpResult(p, asked, row);
}
}
diff --git a/core/ninep/events.zig b/core/ninep/events.zig
index 1951a434..1fd05b54 100644
--- a/core/ninep/events.zig
+++ b/core/ninep/events.zig
@@ -332,7 +332,7 @@ fn newest(p: *Pardes) ?struct { at: usize, seq: u64, text: []const u8 } {
/// Whether a follower has read the record `seq`, or is part way through it.
fn followerRead(p: *Pardes, seq: u64) bool {
- for (p.fs.opens) |o| if (o.node != 0 and o.what == .log) {
+ for (p.fs.opens[0..p.fs.opens_len]) |o| if (o.node != 0 and o.what == .log) {
const l = o.what.log;
if (l.follow and (l.next > seq or (l.next == seq and l.part > 0))) return true;
};
@@ -437,6 +437,8 @@ fn pushLog(p: *Pardes, raw: []u8) void {
/// What an open of /log holds.
pub const LogOpen = struct {
+ /// Its reader's alone: what it is answered with (the log is the session's).
+ pub const replica = .{ .authority = .{ "bytes", "follow", "next", "part", "pos" } };
/// The ring's text when it was opened.
bytes: []const u8 = &.{},
/// This open waits for records after `bytes`, from `next`.
diff --git a/core/ninep/pane.zig b/core/ninep/pane.zig
index 1d514a3c..d47b637b 100644
--- a/core/ninep/pane.zig
+++ b/core/ninep/pane.zig
@@ -30,6 +30,28 @@ const Node = tree.Node;
/// Filesystem state a pane carries beside its editor state.
pub const State = struct {
+ /// What a step reads of it is digested and dumped (fs.Namespace); the
+ /// readers' records and the server's say of them are the session's.
+ pub const replica = .{ .authority = .{ "readers", "event_reader", "events", "tag_snap", "pty_reader", "pty_out", "winsize", "unannounced" } };
+
+ /// Its digest (core/walk.zig): nothing for a pane no script has set
+ /// anything of (most of them, at every unit a replica confirms); the
+ /// rest's fields as one run of bytes, not a hash's call a field.
+ pub fn digest(st: *const State, h: *pardes.walk.Hasher) void {
+ const untouched: State = .{};
+ var touched = false;
+ inline for (comptime pardes.walk.fieldNames(State)) |name| touched = touched or !std.meta.eql(@field(st, name), @field(untouched, name));
+ if (!touched) return;
+ var buf: [256]u8 = undefined;
+ var w: std.Io.Writer = .fixed(&buf);
+ // Longer than the room (a chord's text): field by field.
+ if (encoded(st, &w)) |_| h.update(w.buffered()) else |_| inline for (comptime pardes.walk.fieldNames(State)) |name| pardes.walk.hash(@FieldType(State, name), &@field(st, name), h);
+ }
+
+ fn encoded(st: *const State, w: *std.Io.Writer) std.Io.Writer.Error!void {
+ inline for (comptime pardes.walk.fieldNames(State)) |name| try pardes.walk.encode(@FieldType(State, name), &@field(st, name), w);
+ }
+
/// The range `data` and `xdata` read and write through. acme clears it
/// when the first client opens `addr` (editors/acme/xfid.c:105-108),
/// which suits a client that holds the fid open; a shell cannot, and
diff --git a/core/ninep/pty.zig b/core/ninep/pty.zig
index 4b0cee66..ec752311 100644
--- a/core/ninep/pty.zig
+++ b/core/ninep/pty.zig
@@ -164,6 +164,7 @@ pub const output_rows = output_cap / 8;
/// What an open of run holds (tree.zig's open records).
pub const Run = struct {
+ pub const replica = .{ .len = .{.{ "answer", "len" }} };
/// `waiting`: the line is kept until the shell's first prompt (a new
/// terminal's shell takes a moment to draw it), then sent.
phase: enum { idle, waiting, sent, done } = .idle,
diff --git a/core/ninep/tree.zig b/core/ninep/tree.zig
index 1eaaa8cb..2c0ce1b0 100644
--- a/core/ninep/tree.zig
+++ b/core/ninep/tree.zig
@@ -124,9 +124,45 @@ pub const out_reserve = 4 * 1024;
/// (editors/acme/dat.h:373-385). An open that holds something answers its
/// record's index plus one as the handle; one that holds nothing answers 0.
pub const Open = struct {
+ /// A client's join carries it and the digest covers it (fs.Namespace),
+ /// but what only its reader is answered with: the listener's held
+ /// read and the stream's last answer.
+ pub const replica = .{ .authority = .{ "held", "replay" } };
/// The node it was opened on, which every use checks; 0 is a free record.
node: u64 = 0,
- what: union(enum) {
+ what: What = .{ .snapshot = null },
+ /// What a write to a file of command lines left unfinished: a last line
+ /// with no newline yet, or an Edit block still open. A write through a
+ /// mount is cut at the 9P message size, so one `echo` of many lines may
+ /// come as several writes, cut anywhere; the rest waits for the open's
+ /// next write, or its release, and never runs as a fragment.
+ pending: std.ArrayList(u8) = .empty,
+ /// The panes this open's last write touched, which a read of look or
+ /// exec on it answers, as /net/tcp/clone answers on the open that
+ /// asked; a fresh open holds the session's last, from before it opened.
+ results: Results = .{},
+ /// A read that found nothing yet (`.again`), kept to be answered when
+ /// this open's file has something, the way factotum keeps its log's
+ /// waiting reads and answers them on append (security/auth/factotum/
+ /// log.c:4-52) and acme an event read (editors/acme/xfid.c:994). One at a
+ /// time, as acme's window keeps one `eventx`: a newer read takes the
+ /// place of the older. The listener fills it in and answers it
+ /// (runtime/9p_io.zig, `answerHeld`).
+ held: ?Held = null,
+ /// The last answer a stream open (a followed log, event, pty/data) gave,
+ /// and the offset it was read at. A read at an offset inside it is
+ /// answered from it again: bash's `read` takes a chunk, keeps a line and
+ /// lseeks back to just past it, and a stream has already moved on.
+ replay: ?Replay = null,
+ /// A `name` open has named its pane: one name an open, so a second line
+ /// on it (bash writes `printf 'a\nb\n'` a line at a time) is refused.
+ named: bool = false,
+ /// A line over 1 MiB was refused: what follows of it, through its
+ /// newline, is dropped rather than run as a line of its own.
+ discarding: bool = false,
+
+ /// What it is an open of, and what that holds.
+ pub const What = union(enum) {
/// /screen's frame from the open, a terminal body's history from its
/// first read.
snapshot: ?[]const u8,
@@ -160,40 +196,27 @@ pub const Open = struct {
/// An open reading a plumb port (Plumb.zig's ports, plumber(4)'s):
/// the messages sent to it since the open, packed, a read each.
port: struct { index: u8, queue: events.Queue = .{} },
- } = .{ .snapshot = null },
- /// What a write to a file of command lines left unfinished: a last line
- /// with no newline yet, or an Edit block still open. A write through a
- /// mount is cut at the 9P message size, so one `echo` of many lines may
- /// come as several writes, cut anywhere; the rest waits for the open's
- /// next write, or its release, and never runs as a fragment.
- pending: std.ArrayList(u8) = .empty,
- /// The panes this open's last write touched, which a read of look or
- /// exec on it answers, as /net/tcp/clone answers on the open that
- /// asked; a fresh open holds the session's last, from before it opened.
- results: Results = .{},
- /// A read that found nothing yet (`.again`), kept to be answered when
- /// this open's file has something, the way factotum keeps its log's
- /// waiting reads and answers them on append (security/auth/factotum/
- /// log.c:4-52) and acme an event read (editors/acme/xfid.c:994). One at a
- /// time, as acme's window keeps one `eventx`: a newer read takes the
- /// place of the older. The listener fills it in and answers it
- /// (runtime/9p_io.zig, `answerHeld`).
- held: ?Held = null,
- /// The last answer a stream open (a followed log, event, pty/data) gave,
- /// and the offset it was read at. A read at an offset inside it is
- /// answered from it again: bash's `read` takes a chunk, keeps a line and
- /// lseeks back to just past it, and a stream has already moved on.
- replay: ?Replay = null,
- /// A `name` open has named its pane: one name an open, so a second line
- /// on it (bash writes `printf 'a\nb\n'` a line at a time) is refused.
- named: bool = false,
- /// A line over 1 MiB was refused: what follows of it, through its
- /// newline, is dropped rather than run as a line of its own.
- discarding: bool = false,
+
+ /// What a step reads of it: not the text a reader is answered from
+ /// (a screen, a listing, the log, a port's messages), which each
+ /// process makes of its own state, and a replica never answers.
+ pub fn digest(w: *const What, h: *pardes.walk.Hasher) void {
+ const tag = std.meta.activeTag(w.*);
+ pardes.walk.hash(@TypeOf(tag), &tag, h);
+ switch (w.*) {
+ .run => |*run| pardes.walk.hash(pty.Run, run, h),
+ .event => |*reader| pardes.walk.hash(bool, reader, h),
+ .pager => |*serial| pardes.walk.hash(u32, serial, h),
+ .port => |*port| pardes.walk.hash(u8, &port.index, h),
+ .snapshot, .log, .frozen, .pty_data, .ctl, .lines, .writes, .plumb => {},
+ }
+ }
+ };
pub const Replay = struct { off: u64, bytes: []u8 };
pub const Results = struct {
+ pub const replica = .{ .len = .{.{ "list", "len" }} };
list: [pardes.MAX_PANES]u32 = undefined,
len: u8 = 0,
/// Written on: reads are a stream from the write on, whatever
@@ -230,7 +253,7 @@ pub const open_slots = 64;
/// The record a request's handle names, when it was opened on that node.
pub fn openOf(p: *Pardes, req: Req) ?*Open {
- if (req.handle == 0 or req.handle > p.fs.opens.len) return null;
+ if (req.handle == 0 or req.handle > p.fs.opens_len) return null;
const o = &p.fs.opens[req.handle - 1];
return if (o.node == req.node) o else null;
}
@@ -614,7 +637,7 @@ fn runAttr(p: *Pardes, req: Req, target: Target) ?Reply.Attr {
.top, .col, .port => return null,
};
if (t.file != .pty_run) return null;
- const run = if (req.handle != 0) openOf(p, req) else for (&p.fs.opens) |*o| {
+ const run = if (req.handle != 0) openOf(p, req) else for (p.fs.opens[0..p.fs.opens_len]) |*o| {
if (o.node == req.node and o.what == .run) break o;
} else null;
if ((run orelse return null).what != .run) return null;
@@ -895,7 +918,7 @@ fn open(p: *Pardes, req: Req, target: Target) Reply {
.ctl => if (linesOpen(target, req)) .lines else .{ .frozen = &.{} },
// One writer of the rules at a time, as plumber(4)'s.
.rules, .send => if (req.omode & 3 == 0) return .{ .tag = req.tag } else plumb: {
- if (f == .rules) for (p.fs.opens) |o| if (o.node == req.node and o.what == .plumb) return failText(req.tag, E.BUSY, e_in_use);
+ if (f == .rules) for (p.fs.opens[0..p.fs.opens_len]) |o| if (o.node == req.node and o.what == .plumb) return failText(req.tag, E.BUSY, e_in_use);
break :plumb .plumb;
},
else => if (linesOpen(target, req)) .lines else return .{ .tag = req.tag },
@@ -934,7 +957,9 @@ fn open(p: *Pardes, req: Req, target: Target) Reply {
// record would be another than the session's.
const i = p.tape.authority(freeOpen, .{p}) orelse return Reply.fail(req.tag, E.NFILE);
const o = &p.fs.opens[i];
+ // Past `opens_len` a record is nothing: written over, never freed.
o.* = .{ .node = req.node, .what = what };
+ p.fs.opens_len = @max(p.fs.opens_len, @as(u8, @intCast(i + 1)));
if (resultsFile(target)) {
@memcpy(o.results.list[0..p.fs.results_len], p.fs.results[0..p.fs.results_len]);
o.results.len = p.fs.results_len;
@@ -1074,6 +1099,7 @@ fn releaseHandle(p: *Pardes, req: Req) void {
.snapshot, .log, .lines, .writes, .frozen, .pager, .plumb, .port => {},
};
o.deinit(p.gpa);
+ while (p.fs.opens_len > 0 and p.fs.opens[p.fs.opens_len - 1].node == 0) p.fs.opens_len -= 1;
}
fn setattr(p: *Pardes, req: Req, target: Target) Reply {
diff --git a/core/panes.zig b/core/panes.zig
index 89d9f309..15e1db50 100644
--- a/core/panes.zig
+++ b/core/panes.zig
@@ -27,12 +27,11 @@ pub const EditText = struct { text: []u8, row0: i32 };
pub const Pane = struct {
/// What the replay digest leaves out (core/walk.zig): the view's geometry,
- /// made again from the rest (File.geometry); the 9P server's record of
- /// the pane's opens and readers; the other views' share of it (views.zig).
+ /// made again from the rest (File.geometry); the other views' share of
+ /// it (views.zig). (The 9P server's part of `fs` says so in its type.)
pub const replica = .{
.local = .{ "pv", "pv_known" },
.derived = .{ "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "notices", "pan" },
- .authority = .{"fs"},
.len = .{ .{ "msg", "msg_len" }, .{ "msg_older", "msg_older_len" }, .{ "question", "question_len" }, .{ "shell_tail", "shell_tail_len" }, .{ "sel_snap", "nsel_snap" } },
// A picture's memory is its own allocator's (a dump loaded makes
// it there).
@@ -148,10 +147,10 @@ pub const Pane = struct {
vweight: f32 = 1,
/// A folded pane keeps its expansion weight, but occupies only its tag row.
collapsed: bool = false,
- /// The serial of the pane this one is attached to, its owner: a query
+ /// The serial of the pane this one is docked to, its owner: a query
/// pane or its +Preview sits right under its owner in the owner's
/// column, takes its rows from the owner alone, and moves, folds and
- /// closes with it (layout.zig, "Attached panes"). An owner that is
+ /// closes with it (layout.zig, "Docked panes"). An owner that is
/// gone, or a pane no longer right under its owner's group, leaves it
/// an ordinary pane (layout.keepGroups).
docked_to: ?u32 = null,
@@ -1485,14 +1484,14 @@ pub fn paneDir(pane: *const Pane) []const u8 {
pub fn removePane(p: *Pardes, id: usize, to: ?usize) error{OutOfMemory}!void {
const v = p.view();
const pane = p.panes[id] orelse return;
- // What is attached to it closes with it, first, each giving its rows
+ // What is docked to it closes with it, first, each giving its rows
// back to it: then its rows, theirs among them, go where a pane's go.
for (0..p.panes.len) |k| if (p.panes[k]) |other| if (k != id and other.docked_to == pane.serial) {
if (layout.ownerOf(p, k) != id) continue;
try p.removePane(k, id);
layout.compute(p);
};
- // An attachment's rows go back to its owner and nobody else.
+ // A docked pane's rows go back to its owner and nobody else.
const owner = layout.ownerOf(p, id);
const place = layout.findPane(p, id);
const emptied = if (place) |f| (if (v.cols[f.col].n == 1) f.col else null) else null;
diff --git a/core/replica.zig b/core/replica.zig
index e05cf79e..39ee53b2 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -157,7 +157,7 @@ pub const Authority = struct {
seq: u32 = 0,
/// Each client's view (core/views.zig): its own layout, focus and
/// cursors over the session's text. The first client has the session's.
- view_of: [64]u8 = @splat(0),
+ view_of: [64]Pardes.View.Id = @splat(.at(0)),
/// Steps of its own taken since the last unit (`output`): one unit,
/// `pending`, sent before the next input it steps and at a frame.
batched: u32 = 0,
@@ -182,6 +182,7 @@ pub const Authority = struct {
a.t.whole_digest = screens and std.c.getenv("PARDES_REPLICA_TRACE") == null;
// A digest at a unit's end, as the session's (Peers.unit).
a.t.no_digest = true;
+ opts.tape = &a.t;
const was = Stepping.begin(&a.t, null);
defer was.end();
a.core = try Pardes.init(gpa, opts);
@@ -278,7 +279,7 @@ pub const Authority = struct {
};
a.core.pump(a.host) catch {};
was.end();
- a.view_of[client] = k.index();
+ a.view_of[client] = k;
a.seq += 1;
return .{ .view = k.index(), .unit = try a.unit(0, a.seq) };
}
@@ -295,7 +296,7 @@ pub const Authority = struct {
const again = if (back) |v| a.core.rejoinView(.at(v)) else false;
const k = (if (again) back else if (a.core.openView()) |o| o.index() else null) orelse return null;
a.core.undrawn |= @as(u8, 1) << @intCast(k);
- a.view_of[client] = k;
+ a.view_of[client] = .at(k);
a.seq += 1;
const u = try a.unit(0, a.seq);
var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty;
@@ -321,8 +322,8 @@ pub const Authority = struct {
std.debug.assert(a.batched == 0);
const was = Stepping.begin(&a.t, null);
const k = a.view_of[client];
- a.core.undrawn &= ~(@as(u8, 1) << @intCast(k));
- if (again) a.core.awayView(.at(k)) else a.core.closeView(.at(k));
+ a.core.undrawn &= ~(@as(u8, 1) << @intCast(k.index()));
+ if (again) a.core.awayView(k) else a.core.closeView(k);
was.end();
a.seq += 1;
return a.unit(0, a.seq);
@@ -332,7 +333,7 @@ pub const Authority = struct {
pub fn closeView(a: *Authority, client: u16) ![]const u8 {
std.debug.assert(a.batched == 0);
const was = Stepping.begin(&a.t, null);
- a.core.closeView(.at(a.view_of[client]));
+ a.core.closeView(a.view_of[client]);
was.end();
a.seq += 1;
return a.unit(0, a.seq);
@@ -344,7 +345,7 @@ pub const Authority = struct {
std.debug.assert(a.batched == 0);
const in = parseInput(msg) orelse return error.BadInput;
const was = Stepping.begin(&a.t, null);
- a.core.toView(.at(a.view_of[in.client]));
+ a.core.toView(a.view_of[in.client]);
a.t.stamp = stampOf(in);
a.core.update(in.event);
a.core.step();
@@ -449,7 +450,7 @@ pub const Screens = struct {
/// What `peer` is owed of every terminal, each a message onto `out`
/// (owned): nothing for one it has as it is, or with `bound` in flight.
- pub fn flush(s: *Screens, core: *Pardes, peer: u16, _: u8, out: *std.ArrayListUnmanaged([]u8)) !void {
+ pub fn flush(s: *Screens, core: *Pardes, peer: u16, out: *std.ArrayListUnmanaged([]u8)) !void {
const t0 = nowNs();
defer s.encode_ns += nowNs() - t0;
for (core.panes, 0..) |slot, id| {
@@ -1667,12 +1668,14 @@ pub const Peer = struct {
peers: *Peers,
fd: c_int,
id: u16,
- view: u8,
+ view: Pardes.View.Id,
/// Its process (its socket's peer), for `--ps`; 0 not known.
pid: libc.pid_t = 0,
/// Its bye said it joins again for its view (a divergence's rejoin):
/// kept for it (views.away), not closed. Its reader's, read after its end.
again: bool = false,
+ /// ...or that its window was closed (Peers.closed).
+ close: bool = false,
/// Its number in the session's `Screens`.
sid: u16 = 0,
/// Inputs read (each one's seq, as the client numbered them).
@@ -1943,7 +1946,9 @@ pub const Peer = struct {
switch (t) {
.hello => return false,
.bye => {
- peer.again = (wire.decodeClient(tag, payload) catch return false).bye.again;
+ const b = (wire.decodeClient(tag, payload) catch return false).bye;
+ peer.again = b.again;
+ peer.close = b.close;
return false;
},
.ping => {
@@ -2066,6 +2071,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 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,
/// 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,
@@ -2204,7 +2213,7 @@ pub const Peers = struct {
// The terminals as this step reads them, then the step, the rows
// it read, its unit (part B terminal notes' order).
ps.screensOut(core, .flush);
- core.toView(.at(peer.view));
+ core.toView(peer.view);
ps.t.stamp = stampOf(in);
core.update(in.event);
core.step();
@@ -2242,7 +2251,7 @@ pub const Peers = struct {
ps.msgs.clearRetainingCapacity();
}
(switch (what) {
- .flush => ps.screens.flush(core, peer.sid, peer.view, &ps.msgs),
+ .flush => ps.screens.flush(core, peer.sid, &ps.msgs),
.fill => ps.screens.fill(core, peer.sid, &ps.msgs),
}) catch return;
if (what == .flush) if (ps.flushed) |h| h.f(h.ctx, core, &ps.screens);
@@ -2328,12 +2337,12 @@ pub const Peers = struct {
core.gpa.free(bytes);
return daemon.refuseReplica(fd, "out of memory");
};
- peer.* = .{ .peers = ps, .fd = fd, .id = ps.next_id, .view = k, .dump = bytes, .blobs = blobs, .dump_gpa = core.gpa };
+ peer.* = .{ .peers = ps, .fd = fd, .id = ps.next_id, .view = .at(k), .dump = bytes, .blobs = blobs, .dump_gpa = core.gpa };
ps.next_id +%= 1;
if (ps.next_id == 0) ps.next_id = 1;
// The session's digest as dumped, for the joiner to check its load by.
const digest = tape.digestOf(core);
- peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = @intCast(libc.getpid()), .session = ps.name[0..@min(ps.name.len, wire.max_name)], .client = peer.id, .view = .at(k), .dump_len = whole, .gmtoff = gmtoff(), .digest = digest, .semantics = wire.semantics, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len;
+ peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = @intCast(libc.getpid()), .session = ps.name[0..@min(ps.name.len, wire.max_name)], .client = peer.id, .view = peer.view, .dump_len = whole, .gmtoff = gmtoff(), .digest = digest, .semantics = wire.semantics, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len;
if (ps.threads) peer.writer = std.Thread.spawn(.{}, Peer.writeLoop, .{peer}) catch null;
if (ps.threads) peer.reader = std.Thread.spawn(.{}, Peer.readLoop, .{peer}) catch null;
if (ps.threads and (peer.writer == null or peer.reader == null)) {
@@ -2362,11 +2371,12 @@ pub const Peers = struct {
log.info("client {d} left '{s}'", .{ peer.id, ps.name });
ps.tellClients();
ps.screens.dropPeer(peer.sid);
- core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view));
+ core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view.index()));
// Cut off, it joins again after the words why (`send`); its reader
// has ended and no other thread sets `cut` now.
ps.closeViewOf(core, peer, peer.again or peer.cut);
if (ps.count() == 0) core.unattended = ps.detached;
+ 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);
@@ -2378,7 +2388,7 @@ pub const Peers = struct {
/// session no one else watches leaves the session its layout, for a
/// client that comes after to find.
fn closeViewOf(ps: *Peers, core: *Pardes, peer: *Peer, again: bool) void {
- if (again) core.awayView(.at(peer.view)) else if (ps.count() == 0 and ps.detached) core.leaveView(.at(peer.view)) else core.closeView(.at(peer.view));
+ if (again) core.awayView(peer.view) else if (ps.count() == 0 and ps.detached) core.leaveView(peer.view) else core.closeView(peer.view);
}
/// Its threads ended and joined, its link closed.
@@ -2470,7 +2480,8 @@ pub const Peers = struct {
/// Detach typed in client view `k`'s: told it left the session running
/// (`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 == k) {
+ for (ps.list) |slot| if (slot) |peer| if (peer.view.index() == k) {
+ 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;
@@ -2507,7 +2518,7 @@ pub const Peers = struct {
fn drop(ps: *Peers, core: *Pardes, again: bool) void {
for (&ps.list) |*slot| if (slot.*) |peer| {
slot.* = null;
- core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view));
+ core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view.index()));
ps.closeViewOf(core, peer, again);
ps.screens.dropPeer(peer.sid);
ps.letGo(peer);
@@ -2941,10 +2952,11 @@ pub fn askCheck(fd: c_int) bool {
return writeAll(fd, wire.encodeClient(&out, .check) catch unreachable);
}
-/// The client's last word: `again`, it joins again for its view at once.
-pub fn bye(fd: c_int, again: bool) void {
+/// The client's last word: `again`, it joins again for its view at once;
+/// `close`, its window was closed.
+pub fn bye(fd: c_int, how: @FieldType(wire.ClientMsg, "bye")) void {
var out: [16]u8 = undefined;
- if (wire.encodeClient(&out, .{ .bye = .{ .again = again } })) |b| _ = writeAll(fd, b) else |_| {}
+ if (wire.encodeClient(&out, .{ .bye = how })) |b| _ = writeAll(fd, b) else |_| {}
}
/// What the session streams a client after its dump, as its frontend's loop
@@ -2998,6 +3010,13 @@ pub fn ended(why: []const u8) bool {
/// The words a client goes with when its session runs another build now.
const upgrade_words = "session upgraded to a newer pardes: upgrade this client too";
+/// A join's failure that is its session's running another build now: a
+/// client whose own start path holds a newer one execs that instead
+/// (runtime/client.zig).
+pub fn otherBuild(why: []const u8) bool {
+ return std.mem.endsWith(u8, std.mem.sliceTo(why, 0), upgrade_words);
+}
+
/// A replica client's join, the terminal's and the window's alike (their
/// `runClient`): the session at `path` dialled (or, first, the one on its
/// pair, `o.pair`), its build checked to be this
@@ -3022,7 +3041,10 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
};
if (have) |h| h.left();
prev.deinit();
- } else j.* = sameBuild(gpa, (if (o.pair) |fd| joinOn(gpa, fd, null, why, have, null) else dial(gpa, path, session, why, have, null)) orelse return null, why) orelse return null;
+ } else j.* = (if (o.join_view) |v|
+ redial(gpa, path, session, why, have, true, v)
+ else
+ sameBuild(gpa, (if (o.pair) |fd| joinOn(gpa, fd, null, why, have, null) else dial(gpa, path, session, why, have, null)) orelse return null, why)) orelse return null;
defer {
if (have) |h| h.store(gpa, j) else gpa.free(j.dump);
j.dump = &.{};
@@ -3057,7 +3079,7 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
/// an upgrade under way may not have said yet.
fn sameBuild(gpa: Allocator, j: Joined, why: []u8) ?Joined {
if (j.semantics == wire.semantics) return j;
- bye(j.fd, false);
+ bye(j.fd, .{});
_ = libc.close(j.fd);
var jj = j;
jj.rest.deinit(gpa);
@@ -3078,7 +3100,10 @@ fn redial(gpa: Allocator, path: []const u8, session: []const u8, why: *[600]u8,
while (true) : (tries += 1) {
why.* = @splat(0);
if (dial(gpa, path, session, why, have, view)) |j| return sameBuild(gpa, j, why);
- if (std.mem.indexOf(u8, std.mem.sliceTo(why, 0), "runs another build") != null) {
+ // Another build, or another protocol (the daemon moved with its
+ // session): no dial again will do.
+ const words = std.mem.sliceTo(why, 0);
+ if (std.mem.indexOf(u8, words, "runs another build") != null or std.mem.indexOf(u8, words, "run the same pardes at both ends") != null) {
_ = std.fmt.bufPrint(why, "{s}\x00", .{upgrade_words}) catch {};
return null;
}
@@ -3099,6 +3124,8 @@ pub const Link = struct {
r: *Replica,
fd: c_int,
quit: bool = false,
+ /// ...because its window was closed: said in its bye.
+ close: bool = false,
/// The session hung up.
gone: bool = false,
/// Something to draw: an input applied, a unit taken.
@@ -3501,7 +3528,7 @@ fn deliver(a: *Authority, screens: *Screens, peer: u16, r: *Replica, comptime wh
msgs.deinit(gpa);
}
switch (what) {
- .flush => try screens.flush(a.core, peer, r.view, &msgs),
+ .flush => try screens.flush(a.core, peer, &msgs),
.fill => {
try screens.fill(a.core, peer, &msgs);
screens.filled(a.core);
@@ -3534,7 +3561,7 @@ fn farJoinOnce(ps: *Peers, core: *Pardes, have: ?*Have) !Joined {
var whole = state.len;
for (blobs.items) |b| whole += b.bytes.len;
const peer = try ps.gpa.create(Peer);
- peer.* = .{ .peers = ps, .fd = fds[0], .id = 1, .view = 0, .dump = state, .blobs = blobs, .dump_gpa = core.gpa };
+ peer.* = .{ .peers = ps, .fd = fds[0], .id = 1, .view = .at(0), .dump = state, .blobs = blobs, .dump_gpa = core.gpa };
peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = 1, .session = "t", .dump_len = whole, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len;
const Serve = struct {
fn run(p: *Peer) void {
@@ -5289,7 +5316,7 @@ test "a client that diverged joins again for its view: kept for it meanwhile, it
const back = try joinedNow(a, 3, opened.view);
defer back.deinit();
try std.testing.expectEqual(digestOf(a), back.digest());
- a.view_of[3] = opened.view;
+ a.view_of[3] = .at(opened.view);
const u = try gpa.dupe(u8, try a.take(try back.input(.{ .key = .{ .cp = 'l', .text = "l" } })));
defer gpa.free(u);
old.confirm(u);
@@ -5391,13 +5418,13 @@ test "a client cut off for what it left unread is told why and joins again for i
// ...once its old link's end is heard: its view kept for it meanwhile.
ps.post(.{ .gone = first.peer });
ps.boundary(core);
- try std.testing.expect(pardes.views.isAway(core, view));
+ try std.testing.expect(pardes.views.isAway(core, view.index()));
first.r.deinit();
_ = libc.close(fd);
- const back = try MemoryLinks.join(&ps, core, view, &fd);
+ const back = try MemoryLinks.join(&ps, core, view.index(), &fd);
defer back.r.deinit();
try std.testing.expectEqual(view, back.peer.view);
- link.reset(back.r, &.{ .fd = fd, .pid = 0, .client = back.r.id, .view = view, .gmtoff = 0, .dump = &.{} });
+ link.reset(back.r, &.{ .fd = fd, .pid = 0, .client = back.r.id, .view = view.index(), .gmtoff = 0, .dump = &.{} });
core.update(.{ .paste = "back" });
try core.pump(core.host);
ps.boundary(core);
@@ -5462,7 +5489,7 @@ test "a client's writer, the client cut off while it waits on the socket, writes
if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket;
defer _ = libc.close(fds[1]);
const peer = try gpa.create(Peer);
- peer.* = .{ .peers = &ps, .fd = fds[0], .id = 1, .view = 0, .dump_gpa = gpa, .far = false, .limit = 256 << 10 };
+ peer.* = .{ .peers = &ps, .fd = fds[0], .id = 1, .view = .at(0), .dump_gpa = gpa, .far = false, .limit = 256 << 10 };
peer.welcome_len = (try wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = 1, .session = "t" } })).len;
peer.writer = try std.Thread.spawn(.{}, Peer.writeLoop, .{peer});
defer ps.letGo(peer);
@@ -7222,9 +7249,6 @@ test "a client joined from a dump lands a click on a rail's tick as the session
r.confirm(try a.take(m));
r.settle();
}
- // (The key may be mispredicted: a step's places are a frame's time's
- // worth, `tape.over`, the session's verdict, and its drawn caches let
- // it find more in that time than the client's speculation did.)
try agrees(a, r);
try std.testing.expectEqual(a.core.panes[owner].?.places.current, r.core().panes[owner].?.places.current);
}
@@ -7476,6 +7500,111 @@ test "a client of screen-state terminals takes a 9P pty/run in a shell as the se
try agrees(a, late);
}
+// daemon.py --clients' client C (2026-11-20): idle, a copy taken ahead; the
+// session's script opens pty/run and its command prints, replayed over the
+// copy and kept; the client types into the shell, its speculation stops at
+// the pty write, and the rollback replays the open again over a record the
+// copy never held (it holds the opens as far as `opens_len`), whose line
+// and output the epoch had freed: freed again there, the client's C heap
+// was corrupt.
+test "a 9P open the session made over a copy taken ahead, replayed after a rollback: the record past the opens the copy holds is written over, never freed again" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const gpa = std.testing.allocator;
+ const RunHost = struct {
+ fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool {
+ return false;
+ }
+ fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {}
+ const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write };
+ };
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &RunHost.vtable }, true);
+ defer a.deinit();
+ var screens: Screens = .init(gpa);
+ defer screens.deinit(a.core);
+ const peer = try screens.addPeer();
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0), true);
+ defer r.deinit();
+ const shell: u8 = for (a.core.panes, 0..) |slot, id| {
+ if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
+ } else return error.NoShell;
+ const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
+ a.output(.{ .output = .{ .pane = .at(shell), .bytes = prompt } });
+ r.confirm((try a.pending()).?);
+ try deliver(a, &screens, peer, r, .flush);
+ r.ready();
+ try std.testing.expect(r.copy.held and r.core().fs.opens_len == 0);
+ const node = pardes.ctlfs.Node.of(a.core.panes[shell].?.serial, .pty_run);
+ const Serve = struct {
+ fn serve(s: *Authority, x: *Replica, req: pardes.ctlfs.Req) !pardes.ctlfs.Reply {
+ const was = Stepping.begin(&s.t, null);
+ const reply = s.core.serveFs(req);
+ s.core.pump(s.host) catch {};
+ was.end();
+ s.seq += 1;
+ const u = try std.testing.allocator.dupe(u8, try s.unit(0, s.seq));
+ defer std.testing.allocator.free(u);
+ x.confirm(u);
+ x.settle();
+ return reply;
+ }
+ };
+ const h = (try Serve.serve(a, r, .{ .tag = 1, .op = .open, .node = node, .omode = 2 })).handle;
+ _ = try Serve.serve(a, r, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "echo x\n" });
+ a.output(.{ .output = .{ .pane = .at(shell), .bytes = "echo x\r\n\x1b]133;C;aid=pardes\x07x\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt } });
+ r.confirm((try a.pending()).?);
+ r.settle();
+ // Kept over the copy: the record past its opens holds the run's output.
+ try std.testing.expect(r.copy.held and r.since.items.len > 0);
+ try std.testing.expectEqualStrings("x\n", r.core().fs.opens[h - 1].what.run.output);
+ var sent: std.ArrayListUnmanaged([]u8) = .empty;
+ defer {
+ for (sent.items) |m| gpa.free(m);
+ sent.deinit(gpa);
+ }
+ // A key into the shell: its speculation stops at the pty write, and
+ // the copy is put back, the units since replayed (the open again).
+ try key(r, 'e', &sent);
+ try std.testing.expect(r.applied == 0 and r.stats.stopped > 0);
+ r.confirm(try a.take(sent.items[0]));
+ r.settle();
+ try deliver(a, &screens, peer, r, .flush);
+ _ = try Serve.serve(a, r, .{ .tag = 3, .op = .release, .node = node, .handle = h, .opened = true });
+ if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why});
+ try std.testing.expect(r.diverged == null and r.quiet());
+ try agrees(a, r);
+}
+
+test "a script's half line held over a copy taken ahead, its next write run and its rest moved to the front in place, put back by a rollback: the line replayed is the session's" {
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ try n.join();
+ const r = n.late.?;
+ const exec = n.node(.exec);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = exec, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = exec, .handle = h, .data = "Ta" }, true);
+ r.ready();
+ // Replayed over the copy and kept: `Tab 8` runs, `Un` is held where
+ // `Ta` was, in the buffer the copy holds.
+ _ = try n.serve(.{ .tag = 3, .op = .write, .node = exec, .handle = h, .data = "b 8\nUn" }, true);
+ try std.testing.expect(r.copy.held and r.since.items.len > 0);
+ var sent: std.ArrayListUnmanaged([]u8) = .empty;
+ defer {
+ for (sent.items) |m| std.testing.allocator.free(m);
+ sent.deinit(std.testing.allocator);
+ }
+ try key(r, 'l', &sent);
+ try std.testing.expectEqual(@as(usize, 1), r.applied);
+ // The session's key first: a rollback, the write replayed again.
+ try n.send(try n.a.local(.{ .key = .{ .cp = 'j', .text = "j" } }));
+ try std.testing.expect(r.stats.foreign > 0);
+ try n.send(try n.a.take(sent.items[0]));
+ _ = try n.serve(.{ .tag = 4, .op = .write, .node = exec, .handle = h, .data = "do\n" }, true);
+ _ = try n.serve(.{ .tag = 5, .op = .release, .node = exec, .handle = h, .opened = true }, true);
+ if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why});
+ try std.testing.expect(r.diverged == null and r.quiet());
+ try n.agree();
+}
+
// Del with a pane above and below asks which way the space goes, its
// question shown once a delay is up (builtins.zig): its time was the
// host's clock read in the step, an answering entry a speculation stops at.
@@ -7523,3 +7652,376 @@ test "a far client's Del with panes above and below is applied at once, and its
try agrees(a, r);
try std.testing.expectEqual(Clocked.now_ns + pardes.config.del_question_delay_ns, r.core().panes[mid].?.question_due_ns);
}
+
+// ---- a client that joins a session with 9P work under way ----
+//
+// A 9P request is an input every replica replays, so the state the 9P
+// tree builds from the requests (the open records, each pane's `fs`) is
+// a client's for everything after its join: what was made before it
+// comes in the join's dump, or the client steps the next request
+// otherwise than its session.
+
+/// A session with a file pane and its 9P server, and a client joined
+/// from its dump (`join`) that takes every unit after.
+const NinepJoin = struct {
+ a: *Authority,
+ late: ?*Replica = null,
+ serial: u32,
+
+ fn init(text: []const u8, host: pardes.Host) !NinepJoin {
+ const a = try Authority.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, host, false);
+ errdefer a.deinit();
+ const was = Stepping.begin(&a.t, null);
+ const pane = try a.core.setTestFile(text);
+ was.end();
+ _ = try a.unit(0, 0);
+ return .{ .a = a, .serial = pane.serial };
+ }
+
+ fn deinit(n: *NinepJoin) void {
+ if (n.late) |r| r.deinit();
+ n.a.deinit();
+ }
+
+ fn node(n: *const NinepJoin, file: pardes.ctlfs.PaneFile) u64 {
+ return pardes.ctlfs.Node.of(n.serial, file);
+ }
+
+ /// One request as the session's 9P server serves it, a step of its
+ /// own, then (`pumped`) its loop's pass: a join can come between the
+ /// two, the session's loop being elsewhere. Its unit to the client.
+ fn serve(n: *NinepJoin, req: pardes.ctlfs.Req, pumped: bool) !pardes.ctlfs.Reply {
+ const a = n.a;
+ const was = Stepping.begin(&a.t, null);
+ const reply = a.core.serveFs(req);
+ if (pumped) a.core.pump(a.host) catch {};
+ was.end();
+ a.seq += 1;
+ try n.send(try a.unit(0, a.seq));
+ return reply;
+ }
+
+ /// A pass of the session's loop with no request: its unit.
+ fn pump(n: *NinepJoin) !void {
+ n.a.pump();
+ try n.send((try n.a.pending()).?);
+ }
+
+ fn send(n: *NinepJoin, u: []const u8) !void {
+ const r = n.late orelse return;
+ const kept = try std.testing.allocator.dupe(u8, u);
+ defer std.testing.allocator.free(kept);
+ r.confirm(kept);
+ r.settle();
+ }
+
+ /// A client joins now, from the session's dump, at the digest the
+ /// session had.
+ fn join(n: *NinepJoin) !void {
+ const joined = (try n.a.join(1, null)).?;
+ defer std.testing.allocator.free(joined.dump);
+ const r = try Replica.initDump(std.testing.allocator, 1, joined.view, joined.dump, .{ .cols = 80, .rows = 24 });
+ r.t.screen_state = false;
+ r.core().echo = null;
+ n.late = r;
+ try std.testing.expectEqual(joined.digest, r.digest());
+ }
+
+ fn agree(n: *NinepJoin) !void {
+ try agrees(n.a, n.late.?);
+ }
+};
+
+test "a client joined while a script's open of a pane's exec holds half a line runs the line its session runs" {
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ const exec = n.node(.exec);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = exec, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = exec, .handle = h, .data = "Ne" }, true);
+ try n.join();
+ _ = try n.serve(.{ .tag = 3, .op = .write, .node = exec, .handle = h, .data = "w\n" }, true);
+ _ = try n.serve(.{ .tag = 4, .op = .release, .node = exec, .handle = h, .opened = true }, true);
+ try n.agree();
+}
+
+test "a client joined between two writes of one open to a body makes them one undo step, as its session does" {
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ const body = n.node(.body);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = body, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = body, .handle = h, .data = "a\n" }, true);
+ try n.join();
+ _ = try n.serve(.{ .tag = 3, .op = .write, .node = body, .handle = h, .data = "b\n" }, true);
+ _ = try n.serve(.{ .tag = 4, .op = .release, .node = body, .handle = h, .opened = true }, true);
+ _ = try n.serve(.{ .tag = 5, .op = .write, .node = n.node(.ctl), .data = "Undo" }, true);
+ try n.agree();
+}
+
+test "a client joined while a script's ctl open holds a pane's lock refuses another open's lock, as its session does" {
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ const ctl = n.node(.ctl);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = ctl, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = ctl, .handle = h, .data = "lock\n" }, true);
+ try n.join();
+ const g = (try n.serve(.{ .tag = 3, .op = .open, .node = ctl, .omode = 1 }, true)).handle;
+ try std.testing.expectEqual(pardes.ctlfs.Status.err, (try n.serve(.{ .tag = 4, .op = .write, .node = ctl, .handle = g, .data = "lock\n" }, true)).status);
+ // Who holds it, by name: on the base no digest covered it.
+ const id = n.a.core.paneBySerial(n.serial).?;
+ try std.testing.expectEqual(n.a.core.panes[id].?.fs.lock, n.late.?.core().panes[id].?.fs.lock);
+ try n.agree();
+ _ = try n.serve(.{ .tag = 5, .op = .release, .node = ctl, .handle = g, .opened = true }, true);
+ _ = try n.serve(.{ .tag = 6, .op = .release, .node = ctl, .handle = h, .opened = true }, true);
+ try n.agree();
+}
+
+test "a client joined after a script set a pane's addr, its limit, or truncated its dot writes where its session writes" {
+ // addr: the next data write replaces what it says.
+ {
+ var n = try NinepJoin.init("one two\nthree\n", TestHost.host());
+ defer n.deinit();
+ _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.addr), .data = "/two/" }, true);
+ try n.join();
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = n.node(.data), .data = "2" }, true);
+ try n.agree();
+ }
+ // limit: an address is looked for inside it.
+ {
+ var n = try NinepJoin.init("one two\nthree\n", TestHost.host());
+ defer n.deinit();
+ _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.limit), .data = "#0,#3" }, true);
+ try n.join();
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = n.node(.addr), .data = "/two/" }, true);
+ _ = try n.serve(.{ .tag = 3, .op = .write, .node = n.node(.data), .data = "2" }, true);
+ try n.agree();
+ }
+ // dot truncated: its open's release with no write empties it.
+ {
+ var n = try NinepJoin.init("one two\nthree\n", TestHost.host());
+ defer n.deinit();
+ const dot = n.node(.dot);
+ _ = try n.serve(.{ .tag = 1, .op = .write, .node = dot, .data = "#0,#3" }, true);
+ const h = (try n.serve(.{ .tag = 2, .op = .open, .node = dot, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 3, .op = .setattr, .node = dot, .handle = h, .truncate = true }, true);
+ try n.join();
+ _ = try n.serve(.{ .tag = 4, .op = .release, .node = dot, .handle = h, .opened = true }, true);
+ try n.agree();
+ }
+}
+
+test "a client joined between two writes of one open to a pane's sel runs the second on from the first, as its session does" {
+ var n = try NinepJoin.init("one two\n", TestHost.host());
+ defer n.deinit();
+ const sel = n.node(.sel);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = sel, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = sel, .handle = h, .data = "a" }, true);
+ try n.join();
+ _ = try n.serve(.{ .tag = 3, .op = .write, .node = sel, .handle = h, .data = "b" }, true);
+ _ = try n.serve(.{ .tag = 4, .op = .release, .node = sel, .handle = h, .opened = true }, true);
+ try n.agree();
+}
+
+test "a client joined after a script's nomark or noscroll writes as its session does" {
+ // nomark: writes under it are one undo step.
+ {
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.ctl), .data = "nomark" }, true);
+ try n.join();
+ // Two opens' writes, each its own undo step but for nomark.
+ const body = n.node(.body);
+ for ([_][]const u8{ "two\n", "three\n" }) |text| {
+ const h = (try n.serve(.{ .tag = 2, .op = .open, .node = body, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 3, .op = .write, .node = body, .handle = h, .data = text }, true);
+ _ = try n.serve(.{ .tag = 4, .op = .release, .node = body, .handle = h, .opened = true }, true);
+ }
+ _ = try n.serve(.{ .tag = 5, .op = .write, .node = n.node(.ctl), .data = "mark" }, true);
+ _ = try n.serve(.{ .tag = 6, .op = .write, .node = n.node(.ctl), .data = "Undo" }, true);
+ try n.agree();
+ }
+ // noscroll: a write past the screen leaves the view where it was.
+ {
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.scroll), .data = "0" }, true);
+ try n.join();
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = n.node(.body), .data = &@as([100]u8, @splat('\n')) }, true);
+ try n.agree();
+ }
+}
+
+test "a client joined after a script truncated a pane's tag writes the tag its session writes" {
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ const tag = n.node(.tag);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = tag, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .setattr, .node = tag, .handle = h, .truncate = true }, true);
+ try n.join();
+ _ = try n.serve(.{ .tag = 3, .op = .write, .node = tag, .handle = h, .data = "Get Put\n" }, true);
+ _ = try n.serve(.{ .tag = 4, .op = .release, .node = tag, .handle = h, .opened = true }, true);
+ try n.agree();
+}
+
+test "a client joined after a script truncated the workspace's tag writes the tag its session writes" {
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ const tag: u64 = @backingInt(pardes.ctlfs.TopFile.tag);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = tag, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .setattr, .node = tag, .handle = h, .truncate = true }, true);
+ try n.join();
+ _ = try n.serve(.{ .tag = 3, .op = .write, .node = tag, .handle = h, .data = "Exit\n" }, true);
+ _ = try n.serve(.{ .tag = 4, .op = .release, .node = tag, .handle = h, .opened = true }, true);
+ try n.agree();
+}
+
+test "a client joined while a chorded exec waits for its event reader's write-back runs it with its argument, as its session does" {
+ var n = try NinepJoin.init("Msg said\narg-text\n", TestHost.host());
+ defer n.deinit();
+ const event = n.node(.event);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = event, .omode = 2 }, true)).handle;
+ // The session's chorded click, told to the reader, its argument kept.
+ {
+ const was = Stepping.begin(&n.a.t, null);
+ const id = n.a.core.paneBySerial(n.serial).?;
+ try std.testing.expect(pardes.mouse.reportRange(n.a.core, id, pardes.config.exec_cmd, "Msg", false, .{ .q0 = 0, .q1 = 3 }, "arg-text"));
+ was.end();
+ n.a.seq += 1;
+ _ = try n.a.unit(0, n.a.seq);
+ }
+ try n.join();
+ // The command's record written back alone: its argument is the one kept.
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = event, .handle = h, .data = "MX0 3 9 3 Msg\n" }, true);
+ _ = try n.serve(.{ .tag = 3, .op = .release, .node = event, .handle = h, .opened = true }, true);
+ try n.agree();
+}
+
+test "a client joined while a script's writes to a body are held to go in as one edit puts them in as its session does" {
+ // A host with a clock: held writes go in once they have paused
+ // (pane.batch_pause_ns), and the join came before that.
+ const Clock = struct {
+ var now_ns: u64 = 5 * std.time.ns_per_s;
+ fn now(_: ?*anyopaque) u64 {
+ return now_ns;
+ }
+ const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .now = now };
+ };
+ var n = try NinepJoin.init("one\n", .{ .vtable = &Clock.vtable });
+ defer n.deinit();
+ const body = n.node(.body);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = body, .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = body, .handle = h, .data = "two\n" }, true);
+ try std.testing.expect(n.a.core.fs.batch.bytes.items.len > 0);
+ try n.join();
+ Clock.now_ns += std.time.ns_per_s;
+ try n.pump();
+ try n.agree();
+ _ = try n.serve(.{ .tag = 3, .op = .release, .node = body, .handle = h, .opened = true }, true);
+ 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 {
+ fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool {
+ return false;
+ }
+ fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {}
+ const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write };
+ const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
+
+ /// The session at its shell's first prompt, and the shell's slot.
+ fn init(n: *NinepJoin) !u8 {
+ const a = try Authority.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &vtable }, false);
+ n.* = .{ .a = a, .serial = 0 };
+ _ = try a.unit(0, 0);
+ const shell: u8 = for (a.core.panes, 0..) |slot, id| {
+ if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
+ } else return error.NoShell;
+ n.serial = a.core.panes[shell].?.serial;
+ return shell;
+ }
+
+ fn output(n: *NinepJoin, shell: u8, bytes: []const u8) !void {
+ n.a.output(.{ .output = .{ .pane = .at(shell), .bytes = bytes } });
+ try n.send((try n.a.pending()).?);
+ }
+};
+
+test "a client joined while a script's pty/run waits on the command it sent ends the run as its session does" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ var n: NinepJoin = undefined;
+ const shell = try RunJoin.init(&n);
+ defer n.deinit();
+ // The shell's greeting (`ls`) run at its first prompt, done.
+ try RunJoin.output(&n, shell, RunJoin.prompt ++ "ls\r\n\x1b]133;C;aid=pardes\x07a b\r\n\x1b]133;D;0;aid=pardes\x07" ++ RunJoin.prompt);
+ const run = n.node(.pty_run);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = run, .omode = 2 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = run, .handle = h, .data = "true\n" }, true);
+ try n.join();
+ try RunJoin.output(&n, shell, "true\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;0;aid=pardes\x07" ++ RunJoin.prompt);
+ const answer = try n.serve(.{ .tag = 3, .op = .read, .node = run, .handle = h, .size = 64 }, true);
+ try std.testing.expectEqualStrings("exit 0\n", n.a.core.fsPayload(answer));
+ // The open's next line, sent at the prompt the first left.
+ _ = try n.serve(.{ .tag = 4, .op = .write, .node = run, .handle = h, .data = "false\n" }, true);
+ try RunJoin.output(&n, shell, "false\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;1;aid=pardes\x07" ++ RunJoin.prompt);
+ _ = try n.serve(.{ .tag = 5, .op = .release, .node = run, .handle = h, .opened = true }, true);
+ try n.agree();
+}
+
+test "a client joined after its session's shell was found to have no prompt marks answers a pty/run as its session does" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ var n: NinepJoin = undefined;
+ const shell = try RunJoin.init(&n);
+ defer n.deinit();
+ {
+ const was = Stepping.begin(&n.a.t, null);
+ n.a.core.acknowledgeShell(.at(shell), "/bin/sh", false);
+ was.end();
+ n.a.seq += 1;
+ _ = try n.a.unit(0, n.a.seq);
+ }
+ try n.join();
+ const run = n.node(.pty_run);
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = run, .omode = 2 }, true)).handle;
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = run, .handle = h, .data = "true\n" }, true);
+ const answer = try n.serve(.{ .tag = 3, .op = .read, .node = run, .handle = h, .size = 64 }, true);
+ try std.testing.expectEqualStrings("error no prompt marks\n", n.a.core.fsPayload(answer));
+ _ = try n.serve(.{ .tag = 4, .op = .release, .node = run, .handle = h, .opened = true }, true);
+ try n.agree();
+}
diff --git a/core/rollback.zig b/core/rollback.zig
index c7d0a4e8..a55d3c87 100644
--- a/core/rollback.zig
+++ b/core/rollback.zig
@@ -404,9 +404,7 @@ pub const Copy = struct {
},
.@"struct" => |s| {
if (comptime walk.machinery(T)) return;
- // A terminal: the authority's (its emulator is never written
- // by a speculation: terminal.zig's guards).
- if (comptime @hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *walk.Hasher) void) return;
+ if (comptime unwalked(T)) return;
if (s.layout == .@"packed") return;
// std's lists (a safe build's have a third field, a lock).
if (comptime walk.isList(T)) {
@@ -467,7 +465,7 @@ pub const Copy = struct {
if (comptime walk.machinery(P)) return;
const addr = @intFromPtr(ptr);
if (try c.reached(P, addr)) return;
- if (comptime @hasDecl(P, "digest") and @TypeOf(P.digest) == fn (*const P, *walk.Hasher) void) return;
+ if (comptime unwalked(P)) return;
if (c.epoch.?.owns(addr) != null) {
_ = try c.reached(void, addr);
try c.fields(P, ptr);
@@ -513,6 +511,16 @@ pub const Copy = struct {
}
};
+/// A type that hashes itself and says nothing of its fields (`replica`):
+/// a terminal, the authority's (its emulator is never written by a
+/// speculation: terminal.zig's guards), or a location row, made again and
+/// never written. One that says its fields' kinds is walked by them,
+/// whatever digest it has (the 9P state, fs.Namespace and a pane's: a
+/// replayed request writes its buffers in place).
+fn unwalked(comptime T: type) bool {
+ return @hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *walk.Hasher) void and !@hasDecl(T, "replica");
+}
+
fn annotatedStruct(comptime T: type) bool {
return @typeInfo(T) == .@"struct" and @hasDecl(T, "replica");
}
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/core/tape.zig b/core/tape.zig
index 88a7047b..6af332a3 100644
--- a/core/tape.zig
+++ b/core/tape.zig
@@ -114,7 +114,6 @@ pub const Site = enum(u16) {
fonts,
// Read in place (`value`).
clock,
- budget,
wake,
env,
interpreter,
@@ -281,6 +280,8 @@ pub const Tape = struct {
/// checks.
speculating: bool = false,
poisoned: bool = false,
+ /// The turn's yields when the speculation began (`stray`).
+ yields: u64 = 0,
/// What stopped it: a host function's or a site's name, or a poison's
/// reason (PARDES_REPLICA_STATS counts them).
poisoned_by: []const u8 = "",
@@ -410,7 +411,7 @@ pub const Tape = struct {
if (!t.host_side) return .{};
t.host_side = false;
t.depth += 1;
- if (t.replay) return .{ .outer = true };
+ if (t.replay) return .{ .tape = t };
if (p) |core| {
if (t.core == null) t.core = core;
t.noteWrites();
@@ -422,7 +423,7 @@ pub const Tape = struct {
bare.update.args[0].output.bytes = &.{};
t.record(.input, Input, &bare);
} else t.record(.input, Input, input);
- return .{ .outer = true };
+ return .{ .tape = t };
}
fn leaveInput(t: *Tape, p: ?*Pardes) void {
@@ -665,6 +666,9 @@ pub const Tape = struct {
defer t.applying = outer;
t.host_side = true;
defer t.host_side = true;
+ // Not at the end: the dump checked there reads through no tape.
+ const yields = pardes.turn.yields;
+ defer if (input != .deinit) t.stray(yields);
switch (input) {
.init, .init_from_dump => {
var opts = switch (input) {
@@ -768,12 +772,6 @@ pub const Tape = struct {
return t.value(.authority, f, args);
}
- /// A budget of `budget_ns` from `since_ns` on the monotonic clock is spent:
- /// what the clock said is taped, so a replica stops its work where this did.
- pub fn over(t: *Tape, since_ns: u64, budget_ns: u64) bool {
- return t.value(.budget, overNow, .{ since_ns, budget_ns });
- }
-
/// A body whose first parameter is an `std.Io` its caller does not pass
/// is handed the tape's (`args` are the rest): the only way core/ comes
/// to hold one.
@@ -865,11 +863,13 @@ pub const Tape = struct {
return t.replay or t.speculating;
}
- /// A syscall of the core's that is no site, made by a replica: what it
- /// returns is the authority's to say. A speculation waits for it, and a
- /// replay has diverged.
- pub fn stray(t: *Tape) void {
- if (t.through) return;
+ /// A syscall of the core's that is no site, made by a replica since the
+ /// turn's count of yields was `since`: what it returned is the
+ /// authority's to say. A speculation waits for it, and a replay has
+ /// diverged (it joins again), never the process (a window client's
+ /// `Term fish`, H17).
+ fn stray(t: *Tape, since: u64) void {
+ if (pardes.turn.yields == since) return;
if (t.speculating) t.poisoned = true else t.diverge("a syscall that is no tape site, made replaying", .{});
}
@@ -1023,44 +1023,45 @@ fn partsDiffer(got: []const u64, want: []const u64, a: std.mem.Allocator) []cons
return said.items;
}
-/// A call into the core: the host's, and recorded, or the core's own.
-pub const Entered = struct { outer: bool = false };
+/// A call into the core: the host's, and recorded, or the core's own. The
+/// tape it entered (null: the core's own, or nobody records), so `leave`
+/// needs neither the global nor a core `init` did not make or `deinit` freed.
+pub const Entered = struct { tape: ?*Tape = null };
pub inline fn enter(p: ?*Pardes, input: Input) Entered {
- // A core's tape is the one `on` says while both are (P20: the global
- // goes at the last step): every entry a safe build makes checks it.
- // With none on, a client's core is entered between its steps (its own
- // frame drawn, Replica.draw), its tape idle.
- //
- // The idle tape, the rule for the step that has this read the field
- // (P20's last): a client's tape between its steps is neither replaying
- // nor speculating, and its core is entered all the same (its frame);
- // `enter` must not record into an idle replica's tape. Only a tape
- // stepping its core records. The test "a client's frame drawn between
- // its steps records nothing into its idle tape" (this file's end)
- // fails when it does.
- if (std.debug.runtime_safety) if (p) |core| if (if (on) |t| core.tape != t else core.tape.stepping())
+ // While the global is (P20: the terminal's questions read it), a core
+ // stepped is the one it says: every entry a safe build makes checks it.
+ if (std.debug.runtime_safety) if (p) |core| if (on) |was| if (core.tape != was)
@panic("tape: a core's field is not the tape being stepped (tape.on)");
- const t = on orelse return .{};
+ const t = tapeOf(p, &input);
+ // A client's tape between its steps records nothing (its frame drawn,
+ // its core freed: the test "a client's frame drawn between its steps
+ // records nothing into its idle tape"); an authority's records every
+ // entry, in a Stepping scope or not, as a real session's.
+ if (!records(t)) return .{};
return t.enterInput(p, &input);
}
-pub inline fn leave(p: ?*Pardes, e: Entered) void {
- if (e.outer) on.?.leaveInput(p);
-}
-
-// The entry points on `on`, the methods' (`Tape.site` and the rest).
-
-pub fn adopt(p: *Pardes) void {
- (on orelse &none).adopt(p);
+/// The tape an entry steps: its core's; for a session not made yet, the one
+/// its options name (`Pardes.create`'s).
+fn tapeOf(p: ?*Pardes, input: *const Input) *Tape {
+ if (p) |core| return core.tape;
+ const opts = switch (input.*) {
+ .init => |o| o,
+ .init_from_dump => |d| d.opts,
+ else => return &none,
+ };
+ return opts.tape orelse &none;
}
-pub fn current(p: *const Pardes) bool {
- return (on orelse &none).current(p);
+/// Whether an entry on `t` is recorded: not on the tape nobody records, nor
+/// on a replica's between its steps (a client's frame drawn, its core freed).
+fn records(t: *const Tape) bool {
+ return !(t.through or (t.replica and !t.replaying()));
}
-pub fn forget(p: *Pardes) void {
- (on orelse &none).forget(p);
+pub inline fn leave(p: ?*Pardes, e: Entered) void {
+ if (e.tape) |t| t.leaveInput(p);
}
/// An entry written once (P22): its public name made from the private
@@ -1324,14 +1325,6 @@ pub fn resync(t: *Tape) void {
t.real = .{};
}
-pub fn over(since_ns: u64, budget_ns: u64) bool {
- return (on orelse &none).over(since_ns, budget_ns);
-}
-
-fn overNow(since_ns: u64, budget_ns: u64) bool {
- return pardes.FrameStats.nowNs() -| since_ns > budget_ns;
-}
-
/// One host call, `f(args)`, made out of the turn (pardes.turn).
pub fn out(comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? {
pardes.turn.yield();
@@ -1343,10 +1336,6 @@ pub fn replaying() bool {
return (on orelse &none).replaying();
}
-pub fn stray() void {
- (on orelse &none).stray();
-}
-
/// A replica speculating (core/replica.zig): state only the authority
/// changes (a terminal's emulator) is left alone, and the input waits.
pub fn speculating() bool {
@@ -1477,12 +1466,14 @@ pub fn beginSpeculation(t: *Tape) void {
t.poisoned_by = "";
t.touched = false;
t.no_digest = true;
+ t.yields = pardes.turn.yields;
t.buf.clearRetainingCapacity();
t.seeFields();
}
/// Whether it stayed clean (no host call, no syscall, no authority state).
pub fn endSpeculation(t: *Tape) bool {
+ t.stray(t.yields);
t.speculating = false;
t.no_digest = false;
return !t.poisoned;
@@ -1592,19 +1583,21 @@ pub fn digestOf(p: *const Pardes) u64 {
return walk.digest(Pardes, p);
}
-/// PARDES_RECORD set: the tape is written from the session's first call.
-pub fn startFromEnv() void {
- if (on != null) return;
- const prefix = std.mem.span(libc.getenv("PARDES_RECORD") orelse return);
- if (prefix.len == 0) return;
+/// PARDES_RECORD set: the tape a session is written to from its first
+/// call, which whoever starts it hands in `Options.tape` (runtime/session.zig,
+/// the Mac's start). `on` too, while the terminal's questions read it (P20).
+pub fn fromEnv() ?*Tape {
+ const prefix = std.mem.span(libc.getenv("PARDES_RECORD") orelse return null);
+ if (prefix.len == 0) return null;
const gpa = std.heap.c_allocator;
var path_buf: [4096]u8 = undefined;
- const path = std.fmt.bufPrintSentinel(&path_buf, "{s}{d}.tape", .{ prefix, libc.getpid() }, 0) catch return;
+ const path = std.fmt.bufPrintSentinel(&path_buf, "{s}{d}.tape", .{ prefix, libc.getpid() }, 0) catch return null;
const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644));
- if (fd < 0) return;
- const t = gpa.create(Tape) catch return;
+ if (fd < 0) return null;
+ const t = gpa.create(Tape) catch return null;
t.* = .{ .gpa = gpa, .replay = false, .fd = fd, .scratch = .init(gpa), .arena = .init(gpa), .every = libc.getenv("PARDES_RECORD_EVERY") != null };
on = t;
+ return t;
}
/// `PARDES_REPLAY=<tape>`: the tape replayed into three replicas, each
@@ -1661,16 +1654,19 @@ test "a syscall that is no site, made replaying, diverges the replay and poisons
defer t.scratch.deinit();
defer t.arena.deinit();
defer if (t.diverged) |why| gpa.free(why);
- on = &t;
- defer on = null;
+ const since = pardes.turn.yields;
+ t.stray(since);
+ try std.testing.expect(t.diverged == null);
pardes.turn.yield();
pardes.turn.back();
+ t.stray(since);
try std.testing.expect(t.diverged != null);
t.replay = false;
t.speculating = true;
+ t.yields = pardes.turn.yields;
pardes.turn.yield();
pardes.turn.back();
- try std.testing.expect(t.poisoned);
+ try std.testing.expect(!endSpeculation(&t));
}
test "a replay that finds no answer where its core reads one diverges, and the read goes on harmless" {
@@ -1700,7 +1696,7 @@ test "a replay that finds no answer where its core reads one diverges, and the r
/// The functions of core/ that set `on` and leave a core's field be, each
/// with why the field is that tape already.
const sets_on_alone = [_]struct { []const u8, []const u8, []const u8 }{
- .{ "tape.zig", "startFromEnv", "no core yet: the one made next takes `on` (Pardes.create)" },
+ .{ "tape.zig", "fromEnv", "no core yet: its starter hands the tape in Options.tape" },
.{ "tape.zig", "replayBytes", "its replay's core is made with this tape in its options (apply)" },
.{ "replica.zig", "begin", "Stepping: the core stepped holds this tape already (adoptCore), which `enter` checks in a safe build" },
.{ "replica.zig", "end", "Stepping: `on` put back as `begin` found it" },
diff --git a/core/walk.zig b/core/walk.zig
index 6d7c594d..9b760144 100644
--- a/core/walk.zig
+++ b/core/walk.zig
@@ -31,8 +31,9 @@
//! .blob = .{ "content" },
//! };
//!
-//! None of the three kinds is in a digest or a dump. A type with a `pub fn
-//! digest(*const T, *Hasher) void` of its own hashes itself; one with
+//! None of the three kinds is in a digest or a dump. A type (a struct or a
+//! tagged union) with a `pub fn digest(*const T, *Hasher) void` of its own
+//! hashes itself; one with
//! `dumpWrite`, `dumpRead` (and `dumpFree`) dumps itself as bytes.
const std = @import("std");
const xitdb = @import("xitdb");
@@ -242,6 +243,7 @@ pub fn hash(comptime T: type, v: *const T, h: *Hasher) void {
},
.@"union" => |u| {
if (u.tag_type == null) @compileError("walk: an untagged union: " ++ @typeName(T));
+ if (comptime @hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *Hasher) void) return v.digest(h);
const tag: u.tag_type.? = v.*;
hash(u.tag_type.?, &tag, h);
switch (v.*) {
diff --git a/dev/Inbox.zig b/dev/Inbox.zig
index aac1f7a1..d733b971 100644
--- a/dev/Inbox.zig
+++ b/dev/Inbox.zig
@@ -47,8 +47,12 @@ pub const Msg = union(enum) {
}
};
-pub const capacity = 512;
-pub const output_capacity = capacity - pardes.MAX_PANES;
+/// The ring's room: output up to `output_capacity` (a reader waits for
+/// more), an Adopt's shells beyond it (one note's: never lost to a flood),
+/// and each pane's end of file beyond those (lost to neither).
+pub const output_capacity = 512 - pardes.MAX_PANES;
+const adopt_capacity = output_capacity + pardes.MAX_PANES + 1;
+pub const capacity = adopt_capacity + pardes.MAX_PANES;
pub const Batch = struct {
items: [capacity + 2 * selection_pipe.Tasks.capacity + 2]Msg = undefined,
@@ -63,6 +67,11 @@ gpa: std.mem.Allocator,
lsp_allocator: std.mem.Allocator,
/// The query in flight; the UI thread's alone (spawnLsp, teardown).
lsp_task: ?Lsp.Task = null,
+/// The `|` pipes' and the addons' jobs' and draws' workers in flight, each
+/// posting its answer here (`pushPipe`, `pushJob`); the loop's thread's
+/// alone: joined as their answers land (`land`), canceled at the end.
+pipe_tasks: selection_pipe.Tasks = .{},
+job_tasks: selection_pipe.Tasks = .{},
/// Wakes the host's loop after a push from another thread: an SDL
/// event, a macOS runtime callback. Null: nobody to wake (tests).
wake_fn: ?*const fn (?*anyopaque) void = null,
@@ -77,6 +86,11 @@ len: usize = 0,
closed: bool = false,
files_changed: bool = false,
readers: [pardes.MAX_PANES]?u32 = @splat(null),
+/// Each pane's reads read out of its pty and not yet applied (`applied`):
+/// a command's exit is told only once none is (Ptys.unapplied), since
+/// the poll that asks whether its output is in (CommandWatch.due) cannot
+/// see a read the reader holds or the queue does.
+unapplied: [pardes.MAX_PANES]std.atomic.Value(u32) = @splat(.init(0)),
waiting: usize = 0,
lsp_id: ?u32 = null,
completions: [2 * selection_pipe.Tasks.capacity + 1]Msg = undefined,
@@ -101,6 +115,12 @@ pub fn acceptReader(q: *Inbox, pane: pardes.Pane.Id, gen: u32) void {
q.readers[pane.index()] = gen;
}
+/// One of `pane`'s reads applied, or dropped unapplied.
+pub fn applied(q: *Inbox, pane: pardes.Pane.Id) void {
+ const n = &q.unapplied[pane.index()];
+ if (n.load(.acquire) > 0) _ = n.fetchSub(1, .acq_rel);
+}
+
pub fn cancelReader(q: *Inbox, pane: pardes.Pane.Id, gen: u32) void {
q.lock();
defer q.unlock();
@@ -114,7 +134,10 @@ pub fn cancelReader(q: *Inbox, pane: pardes.Pane.Id, gen: u32) void {
.eof => |e| e.pane == pane and e.gen == gen,
else => false,
};
- if (matches) q.removeAt(i).deinit(q.gpa, q.lsp_allocator) else i += 1;
+ if (matches) {
+ if (msg == .output) q.applied(pane);
+ q.removeAt(i).deinit(q.gpa, q.lsp_allocator);
+ } else i += 1;
}
q.space.broadcast(q.io);
}
@@ -189,7 +212,7 @@ pub fn push(q: *Inbox, m: Msg) void {
return;
}
std.debug.assert(q.len < q.items.len);
- } else if (q.len >= output_capacity) {
+ } else if (q.len >= @as(usize, if (m == .adopted) adopt_capacity else output_capacity)) {
q.unlock();
m.deinit(q.gpa, q.lsp_allocator);
return;
@@ -262,9 +285,11 @@ pub fn close(q: *Inbox) void {
}
pub fn deinit(q: *Inbox) void {
- // The query in flight ends first: what it still delivers is dropped.
+ // The workers in flight end first: what they still deliver is dropped.
if (q.lsp_task) |*t| t.future.cancel(q.io);
q.lsp_task = null;
+ q.pipe_tasks.cancelAll(q.io);
+ q.job_tasks.cancelAll(q.io);
q.close();
std.debug.assert(q.waiting == 0);
}
@@ -291,11 +316,14 @@ fn readPty(q: *Inbox, pty: std.Io.File, pane: pardes.Pane.Id, gen: u32) void {
},
};
if (n == 0) continue;
+ // Counted at once: out of the pty, the poll no longer sees it.
+ _ = q.unapplied[pane.index()].fetchAdd(1, .acq_rel);
const bytes = q.gpa.dupe(u8, buf[0..n]) catch |err| {
+ q.applied(pane);
failure = err;
break;
};
- if (!q.pushOutput(pane, gen, bytes)) return;
+ if (!q.pushOutput(pane, gen, bytes)) return q.applied(pane);
}
q.push(.{ .eof = .{ .pane = pane, .gen = gen, .failure = failure } });
}
@@ -311,9 +339,10 @@ 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 {
+/// A worker's answer taken off the queue, to the core (whichever frontend
+/// took it), its worker joined: a language server's answer or status line,
+/// a pipe's, a search's rows, an addon's job or draw, a handover's end.
+pub fn land(q: *Inbox, core: *pardes.Pardes, m: Msg) void {
switch (m) {
.lsp => |l| {
core.update(.{ .lsp_resp = .{ .id = l.id, .rows = l.rows } });
@@ -324,7 +353,30 @@ pub fn landLsp(q: *Inbox, core: *pardes.Pardes, m: Msg) void {
core.setStatus(.at(core.view().active), pardes.Messages.Message.stamp(&mbuf, "lsp", text));
q.lsp_allocator.free(text);
},
- else => unreachable,
+ .pipe => |response_value| {
+ var response = response_value;
+ core.update(.{ .pipe_resp = .{
+ .id = response.id,
+ .success = response.success,
+ .outputs = response.outputs,
+ .failure = response.failure,
+ } });
+ response.deinit(q.gpa);
+ q.pipe_tasks.finish(q.io, response_value.id);
+ },
+ .search => |b| {
+ core.update(.{ .search = b });
+ b.deinit(q.gpa);
+ },
+ .kind_job => |j| {
+ q.job_tasks.finish(q.io, j.id);
+ j.land(core);
+ },
+ .handed => |h| {
+ core.update(.{ .handed = .{ .seq = h.seq, .to = if (h.ok) h.words else "", .failure = if (h.ok) null else h.words } });
+ q.gpa.free(h.words);
+ },
+ .output, .eof, .files_changed, .fs_ready, .adopted => unreachable,
}
}
@@ -340,12 +392,13 @@ pub fn lspStatus(ctx: ?*anyopaque, text: []const u8) void {
q.push(.{ .lsp_status = copy });
}
-/// A `|` job's answer (selection_pipe.start's sink).
+/// An addon's job or draw done (KindJob.go's sink).
pub fn pushJob(ctx: ?*anyopaque, j: *KindJob) void {
const q: *Inbox = @ptrCast(@alignCast(ctx.?));
q.push(.{ .kind_job = j });
}
+/// A `|` pipe's answer (selection_pipe.start's sink).
pub fn pushPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void {
const q: *Inbox = @ptrCast(@alignCast(ctx.?));
q.push(.{ .pipe = response });
diff --git a/dev/Ptys.zig b/dev/Ptys.zig
index 16a31939..583e3c38 100644
--- a/dev/Ptys.zig
+++ b/dev/Ptys.zig
@@ -180,6 +180,7 @@ pub fn close(p: *Ptys, id: pardes.Pane.Id) void {
/// A reader's read, off the queue (freed here).
pub fn output(p: *Ptys, core: *pardes.Pardes, o: @FieldType(Inbox.Msg, "output")) void {
defer p.queue.gpa.free(o.bytes);
+ defer p.queue.applied(o.pane);
if (p.gens[o.pane.index()] == o.gen) core.update(.{ .output = .{ .pane = o.pane, .bytes = o.bytes } });
}
@@ -213,6 +214,11 @@ pub fn takeExits(p: *Ptys, core: *pardes.Pardes) void {
host_io.takeExits(core, &p.slots, p, closeWatched);
}
+/// Whether pane `id` has reads not yet applied (host_io.takeExits).
+pub fn unapplied(p: *const Ptys, id: usize) bool {
+ return p.queue.unapplied[id].load(.acquire) > 0;
+}
+
fn closeWatched(p: *Ptys, id: usize) void {
p.close(.at(id));
}
@@ -401,3 +407,31 @@ test "a post of an older generation is passed over" {
try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null);
try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null);
}
+
+test "a command's exit is told after its output a reader read, however long that waits in the queue" {
+ const gpa = std.testing.allocator;
+ const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
+ defer core.deinit();
+ var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa };
+ defer queue.deinit();
+ var p = testing(&queue);
+ defer p.deinit();
+ // A command done (reaped), its pty held open by what it left running
+ // (the pipe's write end): no end of file, and no output in the kernel
+ // once the reader has read it.
+ var fds: [2]c_int = undefined;
+ if (libc.pipe(&fds) != 0) return error.PipeFailed;
+ defer _ = libc.close(fds[1]);
+ p.slots[0] = .{ .fd = fds[0], .pid = 0, .cmd = .{ .watched = true, .fd = fds[0], .exited = true, .status = 0 } };
+ p.slots[0].?.reader = try queue.startReader(.{ .handle = fds[0], .flags = .{ .nonblocking = false } }, .at(0), p.gens[0]);
+ try std.testing.expect(host_io.writeFd(fds[1], "LAST"));
+ const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000;
+ while (queue.len == 0 and std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) try std.testing.io.sleep(.fromMilliseconds(1), .awake);
+ try std.testing.expectEqual(@as(usize, 1), queue.len);
+ p.takeExits(core);
+ try std.testing.expect(!p.slots[0].?.cmd.told);
+ var batch = queue.take();
+ for (batch.slice()) |msg| p.output(core, msg.output);
+ p.takeExits(core);
+ try std.testing.expect(p.slots[0].?.cmd.told);
+}
diff --git a/dev/file_watch.zig b/dev/file_watch.zig
index c575f436..a0a500d7 100644
--- a/dev/file_watch.zig
+++ b/dev/file_watch.zig
@@ -611,12 +611,12 @@ pub fn applyThemeEffect(
const pane = request.pane;
const bytes = filesystem.readFile(&pardes.tape.none, gpa, request.path) catch |err| {
colors.failThemeFile(core, generation, err);
- core.noteLateFailure(.at(pane));
+ core.noteLateFailure(pane);
return false;
};
defer gpa.free(bytes);
if (!colors.loadThemeFile(core, generation, bytes)) {
- core.noteLateFailure(.at(pane));
+ core.noteLateFailure(pane);
return false;
}
const hash = std.hash.Wyhash.hash(0, bytes);
@@ -659,7 +659,7 @@ pub fn reloadTheme(
live.generation = .{ .text = hash };
if (announce) {
var msg_buf: [256]u8 = undefined;
- core.setMessage(.at(request.pane), message.stamp(&msg_buf, "reloaded theme", request.path));
+ core.setMessage(request.pane, message.stamp(&msg_buf, "reloaded theme", request.path));
}
return false;
}
diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig
index 59e70935..521f685f 100644
--- a/dev/gui/gui.zig
+++ b/dev/gui/gui.zig
@@ -379,7 +379,6 @@ fn sdlWake(_: ?*anyopaque) void {
sev.type = c.SDL_EVENT_USER;
_ = c.SDL_PushEvent(&sev);
}
-const PipeTasks = selection_pipe.Tasks;
const output_capacity = Queue.output_capacity;
const Gui = struct {
@@ -991,7 +990,6 @@ const Own = struct {
g: *Gui,
test_mode: bool,
detached: bool,
- pipe_tasks: PipeTasks = .{},
shell: Shell = undefined,
const Session = session_loop.Loop(Own);
@@ -1024,7 +1022,6 @@ const Own = struct {
.lsp_allocator = l.allocs.lsp,
.ptys = &l.ptys,
.queue = &l.inbox,
- .pipe_tasks = &o.pipe_tasks,
.watches = &l.watches,
.fs = l.fs,
.test_mode = o.test_mode,
@@ -1044,15 +1041,10 @@ const Own = struct {
return host;
}
- pub fn close(o: *Own, l: *Session) void {
- const io = l.io;
+ pub fn close(o: *Own, _: *Session) void {
o.shell.fs = null;
host_io.setExitWake(null, null);
pardes.Kind.drawer = null;
- o.shell.job_tasks.cancelAll(io);
- o.pipe_tasks.cancelAll(io);
- // Its worker may be waiting on the queue for room.
- l.core.stream.cancelTask();
o.g.hit_core = null;
}
@@ -1079,12 +1071,7 @@ const Own = struct {
if (o.shell.upgrade_asked) |pane| o.shell.upgradeNow(pane);
}
- pub fn note(o: *Own, n: daemon.Note) void {
- deliverNote(&o.shell, n);
- }
-
pub fn restoring(o: *Own, nc: *pardes.Pardes) void {
- o.pipe_tasks.cancelAll(o.shell.io);
// One view, the window's (host_io.restoreCore).
o.shell.gview = 0;
o.g.cells.clearImages();
@@ -1415,7 +1402,6 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = start.allocs.lsp, .wake_fn = sdlWake };
defer queue.deinit();
var ptys: host_io.Ptys = .{ .queue = &queue, .prompt_rcs = undefined };
- var pipe_tasks: PipeTasks = .{};
var no_watches: file_watch.Watches = .{ .io = io, .gpa = gpa, .queue = &queue };
var no_peers: replica.Peers = .{};
var shell: Shell = .{
@@ -1426,7 +1412,6 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
.lsp_allocator = start.allocs.lsp,
.ptys = &ptys,
.queue = &queue,
- .pipe_tasks = &pipe_tasks,
.watches = &no_watches,
.test_mode = test_mode,
.client = &window,
@@ -1435,7 +1420,6 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
window.shell = &shell;
pardes.Kind.drawer = .{ .ctx = &shell, .go = kindDraw };
defer pardes.Kind.drawer = null;
- defer shell.job_tasks.cancelAll(io);
g.no_blink = test_mode;
defer g.hit_core = null;
_ = c.SDL_StartTextInput(g.window);
@@ -1444,12 +1428,22 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
.done => {},
.gone => Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{to.session}),
.failed => Said.no(io, "{s}", .{start.said()}),
+ // A new process's window: the build at its start path, exec'd.
+ .upgrade => |view| Said.no(io, "{s}", .{client_loop.execAgain(&start, view)}),
.left => {
var said: [600]u8 = undefined;
std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes-gui: detached from '{s}', which is still running; come back with `pardes-gui attach {s}`\n", .{ to.session, to.session }) catch "pardes-gui: detached\n") catch {};
std.process.exit(0);
},
- .ended => |code| std.process.exit(code),
+ .ended => |code| {
+ // A pair's window is its session's parent: its status once it
+ // is gone, as the terminal's (tui.zig `runClient`).
+ if (opts_in.pair != null) {
+ var status: c_int = 0;
+ while (libc.waitpid(@intCast(start.joined.pid), &status, 0) < 0 and libc.errno(-1) == .INTR) {}
+ }
+ std.process.exit(code);
+ },
}
}
@@ -1501,6 +1495,7 @@ const StdinFeed = struct {
// so a driver exercises the real pointer path (pixel to cell,
// tag and body hits). SGR mouse carries only cells.
// finger;<kind>;<id>;<x>;<y>;<pressure>
+ // close: the window's close button
// One the read cut short, or what may yet begin one, waits for
// the next read.
const rest = f.buf[seq_start..len];
@@ -1564,6 +1559,12 @@ const StdinFeed = struct {
dispatch(gp, in, &sev);
c.SDL_SetModState(before);
}
+ } else if (std.mem.eql(u8, event[0..semi], "close")) {
+ if (g) |gp| {
+ var sev = std.mem.zeroes(c.SDL_Event);
+ sev.type = c.SDL_EVENT_WINDOW_CLOSE_REQUESTED;
+ dispatch(gp, in, &sev);
+ }
} else if (std.mem.eql(u8, event[0..semi], "finger")) {
if (parseFinger(fields)) |finger| if (g) |gp| {
var wpw: c_int = 0;
@@ -1744,6 +1745,8 @@ const Input = struct {
fn close(in: *Input) void {
if (in.client) |r| {
+ // Its bye says so: a pair's session ends at its last client's.
+ r.loop.link.close = true;
r.loop.link.quit = true;
in.quit = true;
return;
@@ -2357,8 +2360,6 @@ const Shell = struct {
queue: *Queue,
/// What drainQueue takes each wakeup, kept rather than rebuilt.
batch: Queue.Batch = .{},
- pipe_tasks: *PipeTasks,
- job_tasks: PipeTasks = .{},
/// The session's file watches (runtime/session.zig's); a client's,
/// none.
watches: *file_watch.Watches,
@@ -2567,10 +2568,7 @@ const Shell = struct {
fn takeDraws(s: *Shell) bool {
s.queue.takeInto(&s.batch);
for (s.batch.slice()) |m| switch (m) {
- .kind_job => |j| {
- s.job_tasks.finish(s.io, j.id);
- j.land(s.core);
- },
+ .kind_job => s.queue.land(s.core, m),
else => m.deinit(s.gpa, s.lsp_allocator),
};
return s.batch.slice().len > 0;
@@ -2586,33 +2584,10 @@ 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, .lsp_status => s.queue.landLsp(s.core, m),
- .pipe => |response_value| {
- var response = response_value;
- s.core.update(.{ .pipe_resp = .{
- .id = response.id,
- .success = response.success,
- .outputs = response.outputs,
- .failure = response.failure,
- } });
- response.deinit(s.gpa);
- s.pipe_tasks.finish(s.io, response_value.id);
- },
- .search => |b| {
- s.core.update(.{ .search = b });
- b.deinit(s.gpa);
- },
- .handed => |h| {
- s.core.update(.{ .handed = .{ .seq = h.seq, .to = if (h.ok) h.words else "", .failure = if (h.ok) null else h.words } });
- s.gpa.free(h.words);
- },
- .kind_job => |j| {
- s.job_tasks.finish(s.io, j.id);
- j.land(s.core);
- },
.files_changed => check_files = true,
.fs_ready => {},
.adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd),
+ else => s.queue.land(s.core, m),
};
if (check_files) s.watches.reload(s.core);
}
@@ -3119,21 +3094,6 @@ fn guiNow(ctx: ?*anyopaque) u64 {
return s.test_clock orelse s.paced_ns orelse c.SDL_GetTicksNS();
}
-/// The daemon's thread: what it says, onto the queue (drainQueue).
-fn deliverNote(ctx: *anyopaque, note: daemon.Note) void {
- const s: *Shell = @ptrCast(@alignCast(ctx));
- const q = s.queue;
- switch (note) {
- .relinked => q.wake(),
- .adopted => |a| {
- for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| q.push(.{ .adopted = .{ .pid = pid, .fd = fd } });
- q.push(.{ .adopted = .{ .pid = 0, .fd = -1 } });
- },
- // Joined at the next step boundary (Peers, any thread).
- .replica => |j| s.peers.handed(j.fd, j.view),
- }
-}
-
fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void {
host_io.writeDump(shellOf(ctx).core, bytes);
}
@@ -3184,7 +3144,7 @@ fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void {
fn pipe(ctx: ?*anyopaque, id: u32) void {
const s = shellOf(ctx);
- if (s.threads_ok) return selection_pipe.start(s.io, s.gpa, s.core, s.pipe_tasks, id, s.queue, Queue.pushPipe);
+ if (s.threads_ok) return selection_pipe.start(s.io, s.gpa, s.core, &s.queue.pipe_tasks, id, s.queue, Queue.pushPipe);
s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } });
s.core.reportError(.at(s.core.view().active), "pipe", error.WorkersUnavailable);
}
@@ -3192,13 +3152,13 @@ fn pipe(ctx: ?*anyopaque, id: u32) void {
/// A draw (api.draw) on a worker, as a job is.
fn kindDraw(ctx: ?*anyopaque, j: *host_io.KindJob) bool {
const s = shellOf(ctx);
- return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.job_tasks, j, s.queue, Queue.pushJob);
+ return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.queue.job_tasks, j, s.queue, Queue.pushJob);
}
fn kindJob(ctx: ?*anyopaque, id: pardes.Pane.Id, serial: u32, token: u32) void {
const pane = id.index();
const s = shellOf(ctx);
- if (s.threads_ok) return host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s.queue, Queue.pushJob);
+ if (s.threads_ok) return host_io.KindJob.start(s.io, s.core, &s.queue.job_tasks, pane, serial, token, s.queue, Queue.pushJob);
host_io.KindJob.runHere(s.core, pane, serial, token);
}
@@ -5982,7 +5942,6 @@ test "GUI worker setup failures finish matching LSP and pipe requests" {
.lsp_allocator = failing.allocator(),
};
defer queue.deinit();
- var tasks: PipeTasks = .{};
core.lspRequest(core.view().active, .status, "");
const req: host_io.Lsp.Request = .{
.id = core.lsp_ask.wait.?.id,
@@ -6014,11 +5973,11 @@ test "GUI worker setup failures finish matching LSP and pipe requests" {
core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } });
core.update(.{ .key = .{ .cp = pardes.Key.enter } });
const pipe_id = core.pipe.wait.?.id;
- selection_pipe.start(failing_io, failing.allocator(), core, &tasks, pipe_id, &queue, Queue.pushPipe);
+ selection_pipe.start(failing_io, failing.allocator(), core, &queue.pipe_tasks, pipe_id, &queue, Queue.pushPipe);
try std.testing.expect(core.pipe.wait == null);
try std.testing.expectEqualStrings("abc", pane.file.?.content);
try std.testing.expect(queue.lsp_task == null);
- try std.testing.expectEqual(@as(usize, 0), tasks.len);
+ try std.testing.expectEqual(@as(usize, 0), queue.pipe_tasks.len);
try std.testing.expectEqual(@as(usize, 0), queue.len);
}
}
@@ -7682,9 +7641,8 @@ test "a detached GUI authority follows terminal directory changes with no window
const rcs: host_io.Shell.PromptFiles = .{};
var ptys: host_io.Ptys = .{ .queue = &queue, .prompt_rcs = &rcs, .gens = @splat(1) };
defer ptys.deinit();
- var pipes: PipeTasks = .{};
var no_peers: replica.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 };
+ var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .ptys = &ptys, .queue = &queue, .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/host_io.zig b/dev/host_io.zig
index 5465fc7a..a22bf5ce 100644
--- a/dev/host_io.zig
+++ b/dev/host_io.zig
@@ -1105,6 +1105,8 @@ pub fn takeExits(core: *pardes.Pardes, ptys: anytype, ctx: anytype, comptime clo
for (ptys, 0..) |*slot, id| {
const pt = slotPty(slot) orelse continue;
if (!pt.cmd.watched or !pt.cmd.due()) continue;
+ // Its output read and not yet applied (a host whose reader counts).
+ if (comptime @hasDecl(@TypeOf(ctx.*), "unapplied")) if (!pt.cmd.eof and ctx.unapplied(id)) continue;
pt.cmd.told = true;
const eof = pt.cmd.eof;
core.update(.{ .exited = .{ .pane = .at(id), .status = pt.cmd.status } });
@@ -2265,11 +2267,62 @@ test "PTY EOF reserve cannot evict terminal output" {
for (0..pardes.MAX_PANES) |pane| queue.push(.{ .eof = .{ .pane = .at(pane), .gen = 1 } });
var batch = queue.take();
defer for (batch.slice()) |msg| msg.deinit(gpa, gpa);
- try std.testing.expectEqual(Inbox.capacity, batch.len);
+ try std.testing.expectEqual(Inbox.output_capacity + pardes.MAX_PANES, batch.len);
for (batch.items[0..Inbox.output_capacity]) |msg| try std.testing.expectEqualStrings("before", msg.output.bytes);
for (batch.items[Inbox.output_capacity..batch.len], 0..) |msg, pane| try std.testing.expectEqual(pane, msg.eof.pane.index());
}
+test "a search's rows posted into a full queue wait for room: a take lets them in, a cancel ends the wait and frees them" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var queue: Inbox = .{ .io = io, .gpa = gpa, .lsp_allocator = gpa };
+ defer queue.deinit();
+ queue.acceptReader(.at(0), 1);
+ const Post = struct {
+ fn run(q: *Inbox, posted: *?bool) void {
+ const rows = std.testing.allocator.dupe(u8, "a.txt:1:1-2 hit\n") catch return;
+ posted.* = Inbox.pushSearch(q, .{ .gen = 1, .rows = rows });
+ }
+ };
+ for ([_]bool{ false, true }) |cancel| {
+ // The loop busy: its queue full of output.
+ for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = .at(0), .gen = 1, .bytes = try gpa.dupe(u8, "busy") } });
+ var posted: ?bool = null;
+ var worker = try io.concurrent(Post.run, .{ &queue, &posted });
+ try PtyTests.waitBlocked(&queue);
+ if (cancel) worker.cancel(io) else {
+ var batch = queue.take();
+ for (batch.slice()) |msg| msg.deinit(gpa, gpa);
+ worker.await(io);
+ }
+ try std.testing.expectEqual(!cancel, posted.?);
+ var rest = queue.take();
+ defer for (rest.slice()) |msg| msg.deinit(gpa, gpa);
+ try std.testing.expectEqual(@as(usize, if (cancel) Inbox.output_capacity else 1), rest.len);
+ if (!cancel) try std.testing.expectEqualStrings("a.txt:1:1-2 hit\n", rest.items[0].search.rows);
+ try std.testing.expectEqual(@as(usize, 0), queue.waiting);
+ }
+}
+
+test "an Adopt's shells are taken in whatever output fills the queue" {
+ const gpa = std.testing.allocator;
+ var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa };
+ defer queue.deinit();
+ queue.acceptReader(.at(0), 1);
+ for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = .at(0), .gen = 1, .bytes = try gpa.dupe(u8, "flood") } });
+ var fds: [2]c_int = undefined;
+ if (libc.pipe(&fds) != 0) return error.PipeFailed;
+ defer _ = libc.close(fds[1]);
+ queue.push(.{ .adopted = .{ .pid = 42, .fd = fds[0] } });
+ queue.push(.{ .adopted = .{ .pid = 0, .fd = -1 } });
+ var batch = queue.take();
+ defer for (batch.slice()) |msg| msg.deinit(gpa, gpa);
+ try std.testing.expectEqual(Inbox.output_capacity + 2, batch.len);
+ try std.testing.expectEqual(@as(libc.pid_t, 42), batch.items[Inbox.output_capacity].adopted.pid);
+ try std.testing.expectEqual(fds[0], batch.items[Inbox.output_capacity].adopted.fd);
+ try std.testing.expectEqual(@as(libc.pid_t, 0), batch.items[Inbox.output_capacity + 1].adopted.pid);
+}
+
test "completions retain their arrival order across LSP and pipes" {
const gpa = std.testing.allocator;
var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = 2 };
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/macos/Sources/AppDelegate.swift b/dev/macos/Sources/AppDelegate.swift
index 4168999f..5ee775cf 100644
--- a/dev/macos/Sources/AppDelegate.swift
+++ b/dev/macos/Sources/AppDelegate.swift
@@ -132,7 +132,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, PardesViewDelegate {
// to change the day macos_min_version reaches 14.
NSApp.activate(ignoringOtherApps: true)
- var runtime = pardes_callbacks_s(
+ var callbacks = pardes_callbacks_s(
userdata: Unmanaged.passUnretained(self).toOpaque(),
wakeup: { ud in
// A pty reader thread. Every other function in pardes.h is
@@ -168,7 +168,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, PardesViewDelegate {
// greeting until it has seen a size, so a correction sent afterwards
// arrives with the first prompt already wrapped to the wrong width.
let grid = view.gridSize
- let rc = pardes_init(&runtime, grid.cols, grid.rows)
+ let rc = pardes_init(&callbacks, grid.cols, grid.rows)
if rc != 0 {
NSLog("pardes: the core failed to boot at \(grid.cols)x\(grid.rows), pardes_init returned \(rc)")
// Not NSApp.terminate — that runs applicationWillTerminate, which
diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig
index bf051e9a..e441df92 100644
--- a/dev/tui/tui.zig
+++ b/dev/tui/tui.zig
@@ -97,15 +97,14 @@ fn kittyShmProbe(w: *std.Io.Writer, feed: *Feed) void {
w.flush() catch {};
}
-/// What the loop's queue carries: a terminal's input, a pane's output, a
-/// worker's answer, a wake.
+/// What the loop's queue carries: a terminal's input, a wake, what a
+/// replica client's reader hands over. A pane's output, a worker's answer
+/// and the daemon's notes are the session's queue's (Inbox, `takeQueue`).
const Msg = union(enum) {
nop,
/// The terminal's input ended: its end of file, a hangup. A session
/// a daemon keeps carries on detached; any other ends.
quit,
- /// A shell a dead session left, its pty's master (daemon.Note.adopted).
- adopted: struct { pid: posix.pid_t, fd: posix.fd_t },
/// A timed wait ran out: the core's next wake has come.
wake,
/// A SIGWINCH: a terminal changed size (Shell.winched).
@@ -120,14 +119,7 @@ const Msg = union(enum) {
paste: []const u8,
paste_start,
paste_end,
- pipe_done: selection_pipe.Response,
- /// A streaming search's rows (pardes.Stream).
- search_rows: pardes.Stream.Batch,
- /// A kind's job done on a worker (host_io.KindJob).
- kind_job: *host_io.KindJob,
fs_ready,
- /// A replica's connection, handed over by the daemon (Peers).
- replica: daemon.Joining,
/// A replica's reader posted: the step boundary takes it in.
replica_mail,
/// A replica client's: what the session streamed (replica.Link).
@@ -369,8 +361,6 @@ const TestReader = struct {
}
};
-const PipeTasks = selection_pipe.Tasks;
-
/// A watched child exited: wake the loop, which takes it (`takeExits`).
fn wakeForExit(ctx: ?*anyopaque) void {
const loop: *Loop = @ptrCast(@alignCast(ctx.?));
@@ -731,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();
@@ -760,7 +753,7 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8,
var c = try Client.init(&tty, &start);
defer c.link.deinit(gpa);
// A client has no clients of its own, and spawns nothing: its pty
- // table an empty one over an empty queue.
+ // table an empty one over a queue that carries its draws alone.
var no_peers: replica.Peers = .{};
var no_inbox: host_io.Inbox = .{ .io = io, .gpa = gpa, .lsp_allocator = start.allocs.lsp };
defer no_inbox.deinit();
@@ -783,6 +776,8 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8,
.ptys = &no_ptys,
};
tty = .{ .sh = &sh, .screen = &screen, .loop = &loop, .joins = &start };
+ no_inbox.wake_fn = Shell.wakeForQueue;
+ no_inbox.wake_ctx = &sh;
pardes.Kind.drawer = .{ .ctx = &sh, .go = Shell.draw };
defer pardes.Kind.drawer = null;
@@ -817,6 +812,12 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8,
screen.leave();
Said.no(io, "{s}", .{start.said()});
},
+ .upgrade => |view| {
+ // The blink: its screen left, the build at its start path
+ // exec'd, which enters it again.
+ screen.leave();
+ Said.no(io, "{s}", .{client_loop.execAgain(&start, view)});
+ },
}
}
@@ -908,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;
@@ -939,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);
}
@@ -1001,19 +1004,8 @@ const Own = struct {
stopInput(io, &o.screen.thread);
pardes.Kind.drawer = null;
host_io.setExitWake(null, 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)),
- .pipe_done => |response_value| {
- var response = response_value;
- response.deinit(gpa);
- },
- .search_rows => |b| b.deinit(gpa),
- .kind_job => |j| j.drop(),
- .adopted => |a| _ = libc.close(a.fd),
else => {},
};
o.screen.art.deinit(gpa);
@@ -1049,14 +1041,9 @@ const Own = struct {
if (o.sh.upgrade_asked) |pane| o.sh.upgradeNow(pane);
}
- pub fn note(o: *Own, n: daemon.Note) void {
- deliverNote(o.loop, n);
- }
-
pub fn restoring(o: *Own, nc: *pardes.Pardes) void {
const sh = &o.sh;
const io = sh.io;
- sh.pipe_tasks.cancelAll(io);
// One view, the terminal's (host_io.restoreCore).
const live = o.screen;
stopInput(io, &live.thread);
@@ -1085,24 +1072,6 @@ fn clearNativeImages(
kitty_handles.clearRetainingCapacity();
}
-/// The daemon's thread: what it says, onto the loop's queue.
-fn deliverNote(ctx: *anyopaque, note: daemon.Note) void {
- const loop: *Loop = @ptrCast(@alignCast(ctx));
- switch (note) {
- // A full queue wakes it anyway.
- .relinked => _ = loop.tryPostEvent(.nop) catch false,
- .adopted => |a| {
- for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| loop.postEvent(.{ .adopted = .{ .pid = pid, .fd = fd } }) catch {
- _ = libc.close(fd);
- };
- loop.postEvent(.{ .adopted = .{ .pid = 0, .fd = -1 } }) catch {};
- },
- .replica => |j| loop.postEvent(.{ .replica = j }) catch {
- _ = libc.close(j.fd);
- },
- }
-}
-
/// A replica reader's post: the session's wait ends, and its step
/// boundary takes the post in.
fn wakeForReplica(ctx: ?*anyopaque) void {
@@ -1140,8 +1109,6 @@ const Shell = struct {
batch: host_io.Inbox.Batch = .{},
batch_at: usize = 0,
queue_woken: std.atomic.Value(bool) = .init(false),
- pipe_tasks: PipeTasks = .{},
- job_tasks: PipeTasks = .{},
threads_ok: bool = false,
check_files: bool = false,
in_paste: bool = false,
@@ -1315,6 +1282,10 @@ const Shell = struct {
const core = s.core;
var why: [800]u8 = undefined;
const path = upgrade.exe() orelse return core.reportFailure(pane, "Upgrade: this process does not know the path it was started from");
+ // A client of a session no daemon keeps is a pair's first (no other
+ // can attach): let go, it has no socket to find the session again
+ // by, and the session would end with its last link.
+ if (s.peers.count() > 0 and daemon.link < 0) return core.reportFailure(pane, "Upgrade: no daemon keeps this session, so its client could not join it again; this session stays as it is");
// 9P is served while the new binary is asked (its clients' clunks
// and reads after the word are answered), and not after.
pardes.turn.rest();
@@ -1511,11 +1482,9 @@ const Shell = struct {
// is held for the next wait: `split`).
s.takeQueue();
// An exit's wake (a .nop) or output an exit waited behind: told
- // here, inside the step, so the frame after it shows it; not while
- // reads taken off the queue wait their steps (`takeQueue`): one of
- // them may be the command's own last output, which its exit would
- // be drawn above (CommandWatch.due cannot see it).
- if (s.batch_at == s.batch.len) s.takeExits();
+ // here, inside the step, so the frame after it shows it (a read
+ // still to be applied holds it back: Ptys.unapplied).
+ s.takeExits();
s.reloadWatched();
}
@@ -1580,15 +1549,15 @@ 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;
}
// The terminal went: a session the daemon keeps carries on
- // without it, to be attached again. Gone before the first
- // frame, the reader that takes the daemon's `ok` (kept
- // waits on it) is not started yet: started here.
- daemon.watch(s.loop, deliverNote);
+ // without it, to be attached again.
if (daemon.kept()) {
if (!s.detached()) s.leaveTerminal();
return true;
@@ -1596,11 +1565,6 @@ const Shell = struct {
core.quit = true;
return true;
},
- .adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd),
- .replica => |j| {
- s.peers.handed(j.fd, j.view);
- s.input_seen = true;
- },
.replica_mail => if (s.peers.urgent.swap(false, .acq_rel)) {
s.input_seen = true;
},
@@ -1656,27 +1620,6 @@ const Shell = struct {
s.paste_buf.clearRetainingCapacity();
},
.fs_ready => {},
- .pipe_done => |response_value| {
- var response = response_value;
- core.update(.{ .pipe_resp = .{
- .id = response.id,
- .success = response.success,
- .outputs = response.outputs,
- .failure = response.failure,
- } });
- response.deinit(s.gpa);
- s.pipe_tasks.finish(s.io, response_value.id);
- },
- .search_rows => |b| {
- core.update(.{ .search = b });
- b.deinit(s.gpa);
- },
- .kind_job => |j| {
- s.job_tasks.finish(s.io, j.id);
- j.land(core);
- // A client's draw done: its frame is its own to draw again.
- if (s.client) |cl| cl.link.dirty = true;
- },
}
return false;
}
@@ -1848,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 {};
@@ -1885,7 +1830,8 @@ const Shell = struct {
}
/// What the session's queue holds: its ptys' output (`waitInput`
- /// paces it; the focused pane's is its echo) and their ends of file.
+ /// paces it; the focused pane's is its echo), their ends of file and
+ /// the workers' answers.
/// A read a step, as the terminal's own queue gave them: the frame
/// after one shows it before what came after it (a command's last line
/// before its exit scrolls it away), the rest kept for the next wait.
@@ -1913,8 +1859,14 @@ 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),
+ .kind_job => {
+ s.ptys.queue.land(s.core, m);
+ // A client's draw done: its frame is its own to draw again.
+ if (s.client) |cl| cl.link.dirty = true;
+ },
+ .adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd),
+ .fs_ready => {},
+ else => s.ptys.queue.land(s.core, m),
}
}
}
@@ -1969,68 +1921,48 @@ const Shell = struct {
s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } });
return s.core.reportError(.at(s.core.view().active), "pipe", error.WorkersUnavailable);
}
- selection_pipe.start(s.io, s.gpa, s.core, &s.pipe_tasks, id, s, deliverPipe);
+ const q = s.ptys.queue;
+ selection_pipe.start(s.io, s.gpa, s.core, &q.pipe_tasks, id, q, host_io.Inbox.pushPipe);
}
fn search(ctx: ?*anyopaque, gen: u32) void {
const s = of(ctx);
- if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s, deliverSearch);
+ if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s.ptys.queue, host_io.Inbox.pushSearch);
pardes.Stream.runHere(s.core, gen, true);
}
/// A draw (api.draw) on a worker, as a job is.
fn draw(ctx: ?*anyopaque, j: *host_io.KindJob) bool {
const s = of(ctx);
- return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.job_tasks, j, s, struct {
- fn deliver(c: ?*anyopaque, k: *host_io.KindJob) void {
- of(c).loop.postEvent(.{ .kind_job = k }) catch k.drop();
- }
- }.deliver);
+ const q = s.ptys.queue;
+ return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &q.job_tasks, j, q, host_io.Inbox.pushJob);
}
fn job(ctx: ?*anyopaque, id: pardes.Pane.Id, serial: u32, token: u32) void {
const pane = id.index();
const s = of(ctx);
if (!s.threads_ok) return host_io.KindJob.runHere(s.core, pane, serial, token);
- host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s, struct {
- fn deliver(c: ?*anyopaque, j: *host_io.KindJob) void {
- of(c).loop.postEvent(.{ .kind_job = j }) catch j.drop();
- }
- }.deliver);
- }
-
- /// The loop's queue waits for room (a wait the worker's cancel ends).
- fn deliverSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool {
- const s = of(ctx);
- s.loop.postEvent(.{ .search_rows = batch }) catch {
- batch.deinit(s.gpa);
- return false;
- };
- return true;
- }
-
- fn deliverPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void {
- const s = of(ctx);
- var owned = response;
- s.loop.postEvent(.{ .pipe_done = owned }) catch owned.deinit(s.gpa);
+ const q = s.ptys.queue;
+ host_io.KindJob.start(s.io, s.core, &q.job_tasks, pane, serial, token, q, host_io.Inbox.pushJob);
}
};
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 {};
}
}
@@ -2449,6 +2381,22 @@ test "an ESC read by itself is the Escape key at once" {
t.vx.caps.kitty_keyboard = false;
}
+test "an Escape read with the click after it is the Escape key, then the click" {
+ var t: TestInput = undefined;
+ try t.init();
+ defer t.deinit();
+ // A busy session reads them in one: no terminal sends Alt on a mouse
+ // report as an ESC before it (it is in the report's button).
+ var reader: TestReader = .{ .parts = &.{"\x1b\x1b[<1;105;9M"} };
+ try readInput(&t.loop, &reader, &t.vx, &t.feed);
+ try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?));
+ const escape = (try t.loop.tryEvent()).?.key_press;
+ try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint);
+ try std.testing.expect(!escape.mods.alt);
+ try std.testing.expectEqual(.mouse, std.meta.activeTag((try t.loop.tryEvent()).?));
+ try std.testing.expect(try t.loop.tryEvent() == null);
+}
+
test "a frame's answer is taken wherever the reads cut it, and never typed" {
const gpa = std.testing.allocator;
var t: TestInput = undefined;
@@ -2745,7 +2693,7 @@ test "TTY worker setup failures finish matching LSP and pipe requests" {
try std.testing.expect(core.pipe.wait == null);
try std.testing.expectEqualStrings("abc", pane.file.?.content);
try std.testing.expect(queue.lsp_task == null);
- try std.testing.expectEqual(@as(usize, 0), shell.pipe_tasks.len);
+ try std.testing.expectEqual(@as(usize, 0), queue.pipe_tasks.len);
}
}
diff --git a/docs/next-daemon.md b/docs/next-daemon.md
index 37ba0241..9ed25f9c 100644
--- a/docs/next-daemon.md
+++ b/docs/next-daemon.md
@@ -710,9 +710,10 @@ Decisions taken at the forks, with the ponytail lens:
- **Clock.** `advance`'s wakes are the recording session's
(`tape.value(.wake, nextWake)`): a picture decoding or a fade asks a
frame, and a replica that draws none must still take the session's
- ticks. The budgets of Places, Names and Tables are taped verdicts
- (`tape.over`), as are a message's time of day (TZ included), File.mtime
- and the pump's clock read (made whether or not it waits). A message's
+ ticks. The budgets of Places and Names are counts (bytes read, the
+ scorer's cells), the same on every side, never the clock's verdict
+ (P27, P30). A message's time of day (TZ included), File.mtime
+ and the pump's clock read (made whether or not it waits) are taped. A message's
stamp and an unattended session's expiry of it read the clock through
the tape too, not the session clock: that is the last pump's, and
stamped by it a message written over 9P after an idle spell was as old
@@ -1443,7 +1444,7 @@ dump hooks; `pardes-snap --dump`, `pardes-monkey --dump`, and both in
Handover's dump in flight and its carrier, and the host's fallback file
table are authority: host errands, not state.
- **Restore keeps serials.** Renumbering would rewrite every serial the
- session holds (attachments, query owners, places, messages, LSP and
+ session holds (docked panes, query owners, places, messages, LSP and
callstack requests); Restore hangs up every connection anyway. The next
serials are past the old session's; `restored`/`restoredcol` records
are gone. A Restore over an older session keeps the host's facts (cell
diff --git a/docs/next-drag.md b/docs/next-drag.md
index 47ccdb0b..dd2f24ed 100644
--- a/docs/next-drag.md
+++ b/docs/next-drag.md
@@ -43,7 +43,7 @@ window it goes to is found by asking every registry session.
grip) released outside goes to `Handover.begin` instead of the layout
move. Inside the window the grip drag is exactly as before.
- `core/Handover.zig` (`Pardes.handover`), the core half: the pane with the
- panes attached to it (an attachment dragged alone goes alone, unattached),
+ panes docked to it (a docked pane dragged alone goes alone, undocked),
or the column, is dumped alone: `dump.dumpBytes(p, keep, carried)`, which
`dumpState` now calls with no mask; `State.carried` (`pane`/`column`)
marks such a dump. Each carried pane's serial and `File.revision` is
@@ -61,7 +61,7 @@ window it goes to is found by asking every registry session.
- `Handover.finish`: taken, each carried pane is closed with
`Pardes.removePane` (Del's rows rule: its rows go to its neighbour; a
carried column's empty column is dropped); a pane whose revision changed
- since the dump is kept, unattached ("copied to …; edited on the way, kept
+ since the dump is kept, undocked ("copied to …; edited on the way, kept
here too"). Refused or failed: everything stays, the reason on the
message row. One handover flies at a time.
- New option `--geometry=WxH[+X+Y]` (runtime/main.zig, `Options.geometry`).
@@ -80,7 +80,7 @@ window it goes to is found by asking every registry session.
dumped panes into free slots and places them where the pointer is: a
pane goes right under the group the pointer is over, out of that group
owner's rows alone (the owner keeps its rows down to the pointer's row;
- over one of its attachments, half); a column goes beside the column the
+ over one of its docked panes, half); a column goes beside the column the
pointer is over, out of that column's width alone (`insertColumn`). Every
other pane's rect is unchanged (tested). The ctl write is answered after
the panes are in, so the source closes its pane only once the target has
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/search-proto-converge.md b/docs/search-proto-converge.md
index da336f7c..3af49a06 100644
--- a/docs/search-proto-converge.md
+++ b/docs/search-proto-converge.md
@@ -2,11 +2,11 @@
The design the twelve prototypes added up to (CONVERGE.md), built as the
product in six changes. One pane kind does all searching: the **query
-pane**, a `+Search` attached under the pane that asked (its *owner*), whose
+pane**, a `+Search` docked under the pane that asked (its *owner*), whose
body's line 1 is the query, typed into, and whose rows below are made live
from a source. The owner shows the set in its own text (its **places**:
tints, rail ticks, the current one selected), and a row that points at a
-file no pane shows is shown in a **+Preview** attached under the query
+file no pane shows is shown in a **+Preview** docked under the query
pane. Everything on screen is text in a pane: B1/B2/B3 and the chords work
on all of it, nothing is drawn over anything, and the notice band keeps
only the prompts that are not search.
@@ -15,7 +15,7 @@ only the prompts that are not search.
| piece | file | lifted from |
|---|---|---|
-| attached panes: a group under its owner, rows from the owner alone, moving/folding/closing with it, seam drag, Dump/Restore, `Undock` | `core/layout.zig` "Attached panes", `Pane.docked_to` | attached |
+| docked panes: a group under its owner, rows from the owner alone, moving/folding/closing with it, seam drag, Dump/Restore, `Undock` | `core/layout.zig` "Docked panes", `Pane.docked_to` | attached |
| places: every match tinted, rail ticks (B1 on a tick goes there), current selected and in view, smart-case regex, view-first sliced scan, silent wrap | `core/Places.zig`, `Pane.places` | incsearch (MatchSet) |
| the query pane: line 1, its first word the source, live rows, preview, Enter/Esc/Del, reuse, settings | `core/Query.zig`, `Pane.query` | queryline, pick, live, preview, everywhere |
| fuzzy names (files, recent, panes, declarations) | `core/Names.zig` | pick (its scorer, whole) |
@@ -113,7 +113,7 @@ tint (`Query.paintMark`), no selection: a click, a sweep or a chord never
erases it and B2 / B3 on it take the word clicked, as on any row.
**Enter** puts the keyboard on the current hit in its pane (the +Preview
-promoted in place: same slot, serial, rect, an unattached file pane from
+promoted in place: same slot, serial, rect, an undocked file pane from
then on), fills `/`, and freezes the rows into ordinary text (tag ` Save
Undock Del`). A `/` freezes its whole list (every place found first, 2000
rows at most), a Grep every line it has. **Esc** while typing puts every
diff --git a/docs/typ/building.typ b/docs/typ/building.typ
index d4732fa9..94939452 100644
--- a/docs/typ/building.typ
+++ b/docs/typ/building.typ
@@ -129,7 +129,7 @@ Every dependency but tree-sitter's runtime is lazy in the manifest, so
such a package fetches what it asked for and nothing else.
`pardes-editor` has `pardes-syntax` in it as `.syntax`: a file belongs
to one module, so a package imports one of the two. `test/consumer` is
-such a package, with both shapes; `lib-test`, which `unit-test` runs,
+such a package, with both shapes; `consumer-test`, which `unit-test` runs,
builds and runs it.
`build.zig.zon` names pardes by its path: `.pardes = .{ .path = "../pardes" }`.
@@ -197,9 +197,8 @@ 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 lib-test the library, from a package that depends on pardes (test/consumer);
+zig build consumer-test the library, from a package that depends on pardes (test/consumer);
unit-test runs it too
zig build hxlib helix's cases on the library's editor (-- --parity: against the file pane)
zig build behaviour-test behaviour through the 9P tree, in process (test/behaviour/),
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 bcb0f81b..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
@@ -1896,7 +1896,9 @@ pub const Client = struct {
/// same open, as /pane/new answers its own open: a session's last
/// answer, from another client, can never be what comes back. `exec
/// 3<>file`. `more` (`pardes -`'s text after its /pager line) goes in
- /// Twrites at rising offsets, each answer giving the next its budget.
+ /// Twrites at rising offsets. Untimed once connected: the answer comes
+ /// when the session's step has run, however long a loaded machine
+ /// takes over 256 MiB, and a session that died ends the connection.
pub fn ask(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, request: []const u8, more: []const u8) ![]u8 {
if (comptime !supported) return error.Unsupported;
var names: [max_depth][]const u8 = undefined;
@@ -1905,6 +1907,7 @@ pub const Client = struct {
errdefer said = remote;
const s = try startSession(dial, path);
defer endSession(s, false);
+ s.deadline = std.math.maxInt(i64);
const fid = try walkTo(s, names[0..n], &remote);
_ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote);
var written: usize = 0;
@@ -1914,7 +1917,6 @@ pub const Client = struct {
const count = (try s.ask(.{ .write = .{ .fid = fid, .offset = written, .data = chunk } }, &remote)).write;
if (count == 0 or count > chunk.len) return Error.Botch;
written += count;
- s.deadline = nowMs() +| write_budget_ms;
}
var out: std.ArrayList(u8) = .empty;
errdefer out.deinit(gpa);
diff --git a/runtime/client.zig b/runtime/client.zig
index 7c0bcb7f..55171af2 100644
--- a/runtime/client.zig
+++ b/runtime/client.zig
@@ -37,6 +37,7 @@ const std = @import("std");
const libc = std.c;
const pardes = @import("core");
const replica = pardes.replica;
+const upgrade = @import("upgrade.zig");
/// A wait with no wake of its own: until an input or a message.
pub const forever: u32 = std.math.maxInt(u32);
@@ -92,6 +93,8 @@ pub const Start = struct {
s.o.distrusted = &s.distrusted;
// Its frame timings, this process's (Pardes.frames).
s.o.frames = &s.frames;
+ // Exec'd at an Upgrade (`execAgain`): for the view it had.
+ if (init.environ_map.get("PARDES_JOIN_VIEW")) |v| s.o.join_view = std.fmt.parseInt(u8, v, 10) catch null;
s.r = replica.join(s.gpa, &s.joined, dial.path, dial.session, s.o, s.have, &s.why, null) orelse return false;
return true;
}
@@ -111,8 +114,49 @@ pub const Start = struct {
/// How a client's joins ended: it quit, the session let it go, it could
/// not join again (`Start.said`), it left the session running (a Detach in
-/// it), or the session ended, with its code.
-pub const Ended = union(enum) { done, gone, failed, left, ended: u8 };
+/// it), the session ended, with its code, or it runs another build now and
+/// one is installed at this client's start path since it started: the
+/// frontend lets its screen go and execs that, for this view (`execAgain`).
+pub const Ended = union(enum) { done, gone, failed, left, ended: u8, upgrade: u8 };
+
+/// An Upgrade's client again (`Ended.upgrade`), its frontend's screen let
+/// go: this process exec'd as the file at its start path, an attach of the
+/// same session through the same socket (a far one's forward, its ssh this
+/// process's child still), joining for `view` (PARDES_JOIN_VIEW; far,
+/// PARDES_REPLICA_FAR). The terminal's blink: no record crosses the exec.
+/// Returns only when the exec failed: why.
+pub fn execAgain(s: *Start, view: u8) []const u8 {
+ const path = upgrade.exe() orelse return "Upgrade: this client does not know the path it was started from";
+ var at_buf: [4200]u8 = undefined;
+ const at = std.fmt.bufPrintSentinel(&at_buf, "--attach={s}:{s}", .{ s.dial.path, s.dial.session }, 0) catch return "Upgrade: the session's socket's path is too long to attach again by";
+ const argv = [_:null]?[*:0]const u8{ path, at };
+ var view_buf: [32]u8 = undefined;
+ const joining = std.fmt.bufPrintSentinel(&view_buf, "PARDES_JOIN_VIEW={d}", .{view}, 0) catch unreachable; // a u8 fits 32
+ var n: usize = 0;
+ while (libc.environ[n] != null) n += 1;
+ const envp = s.gpa.allocSentinel(?[*:0]const u8, n + 2, null) catch return "Upgrade: no memory for this client's environment";
+ var k: usize = 0;
+ for (libc.environ[0..n]) |e| {
+ const entry = std.mem.span(e.?);
+ if (std.mem.startsWith(u8, entry, "PARDES_JOIN_VIEW=") or std.mem.startsWith(u8, entry, "PARDES_REPLICA_FAR=")) continue;
+ envp[k] = e;
+ k += 1;
+ }
+ envp[k] = joining.ptr;
+ k += 1;
+ if (s.have != null) {
+ envp[k] = "PARDES_REPLICA_FAR=1";
+ 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";
+}
pub fn Loop(comptime Frontend: type) type {
return struct {
@@ -143,6 +187,8 @@ pub fn Loop(comptime Frontend: type) type {
/// (to upgrade, or cut off); the frontend stays as it is.
pub fn run(l: *L, s: *Start) !Ended {
const link = &l.link;
+ // Its start path's file, for an Upgrade's question (`upgrade`).
+ upgrade.locate();
while (true) {
link.reset(s.r, &s.joined);
l.fe.start(l);
@@ -153,7 +199,7 @@ pub fn Loop(comptime Frontend: type) type {
l.after();
}
if (s.env.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file);
- if (!link.gone) replica.bye(s.joined.fd, s.r.diverged != null or link.lagged != 0);
+ if (!link.gone) replica.bye(s.joined.fd, .{ .again = s.r.diverged != null or link.lagged != 0, .close = link.close });
// The link's reader ends with the link, posting as it goes:
// what it posted is let go until it has (a terminal's queue
// is bounded: a reader blocked on it would never end).
@@ -178,8 +224,11 @@ pub fn Loop(comptime Frontend: type) type {
}
// The session again, the core it leaves held meanwhile: its
// blobs are not sent again.
- s.r = replica.join(s.gpa, &s.joined, s.dial.path, s.dial.session, s.o, s.have, &s.why, s.r) orelse
- return if (replica.ended(&s.why)) .gone else .failed;
+ s.r = replica.join(s.gpa, &s.joined, s.dial.path, s.dial.session, s.o, s.have, &s.why, s.r) orelse {
+ if (replica.ended(&s.why)) return .gone;
+ if (replica.otherBuild(&s.why) and upgrade.replaced()) return .{ .upgrade = s.joined.view };
+ return .failed;
+ };
}
}
diff --git a/runtime/daemon.zig b/runtime/daemon.zig
index a2e890f9..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, &.{});
}
@@ -290,22 +290,42 @@ fn hello(fd: c_int, k: Kind, pid: libc.pid_t, named: []const u8, detached: bool)
/// This session's registration (`register`), which forkShell and the hosts
/// tell of their ptys; -1 with none (no daemon, or PARDES_DAEMON=off).
pub var link: c_int = -1;
-/// The daemon said `ok` to the hello, and the link has not ended since;
-/// `gone` once it has ended for good (`readNotes`).
-var up = std.atomic.Value(bool).init(false);
-var gone = std.atomic.Value(bool).init(false);
+/// The hello's answer, as the reader took it (`readNotes`): `up`, the
+/// daemon said `ok` and the link has not ended since; `gone`, it has ended
+/// for good; `asked` until either (and while a new daemon is dialled).
+const Answer = enum(u32) { asked, up, gone };
+var answer = std.atomic.Value(Answer).init(.asked);
/// The session is ending (`quit`): its link's end is no daemon's death.
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`), 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];
@@ -314,12 +334,22 @@ pub fn name() []const u8 {
/// Whether a daemon keeps this session: what Detach, and a terminal's end,
/// need, or the session would be left where nothing can attach to it. A
/// daemon just started answers the hello once it runs, so this waits for
-/// that answer (up to 2 s): never on a startup's path, only on those two.
+/// that answer, or the link's end, whenever they come: never on a startup's
+/// path, only on those two. The reader takes it: started here if the first
+/// frame has not started it yet.
pub fn kept() bool {
if (link < 0) return false;
- var waited: u32 = 0;
- while (!up.load(.acquire) and !gone.load(.acquire) and waited < 2000) : (waited += 1) sleepMs(1);
- return up.load(.acquire);
+ watch();
+ if (reader == null) return false;
+ const io = std.Io.Threaded.global_single_threaded.io();
+ while (answer.load(.acquire) == .asked) io.futexWaitUncancelable(Answer, &answer.raw, .asked);
+ return answer.load(.acquire) == .up;
+}
+
+/// The reader's word on the hello's answer, to `kept` waiting on it.
+fn settle(a: Answer) void {
+ answer.store(a, .release);
+ std.Io.Threaded.global_single_threaded.io().futexWake(Answer, &answer.raw, 1);
}
/// The name a session goes by: its 9P socket's (`--9p=`, `--detach=`), else
@@ -334,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;
}
@@ -373,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", &.{});
}
@@ -416,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) {
@@ -438,24 +468,50 @@ pub const Note = union(enum) {
pub const Joining = struct { fd: c_int, view: ?u8 = null };
-/// Hands every note the daemon sends on to `deliver`, on a thread of its
+/// Where every note the daemon sends goes, once `watch` has started the
+/// 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(ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void {
- if (link < 0 or reader != null) return;
- reader = std.Thread.spawn(.{}, readNotes, .{ link, ctx, deliver }) catch null;
+pub fn watch() void {
+ 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| {
var words = std.mem.tokenizeScalar(u8, got.words, ' ');
const verb = words.next() orelse "";
if (std.meta.stringToEnum(enum { ok, replica, adopted }, verb)) |v| switch (v) {
- .ok => up.store(true, .release),
+ .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 => {
@@ -470,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);
@@ -482,12 +538,12 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no
// link's end is what wakes this, never a timer. One that never took
// it (another build's daemon), or the session's own end, is not:
// an end begun while it dialled finds the new link (`quit`).
- if (!up.swap(false, .acq_rel) or quitting.load(.acquire) or !redial(fd) or quitting.load(.acquire)) break;
+ 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.
- gone.store(true, .release);
+ settle(.gone);
}
/// A new connection in the place of `fd`, the link (its number kept, so
@@ -498,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
@@ -758,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.
@@ -851,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;
};
@@ -876,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) {
@@ -886,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) {
@@ -1006,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;
@@ -1056,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]);
@@ -1184,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/macos.zig b/runtime/macos.zig
index cfe93b13..23d70b27 100644
--- a/runtime/macos.zig
+++ b/runtime/macos.zig
@@ -250,7 +250,7 @@ const State = struct {
io: std.Io,
core: *pardes.Pardes,
started: bool = false,
- runtime: Callbacks,
+ callbacks: Callbacks,
tag_cells: [pardes.MAX_TAG_LAYERS][]Cell = @splat(&.{}),
layer_cells: [pardes.MAX_PANES][]Cell = @splat(&.{}),
cells: []Cell = &.{},
@@ -290,9 +290,9 @@ const State = struct {
var state: ?State = null;
-export fn pardes_init(runtime: ?*const Callbacks, cols_arg: u16, rows_arg: u16) c_int {
+export fn pardes_init(callbacks: ?*const Callbacks, cols_arg: u16, rows_arg: u16) c_int {
if (state != null) return 1; // already up; deinit first
- initCore(runtime, cols_arg, rows_arg) catch |err| {
+ initCore(callbacks, cols_arg, rows_arg) catch |err| {
log.err("init failed: {t}", .{err});
return 2;
};
@@ -302,7 +302,7 @@ export fn pardes_init(runtime: ?*const Callbacks, cols_arg: u16, rows_arg: u16)
/// The shell's gpa in a Debug build, as std.start's is for the others.
var debug_gpa: std.heap.DebugAllocator(.{}) = .init;
-fn initCore(runtime: ?*const Callbacks, cols_arg: u16, rows_arg: u16) !void {
+fn initCore(callbacks: ?*const Callbacks, cols_arg: u16, rows_arg: u16) !void {
// The allocator every other shell gets from std.start: a DebugAllocator
// in Debug, libc's malloc otherwise. libc's measured at least as fast as
// std.heap.smp_allocator everywhere and faster on MuPDF's page-sized
@@ -348,6 +348,7 @@ fn initCore(runtime: ?*const Callbacks, cols_arg: u16, rows_arg: u16) !void {
pardes.syntax.start(allocs.tree_sitter);
errdefer pardes.syntax.stop();
+ opts.tape = pardes.tape.fromEnv();
const core = try pardes.Pardes.init(allocs.pardes, opts);
errdefer core.deinit();
// The workspace tag row is the macOS menu bar's business here (see
@@ -372,7 +373,7 @@ fn initCore(runtime: ?*const Callbacks, cols_arg: u16, rows_arg: u16) !void {
.core = core,
.config_arena = config_arena,
.prompt_rcs = prompt_rcs,
- .runtime = if (runtime) |r| r.* else .{},
+ .callbacks = if (callbacks) |c| c.* else .{},
};
const st = &state.?;
st.inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = io, .wake_fn = wakeHost, .wake_ctx = st };
@@ -682,7 +683,7 @@ fn reloadWatchedTheme(st: *State, announce: bool) bool {
live.retries_left = 0;
if (announce) {
var mbuf: [256]u8 = undefined;
- st.core.setMessage(.at(request.pane), message.stamp(&mbuf, "reloaded theme", request.path));
+ st.core.setMessage(request.pane, message.stamp(&mbuf, "reloaded theme", request.path));
}
return true;
}
@@ -1757,14 +1758,14 @@ fn dumpThemes(ctx: ?*anyopaque, id: pardes.Pane.Id) void {
fn setClipboard(ctx: ?*anyopaque, text: []const u8) void {
const st = hostState(ctx);
- const cb = st.runtime.set_clipboard orelse return;
- cb(st.runtime.userdata, text.ptr, text.len);
+ const cb = st.callbacks.set_clipboard orelse return;
+ cb(st.callbacks.userdata, text.ptr, text.len);
}
fn readClipboard(ctx: ?*anyopaque) void {
const st = hostState(ctx);
- const cb = st.runtime.read_clipboard orelse return;
- cb(st.runtime.userdata);
+ const cb = st.callbacks.read_clipboard orelse return;
+ cb(st.callbacks.userdata);
}
fn openLink(_: ?*anyopaque, url: []const u8) void {
@@ -1802,9 +1803,9 @@ fn wakeHost(ctx: ?*anyopaque) void {
}
fn wake(st: *State) void {
- const cb = st.runtime.wakeup orelse return;
+ const cb = st.callbacks.wakeup orelse return;
if (st.wake_pending.swap(true, .acq_rel)) return;
- cb(st.runtime.userdata);
+ cb(st.callbacks.userdata);
}
fn captureEnv(arena: std.mem.Allocator) ?std.process.Environ.Map {
@@ -2057,7 +2058,7 @@ test "mac queued results never cancel a newer LSP request" {
.threaded = undefined,
.io = std.testing.io,
.core = core,
- .runtime = .{},
+ .callbacks = .{},
.config_arena = .init(gpa),
.prompt_rcs = .{},
.inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = std.testing.io },
@@ -2100,7 +2101,7 @@ test "mac worker setup failures finish matching LSP and pipe requests" {
.threaded = undefined,
.io = failing_io,
.core = core,
- .runtime = .{},
+ .callbacks = .{},
.config_arena = .init(gpa),
.prompt_rcs = .{},
.inbox = .{ .gpa = failing.allocator(), .lsp_allocator = failing.allocator(), .io = failing_io },
@@ -2111,7 +2112,7 @@ test "mac worker setup failures finish matching LSP and pipe requests" {
const req: host_io.Lsp.Request = .{
.id = core.lsp_ask.wait.?.id,
.kind = .status,
- .pane = @intCast(core.view().active),
+ .pane = .at(core.view().active),
.offset = 0,
.arg = "",
};
@@ -2223,7 +2224,7 @@ test "mac Restore keeps host state and rejects callbacks from the old core" {
.threaded = undefined,
.io = std.testing.io,
.core = core,
- .runtime = .{},
+ .callbacks = .{},
.config_arena = .init(gpa),
.prompt_rcs = .{},
.inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = std.testing.io },
@@ -2265,8 +2266,8 @@ test "mac Restore keeps host state and rejects callbacks from the old core" {
.failure = .{ .kind = .exit, .code = 1, .stderr = try gpa.dupe(u8, "old filter failure") },
} });
}
- st.inbox.acceptReader(0, 23);
- _ = st.inbox.pushOutput(0, 23, try gpa.dupe(u8, "old PTY output"));
+ st.inbox.acceptReader(.at(0), 23);
+ _ = st.inbox.pushOutput(.at(0), 23, try gpa.dupe(u8, "old PTY output"));
core.update(.{ .command = try std.fmt.bufPrint(&command, "Restore .zig-cache/tmp/{s}/restore.zon", .{tmp.sub_path}) });
try std.testing.expect(restoreCore(&st));
try std.testing.expect(st.core != core);
@@ -2324,7 +2325,7 @@ test "mac Restore cancels a PTY reader waiting for output capacity" {
.threaded = undefined,
.io = io,
.core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }),
- .runtime = .{},
+ .callbacks = .{},
.config_arena = .init(gpa),
.prompt_rcs = .{},
.inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = io },
@@ -2336,8 +2337,8 @@ test "mac Restore cancels a PTY reader waiting for output capacity" {
try dump.dumpState(st.core);
try tmp.dir.writeFile(io, .{ .sub_path = "restore.zon", .data = st.core.dump_out.? });
while (st.core.nextEffect()) |_| {}
- st.inbox.acceptReader(1, 1);
- for (0..Inbox.output_capacity) |_| _ = st.inbox.pushOutput(1, 1, try gpa.dupe(u8, "retained output"));
+ st.inbox.acceptReader(.at(1), 1);
+ for (0..Inbox.output_capacity) |_| _ = st.inbox.pushOutput(.at(1), 1, try gpa.dupe(u8, "retained output"));
const child = try host_io.forkShell(null, 0, &st.prompt_rcs, "/bin/sh", "", 12, 40);
st.gens[0] = 1;
st.ptys[0] = .{ .file = child.file, .pid = child.pid, .gen = 1, .reader = .{ .any_future = null, .result = {} } };
@@ -2361,8 +2362,8 @@ test "mac Restore cancels a PTY reader waiting for output capacity" {
try std.testing.expect(st.ptys[0] == null);
try std.testing.expectEqual(@as(usize, 0), st.inbox.len);
try std.testing.expectEqual(@as(u16, 0), st.inbox.space.state.load(.acquire).waiters);
- st.inbox.acceptReader(0, st.gens[0]);
- _ = st.inbox.pushOutput(0, st.gens[0], try gpa.dupe(u8, "fresh output"));
+ st.inbox.acceptReader(.at(0), st.gens[0]);
+ _ = st.inbox.pushOutput(.at(0), st.gens[0], try gpa.dupe(u8, "fresh output"));
var batch = st.inbox.take();
defer for (batch.slice()) |msg| msg.deinit(gpa, gpa);
try std.testing.expectEqual(@as(usize, 1), batch.len);
@@ -2626,7 +2627,7 @@ test "mac row metrics ABI preserves PDF cell dimensions and the unrendered grid"
const gpa = std.testing.allocator;
const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer core.deinit();
- state = .{ .gpa = gpa, .threaded = undefined, .io = std.testing.io, .core = core, .runtime = .{}, .config_arena = .init(gpa), .prompt_rcs = .{} };
+ state = .{ .gpa = gpa, .threaded = undefined, .io = std.testing.io, .core = core, .callbacks = .{}, .config_arena = .init(gpa), .prompt_rcs = .{} };
defer {
state.?.config_arena.deinit();
state = null;
@@ -2645,7 +2646,7 @@ test "mac tag layer ABI preserves logical capacity and physical grip" {
const gpa = std.testing.allocator;
const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 8, .rows = 3 });
defer core.deinit();
- state = .{ .gpa = gpa, .threaded = undefined, .io = std.testing.io, .core = core, .runtime = .{}, .config_arena = .init(gpa), .prompt_rcs = .{} };
+ state = .{ .gpa = gpa, .threaded = undefined, .io = std.testing.io, .core = core, .callbacks = .{}, .config_arena = .init(gpa), .prompt_rcs = .{} };
defer {
for (state.?.tag_cells) |cells| gpa.free(cells);
state.?.config_arena.deinit();
diff --git a/runtime/main.zig b/runtime/main.zig
index 29c19bc0..0751f6b0 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",
@@ -1157,6 +1159,13 @@ fn nativeMain(std_init: std.process.Init) !void {
upgrade.resumed = upgrade.Record.decode(args[1][upgrade.flag.len..]) catch badArgs(init.io, "--upgraded: a record this build cannot read", .{});
};
const resuming = upgrade.resumed != null;
+ // A window's pair's session (`pair`): the pardes beside a pardes-gui,
+ // exec'd in its child, its first client on the fd named, the window's
+ // arguments after it.
+ const paired: ?c_int = if (!resuming and args.len > 1 and std.mem.startsWith(u8, args[1], upgrade.paired_flag))
+ std.fmt.parseInt(c_int, args[1][upgrade.paired_flag.len..], 10) catch badArgs(init.io, "{s}: not a descriptor", .{args[1]})
+ else
+ null;
var session_only = true;
var new_session = false;
// `pardes new`: with --detach it returns once the session runs.
@@ -1166,21 +1175,29 @@ fn nativeMain(std_init: std.process.Init) !void {
var attach: ?[]const u8 = null;
var positional: ?[:0]const u8 = null;
var wait = false;
- var i: usize = if (resuming) 2 else 1;
+ var i: usize = if (resuming or paired != null) 2 else 1;
+ // An upgraded session's arguments are the ones it was started with: its
+ // `new` is the verb still, not a file's name (taken for one, the file
+ // after it was "the second" and the session ended at its Upgrade).
+ if (resuming and args.len > i and std.meta.stringToEnum(Cmd, args[i]) == .new) {
+ new_session = true;
+ new_verb = true;
+ i += 1;
+ }
// A command's name first: new and attach go on to start or join a
// session, with the flags after them; the rest are done in `command`.
- if (!resuming and args.len > 1) if (std.meta.stringToEnum(Cmd, args[1])) |cmd| switch (cmd) {
+ if (!resuming and args.len > i) if (std.meta.stringToEnum(Cmd, args[i])) |cmd| switch (cmd) {
.new => {
new_session = true;
new_verb = true;
- i = 2;
+ i += 1;
},
.attach => {
- const named = args.len > 2 and args[2].len > 0 and args[2][0] != '-';
- attach = if (named) args[2] else "";
- i = if (named) 3 else 2;
+ const named = args.len > i + 1 and args[i + 1].len > 0 and args[i + 1][0] != '-';
+ attach = if (named) args[i + 1] else "";
+ i += if (named) 2 else 1;
},
- else => runCommand(init, cmd, args[2..]),
+ else => runCommand(init, cmd, args[i + 1 ..]),
};
while (i < args.len) : (i += 1) {
const a = args[i];
@@ -1521,11 +1538,8 @@ fn nativeMain(std_init: std.process.Init) !void {
// detached session, as `pardes --detach` (`ps` says tty), its
// windows clients. Without one there, it carries on as a window's.
if (comptime pardes.platform == .gui) if (!resuming) {
- var exe: [4096]u8 = undefined;
- const n = std.c.readlink("/proc/self/exe", &exe, exe.len);
- if (n > 0) if (std.Io.Dir.path.dirname(exe[0..@intCast(n)])) |bin| if (args.len < 64) {
- var path_buf: [4104]u8 = undefined;
- const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/pardes", .{bin}, 0) catch unreachable; // 4096 + 8 fits
+ var path_buf: [4104]u8 = undefined;
+ if (pardesBeside(&path_buf)) |path| if (args.len < 64) {
var argv: [64:null]?[*:0]const u8 = @splat(null);
argv[0] = path.ptr;
for (args[1..], 1..) |a, k| argv[k] = a.ptr;
@@ -1566,15 +1580,25 @@ 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);
- } else if (pardes.platform == .tui and detach == null and std.c.getenv("PARDES_PAIR") != null) {
+ 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, .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 a client of a session forked off for it (`pair`).
- pair(init, &opts);
+ // this terminal or window a client of a session forked off for it
+ // (`pair`).
+ pair(init, &opts, args);
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
@@ -1598,7 +1622,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 } };
}
}
@@ -1650,7 +1674,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,
@@ -1708,23 +1737,48 @@ fn commOf(io: std.Io, pid: []const u8, buf: *[64]u8) []const u8 {
return std.mem.trimEnd(u8, std.Io.Dir.cwd().readFile(io, path, buf) catch return "", "\n");
}
-/// PARDES_PAIR: `pardes` in a terminal as a session and its first client
-/// over a socket pair (docs/next-run.md; the last step's design, 1.1). The
-/// daemon dialled first, as for a stub; then a fork: the parent the CLIENT
-/// (the shell's job, the terminal its own; signals reach what draws), its
-/// first join on its end of the pair; the child the SESSION (setsid, 0, 1
-/// and 2 on /dev/null, detached), its end of the pair its first client,
-/// taken before its first effects (runtime/session.zig). Returns in the
-/// session; the client exits. No fork to be had: returns, and this process
-/// is the session, with no terminal: said by the caller's run.
-fn pair(init: std.process.Init, opts: *pardes.Options) void {
- const conn: ?c_int = if (daemon.wanted()) daemon.connect(true) else null;
+/// The terminal's binary beside this one, as /proc names this one (Linux),
+/// in `buf`.
+fn pardesBeside(buf: *[4104]u8) ?[:0]const u8 {
+ var exe: [4096]u8 = undefined;
+ const n = std.c.readlink("/proc/self/exe", &exe, exe.len);
+ if (n <= 0) return null;
+ const bin = std.Io.Dir.path.dirname(exe[0..@intCast(n)]) orelse return null;
+ return std.fmt.bufPrintSentinel(buf, "{s}/pardes", .{bin}, 0) catch unreachable; // 4096 + 8 fits
+}
+
+/// PARDES_PAIR: `pardes` in a terminal, or `pardes-gui`, as a session and
+/// its first client over a socket pair (docs/next-run.md; the last step's
+/// design, 1.1 and 1.2). The daemon dialled first, as for a stub; then a
+/// fork: the parent the CLIENT (the shell's job, the terminal its own,
+/// signals reach what draws; or the window), its first join on its end of
+/// the pair; the child the SESSION (setsid, 0, 1 and 2 on /dev/null,
+/// detached), its end of the pair its first client, taken before its first
+/// effects (runtime/session.zig). A window's child execs the `pardes`
+/// beside it (`--paired=FD` first, its arguments after), which dials the
+/// daemon itself: a window's session loop is woken through SDL (gui.zig
+/// `sdlWake`), a terminal's needs none. Returns in a terminal's session;
+/// the client exits. No fork to be had: returns, and this process is the
+/// session, with no terminal: said by the caller's run. A window with no
+/// `pardes` beside it returns at once, its own session as before.
+fn pair(init: std.process.Init, opts: *pardes.Options, args: []const [:0]const u8) void {
+ var path_buf: [4104]u8 = undefined;
+ var fd_buf: [32]u8 = undefined;
+ var argv: [64:null]?[*:0]const u8 = @splat(null);
+ if (pardes.platform == .gui) {
+ const path = pardesBeside(&path_buf) orelse return;
+ if (args.len >= argv.len - 1 or std.c.access(path, std.c.X_OK) != 0) return;
+ argv[0] = path.ptr;
+ for (args[1..], 2..) |a, k| argv[k] = a.ptr;
+ }
+ const conn: ?c_int = if (pardes.platform == .tui and daemon.wanted()) daemon.connect(true) else null;
var fds: [2]c_int = undefined;
if (std.c.socketpair(std.c.AF.UNIX, std.c.SOCK.STREAM | std.c.SOCK.CLOEXEC, 0, &fds) != 0)
die(init.io, "no socket pair for a session and its terminal", .{});
+ if (pardes.platform == .gui) argv[1] = (std.fmt.bufPrintSentinel(&fd_buf, upgrade.paired_flag ++ "{d}", .{fds[0]}, 0) catch unreachable).ptr; // an fd fits 32
// The session laid out at the terminal's size: no reflow at the join.
var ws: std.posix.winsize = undefined;
- if (std.c.ioctl(0, std.posix.T.IOCGWINSZ, &ws) == 0 and ws.col > 0 and ws.row > 0) {
+ if (pardes.platform == .tui and std.c.ioctl(0, std.posix.T.IOCGWINSZ, &ws) == 0 and ws.col > 0 and ws.row > 0) {
opts.cols = ws.col;
opts.rows = ws.row;
}
@@ -1738,10 +1792,16 @@ fn pair(init: std.process.Init, opts: *pardes.Options) void {
_ = std.c.dup2(null_fd, @intCast(i));
};
if (null_fd > 2) _ = std.c.close(null_fd);
+ if (pardes.platform == .gui) {
+ // Its end of the pair across the exec.
+ _ = std.c.fcntl(fds[0], std.c.F.SETFD, @as(c_int, 0));
+ _ = execvp(argv[0].?, &argv);
+ std.c._exit(127);
+ }
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]);
@@ -1752,7 +1812,7 @@ fn pair(init: std.process.Init, opts: *pardes.Options) void {
var sock_buf: [ninep_io.sun_path_len:0]u8 = undefined;
var o = opts.*;
o.pair = fds[1];
- @import("dev").tui.runClient(init, o, daemon.replicaSocket(&sock_buf) orelse "", name, false) catch |err| die(init.io, "{t}", .{err});
+ clientOf(init, o, daemon.replicaSocket(&sock_buf) orelse "", name, false) catch |err| die(init.io, "{t}", .{err});
std.process.exit(0);
}
@@ -1842,8 +1902,11 @@ fn attachClient(init: std.process.Init, opts: pardes.Options, where: []const u8,
Ssh.child = pid;
Ssh.path = here;
_ = atexit(Ssh.end);
+ // Its file is there a moment before ssh listens on it: until a
+ // connect answers.
var waited: u32 = 0;
- while (std.meta.isError(std.Io.Dir.cwd().access(io, here, .{}))) : (waited += 1) {
+ const probe = while (true) : (waited += 1) {
+ if (cloud9.transport.connectFd(.{ .unix = here }, cloud9.transport.nowMs() + 100)) |fd| break fd else |_| {}
var status: c_int = 0;
if (std.c.waitpid(pid, &status, std.c.W.NOHANG) == pid) {
Ssh.child = 0;
@@ -1852,7 +1915,8 @@ fn attachClient(init: std.process.Init, opts: pardes.Options, where: []const u8,
if (waited > 3000) die(io, "--attach: ssh to {s} set up no forward in 30 s", .{where});
const ts: std.c.timespec = .{ .sec = 0, .nsec = 10 * std.time.ns_per_ms };
_ = std.c.nanosleep(&ts, null);
- }
+ };
+ _ = std.c.close(probe);
clientOf(init, opts, here, name, true) catch |err| die(io, "--attach: {t}", .{err});
std.process.exit(0);
}
@@ -1894,7 +1958,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;
}
@@ -1907,6 +1971,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 5d7eff78..60644aa6 100644
--- a/runtime/session.zig
+++ b/runtime/session.zig
@@ -6,10 +6,10 @@
//! posts, `Inbox`), its ptys (`Ptys`) and the files it watches
//! (`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`);
-//! the language servers' answers come through its queue (`Inbox.startLsp`).
-//! What a frontend does is:
+//! parts end in. Its workers (a language server's query, the pipes, the
+//! addons' jobs and draws, a search) answer through its queue, which holds
+//! their tasks and ends them (`Inbox.land`, `Inbox.deinit`); the session's
+//! own input is its frontend's (each `Shell`). What a frontend does is:
//!
//! - `options(o)`: before the core: what it gives the core it starts (a
//! window's size, for a dump's layout).
@@ -25,8 +25,6 @@
//! session's first wait (`l.watch`).
//! - `sent()`: after each step's unit went to the clients.
//! - `upgradeAsked()`: an Upgrade asked in the step, done (it execs).
-//! - `note(n)`: what the daemon says (an adopted shell, a client's
-//! connection, a new daemon's hello taken), onto its queue.
//! - `restoring(nc)`, `restored(l)`: a Restore's new core, before it
//! replaces the old one (its devices let go, what it is told of the
//! frontend) and after (its own view of it again).
@@ -75,6 +73,7 @@ pub fn Loop(comptime Frontend: type) type {
o.tree_sitter_allocator = l.allocs.tree_sitter;
o.frame_allocator = l.allocs.frame;
fe.options(&o);
+ o.tape = pardes.tape.fromEnv();
l.core = if (upgrade.resumed) |*rec|
try upgrade.load(l.gpa, l.allocs.pardes, o, rec)
else if (o.load_path) |lp| blk: {
@@ -90,6 +89,8 @@ 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();
+ // A search's worker may be waiting on the queue for room.
+ defer l.core.stream.cancelTask();
// 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);
@@ -103,6 +104,10 @@ pub fn Loop(comptime Frontend: type) type {
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).
@@ -126,8 +131,9 @@ pub fn Loop(comptime Frontend: type) type {
// Its unit to each replica client, and theirs taken in.
l.peers.boundary(l.core);
// A pair's session with no daemon ends with its last link:
- // nothing could attach to it again.
- if (o.pair != null and daemon.link < 0 and l.peers.count() == 0) break;
+ // nothing could attach to it again; with one, when its last
+ // 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
@@ -154,17 +160,28 @@ pub fn Loop(comptime Frontend: type) type {
while (l.core.nextEffect()) |e| l.core.perform(e);
}
- /// What the daemon says, onto the frontend's queue (once: its
+ /// What the daemon says, onto the session's queue (once: its
/// reader is started by the first call); and a daemon started
/// since the last one died told the shells' masters it held.
pub fn watch(l: *L) void {
if (daemon.relinked()) l.ptys.tellDaemon();
- daemon.watch(l.fe, note);
+ daemon.watch();
}
+ /// The daemon's thread: an adopted shell onto the queue (taken
+ /// in the frontend's wait), a client's connection to `Peers`
+ /// (joined at the next step boundary), a new daemon's hello taken
+ /// a wake (`watch` tells it the rest).
fn note(ctx: *anyopaque, n: daemon.Note) void {
- const fe: *Frontend = @ptrCast(@alignCast(ctx));
- fe.note(n);
+ const l: *L = @ptrCast(@alignCast(ctx));
+ switch (n) {
+ .relinked => l.inbox.wake(),
+ .adopted => |a| {
+ for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| l.inbox.push(.{ .adopted = .{ .pid = pid, .fd = fd } });
+ l.inbox.push(.{ .adopted = .{ .pid = 0, .fd = -1 } });
+ },
+ .replica => |j| l.peers.handed(j.fd, j.view),
+ }
}
/// A Restore: the core its dump makes replaces this one, its clients
@@ -173,7 +190,9 @@ 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.
+ // The old core's pipes end, and an answer to its query is
+ // turned away.
+ l.inbox.pipe_tasks.cancelAll(l.io);
l.inbox.discardCompletions();
l.ptys.stop();
nc.host = l.host;
diff --git a/runtime/upgrade.zig b/runtime/upgrade.zig
index 2a8d6edf..f59117ee 100644
--- a/runtime/upgrade.zig
+++ b/runtime/upgrade.zig
@@ -19,9 +19,13 @@ 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=";
+/// A window's pair's session's first word (main.zig `pair`): its first
+/// client's fd, which an Upgrade does not name again (that client joined).
+pub const paired_flag = "--paired=";
/// What this build says it is (`pardes --version`'s first line).
pub const version_line = if (pardes.commit) |c| "pardes " ++ pardes.version ++ " (" ++ c ++ ")" else "pardes " ++ pardes.version;
@@ -46,6 +50,7 @@ var located = false;
/// deleted).
pub fn remember(args: []const [:0]const u8) void {
given = if (args.len > 1 and std.mem.startsWith(u8, args[1], flag)) args[2..] else if (args.len > 0) args[1..] else &.{};
+ if (given.len > 0 and std.mem.startsWith(u8, given[0], paired_flag)) given = given[1..];
if (resumed) |*rec| if (rec.exe.len > 0 and rec.exe.len < exe_buf.len) {
@memcpy(exe_buf[0..rec.exe.len], rec.exe);
exe_buf[rec.exe.len] = 0;
@@ -91,6 +96,14 @@ pub fn newer() bool {
return true;
}
+/// Another file at its start path than the one it started from: a build
+/// installed there since (`locate` first). A client's question at an
+/// Upgrade (client.zig).
+pub fn replaced() bool {
+ const was = started_inode orelse return false;
+ return (inodeOf(exe() orelse return false) orelse return false) != was;
+}
+
pub fn exe() ?[:0]const u8 {
return if (exe_len == 0) null else exe_buf[0..exe_len :0];
}
@@ -128,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;
@@ -165,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 });
}
@@ -179,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),
@@ -213,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,
}
@@ -371,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";
@@ -441,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);
@@ -462,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/consumer/build.zig b/test/consumer/build.zig
index ca63bb6e..c643bfb3 100644
--- a/test/consumer/build.zig
+++ b/test/consumer/build.zig
@@ -1,5 +1,5 @@
//! A package that depends on pardes, as a program would (build.zig's head
-//! comment has its lines): pardes's `lib-test`, which `unit-test` runs,
+//! comment has its lines): pardes's `consumer-test`, which `unit-test` runs,
//! runs `zig build test` here. `pardes-syntax` with the minimal grammars,
//! as a program that draws source text itself takes it; and
//! `pardes-editor` with no grammar of pardes's and one of its own, C's,
diff --git a/test/daemon.py b/test/daemon.py
index 11c98cd6..37487a99 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -30,7 +30,8 @@ private HOME and runtime directory:
python3 -B test/daemon.py --pair <pardes>
PARDES_PAIR: a terminal's session and its first client
python3 -B test/daemon.py --relink <pardes>
- the daemon killed: its sessions register again with the next
+ the daemon killed: its sessions register again with the next; and
+ one stopped: an Adopt waits for its answer to the hello
python3 -B test/daemon.py --far <pardes>
the far clients and their blob cache alone, one under `yes` across
a slow link, and a file by its hash
@@ -241,7 +242,7 @@ class Replica:
"""A replica's connection (abi/wire.zig): length-prefixed
messages, a tag byte and a little-endian u32 length. It is a near
client: its first word after the hello says so."""
- WIRE = 24
+ WIRE = 26
def __init__(self, path, timeout=10):
self.path, self.timeout = path, timeout
@@ -635,7 +636,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')
@@ -653,12 +654,16 @@ def pair(binary):
c2 = lone.spawn([binary, '--9p=lone', str(notes)], dict(env, PARDES_DAEMON='off'))
nine2, session2 = session_of('lone')
wait_for('the lone pair drawn', lambda: b'line 3 of the notes' in lone.text(), timeout=30)
+ # An Upgrade refused, with why: its client could not find it again.
+ nine2.write('/ctl', b'Upgrade\n')
+ wait_for('the Upgrade refused', lambda: 'its client could not join it again' in screen_text(nine2), timeout=20)
+ assert alive(session2) and c2.poll() is None
nine2.socket.close()
os.kill(c2.pid, signal.SIGKILL)
c2.wait(timeout=10)
wait_for('the lone session ended with its last link', lambda: not alive(session2), timeout=20)
wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
- print(f'pair: with no daemon, client {c2.pid} killed outright, its session {session2} ended; nothing left behind')
+ print(f'pair: with no daemon, an Upgrade refused in words; client {c2.pid} killed outright, its session {session2} ended; nothing left behind')
finally:
for p in processes(root):
try:
@@ -672,12 +677,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))
@@ -693,6 +699,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)
@@ -713,30 +725,120 @@ 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())
+ # Started by `new` with a file: an Upgrade keeps it (its `new` is the
+ # verb still: taken for a file's name, the file was "the second" and
+ # the session ended), and it is attached to after.
+ upgraded('kd', Client(root / 'pardes-9p-kd.sock'), kd).socket.close()
+ assert alive(kd) and state_of('kd') == '(tty, kept)', listed()
+ ended_by('TERM', *attached('kd'))
+ assert alive(kd) and state_of('kd') == '(tty, kept)', listed()
+ print('pair rows: `new --detach` with a file: an Upgrade keeps it, and it is attached to after')
+ 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)
@@ -972,6 +1074,78 @@ def relink(binary):
shutil.rmtree(root, ignore_errors=True)
+def answer_late(binary):
+ """A session's Adopt asked at once, while its daemon has not answered
+ its hello (stopped 3 s, as a loaded machine can keep it), and before
+ the session's reader of the daemon has run: answered when the daemon
+ answers, never refused on a clock (daemon.zig `kept`)."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='ra-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ started = []
+ terms = []
+ wake = None
+ try:
+ term = Term()
+ terms.append(term)
+ stub = term.spawn([binary, '--tty', '--9p=one'], env)
+ started.append(stub.pid)
+ wait_for('the first session', (root / 'pardes-9p-one.sock').exists)
+ one = Client(root / 'pardes-9p-one.sock')
+ session = int(dict(line.split(maxsplit=1) for line in one.read('/status').decode().splitlines())['pid'])
+ started.append(session)
+ shell_pid = int(run(one, terminals(one)[0], b'echo $$\n').split(b'\n')[1])
+ started.append(shell_pid)
+ daemon = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']][0]
+ started.append(daemon)
+ wait_for('its shell listed', lambda: f'shell {shell_pid}' in subprocess.run(
+ [binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())
+ os.kill(session, signal.SIGKILL)
+ one.socket.close()
+ wait_for('the killed session gone', lambda: not alive(session))
+ os.kill(daemon, signal.SIGSTOP)
+ wake = threading.Timer(3, lambda: os.kill(daemon, signal.SIGCONT))
+ wake.start()
+ term = Term()
+ terms.append(term)
+ stub = term.spawn([binary, '--tty', '--9p=two'], env)
+ started.append(stub.pid)
+ wait_for('the next session', (root / 'pardes-9p-two.sock').exists)
+ two = Client(root / 'pardes-9p-two.sock', timeout=30)
+ started.append(int(dict(line.split(maxsplit=1) for line in two.read('/status').decode().splitlines())['pid']))
+ before = set(terminals(two))
+ asked = time.monotonic()
+ two.write(f'/pane/{min(before)}/exec', b'Adopt\n')
+ took = time.monotonic() - asked
+ pane = wait_for('the adopted pane', lambda: set(terminals(two)) - before).pop()
+ assert run(two, pane, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode()
+ print(f'answer late: an Adopt asked while the daemon was stopped waited {took:.1f} s for its answer, '
+ f'and shell {shell_pid} was adopted')
+ exit_session(two, pane)
+ two.socket.close()
+ wait_for('the shells hung up', lambda: not alive(shell_pid))
+ wait_for('the daemon gone once idle', lambda: not alive(daemon), timeout=5)
+ finally:
+ if wake:
+ wake.cancel()
+ for t in terms:
+ try:
+ t.close()
+ except OSError:
+ pass
+ for pid in started + processes(root):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
class Window:
"""A pardes-gui in test mode, its window offscreen and hidden, its keys
written to its stdin (the test feed: Escape as `CSI 27 u`, which a
@@ -1419,12 +1593,13 @@ def far(binary):
f_join = joins(root / 'f.stats')[0]
assert f_join['from_disk'] > 0 and cached(cache) <= (1 << 20) + (64 << 10), (f_join, cached(cache))
far_joins(root / 'pardes-replica.sock', 'files', binary, 200)
- # Through ssh (a stand-in forwarding as `ssh -L` does): a client
- # refused and one detached each end their ssh and its socket (one
- # refused left both, 2026-10-30).
+ # Through ssh (a stand-in forwarding as `ssh -L` does, its socket
+ # bound 0.5 s before it listens: the client dials until it answers):
+ # a client refused and one detached each end their ssh and its
+ # socket (one refused left both, 2026-10-30).
fake = root / 'ssh'
fake.write_text('#!/bin/sh\nwhile [ $# -gt 0 ]; do case $1 in -L) fwd=$2; shift;; esac; shift; done\n'
- f'exec {sys.executable} -B {Path(__file__).parent / "delay_relay.py"} "${{fwd%%:*}}" "${{fwd#*:}}" --delay 0\n')
+ f'exec {sys.executable} -B {Path(__file__).parent / "delay_relay.py"} "${{fwd%%:*}}" "${{fwd#*:}}" --delay 0 --bound 500\n')
fake.chmod(0o755)
senv = dict(env, PARDES_SSH=str(fake), PARDES_REMOTE_RUNTIME=str(root), TMPDIR=str(root))
@@ -1739,6 +1914,138 @@ def games(binary, libs, secs=10):
shutil.rmtree(root, ignore_errors=True)
+def far_find(binary):
+ """A far client types a query into a Find over 40,000 names: each key
+ scores the names again a slice at a time (core/Names.zig `rescore`),
+ the client's guess of the key first. The slice is a count, the same on
+ both sides, so no guess is wrong (a slice the clock ended was the
+ client's clock's verdict, which the session's own contradicted)."""
+ 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))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_REPLICA_FAR='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ tree = root / 'tree'
+ for d in range(200):
+ (tree / f'module_{d}').mkdir(parents=True)
+ for f in range(200):
+ (tree / f'module_{d}' / f'replica_{f}.zig').touch()
+ notes = tree / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
+ started, terms = [], []
+ try:
+ sess = subprocess.Popen([binary, '--detach=find', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
+ started.append(sess.pid)
+ wait_for('the replica socket', (root / 'pardes-replica.sock').exists)
+ wait_for('the session\'s 9P socket', (root / 'pardes-9p-find.sock').exists)
+ nine = Client(root / 'pardes-9p-find.sock')
+ text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ t = Term(30, 100)
+ terms.append(t)
+ c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:find'],
+ dict(env, PARDES_REPLICA_CHECK=str(root / 'q.check'), PARDES_REPLICA_STATS=str(root / 'q.stats')))
+ started.append(c.pid)
+ wait_for('the client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=30)
+ time.sleep(.3)
+ # SPC f f: the Find, typed into, its names walked on the session's worker.
+ os.write(t.master, b' ff')
+ time.sleep(3)
+ wait_for('the client agrees once the walk is done', lambda: agreed(root / 'q.check', 0), timeout=60)
+ query = b'module_19/replica_3'
+ for ch in query:
+ os.write(t.master, bytes([ch]))
+ time.sleep(.15)
+ seen = len(checks(root / 'q.check'))
+ wait_for('the client agrees once quiet', lambda: agreed(root / 'q.check', seen), timeout=60)
+ c.send_signal(signal.SIGHUP)
+ c.wait(timeout=20)
+ line = (root / 'q.stats').read_text().split()
+ got = {line[i]: line[i + 1] for i in range(0, len(line) - 1, 2)}
+ print(f'daemon: a far client typed {len(query)} keys into a Find over 40,000 names: of its {got["inputs"]} inputs '
+ f'{got["mispredicted"]} mispredicted, {got["stopped"]} stopped, {got["fast"]} applied at once')
+ assert got['mispredicted'] == '0', got
+ exit_session(nine, text)
+ sess.wait(timeout=60)
+ nine.socket.close()
+ finally:
+ for term in terms:
+ term.close()
+ for pid in started + processes(root):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
+def restore_client(binary):
+ """A Restore while a client is attached: the client is let go (its link
+ ends), the replacement core is the session's (its tape adopts it, its
+ options keep none), and a client attached after agrees with it, its
+ keys reaching it."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rr-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
+ started, terms = [], []
+ try:
+ sess = subprocess.Popen([binary, '--detach=back', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
+ started.append(sess.pid)
+ wait_for('the replica socket', (root / 'pardes-replica.sock').exists)
+ wait_for('the session\'s 9P socket', (root / 'pardes-9p-back.sock').exists)
+ nine = Client(root / 'pardes-9p-back.sock')
+ text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ def client(name):
+ t = Term(30, 100)
+ terms.append(t)
+ c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:back'],
+ dict(env, PARDES_REPLICA_CHECK=str(root / f'{name}.check')))
+ started.append(c.pid)
+ wait_for(f'client {name}\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=30)
+ time.sleep(.3)
+ return t, c
+ t, c = client('a')
+ nine.write(f'/pane/{text}/exec', b'Dump\n')
+ nine.write(f'/pane/{text}/exec', b'Restore\n')
+ wait_for('client a let go at the Restore', lambda: c.poll() is not None, timeout=30)
+ # The 9P link was the old core's.
+ nine.socket.close()
+ nine = reconnect(root / 'pardes-9p-back.sock')
+ text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ t, c = client('r')
+ os.write(t.master, b'Oafter the restore\x1b')
+ texts = lambda: b''.join(nine.read(f'/pane/{row.split()[0].decode()}/body') for row in nine.read('/index').splitlines()
+ if row.split()[1] == b'text')
+ wait_for('the client\'s keys in the restored session', lambda: b'after the restore' in texts(), timeout=30)
+ seen = len(checks(root / 'r.check'))
+ wait_for('the client agrees once quiet', lambda: agreed(root / 'r.check', seen), timeout=60)
+ assert c.poll() is None, 'the client ended'
+ print(f'daemon: a Restore with a client attached: it was let go, and one attached after agreed ({len(checks(root / "r.check"))} checks), its keys in the restored session')
+ exit_session(nine, text)
+ sess.wait(timeout=60)
+ nine.socket.close()
+ finally:
+ for term in terms:
+ term.close()
+ for pid in started + processes(root):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
def far_joins(sock, session, binary, n):
"""`n` far joins of one session in a row, each read whole (its blobs
asked for by none, its zstd frames unpacked) and answering a ping, then
@@ -1840,6 +2147,7 @@ def main(binary, cycles):
pair_rows(binary)
manage(binary)
relink(binary)
+ answer_late(binary)
shell = terminals(client)[0]
shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1])
started.append(shell_pid)
@@ -2121,6 +2429,108 @@ def gui(binary, cycles):
shutil.rmtree(root, ignore_errors=True)
+def gui_pair(gui_binary):
+ """PARDES_PAIR in a window (the last step's design, 1.2): `pardes-gui
+ FILE` is a window client and a session with no SDL, the `pardes` beside
+ it exec'd in a child (a window's session needs SDL for its wake, a
+ terminal's binary none): the session the window's child, in a session
+ of its own, listed detached with the window its client; the file in
+ the window's first frame, keys in. The window's close ends the session,
+ its last client (a CLOSE); the window killed leaves it running (a LOSS),
+ and with no daemon the session ends with its last link. Test mode:
+ hidden windows, offscreen."""
+ binary = gui_binary.replace('pardes-gui', 'pardes')
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rgp-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_DAEMON='on', TERM='xterm-256color', PARDES_PAIR='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
+ windows = []
+
+ def listed():
+ return subprocess.run([binary, 'ps'], env=env, capture_output=True, timeout=30).stdout.decode()
+
+ def started(name, e):
+ w = Window(root, name, [gui_binary, f'--9p={name}', str(notes)], e)
+ windows.append(w)
+ sock = root / f'pardes-9p-{name}.sock'
+ wait_for(f'session {name}\'s 9P socket', sock.exists, timeout=30)
+ nine = Client(sock)
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ assert session != w.pid and ppid(session) == w.pid and os.getsid(session) == session, (session, w.pid)
+ assert Path(cmdline(session)[0].decode()).name == 'pardes', ('the session is the pardes beside it', cmdline(session))
+ wait_for('the window\'s first frame', lambda: (root / name / 'latest.ppm').exists(), timeout=30)
+ pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ assert nine.read(f'/pane/{pane}/body').startswith(b'line 0 of the notes'), 'the file is the session\'s'
+ return w, nine, session, pane
+
+ try:
+ w, nine, session, pane = started('gp', env)
+ 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'))
+ # The close button (the test feed's word for it): its last client
+ # closed, the session ends.
+ 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 session ended with its window', lambda: not alive(session), timeout=20)
+ nine.socket.close()
+ print(f'pair window: client {w.pid} (the window) and session {session} (the pardes beside it, exec\'d in its child, '
+ 'setsid, listed detached with the window); drawn, typed; the window closed ended both')
+ w, nine, session, pane = started('gl', env)
+ wait_for('the client listed', lambda: f'client {w.pid} ' in listed())
+ 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)' 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)
+ w.p.wait(timeout=10)
+ wait_for('the lone session ended with its last link', lambda: not alive(session), timeout=20)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
+ print('pair window: with no daemon, the window killed, its session ended; nothing left behind')
+ finally:
+ for w in windows:
+ if w.p.poll() is None:
+ w.p.kill()
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
def screen_text(client):
shown = client.screen()
cells = ''.join(cell[0] for cell in shown['cells'])
@@ -2301,7 +2711,9 @@ def upgrades(old, new):
# its terminal and its stub's pipe let go once its stub is told
# (two fewer).
def level():
- gone = 2 if b'detached from' in term2.text() else 1
+ # (A client of a build that execs at an Upgrade comes back: its
+ # connection is the session's again.)
+ gone = 2 if b'detached from' in term2.text() else 0 if knows_exec(old) and stub2.poll() is None else 1
return fds_before[0] - 2 - gone + min(state_fds(session), 1) - state_before, fds_before[1]
try:
wait_for('the fds level', lambda: (fds(session), fds(daemon)) == level(), timeout=5)
@@ -2321,7 +2733,9 @@ def upgrades(old, new):
# build's own, let go (a session shows one frontend of its own now),
# its stub told.
wait_for('the second terminal redrawn or let go', lambda: b'\x1b[?1049h' in term2.text()[before[1]:] or
- (stub2.poll() is not None and (b'detached from' in term2.text() or b'upgrade this client too' in term2.text())))
+ (stub2.poll() is not None and (b'detached from' in term2.text() or b'upgrade this client too' in term2.text()
+ or b'run the same pardes at both ends' in term2.text())),
+ timeout=30)
wait_for('the word said', lambda: 'Upgrade: now pardes' in screen_text(client))
# The daemon lists the session under its new build.
said = Replica(root / 'pardes-replica.sock').hello('work', new_build)
@@ -2410,7 +2824,10 @@ def upgrades(old, new):
install(new, binary)
os.kill(session, signal.SIGKILL)
stub.wait(timeout=10)
- stub2.wait(timeout=10)
+ try:
+ stub2.wait(timeout=30)
+ except subprocess.TimeoutExpired:
+ raise AssertionError(('the second terminal\'s client on', cmdline(stub2.pid), term2.text()[-1200:]))
client.socket.close()
term.close()
term2.close()
@@ -2425,12 +2842,10 @@ def upgrades(old, new):
client = Client(sock)
again = int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid'])
started.append(again)
- # Its reader of the daemon starts after its first frame: an Adopt
- # before that waits for an `ok` nobody reads, and is refused. The
- # daemon lists it once it has taken its hello, which its `ok`
- # answers: an Adopt before that waits at most 2 s for the `ok`
- # (daemon.zig `kept`), which a loaded machine can take (3 in 40 at
- # a load of 35).
+ # A build before daemon.zig's `kept` waited for the hello's answer
+ # (the new-to-old run) refused an Adopt before its reader of the
+ # daemon ran (after its first frame), or within 2 s of a slow `ok`:
+ # it is asked once the daemon lists it (answer_late tests the wait).
wait_for('the next session\'s first frame', lambda: b'\x1b[?1049h' in term.text())
wait_for('the next session listed by the daemon', lambda: f'session again {again} ' in subprocess.run(
[str(binary), '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())
@@ -2457,6 +2872,124 @@ def upgrades(old, new):
shutil.rmtree(root, ignore_errors=True)
+def knows_exec(binary):
+ """Whether a build's client execs the build at its start path at an
+ Upgrade, for the view it is handed (PARDES_JOIN_VIEW)."""
+ return b'PARDES_JOIN_VIEW' in Path(binary).read_bytes()
+
+
+def upgrade_clients(old, new):
+ """Upgrade with near clients (the last step's design, 1.4): a session
+ (`new --detach`) with a terminal client and a window client attached,
+ each in its own view with a pane of its own there, onto another build installed at the path all three were
+ started from. A client of a build that execs (its start path holding
+ another file than the one it runs, the session another build than its
+ own) comes back on the build at its start path, the same process, for
+ its view: the terminal's leaves its screen and enters it again (the
+ blink), the window is a new one; in ITS view when that build joins for
+ a view it is handed (PARDES_JOIN_VIEW), else in a view of its own. One
+ of a build before it is let go and told to upgrade too. The session's
+ shell alive throughout; nothing left behind."""
+ old_gui, new_gui = old.with_name('pardes-gui'), new.with_name('pardes-gui')
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='ruc-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ (root / 'bin').mkdir()
+ binary, gui_binary = root / 'bin' / 'pardes', root / 'bin' / 'pardes-gui'
+ install(old, binary)
+ install(old_gui, gui_binary)
+ terms = []
+ procs = []
+
+ def still(check, key):
+ """Its view the live one (made_live's, for either client)."""
+ seen = len(checks(check))
+ key(b'gg')
+ wait_for('the client\'s key stepped', lambda: agreed(check, seen + 1), timeout=30)
+
+ try:
+ out = subprocess.run([str(binary), 'new', '--detach=up'], env=env, cwd=root, capture_output=True, timeout=30)
+ assert out.returncode == 0, out
+ sock = root / 'pardes-9p-up.sock'
+ nine = Client(sock)
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ shell = terminals(nine)[0]
+ shell_pid = int(run(nine, shell, b'echo $$\n').split(b'\n')[1])
+ t = Term(30, 100)
+ terms.append(t)
+ tc = t.spawn([str(binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 't.check')))
+ procs.append(tc)
+ wait_for('the terminal client drawn', lambda: b'\x1b[?1049h' in t.text(), timeout=30)
+ w = Window(root, 'w', [str(gui_binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 'w.check')))
+ procs.append(w.p)
+ wait_for('the window client drawn', lambda: (root / 'w' / 'latest.ppm').exists(), timeout=30)
+ tkey = lambda b: os.write(t.master, b) # noqa: E731
+ # Each client's view live in turn, a pane of its own made there (New).
+ owners = ((w.keys, root / 'w.check'), (tkey, root / 't.check'))
+ mine = []
+ for key, check in owners:
+ still(check, key)
+ shown = view_panes(nine)
+ nine.write('/exec', b'New\n')
+ mine.append(wait_for('a pane in the client\'s view', lambda: view_panes(nine) - shown).pop())
+ for (key, check), pane, theirs in zip(owners, mine, reversed(mine)):
+ still(check, key)
+ assert pane in view_panes(nine) and theirs not in view_panes(nine), ('each its own view', pane, theirs, nine.read('/layout'))
+ install(new, binary)
+ install(new_gui, gui_binary)
+ mark = len(t.text())
+ nine.write('/ctl', b'Upgrade\n')
+ nine.socket.close()
+ wait_for('the session on the new build', lambda: exe_of(session) == (str(binary), True), timeout=30)
+ nine = reconnect(sock)
+ if not knows_exec(old):
+ # A build before the exec: let go, dialled again for 20 s, told.
+ assert tc.wait(timeout=60) == 1 and w.p.wait(timeout=60) == 1, (tc.returncode, w.p.returncode)
+ said = t.text()[mark:] + w.said().encode()
+ assert b'upgrade this client too' in said or b'run the same pardes at both ends' in said, said[-600:]
+ print('upgrade with clients: the clients of a build before it were let go, dialled again, and told to upgrade too')
+ else:
+ wait_for('the terminal client on the new build', lambda: exe_of(tc.pid) == (str(binary), True), timeout=30)
+ wait_for('the window client on the new build', lambda: exe_of(w.pid) == (str(gui_binary), True), timeout=30)
+ # The blink: its screen left, and entered again.
+ wait_for('the terminal entered again', lambda: t.text().rfind(b'\x1b[?1049h') > t.text().rfind(b'\x1b[?1049l') > mark, timeout=30)
+ assert tc.poll() is None and w.p.poll() is None
+ for (key, check), pane, theirs in zip(owners, mine, reversed(mine)):
+ still(check, key)
+ if knows_exec(new):
+ shown = view_panes(nine)
+ assert pane in shown and theirs not in shown, ('its own view again', pane, theirs, nine.read('/layout'))
+ print('upgrade with clients: a terminal client and a window client exec\'d the build at their start path, the same processes, '
+ + ('each back in its own view, its own pane in it' if knows_exec(new) else 'each in a view of its own (that build joins for no view it is handed)'))
+ assert alive(shell_pid) and ppid(shell_pid) == session
+ for p in procs:
+ if p.poll() is None:
+ p.terminate()
+ p.wait(timeout=20)
+ nine.socket.close()
+ assert subprocess.run([str(binary), 'kill', 'up'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('the session ended', lambda: not alive(session), timeout=30)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
+ print('upgrade with clients: the shell ran on throughout; nothing left behind')
+ finally:
+ for p in procs:
+ if p.poll() is None:
+ p.kill()
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ for t in terms:
+ t.close()
+ shutil.rmtree(root, ignore_errors=True)
+
+
def gui_upgrades(old, new):
"""Upgrade in a window session (test mode: hidden windows, captured):
its window, a client window, an unsaved edit and a shell's job, onto
@@ -2551,6 +3084,11 @@ if __name__ == '__main__':
gui_upgrades(Path(sys.argv[3]).resolve(), Path(sys.argv[4]).resolve())
elif sys.argv[1:2] == ['--upgrade']:
upgrades(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
+ # With a pardes-gui beside each: the clients carried too.
+ if all(Path(a).resolve().with_name('pardes-gui').exists() for a in sys.argv[2:4]):
+ upgrade_clients(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
+ elif sys.argv[1:2] == ['--upgrade-clients']:
+ upgrade_clients(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
elif sys.argv[1:2] == ['--clients']:
clients(sys.argv[2])
elif sys.argv[1:2] == ['--manage']:
@@ -2562,19 +3100,28 @@ if __name__ == '__main__':
pair_rows(sys.argv[2])
elif sys.argv[1:2] == ['--relink']:
relink(sys.argv[2])
+ answer_late(sys.argv[2])
elif sys.argv[1:2] == ['--games']:
games(sys.argv[2], sys.argv[3], float(sys.argv[4]) if len(sys.argv) > 4 else 10)
elif sys.argv[1:2] == ['--far']:
far(sys.argv[2])
far_flood(sys.argv[2])
by_hash(sys.argv[2])
+ far_find(sys.argv[2])
+ elif sys.argv[1:2] == ['--far-find']:
+ far_find(sys.argv[2])
+ elif sys.argv[1:2] == ['--restore']:
+ restore_client(sys.argv[2])
elif sys.argv[1:2] == ['--window-clients']:
window_clients(sys.argv[2], sys.argv[3])
pdf_window(sys.argv[2], sys.argv[3])
elif sys.argv[1:2] == ['--ping']:
ping(sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5]) if len(sys.argv) > 5 else 50)
+ elif sys.argv[1:2] == ['--pair-gui']:
+ gui_pair(sys.argv[2])
elif '--gui' in sys.argv:
args = [a for a in sys.argv[1:] if a != '--gui']
gui(args[0], int(args[1]) if len(args) > 1 else 50)
+ gui_pair(args[0])
else:
main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 50)
diff --git a/test/delay_relay.py b/test/delay_relay.py
index c600a3aa..b0d48e38 100644
--- a/test/delay_relay.py
+++ b/test/delay_relay.py
@@ -8,7 +8,7 @@ the ones before it have crossed at that rate, then waits out the delay. An
optional jitter adds up to that many ms more to each chunk's delay, at
random, its order kept (a chunk never overtakes the one before it).
- python3 -B test/delay_relay.py LISTEN TARGET --delay MS [--rate MB/s] [--jitter MS]
+ python3 -B test/delay_relay.py LISTEN TARGET --delay MS [--rate MB/s] [--jitter MS] [--bound MS]
python3 -B test/delay_relay.py --self-check
An address is a path (a Unix socket) or host:port (TCP). The one-way
@@ -46,7 +46,9 @@ def dial(address):
return s
-def listen(address):
+def listen(address, bound=0.0):
+ """Bound, then listening `bound` s later (an ssh -L's socket file is
+ there a moment before it answers)."""
family, addr = parse(address)
s = socket.socket(family)
if family == socket.AF_UNIX:
@@ -57,6 +59,7 @@ def listen(address):
else:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
+ time.sleep(bound)
s.listen(64)
return s
@@ -260,8 +263,9 @@ def main():
ap.add_argument('--delay', type=float, required=True, help='one-way delay, ms')
ap.add_argument('--rate', type=float, help='a bandwidth cap, MB/s')
ap.add_argument('--jitter', type=float, default=0, help='up to this many ms more a chunk, at random')
+ ap.add_argument('--bound', type=float, default=0, help='ms between the bind and the listen')
a = ap.parse_args()
- listener = listen(a.listen)
+ listener = listen(a.listen, a.bound / 1000)
print(f'relaying {a.listen} -> {a.target}, {a.delay} ms each way'
+ (f', {a.rate} MB/s' if a.rate else '') + (f', jitter {a.jitter} ms' if a.jitter else ''), flush=True)
try:
diff --git a/test/e2e_harness.zig b/test/e2e_harness.zig
index f7d65b03..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;
@@ -149,9 +150,25 @@ pub const Harness = struct {
return true;
}
+ /// The app ended as closing its terminal ends it: the master closed (its
+ /// hangup), the app given `end_ms` to end, SIGKILLed only after, and
+ /// reaped: what it ends at its own end (its shells, its language servers'
+ /// groups) does not outlive the case.
pub fn deinit(self: *Harness) void {
- posix.kill(self.pid, posix.SIG.KILL) catch {};
_ = libc.close(self.master);
+ const end_ms = 5000;
+ const until = nowMs() + end_ms;
+ var status: c_int = 0;
+ var none: [0]posix.pollfd = .{};
+ while (libc.waitpid(self.pid, &status, libc.W.NOHANG) == 0) {
+ if (nowMs() < until) {
+ _ = posix.poll(&none, 5) catch 0;
+ continue;
+ }
+ posix.kill(self.pid, posix.SIG.KILL) catch {};
+ _ = libc.waitpid(self.pid, &status, 0);
+ break;
+ }
self.stream.deinit();
self.gpa.destroy(self.raw);
self.term.deinit(self.gpa);
@@ -235,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.
@@ -317,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/macos_e2e.swift b/test/macos_e2e.swift
index 38d27808..25d83957 100644
--- a/test/macos_e2e.swift
+++ b/test/macos_e2e.swift
@@ -168,7 +168,7 @@ private final class Driver: PardesViewDelegate {
message: "the view measured \(got.cols)x\(got.rows) cells, not the \(cols)x\(rows) the script asked for")
}
- var runtime = pardes_callbacks_s(
+ var callbacks = pardes_callbacks_s(
userdata: Unmanaged.passUnretained(host).toOpaque(),
wakeup: { ud in
// A pty reader thread. One flag and out — see Host.woke.
@@ -200,7 +200,7 @@ private final class Driver: PardesViewDelegate {
text.withCString { pardes_paste($0, text.utf8.count) }
})
- let rc = pardes_init(&runtime, got.cols, got.rows)
+ let rc = pardes_init(&callbacks, got.cols, got.rows)
guard rc == 0 else {
throw ScriptError(message: "pardes_init returned \(rc) at \(cols)x\(rows)")
}
diff --git a/test/panes.zig b/test/panes.zig
index 6bda3519..38eb0a71 100644
--- a/test/panes.zig
+++ b/test/panes.zig
@@ -3949,6 +3949,10 @@ const PdfAddon = struct {
}
};
const id = try opened(a, Land{ .a = a, .r = r });
+ // The effects `jobs` took last are the session's steps: a unit of
+ // its own before the client's input.
+ a.seq += 1;
+ r.confirm(try a.unit(0, a.seq));
const guessed = r.stats.mispredicted;
const stopped = r.stats.stopped;
const told = a.core.panes[id].?.addon.?.views;
diff --git a/test/perf-baseline-gui-debug.json b/test/perf-baseline-gui-debug.json
index b833000d..63c83edf 100644
--- a/test/perf-baseline-gui-debug.json
+++ b/test/perf-baseline-gui-debug.json
@@ -1 +1 @@
-{"harness":"d6c5e18a4acc4fe3","build":{"compiler":"0.17.1","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400}],"cells":[{"op":"open","fixture":"medium","min_us":1713,"med_us":1939,"p90_us":2099,"max_us":2119},{"op":"render","fixture":"medium","min_us":82,"med_us":83,"p90_us":86,"max_us":92},{"op":"key-down","fixture":"medium","min_us":89,"med_us":93,"p90_us":101,"max_us":106},{"op":"key-right","fixture":"medium","min_us":88,"med_us":90,"p90_us":95,"max_us":98},{"op":"page-down","fixture":"medium","min_us":88,"med_us":90,"p90_us":95,"max_us":104},{"op":"wheel","fixture":"medium","min_us":86,"med_us":88,"p90_us":93,"max_us":95},{"op":"edit-char","fixture":"medium","min_us":331,"med_us":391,"p90_us":398,"max_us":429},{"op":"edit-twin","fixture":"medium","min_us":354,"med_us":412,"p90_us":433,"max_us":455},{"op":"body-2m","fixture":"medium","min_us":1006,"med_us":1549,"p90_us":1694,"max_us":1777},{"op":"body-appends","fixture":"medium","min_us":1125,"med_us":1324,"p90_us":1392,"max_us":1416},{"op":"deep-sel","fixture":"medium","min_us":76,"med_us":78,"p90_us":83,"max_us":136},{"op":"image-frame","fixture":"medium","min_us":114,"med_us":121,"p90_us":130,"max_us":142}]}
+{"harness":"837d32e9cf0d2155","build":{"compiler":"0.17.1","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400}],"cells":[{"op":"open","fixture":"medium","min_us":2350,"med_us":2586,"p90_us":2766,"max_us":2827},{"op":"render","fixture":"medium","min_us":88,"med_us":90,"p90_us":95,"max_us":95},{"op":"key-down","fixture":"medium","min_us":95,"med_us":97,"p90_us":100,"max_us":103},{"op":"client-key-down","fixture":"medium","min_us":158,"med_us":162,"p90_us":165,"max_us":166},{"op":"key-right","fixture":"medium","min_us":96,"med_us":97,"p90_us":100,"max_us":104},{"op":"page-down","fixture":"medium","min_us":95,"med_us":97,"p90_us":102,"max_us":105},{"op":"wheel","fixture":"medium","min_us":93,"med_us":95,"p90_us":97,"max_us":97},{"op":"edit-char","fixture":"medium","min_us":383,"med_us":472,"p90_us":526,"max_us":536},{"op":"client-edit-char","fixture":"medium","min_us":899,"med_us":960,"p90_us":1016,"max_us":1045},{"op":"client-delete-undo","fixture":"medium","min_us":4385,"med_us":4615,"p90_us":4947,"max_us":4981},{"op":"edit-twin","fixture":"medium","min_us":397,"med_us":502,"p90_us":527,"max_us":536},{"op":"body-2m","fixture":"medium","min_us":1043,"med_us":1905,"p90_us":2096,"max_us":2111},{"op":"body-appends","fixture":"medium","min_us":1262,"med_us":1507,"p90_us":1600,"max_us":1705},{"op":"deep-sel","fixture":"medium","min_us":77,"med_us":78,"p90_us":79,"max_us":80},{"op":"image-frame","fixture":"medium","min_us":52,"med_us":54,"p90_us":56,"max_us":56}]}
diff --git a/test/perf-baseline-tui-debug.json b/test/perf-baseline-tui-debug.json
index 2ed71e52..ebfcaa78 100644
--- a/test/perf-baseline-tui-debug.json
+++ b/test/perf-baseline-tui-debug.json
@@ -1 +1 @@
-{"harness":"d6c5e18a4acc4fe3","build":{"compiler":"0.17.1","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"tui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400}],"cells":[{"op":"open","fixture":"medium","min_us":1745,"med_us":2061,"p90_us":2178,"max_us":2218},{"op":"render","fixture":"medium","min_us":81,"med_us":86,"p90_us":93,"max_us":97},{"op":"key-down","fixture":"medium","min_us":89,"med_us":96,"p90_us":110,"max_us":124},{"op":"key-right","fixture":"medium","min_us":87,"med_us":88,"p90_us":98,"max_us":109},{"op":"page-down","fixture":"medium","min_us":88,"med_us":88,"p90_us":91,"max_us":91},{"op":"wheel","fixture":"medium","min_us":85,"med_us":86,"p90_us":89,"max_us":94},{"op":"edit-char","fixture":"medium","min_us":328,"med_us":395,"p90_us":431,"max_us":433},{"op":"edit-twin","fixture":"medium","min_us":353,"med_us":405,"p90_us":439,"max_us":440},{"op":"body-2m","fixture":"medium","min_us":927,"med_us":1554,"p90_us":1651,"max_us":1974},{"op":"body-appends","fixture":"medium","min_us":1193,"med_us":1314,"p90_us":1493,"max_us":1511},{"op":"deep-sel","fixture":"medium","min_us":75,"med_us":78,"p90_us":83,"max_us":83},{"op":"image-frame","fixture":"medium","min_us":111,"med_us":119,"p90_us":132,"max_us":134}]}
+{"harness":"837d32e9cf0d2155","build":{"compiler":"0.17.1","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"tui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400}],"cells":[{"op":"open","fixture":"medium","min_us":2043,"med_us":2295,"p90_us":2410,"max_us":2572},{"op":"render","fixture":"medium","min_us":80,"med_us":82,"p90_us":86,"max_us":86},{"op":"key-down","fixture":"medium","min_us":85,"med_us":86,"p90_us":94,"max_us":105},{"op":"client-key-down","fixture":"medium","min_us":148,"med_us":153,"p90_us":160,"max_us":175},{"op":"key-right","fixture":"medium","min_us":85,"med_us":88,"p90_us":91,"max_us":93},{"op":"page-down","fixture":"medium","min_us":86,"med_us":90,"p90_us":101,"max_us":107},{"op":"wheel","fixture":"medium","min_us":82,"med_us":86,"p90_us":89,"max_us":93},{"op":"edit-char","fixture":"medium","min_us":348,"med_us":411,"p90_us":460,"max_us":472},{"op":"client-edit-char","fixture":"medium","min_us":681,"med_us":713,"p90_us":737,"max_us":777},{"op":"client-delete-undo","fixture":"medium","min_us":3727,"med_us":4281,"p90_us":5052,"max_us":5118},{"op":"edit-twin","fixture":"medium","min_us":364,"med_us":464,"p90_us":533,"max_us":543},{"op":"body-2m","fixture":"medium","min_us":928,"med_us":1580,"p90_us":1730,"max_us":1766},{"op":"body-appends","fixture":"medium","min_us":1096,"med_us":1307,"p90_us":1416,"max_us":1532},{"op":"deep-sel","fixture":"medium","min_us":68,"med_us":70,"p90_us":72,"max_us":72},{"op":"image-frame","fixture":"medium","min_us":48,"med_us":52,"p90_us":55,"max_us":65}]}
diff --git a/test/perf-baseline-tui-fast.json b/test/perf-baseline-tui-fast.json
index 5fff67f7..b7a7e0b6 100644
--- a/test/perf-baseline-tui-fast.json
+++ b/test/perf-baseline-tui-fast.json
@@ -1 +1 @@
-{"harness":"d6c5e18a4acc4fe3","build":{"compiler":"0.17.1","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"fast","c_optimize":"fast","terminal_optimize":"fast","platform":"tui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400}],"cells":[{"op":"open","fixture":"medium","min_us":1722,"med_us":2008,"p90_us":2211,"max_us":2219},{"op":"render","fixture":"medium","min_us":74,"med_us":78,"p90_us":80,"max_us":92},{"op":"key-down","fixture":"medium","min_us":79,"med_us":81,"p90_us":83,"max_us":84},{"op":"key-right","fixture":"medium","min_us":79,"med_us":80,"p90_us":81,"max_us":83},{"op":"page-down","fixture":"medium","min_us":79,"med_us":79,"p90_us":81,"max_us":82},{"op":"wheel","fixture":"medium","min_us":76,"med_us":77,"p90_us":80,"max_us":88},{"op":"edit-char","fixture":"medium","min_us":314,"med_us":366,"p90_us":385,"max_us":404},{"op":"edit-twin","fixture":"medium","min_us":347,"med_us":405,"p90_us":469,"max_us":471},{"op":"body-2m","fixture":"medium","min_us":848,"med_us":1376,"p90_us":1575,"max_us":1692},{"op":"body-appends","fixture":"medium","min_us":931,"med_us":1171,"p90_us":1215,"max_us":1246},{"op":"deep-sel","fixture":"medium","min_us":64,"med_us":66,"p90_us":67,"max_us":70},{"op":"image-frame","fixture":"medium","min_us":43,"med_us":45,"p90_us":46,"max_us":49}]}
+{"harness":"837d32e9cf0d2155","build":{"compiler":"0.17.1","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"fast","c_optimize":"fast","terminal_optimize":"fast","platform":"tui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400}],"cells":[{"op":"open","fixture":"medium","min_us":1955,"med_us":2189,"p90_us":2334,"max_us":2374},{"op":"render","fixture":"medium","min_us":74,"med_us":77,"p90_us":81,"max_us":82},{"op":"key-down","fixture":"medium","min_us":78,"med_us":81,"p90_us":87,"max_us":94},{"op":"client-key-down","fixture":"medium","min_us":137,"med_us":142,"p90_us":154,"max_us":160},{"op":"key-right","fixture":"medium","min_us":79,"med_us":81,"p90_us":83,"max_us":94},{"op":"page-down","fixture":"medium","min_us":79,"med_us":83,"p90_us":84,"max_us":89},{"op":"wheel","fixture":"medium","min_us":79,"med_us":84,"p90_us":118,"max_us":135},{"op":"edit-char","fixture":"medium","min_us":331,"med_us":425,"p90_us":454,"max_us":515},{"op":"client-edit-char","fixture":"medium","min_us":700,"med_us":798,"p90_us":857,"max_us":895},{"op":"client-delete-undo","fixture":"medium","min_us":3653,"med_us":4324,"p90_us":5289,"max_us":5555},{"op":"edit-twin","fixture":"medium","min_us":361,"med_us":447,"p90_us":472,"max_us":475},{"op":"body-2m","fixture":"medium","min_us":974,"med_us":1713,"p90_us":2387,"max_us":2524},{"op":"body-appends","fixture":"medium","min_us":944,"med_us":1181,"p90_us":1286,"max_us":1376},{"op":"deep-sel","fixture":"medium","min_us":65,"med_us":67,"p90_us":68,"max_us":70},{"op":"image-frame","fixture":"medium","min_us":46,"med_us":49,"p90_us":50,"max_us":73}]}
diff --git a/test/perf.zig b/test/perf.zig
index 7920dedf..8c88ef01 100644
--- a/test/perf.zig
+++ b/test/perf.zig
@@ -391,6 +391,8 @@ const Options = struct {
creation: bool = false,
startup: bool = false,
mini: bool = false,
+ /// The scans a frame's slice bounds, a call at a time (`measureSearch`).
+ search: bool = false,
terminal_mib: ?usize = null,
/// The real binary's keystroke-to-present, `yes` stream and big open
/// (a tty pardes), or its keystrokes alone (a pardes-gui).
@@ -407,13 +409,14 @@ const Options = struct {
while (i < args.len) : (i += 1) {
const arg = args[i];
if (!std.mem.startsWith(u8, arg, "--")) return error.UnknownOption;
- const option = std.meta.stringToEnum(enum { json, creation, startup, mini, @"terminal-mib", @"self-test", reps, cols, rows, base, only, op, @"max-ratio", live, @"live-gui" }, arg[2..]) orelse
+ const option = std.meta.stringToEnum(enum { json, creation, startup, mini, search, @"terminal-mib", @"self-test", reps, cols, rows, base, only, op, @"max-ratio", live, @"live-gui" }, arg[2..]) orelse
return error.UnknownOption;
switch (option) {
.json => opts.json = true,
.creation => opts.creation = true,
.startup => opts.startup = true,
.mini => opts.mini = true,
+ .search => opts.search = true,
.@"self-test" => opts.self_test = true,
else => {
i += 1;
@@ -475,6 +478,7 @@ pub fn main(init: std.process.Init) !void {
if (opts.creation) return measureCreation(init.io, reps, opts.json);
if (opts.terminal_mib) |mib| return measureTerminalSession(init.io, mib, reps, opts.json);
if (opts.mini) return measureMini(init.io, init.gpa, reps, opts.json);
+ if (opts.search) return measureSearch(init.io);
if (opts.live) |exe| return measureLive(init.io, exe, false, reps, opts.json);
if (opts.live_gui) |exe| return measureLive(init.io, exe, true, reps, opts.json);
// The image-frame cells load the image addon by the path the build baked
@@ -1742,6 +1746,138 @@ fn measureMini(io: std.Io, fallback: std.mem.Allocator, reps: usize, json: bool)
}
}
+/// `--search`: the two scans a frame's slice bounds, each call timed and
+/// its instructions counted (user space, this thread): a find's names
+/// scored again as a query is typed into it over 200,000 paths
+/// (core/Names.zig `rescore`, Names' cap), and a search's places found a
+/// tick at a time over the large fixture, the view in its middle
+/// (core/Places.zig `settle` on a tick). The longest call of each is the
+/// slice a key or a frame can take.
+fn measureSearch(io: std.Io) !void {
+ var random: [12]u8 = undefined;
+ io.random(&random);
+ const dir = try std.fmt.allocPrint(gpa, "/tmp/pardes-perf-{x}", .{random});
+ defer gpa.free(dir);
+ try std.Io.Dir.createDirAbsolute(io, dir, .default_dir);
+ defer std.Io.Dir.cwd().deleteTree(io, dir) catch {};
+ var counter: Instructions = try .open();
+ defer counter.close();
+
+ const Names = @FieldType(pardes.panes.Query, "names");
+ var names: Names = .{};
+ defer names.deinit(gpa);
+ const dirs = [_][]const u8{ "core", "dev/gui", "dev/tui", "runtime", "test/behaviour", "addons/pdf", "zig-pkg/ghostty/src/terminal" };
+ const words = [_][]const u8{ "layout", "places", "names", "query", "stream", "surface", "replica", "tape", "kitty", "render" };
+ var row: [160]u8 = undefined;
+ for (0..200_000) |i| {
+ const path = try std.fmt.bufPrint(&row, "{s}/module_{d}/{s}_{d}.zig", .{ dirs[i % dirs.len], i / 64 % 997, words[i * 7 % words.len], i });
+ try names.add(gpa, path, 0, path.len, Names.baseOf(path), 0);
+ }
+ // Typed a key at a time, as into a find: each key's call, then the
+ // calls of the frames after it while it is busy.
+ for ([_][]const u8{ "m", "tape", "places zig", "core/module_9/replica_1", "zig-pkg/ghostty/src/terminal/module_99/kitty" }) |query| {
+ var slow: Slowest = .{};
+ names.typed(gpa, "");
+ for (1..query.len + 1) |n| {
+ var calls: usize = 0;
+ while (true) : (calls += 1) {
+ const was = counter.read();
+ const t0 = nowNs();
+ if (calls == 0) names.typed(gpa, query[0..n]) else names.rescore(gpa);
+ slow.add(nowNs() -| t0, counter.read() -| was, names.hits.items.len);
+ if (!names.busy()) break;
+ }
+ }
+ slow.report("rescore", query, names.hits.items.len);
+ }
+
+ const fx = fixtures[2];
+ const path = try std.fmt.allocPrint(gpa, "{s}/{s}.zig", .{ dir, fx.name });
+ defer gpa.free(path);
+ const text = try generate(fx);
+ try writeFile(path, text);
+ gpa.free(text);
+ for ([_][]const u8{ "e", "lorem.*amet", "helper_[0-9]+", "qqq" }) |pattern| {
+ const core = try boot();
+ defer core.deinit();
+ pardes.look.lookAt(core, 0, path);
+ pump(core);
+ const id = filePane(core) orelse return error.OpenDidNotOpenFile;
+ const pane = core.panes[id].?;
+ seek(pane, fx, 0);
+ pane.file.?.scroll = fx.lines / 2;
+ pane.body.cur_row = @intCast(fx.lines / 2);
+ _ = try frame(core);
+ const set = &pane.places;
+ set.search(core, pane, .typed, pane.serial, pattern, false, null, false);
+ var slow: Slowest = .{};
+ while (set.busy(pane) and slow.calls < 100_000) {
+ const was = counter.read();
+ const t0 = nowNs();
+ set.settle(core, pane, true);
+ slow.add(nowNs() -| t0, counter.read() -| was, 0);
+ }
+ slow.report("fill", pattern, set.hits.items.len);
+ }
+}
+
+/// The longest of a scan's calls.
+const Slowest = struct {
+ calls: usize = 0,
+ total_ns: u64 = 0,
+ ns: u64 = 0,
+ /// The instructions of the longest call (by time), and the most of any.
+ ins: u64 = 0,
+ most_ins: u64 = 0,
+ /// The same of the calls that left under 1,000 hits to sort: the scan
+ /// alone, nearly (`Names.rescore` sorts every hit at each call).
+ few_ns: u64 = 0,
+ few_ins: u64 = 0,
+
+ fn add(s: *Slowest, ns: u64, ins: u64, hits: usize) void {
+ s.calls += 1;
+ if (hits < 1000 and ns > s.few_ns) {
+ s.few_ns = ns;
+ s.few_ins = ins;
+ }
+ s.total_ns += ns;
+ if (ns > s.ns) {
+ s.ns = ns;
+ s.ins = ins;
+ }
+ s.most_ins = @max(s.most_ins, ins);
+ }
+
+ fn report(s: *const Slowest, what: []const u8, of: []const u8, hits: usize) void {
+ std.debug.print("{s} \"{s}\": {d} calls, {d} hits, {d:.2} ms in all; longest {d} us ({d} instructions); most instructions {d}; longest with under 1,000 hits {d} us ({d} instructions)\n", .{
+ what, of, s.calls, hits, @as(f64, @floatFromInt(s.total_ns)) / 1e6, s.ns / 1000, s.ins, s.most_ins, s.few_ns / 1000, s.few_ins,
+ });
+ }
+};
+
+/// This thread's instructions in user space (perf_event_open).
+const Instructions = struct {
+ fd: std.posix.fd_t,
+
+ fn open() !Instructions {
+ const linux = std.os.linux;
+ var attr: linux.perf_event_attr = .{ .type = .HARDWARE, .config = @intFromEnum(linux.PERF.COUNT.HW.INSTRUCTIONS), .flags = .{ .exclude_kernel = true, .exclude_hv = true } };
+ const rc = linux.perf_event_open(&attr, 0, -1, -1, 0);
+ if (linux.errno(rc) != .SUCCESS) return error.NoInstructionCounter;
+ return .{ .fd = @intCast(rc) };
+ }
+
+ fn read(c: Instructions) u64 {
+ var n: u64 = 0;
+ _ = std.os.linux.read(c.fd, std.mem.asBytes(&n), 8);
+ return n;
+ }
+
+ fn close(c: Instructions) void {
+ _ = std.os.linux.close(c.fd);
+ }
+};
+
fn seek(pane: *pardes.Pane, fx: Fixture, n: usize) void {
const f = &pane.file.?;
const span = @max(1, fx.lines * 8 / 10);
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/replicas.zig b/test/replicas.zig
index e035cd81..e5e719b3 100644
--- a/test/replicas.zig
+++ b/test/replicas.zig
@@ -773,7 +773,7 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run,
const r = cl.r.?;
const link = &cl.loop.link;
// Its link ended by the session (a Detach), it says nothing more.
- if (!link.gone) replica.bye(link.fd, r.diverged != null or link.lagged != 0);
+ if (!link.gone) replica.bye(link.fd, .{ .again = r.diverged != null or link.lagged != 0 });
try drain(cl, c, net, now);
cl.live = 0;
if (link.lagged != 0) {
@@ -1425,7 +1425,7 @@ const Soak = struct {
// A Detach typed in a client's view, or one cut off for its lag: its
// link shut, it hears its end and nothing after; its reader's end
// said (the next boundary lets it go).
- if (s.detach_view) |k| for (s.clients) |*cl| if (cl.peer) |p| if (p.view == k and !cl.shut) {
+ if (s.detach_view) |k| for (s.clients) |*cl| if (cl.peer) |p| if (p.view.index() == k and !cl.shut) {
cl.shut = true;
};
s.detach_view = null;
@@ -1567,7 +1567,6 @@ const Soak = struct {
}
pub fn upgradeAsked(_: *Soak) void {}
- pub fn note(_: *Soak, _: anytype) void {}
pub fn restoring(_: *Soak, _: *pardes.Pardes) void {}
pub fn restored(_: *Soak, _: *SessionLoop) void {}
@@ -2484,7 +2483,7 @@ fn flushAll(sc: *replica.Screens, core: *pardes.Pardes, ps: []const u16, list: *
for (ps, 0..) |peer, c| {
list.clearRetainingCapacity();
// Terminals alone cross: the view is not read.
- try sc.flush(core, peer, 0, list);
+ try sc.flush(core, peer, list);
for (list.items) |bytes| {
tot.deltas += 1;
tot.delta_bytes += bytes.len;
diff --git a/test/session.zig b/test/session.zig
index 1cbee9df..d437ecf2 100644
--- a/test/session.zig
+++ b/test/session.zig
@@ -53,7 +53,7 @@ pub const Session = struct {
/// A session showing one file pane holding `text`, keeping what outlives
/// it in a database in memory (core/Db.zig).
pub fn initFile(gpa: std.mem.Allocator, text: []const u8) !Session {
- const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory });
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .tape = recording });
errdefer p.deinit();
_ = try p.setTestFile(text);
var s: Session = .{ .core = p, .arena = .init(gpa) };
@@ -75,7 +75,7 @@ pub const Session = struct {
/// A session showing one file pane, its startup file `init` (as
/// `~/.config/pardes/init` is read) applied first.
pub fn initStartup(gpa: std.mem.Allocator, init: []const u8) !Session {
- const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .startup_config = init });
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .startup_config = init, .tape = recording });
errdefer p.deinit();
_ = try p.setTestFile("x\n");
var s: Session = .{ .core = p, .arena = .init(gpa) };
@@ -85,7 +85,7 @@ pub const Session = struct {
/// A session showing its terminal pane, as `pardes` starts.
pub fn initTerm(gpa: std.mem.Allocator) !Session {
- const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory });
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .tape = recording });
var s: Session = .{ .core = p, .arena = .init(gpa) };
s.drain();
return s;
@@ -99,7 +99,7 @@ pub const Session = struct {
var arena: std.heap.ArenaAllocator = .init(gpa);
errdefer arena.deinit();
const config = try std.fmt.allocPrint(arena.allocator(), "DumpDir {s}\n", .{dir});
- const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .disk, .startup_config = config });
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .disk, .startup_config = config, .tape = recording });
var s: Session = .{ .core = p, .arena = arena };
s.drain();
return s;
@@ -206,12 +206,16 @@ pub const Session = struct {
s.drain();
}
+ /// The tape `recordTape` started: every session made after it records on it.
+ var recording: ?*pardes.tape.Tape = null;
+
/// Every session started from here on records what it consumes as a
/// tape in memory, as PARDES_RECORD has a real one record it
/// (core/tape.zig); `replayTape` replays it once the session is gone.
pub fn recordTape(gpa: std.mem.Allocator) !void {
const t = try gpa.create(pardes.tape.Tape);
t.* = pardes.tape.memory(gpa);
+ recording = t;
pardes.tape.on = t;
}
@@ -221,7 +225,8 @@ pub const Session = struct {
/// its end loaded to its digest and dumped to its bytes again. False
/// when a replica diverged (said on stderr). After `deinit`.
pub fn replayTape(gpa: std.mem.Allocator) bool {
- const t = pardes.tape.on orelse return true;
+ const t = recording orelse return true;
+ recording = null;
pardes.tape.on = null;
defer {
pardes.tape.release(t);
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;