summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--core/Addon.zig18
-rw-r--r--core/Effect.zig7
-rw-r--r--core/Kind.zig2
-rw-r--r--core/exec.zig3
-rw-r--r--core/replica.zig27
-rw-r--r--core/root.zig4
-rw-r--r--core/tape.zig3
-rw-r--r--dev/fonts.zig6
-rw-r--r--dev/gui/gui.zig32
-rw-r--r--dev/tui/tui.zig47
-rw-r--r--runtime/main.zig38
-rw-r--r--runtime/session.zig12
-rw-r--r--test/daemon.py177
-rw-r--r--test/panes.zig55
14 files changed, 320 insertions, 111 deletions
diff --git a/core/Addon.zig b/core/Addon.zig
index c60f2430..aa3195f9 100644
--- a/core/Addon.zig
+++ b/core/Addon.zig
@@ -567,9 +567,11 @@ pub fn loadedOf(ops: *const Kind.Ops, path: []const u8, hash: [32]u8, words: *[6
/// This process's code for a kind a session's core lists, which a client
/// runs itself: PA_PLAIN, of the same name, version, ABI and functions (a
-/// compiled-in addon's library hash is 0: never by the hash), and not
-/// caught breaking its promise here (`distrusted`, the client's). Null: its
-/// panes say so.
+/// compiled-in addon's library hash is 0: never by the hash), or else the
+/// library at the session's path when its bytes are the session's (P51: a
+/// client on its machine; never bytes the session sent), and not caught
+/// breaking its promise here (`distrusted`, the client's). Null: its panes
+/// say so.
pub fn plainOps(e: *const Kind.Entry, distrusted: ?*const Distrusted) ?*const Kind.Ops {
if (!e.caps.plain or e.refused) return null;
// A client scans for its addons only when its session has a plain kind.
@@ -582,6 +584,16 @@ pub fn plainOps(e: *const Kind.Entry, distrusted: ?*const Distrusted) ?*const Ki
if (l.ops == 0) l.ops = loadListed(i, &why) orelse return null;
return @ptrFromInt(l.ops);
};
+ var words: [64]LoadedWord = undefined;
+ var why: Why = .{};
+ var data_buf: [4096]u8 = undefined;
+ const l = read(dataDir(&data_buf), e.path.slice(), &words, &why);
+ if (l.why.len > 0) return null;
+ const ops: *const Kind.Ops = @ptrFromInt(l.ops);
+ if (std.mem.eql(u8, &l.hash, &e.hash)) return ops;
+ const lib = libOf(ops).?;
+ lib.refs -= 1;
+ closeIdle(lib);
return null;
}
diff --git a/core/Effect.zig b/core/Effect.zig
index abfe4711..bdf41e66 100644
--- a/core/Effect.zig
+++ b/core/Effect.zig
@@ -256,9 +256,10 @@ fn performInner(p: *Pardes, e: Effect) void {
.dump_themes => |d| _ = p.tape.host(p, .dump_themes, .{d.pane}),
.detach => |d| p.tape.host(p, .detach, .{}) orelse p.reportError(d.pane, "detach", error.NotAttached),
// dlopen is the same on every host, so none has a method of its
- // own; a replica's core holds no library (what it brought comes in
- // the event this taped).
- .addon => |a| if (!p.tape.replaying()) @import("Addon.zig").perform(p, a.op, a.pane.index(), a.arg.slice()),
+ // own; a replica's core holds no library: what it brought is the
+ // event inside this call, recorded there and applied by a replay
+ // (its code a client's own, Addon.plainOps); a speculation waits.
+ .addon => |a| if (!p.tape.authorityOnly("an addon's load")) p.tape.value(.landing, @import("Addon.zig").perform, .{ p, a.op, a.pane.index(), a.arg.slice() }),
.job => |j| p.tape.host(p, .job, .{ j.pane, j.serial, j.token }) orelse if (!p.tape.replaying()) host_io.KindJob.runHere(p, j.pane.index(), j.serial, j.token),
// the loop's own condition; a host tears down after its own loop
.quit => p.endSession(),
diff --git a/core/Kind.zig b/core/Kind.zig
index 81997afb..49076f78 100644
--- a/core/Kind.zig
+++ b/core/Kind.zig
@@ -424,7 +424,7 @@ pub fn draw(p: *Pardes, s: *surface.Surface, arena: std.mem.Allocator, pane: *Pa
if (slot.ops == null and slot.live) {
// A client: a plain kind runs where it is shown, and this one lacks
// it; any other runs in its session alone.
- const why = if (caps(p, slot).plain) "it is not in its addons, or it broke its promise here" else "its state is not plain (PA_PLAIN), so it runs in the session alone";
+ const why = if (caps(p, slot).plain) "it is not in its addons nor the session's library at its path here, or it broke its promise here" else "its state is not plain (PA_PLAIN), so it runs in the session alone";
var line: [200]u8 = undefined;
_ = s.print(x, y, cols, std.fmt.bufPrint(&line, "addon {s} {d} does not run in this client: {s}", .{ slot.nameOf(), slot.version, why }) catch &line, .{ .fg = fg, .bg = bg });
return;
diff --git a/core/exec.zig b/core/exec.zig
index 52f54541..99868434 100644
--- a/core/exec.zig
+++ b/core/exec.zig
@@ -20,7 +20,6 @@ const python_lang = blk: {
@setEvalBranchQuota(20_000);
break :blk @import("grammar_manifest.zig").byName("python").?;
};
-const font_picker = pardes.font_picker;
const fonts = pardes.fonts;
const Pane = panes.Pane;
const MAX_COLS = pardes.MAX_COLS;
@@ -1014,7 +1013,7 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Settings.Setting, arg: ?[
return p.reportFailure(v.active, text.print("Theme: no theme \"{s}\"; like it: {s}; Themes lists all", .{ shown, colors.themesNear(near[0..@min(room, near.len)], want) }));
},
.font => {
- if (comptime !font_picker) return;
+ if (comptime !pardes.builtins.capabilities.font_picker) return;
const spec = config.Settings.FontSpec.parse(arg orelse return) orelse return;
// The session's machine's fonts, a question to its disk: a
// client's replay takes the session's answer, never its own.
diff --git a/core/replica.zig b/core/replica.zig
index 3aac5e82..71a8de71 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -1361,6 +1361,12 @@ pub const Peer = struct {
again: bool = false,
/// ...or that its window was closed (Peers.closed).
close: bool = false,
+ /// It said a bye: none, and the session let it go with no word of its
+ /// own (`closing`, `cut`), is a client that died (killed: P48).
+ bye: bool = false,
+ /// A pair's first client (`Joining.own`): the terminal its session
+ /// keeps is its (`Peers.pair_left`).
+ pair: bool = false,
/// Inputs read (each one's seq, as the client numbered them).
seq: u32 = 0,
/// The `stamp` frame its next input came with (its reader's).
@@ -1643,6 +1649,7 @@ pub const Peer = struct {
const b = (wire.decodeClient(tag, payload) catch return false).bye;
peer.again = b.again;
peer.close = b.close;
+ peer.bye = true;
return false;
},
.ping => {
@@ -1775,6 +1782,14 @@ pub const Peers = struct {
/// hung up) and the session is a pair's not kept (daemon.sessionState): it
/// ends there (runtime/session.zig).
closed: bool = false,
+ /// Its pair's first client left (P48): with no word at all (killed),
+ /// true; its session's frontend puts the user's terminal back then,
+ /// and lets it go either way (tui.zig `Own.sent`), and clears this.
+ pair_left: ?bool = null,
+ /// Its pair's first client's terminal or window found again (a focus
+ /// in): the session asks whether a newer build is installed, as its own
+ /// frontend asks at its own (runtime/session.zig), and clears this.
+ pair_focused: bool = false,
/// An Upgrade told its clients so (`refuseAll`): a connection handed
/// over before its exec is told the same, never closed by the exec
/// unanswered. Its exec failed: the next boundary takes joins again.
@@ -1896,6 +1911,7 @@ pub const Peers = struct {
const t0 = nowNs();
defer if (ps.samples) ps.input_ns.append(ps.gpa, nowNs() - t0) catch {};
core.toView(peer.view);
+ if (peer.pair and in.event == .focus and in.event.focus) ps.pair_focused = true;
ps.t.stamp = stampOf(in);
core.update(in.event);
core.step();
@@ -2000,7 +2016,7 @@ 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 = .at(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, .pair = joining.own };
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
@@ -2075,6 +2091,7 @@ pub const Peers = struct {
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;
+ if (peer.pair) ps.pair_left = !peer.bye and !peer.closing and !peer.cut;
ps.seq += 1;
ps.unit(0, ps.seq);
ps.letGo(peer);
@@ -6169,12 +6186,10 @@ const may_wait = [_]Wait{
.{ .what = "*", .on = .addon, .stop = "a kind's close", .why = "a kind's pane closed: its state let go on the session" },
.{ .what = "*", .on = .addon, .stop = "a kind's word", .why = "a word to a kind (a key it takes as one): its own state" },
.{ .what = "*", .on = .addon, .stop = "a kind's open", .why = "a kind's pane opened (`Life`): its state made on the session" },
-} ++ (if (pardes.font_picker) [_]Wait{
- // A window's view (the font words are a window's).
+} ++ (if (pardes.builtins.capabilities.font_picker) [_]Wait{
+ // A window's view's words, which a terminal's build has too: a window
+ // client of its session runs them.
.{ .what = "Font *", .on = .any, .stop = "fonts", .why = "the session's machine's fonts, its disk" },
-} else [_]Wait{}) ++ (if (pardes.builtins.capabilities.font_picker) [_]Wait{
- // ...and Fonts a terminal's build has too, which a window client of its
- // session runs (exec.zig's Font, a window build's alone, does not).
.{ .what = "Fonts", .on = .any, .stop = "fonts", .why = "the session's machine's fonts, its disk" },
} else [_]Wait{});
diff --git a/core/root.zig b/core/root.zig
index 3cc9a90f..3bca5e03 100644
--- a/core/root.zig
+++ b/core/root.zig
@@ -118,7 +118,9 @@ const Loc = Jump.Loc;
pub const can_attach = platform == .tui or platform == .gui;
-pub const fonts = if (font_picker) @import("dev").fonts else struct {};
+/// The machine's fonts: every desktop build's, which steps a window's Font
+/// as the window does (builtins.capabilities), and the Mac's.
+pub const fonts = if (builtins.capabilities.font_picker) @import("dev").fonts else struct {};
pub const Pane = panes.Pane;
const Text = panes.Text;
diff --git a/core/tape.zig b/core/tape.zig
index 1cbf8aed..dc53a7c9 100644
--- a/core/tape.zig
+++ b/core/tape.zig
@@ -140,6 +140,9 @@ pub const Site = enum(u16) {
/// A kitty image's medium as a terminal's emulator read it (a file, a
/// temporary file, shared memory: Term.media), its bytes or its failure.
medium,
+ /// An addon's library loaded or let go (Addon.perform): what it brought
+ /// is the `addon` event inside it, which a replica applies from here.
+ landing,
};
/// What the sites return. wire.semantics hashes their shape with the
diff --git a/dev/fonts.zig b/dev/fonts.zig
index 540e3a60..3d69c8a1 100644
--- a/dev/fonts.zig
+++ b/dev/fonts.zig
@@ -4,9 +4,9 @@
//! because the core has no font and the shells have no builtin dispatch.
//!
//! It lives at src/ rather than under gui/ because two shells draw their own
-//! text. It is compiled only behind `pardes.font_picker` (gui or macos), so
-//! the tui binary never opens a font directory, and the browser has none to
-//! open.
+//! text. It is compiled behind `builtins.capabilities.font_picker` (a
+//! desktop build, whose terminal steps a window's Fonts and Font as the
+//! window does, or the Mac's): the browser has none to open.
//!
//! No fontconfig and no CoreText. Enumerating fonts is a walk over a handful
//! of well-known directories, and the one thing the picker must know about
diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig
index cf384238..3193d966 100644
--- a/dev/gui/gui.zig
+++ b/dev/gui/gui.zig
@@ -1132,6 +1132,9 @@ const Client = struct {
titled: bool = false,
moving: bool = false,
blink: ?Blink = null,
+ /// The session's WindowOpacity this window last took (P47: each
+ /// window applies it to the view it draws; none answers the core).
+ opacity: ?u8 = null,
fn deinit(cl: *Client) void {
cl.pending.deinit(cl.gpa);
@@ -1173,6 +1176,7 @@ const Client = struct {
const g = cl.g;
const core = l.link.r.core();
g.session_font_request = null;
+ cl.opacity = null;
cl.shell.core = core;
cl.shell.gview = cl.joins.joined.view;
cl.shell.surface = null;
@@ -1206,6 +1210,14 @@ const Client = struct {
const link = &l.link;
l.frames.period_ns = refreshNs(g);
if (syncReplicaFont(g, &cl.in.core.settings.font, gpa)) link.dirty = true;
+ const opacity = cl.in.core.settings.window_opacity;
+ if (cl.opacity != opacity) {
+ cl.opacity = opacity;
+ if (applyWindowOpacity(g, opacity) catch return false) |why| {
+ log.warn("WindowOpacity: {s}", .{why});
+ } else g.applied_window_opacity = opacity;
+ link.dirty = true;
+ }
if (scrollRows(g, &cl.in, gpa)) link.dirty = true;
if (fitTaglineFont(g, g.facts.tagline_percent)) link.dirty = true;
const geom = windowCells(g);
@@ -3025,12 +3037,24 @@ fn finishWindowOpacity(core: *pardes.Pardes, applied: *u8, failure: ?[]const u8)
fn syncWindowOpacity(g: *Gui, core: *pardes.Pardes) void {
if (!core.settings.window_opacity_pending) return;
+ const failure = applyWindowOpacity(g, core.settings.window_opacity) catch blk: {
+ core.quit = true;
+ break :blk null;
+ };
+ finishWindowOpacity(core, &g.applied_window_opacity, failure);
+}
+
+/// What the window does at a WindowOpacity, the own window's and a
+/// client's (P47: a window's facts are the process's that draws it): why
+/// it cannot, or null; error.NoWindow when it was made again and could
+/// not be.
+fn applyWindowOpacity(g: *Gui, opacity: u8) error{NoWindow}!?[]const u8 {
// The first opacity under 100 on Wayland: the window made again,
// transparent, presenting through SDL_Renderer from then on (the
// capture's format, the swapchain's, is one it uploads). At a start's
// own WindowOpacity this is before its first frame, so unseen.
const unorm = g.present.swapchain_format == c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM or g.present.swapchain_format == c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM;
- if (g.wayland and !g.present.surface_opacity and core.settings.window_opacity < 100 and unorm) {
+ if (g.wayland and !g.present.surface_opacity and opacity < 100 and unorm) {
// A `--detach` session's window stays hidden.
const hidden = c.SDL_GetWindowFlags(g.window) & c.SDL_WINDOW_HIDDEN;
const mode = g.present.present_mode;
@@ -3046,16 +3070,16 @@ fn syncWindowOpacity(g: *Gui, core: *pardes.Pardes) void {
g.present.surface_opacity = false;
g.present.present_mode = mode;
g.win_flags &= ~@as(c.SDL_WindowFlags, c.SDL_WINDOW_TRANSPARENT);
- if (!reopenWindow(g)) core.quit = true;
+ if (!reopenWindow(g)) return error.NoWindow;
}
g.win_flags &= ~hidden;
}
// Offscreen captures also support per-pixel alpha. Never approximate this
// with SDL_SetWindowOpacity: that would make foreground text translucent.
- finishWindowOpacity(core, &g.applied_window_opacity, if (g.present.surface_opacity or g.present.capture or core.settings.window_opacity == 100)
+ return if (g.present.surface_opacity or g.present.capture or opacity == 100)
null
else
- "background transparency requires a native Wayland or alpha-capable SDL window");
+ "background transparency requires a native Wayland or alpha-capable SDL window";
}
fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) bool {
diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig
index 2f731e68..9117d54d 100644
--- a/dev/tui/tui.zig
+++ b/dev/tui/tui.zig
@@ -559,8 +559,12 @@ fn surfaceHasKittyKey(surface: *const pardes.Surface, key: u64) bool {
/// opens it; one open already (a session forked off its stub,
/// daemon.forkSession); or none, detached from the start (`--detach`).
/// The terminal a session starts on: /dev/tty, one its stub opened (an
-/// upgraded session's is raw already, `termios` the cooked one), or none.
-pub const Term = union(enum) { open, fd: struct { fd: posix.fd_t, termios: ?posix.termios = null }, detached };
+/// upgraded session's is raw already, `termios` the cooked one), or none:
+/// a pair's (main.zig `pair`) draws on none, and keeps its client's, with
+/// its modes before the client took it, to put back if that client dies
+/// with no word (P48: `Own.sent`).
+pub const Term = union(enum) { open, fd: struct { fd: posix.fd_t, termios: ?posix.termios = null }, detached, pair: Kept };
+pub const Kept = struct { fd: posix.fd_t, termios: posix.termios };
pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void {
const io = init.io;
@@ -583,7 +587,7 @@ pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void {
switch (term) {
.open => try screen.enter(try vaxis.Tty.init(io, &tty_buf)),
.fd => |t| try screen.enter(try Screen.ttyOn(io, &tty_buf, t.fd, t.termios)),
- .detached => {},
+ .detached, .pair => {},
}
defer screen.leave();
@@ -591,7 +595,7 @@ pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void {
defer paste_buf.deinit();
var loop: Loop = .init(io, &screen.tty, &screen.vx);
- var own: Own = .{ .screen = &screen, .loop = &loop, .paste_buf = &paste_buf };
+ var own: Own = .{ .screen = &screen, .loop = &loop, .paste_buf = &paste_buf, .kept = if (term == .pair) term.pair else null };
try session_loop.Loop(Own).run(init, opts, &own);
}
@@ -929,7 +933,9 @@ const Screen = struct {
const Killed = struct {
var fd: posix.fd_t = -1;
var cooked: posix.termios = undefined;
- const reset = "\x1b[<u\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1004l\x1b[?2004l\x1b[0m\x1b[?25h\x1b[?1049l";
+ /// Every mode it may have turned on off (the in-band resize its
+ /// terminal query asks for, vaxis's `in_band_resize_set`, too).
+ const reset = "\x1b[<u\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1004l\x1b[?2004l\x1b[?2048l\x1b[0m\x1b[?25h\x1b[?1049l";
fn arm(tty_fd: posix.fd_t, termios: posix.termios) void {
cooked = termios;
fd = tty_fd;
@@ -939,6 +945,11 @@ const Killed = struct {
if (daemon.link < 0) posix.sigaction(.HUP, &on, null);
}
+ fn putBack(tty: posix.fd_t, termios: *const posix.termios) void {
+ _ = std.c.write(tty, reset, reset.len);
+ _ = std.c.tcsetattr(tty, .FLUSH, termios);
+ }
+
/// The terminal gone (put back, or detached): a TERM still takes the
/// socket, the prompt files and the shells with it, and leaves the
/// terminal alone.
@@ -947,10 +958,7 @@ const Killed = struct {
}
fn handle(sig: posix.SIG) callconv(.c) void {
- if (fd >= 0) {
- _ = std.c.write(fd, reset, reset.len);
- _ = std.c.tcsetattr(fd, .FLUSH, &cooked);
- }
+ if (fd >= 0) putBack(fd, &cooked);
// The 9P socket and private prompt files go too: a killed editor
// leaves none behind. Its shells too, the daemon's dups let go.
ninep_io.unlinkOwnSocket();
@@ -971,6 +979,9 @@ const Own = struct {
paste_buf: *std.Io.Writer.Allocating,
frame_arena: std.heap.ArenaAllocator = undefined,
sh: Shell = undefined,
+ /// A pair's: its client's terminal (Term.pair), until that client
+ /// leaves.
+ kept: ?Kept = null,
const Session = session_loop.Loop(Own);
@@ -1007,6 +1018,12 @@ const Own = struct {
if (comptime !builtin.is_test) if (upgrade.resumed) |*rec| sh.resumeTerminals(rec);
// Nobody to see it, and nobody to size it: `size` sets it (ctl.zig).
sh.setAttended(!sh.detached());
+ // An upgraded pair's client joins again at once: what the session
+ // says meanwhile ("Upgrade: now") waits for it, as at a Restore
+ // (session.zig `restore`), not 800 ms on an unattended clock.
+ if (comptime !builtin.is_test) if (upgrade.resumed) |rec| if (rec.state == .pair) {
+ l.core.unattended = false;
+ };
return host;
}
@@ -1027,6 +1044,7 @@ const Own = struct {
o.screen.art.deinit(gpa);
o.screen.glide.deinit(gpa);
o.frame_arena.deinit();
+ if (o.kept) |k| _ = libc.close(k.fd);
}
pub fn start(o: *Own, l: *Session) !void {
@@ -1051,6 +1069,17 @@ const Own = struct {
pub fn sent(o: *Own) void {
const sh = &o.sh;
if (sh.peers.recording and sh.detached()) sh.drawn_ns = @intCast(std.Io.Clock.awake.now(sh.io).nanoseconds);
+ // A pair's client gone: dead with no word (a kill -9), its
+ // terminal put back as the own path's survivor puts it back (a
+ // forked session's when its stub is killed), from the alternate
+ // screen and raw; with a word, it did that itself. Let go either
+ // way: a terminal held open keeps an ssh, or its emulator, waiting.
+ const lost = sh.peers.pair_left orelse return;
+ sh.peers.pair_left = null;
+ const k = o.kept orelse return;
+ o.kept = null;
+ if (lost) Killed.putBack(k.fd, &k.termios);
+ _ = libc.close(k.fd);
}
pub fn upgradeAsked(o: *Own) void {
diff --git a/runtime/main.zig b/runtime/main.zig
index aa35e687..5cdf5ee0 100644
--- a/runtime/main.zig
+++ b/runtime/main.zig
@@ -1583,17 +1583,17 @@ fn nativeMain(std_init: std.process.Init) !void {
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).
+ // its own to dial (and to start, when none runs), listed as the
+ // window's (P49: only a window's pair execs one with `--paired`).
opts.pair = fd;
term = .detached;
detached = true;
- if (daemon.wanted()) _ = daemon.register(null, kind, opts.ninep_name, .pair);
+ if (daemon.wanted()) _ = daemon.register(null, .gui, opts.ninep_name, .pair);
} else if (detach == null and std.c.getenv("PARDES_PAIR") != null) {
// The last step's way, behind its variable until it is the default:
// this terminal or window a client of a session forked off for it
// (`pair`).
- pair(init, &opts, args);
- term = .detached;
+ term = if (pair(init, &opts, args)) |kept| .{ .pair = kept } else .detached;
} else if (daemon.wanted()) {
if (detach != null or pardes.platform == .gui) {
// A session started detached is kept from birth: a pair's word.
@@ -1756,9 +1756,11 @@ fn pardesBeside(buf: *[4104]u8) ?[:0]const u8 {
/// 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
+/// `sdlWake`), a terminal's needs none. Returns in a terminal's session,
+/// with the terminal its client draws on, cooked as it is now (P48: put
+/// back if that client dies with no word); 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.
/// A terminal's launch with no terminal to draw on (a detached pty, a
/// daemon): said, not an error trace, and exit 1.
@@ -1767,23 +1769,22 @@ fn noTerminal(io: std.Io) noreturn {
std.process.exit(1);
}
-fn pair(init: std.process.Init, opts: *pardes.Options, args: []const [:0]const u8) void {
+fn pair(init: std.process.Init, opts: *pardes.Options, args: []const [:0]const u8) ?@import("dev").tui.Kept {
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;
+ const path = pardesBeside(&path_buf) orelse return null;
+ if (args.len >= argv.len - 1 or std.c.access(path, std.c.X_OK) != 0) return null;
argv[0] = path.ptr;
for (args[1..], 2..) |a, k| argv[k] = a.ptr;
}
// Its client draws on /dev/tty: none to be had, said as the own path
- // says it, before a session is forked for nobody.
- if (pardes.platform == .tui) {
- const tty = std.c.open("/dev/tty", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(std.c.mode_t, 0));
- if (tty < 0) noTerminal(init.io);
- _ = std.c.close(tty);
- }
+ // says it, before a session is forked for nobody. The session keeps it,
+ // cooked as it is now. std.posix's termios: glibc's is a bigger struct.
+ const tty: c_int = if (pardes.platform == .tui) std.c.open("/dev/tty", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(std.c.mode_t, 0)) else -1;
+ if (pardes.platform == .tui and tty < 0) noTerminal(init.io);
+ const cooked = if (tty >= 0) std.posix.tcgetattr(tty) catch null else null;
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)
@@ -1815,8 +1816,11 @@ fn pair(init: std.process.Init, opts: *pardes.Options, args: []const [:0]const u
// 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, .pair);
- return;
+ if (cooked) |t| return .{ .fd = tty, .termios = t };
+ if (tty >= 0) _ = std.c.close(tty);
+ return null;
}
+ if (tty >= 0) _ = std.c.close(tty);
_ = std.c.close(fds[0]);
if (conn) |c| _ = std.c.close(c);
daemon.startPending(true);
diff --git a/runtime/session.zig b/runtime/session.zig
index 75e8efcc..50497560 100644
--- a/runtime/session.zig
+++ b/runtime/session.zig
@@ -23,7 +23,8 @@
//! - `start(l)`: after the first effects, the ptys and the watches
//! read: its input, its readers, the listener's wake, a detached
//! session's first wait (`l.watch`).
-//! - `sent()`: after each step's unit went to the clients.
+//! - `sent()`: after each step's unit went to the clients (a pair's
+//! client gone with it: before its session ends).
//! - `upgradeAsked()`: an Upgrade asked in the step, done (it execs).
//! - `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
@@ -130,11 +131,18 @@ pub fn Loop(comptime Frontend: type) type {
try l.core.pump(l.host);
// Its unit to each replica client, and theirs taken in.
l.peers.boundary(l.core);
+ // Before a pair's end: its client's terminal put back (P48).
+ fe.sent();
+ // A pair's client stands for the frontend it was started
+ // for: at its focus in, a newer build said (upgrade.zig).
+ if (l.peers.pair_focused) {
+ l.peers.pair_focused = false;
+ upgrade.noticeNewer(l.core);
+ }
// A pair's session with no daemon ends with its last link:
// nothing could attach to it again; with one, when its last
// client 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
// session whole.
diff --git a/test/daemon.py b/test/daemon.py
index 55cffaf4..9e0047e5 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -29,6 +29,8 @@ private HOME and runtime directory:
`pardes new --detach` returns once its session runs
python3 -B test/daemon.py --pair <pardes>
PARDES_PAIR: a terminal's session and its first client
+ python3 -B test/daemon.py --with-pair <mode> ...
+ any mode with PARDES_PAIR set in every process it starts
python3 -B test/daemon.py --attach-upgrading <pardes>
an attach started as its session upgrades, and two clients' views
across an Upgrade (in plain and --pair too)
@@ -69,6 +71,29 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from ninep import Client # noqa: E402
+# `--with-pair` before a mode: that mode as a user who exported PARDES_PAIR.
+WITH_PAIR = False
+
+
+def base_env():
+ """This process's environment without the caller's PARDES_* (a session
+ of the user's) or a pager; under `--with-pair`, PARDES_PAIR set in it, as
+ for a user who exported it: every mode run with the variable."""
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ if WITH_PAIR:
+ env['PARDES_PAIR'] = '1'
+ return env
+
+
+def listed_as(word, kind='tty'):
+ """How `--ps` lists a session `detached` (started so, or Detached in its
+ own frontend) or that `has a frontend`: under the variable the first is
+ kept (from birth, or at the Detach) and the second a pair (P36)."""
+ if WITH_PAIR:
+ return f'({kind}, kept)' if word == 'detached' else f'({kind})'
+ return f'({kind}, {word})'
+
+
def wait_for(what, check, timeout=10):
deadline = time.monotonic() + timeout
while True:
@@ -454,7 +479,7 @@ def clients(binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rc-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
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)
@@ -596,7 +621,7 @@ def launch(binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rl-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
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)
@@ -623,12 +648,12 @@ def launch(binary):
assert (root / 'pardes-9p-work.sock').exists(), list(root.iterdir())
pid = status_pid('work')
listed = cli('ps').stdout.decode()
- assert f'session work {pid} (tty, detached)' in listed, listed
+ assert f'session work {pid} {listed_as('detached')}' in listed, listed
assert alive(pid) and os.getsid(pid) == pid, (pid, os.getsid(pid))
out = cli('new', '--detach')
assert out.returncode == 0 and out.stdout.strip().isdigit(), out
unnamed = int(out.stdout)
- assert status_pid(str(unnamed)) == unnamed and f'session {unnamed} {unnamed} (tty, detached)' in cli('ps').stdout.decode()
+ assert status_pid(str(unnamed)) == unnamed and f'session {unnamed} {unnamed} {listed_as('detached')}' in cli('ps').stdout.decode()
taken = cli('new', '--detach=work')
assert taken.returncode == 1 and taken.stderr == b'pardes: a session named work is already running\n', taken
# The flag alone runs the session in this process, as a supervisor
@@ -664,7 +689,7 @@ def pair(binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rp-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
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', PARDES_PAIR='1')
(root / 'config' / 'pardes').mkdir(parents=True)
@@ -738,7 +763,7 @@ def pair_rows(binary):
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 = base_env()
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', PARDES_PAIR='1')
(root / 'config' / 'pardes').mkdir(parents=True)
@@ -928,7 +953,7 @@ def attach_upgrading(binary, rounds=6, dump=True):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='ru-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
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)
@@ -1019,7 +1044,7 @@ def kept_views(binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rk-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
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)
@@ -1091,7 +1116,7 @@ def pair_upgrade_views(binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rv-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
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', PARDES_PAIR='1')
(root / 'config' / 'pardes').mkdir(parents=True)
@@ -1197,7 +1222,7 @@ def pair_exec_reaps(old, new):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rpx-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
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', PARDES_PAIR='1')
(root / 'config' / 'pardes').mkdir(parents=True)
@@ -1261,7 +1286,7 @@ def far_exec(old, new):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rfx-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
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)
@@ -1327,7 +1352,7 @@ def pair_window_geometry(gui_binary, new_gui):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rgg-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
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',
SDL_VIDEO_DRIVER='offscreen')
@@ -1399,7 +1424,7 @@ def manage(binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rm-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
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)
@@ -1435,14 +1460,14 @@ def manage(binary):
listed = out.stdout.decode()
assert f'pardes daemon {daemon}' in listed, listed
for name in ('one', 'two'):
- assert f'session {name} {sessions[name]} (tty, detached)' in listed, listed
+ assert f'session {name} {sessions[name]} {listed_as('detached')}' in listed, listed
assert f'shell {shells[name]}' in listed, listed
# The same, a record a line, in each session's /sessions.
with Client(root / 'pardes-9p-one.sock') as c:
records = c.read('/sessions').decode().splitlines()
assert records[0] == f'daemon {daemon}', records
for name in ('one', 'two'):
- at = records.index(f'session {sessions[name]} tty detached {name}')
+ at = records.index(f'session {sessions[name]} tty {"kept" if WITH_PAIR else "detached"} {name}')
assert records[at + 1] == f'shell {shells[name]}', records
print('manage: /sessions read over 9P listed the daemon, both sessions and their shells')
os.kill(sessions['two'], signal.SIGKILL)
@@ -1503,7 +1528,7 @@ def relink(binary):
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 = base_env()
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)
@@ -1545,7 +1570,7 @@ def relink(binary):
own_shell = terminals(own)[0]
own_shell_pid = int(run(own, own_shell, b'echo $$\n').split(b'\n')[1])
started.append(own_shell_pid)
- expected = [f'session work {session} (tty, detached)', f'session own {own_pid} (tty, has a frontend)',
+ expected = [f'session work {session} {listed_as("detached")}', f'session own {own_pid} {listed_as("has a frontend")}',
f'shell {shell_pid}', f'shell {own_shell_pid}']
assert all(row in listed() for row in expected), listed()
daemon = daemons()[0]
@@ -1609,7 +1634,7 @@ def answer_late(binary):
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 = base_env()
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)
@@ -1727,7 +1752,7 @@ def pdf_window(binary, gui_binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='pdfw-', dir=os.environ.get('TMPDIR') or scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
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')
env.pop('XDG_DATA_HOME', None)
@@ -1793,7 +1818,7 @@ def window_clients(binary, gui_binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='wc-', dir=os.environ.get('TMPDIR') or scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
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)
@@ -1845,7 +1870,7 @@ def window_clients(binary, gui_binary):
if not rtt:
# Its clients are no sessions of the daemon's.
listed = sessions_listed(binary, env, root)
- assert [(n, k) for n, _, k in listed] == [('files', '(tty, detached)')], listed
+ assert [(n, k) for n, _, k in listed] == [('files', listed_as('detached'))], listed
# Moved and scrolled, its own view only: agreed again.
n = len(checks(check))
w.keys(b'jjjjjkkk\x06\x06\x02')
@@ -1951,15 +1976,19 @@ def window_clients(binary, gui_binary):
wait_for('the terminal client agrees with the window', lambda: agreed(root / 'b.check', nb), timeout=30)
wait_for('the window client agrees with the window', lambda: agreed(root / 'g.check', ng), timeout=30)
listed = sessions_listed(binary, env, root)
- assert [(n, k) for n, _, k in listed] == [('win', '(gui, has a frontend)')], listed
+ assert [(n, k) for n, _, k in listed] == [('win', listed_as('has a frontend', 'gui'))], listed
assert wg.close() == 0, wg.said()[-800:]
os.write(tb.master, b' sD')
wait_for('the terminal client let go', lambda: b.poll() is not None, timeout=10)
assert win.p.poll() is None
print(f'daemon: a window\'s session served a terminal\'s client and a window\'s, digests agreed '
- f'{len(checks(root / "b.check"))} and {len(checks(root / "g.check"))} times; --ps listed it alone, (gui, has a frontend)')
+ f'{len(checks(root / "b.check"))} and {len(checks(root / "g.check"))} times; --ps listed it alone, {listed_as("has a frontend", "gui")}')
win.close()
nine.socket.close()
+ # Under the variable the window is its session's client, and the
+ # terminal client's Detach kept that session (P36): ended by name.
+ if WITH_PAIR:
+ subprocess.run([binary, '--kill=win'], env=dict(env, PARDES_DAEMON='on'), cwd=root, capture_output=True, timeout=30)
wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=15)
print('daemon: window clients\' sessions ended, nothing left behind')
finally:
@@ -2015,7 +2044,7 @@ def far(binary):
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rf-', dir=scratch))
cache = root / 'cache'
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
XDG_CACHE_HOME=str(cache), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash',
PARDES_NOTIME='1', PARDES_REPLICA_FAR='1')
@@ -2185,7 +2214,7 @@ def far_flood(binary):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='fl-', dir=os.environ.get('TMPDIR') or scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
XDG_CACHE_HOME=str(root / 'cache'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash',
PARDES_NOTIME='1')
@@ -2284,7 +2313,7 @@ def by_hash(binary):
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rh-', dir=scratch))
cache = root / 'cache'
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
XDG_CACHE_HOME=str(cache), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
(root / 'config' / 'pardes').mkdir(parents=True)
@@ -2370,7 +2399,7 @@ def games(binary, libs, secs=10):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rg-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
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)
@@ -2481,7 +2510,7 @@ def far_find(binary):
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 = base_env()
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)
@@ -2541,14 +2570,16 @@ def far_find(binary):
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."""
+ """A Restore while a client is attached: the client is told and joins
+ the restored session again by itself (P44, as at an Upgrade), saying
+ nothing on its screen; its keys reach the replacement core (the
+ session's: its tape adopts it, its options keep none) and it agrees with
+ it, as does a client attached after. A 9P connection is the old core's:
+ cut, dialled again."""
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 = base_env()
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)
@@ -2573,23 +2604,36 @@ def restore_client(binary):
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')
+ ta, ca = 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.
+
+ def cut():
+ try:
+ nine.read('/index')
+ return False
+ except (OSError, EOFError):
+ return True
+ wait_for('the 9P connection cut at the Restore', cut, timeout=30)
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)
+ # Client a, joined again by itself: its keys in the restored core.
+ os.write(ta.master, b'Oa after the restore\x1b')
+ wait_for('client a\'s keys in the restored session', lambda: b'a after the restore' in texts(), timeout=30)
+ assert ca.poll() is None, 'client a ended at the Restore'
+ seen = len(checks(root / 'a.check'))
+ wait_for('client a agrees once quiet', lambda: agreed(root / 'a.check', seen), timeout=60)
+ assert b'joined again' not in ta.text(), ('a notice left on client a\'s screen', ta.text())
+ tr, cr = client('r')
+ os.write(tr.master, b'Or after the restore\x1b')
+ wait_for('client r\'s keys in the restored session', lambda: b'r 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')
+ wait_for('client r agrees once quiet', lambda: agreed(root / 'r.check', seen), timeout=60)
+ assert ca.poll() is None and cr.poll() is None, 'a client ended'
+ print(f'daemon: a Restore with a client attached: it joined again by itself, saying nothing, its keys in the restored session and agreeing ({len(checks(root / "a.check"))} checks); the 9P connection cut; one attached after agreed ({len(checks(root / "r.check"))} checks)')
exit_session(nine, text)
sess.wait(timeout=60)
nine.socket.close()
@@ -2682,7 +2726,7 @@ def kitty_image(binary, secs=5):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='ri-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
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)
@@ -2743,7 +2787,7 @@ def main(binary, cycles):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rt-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
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)
@@ -2804,7 +2848,7 @@ def main(binary, cycles):
wait_for('the client\'s first frame', lambda: b'\x1b[?1049h' in term.text())
listed = wait_for('the client in --ps', lambda: (lambda out: f'client {c.pid} ' in out and out)(
subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode()))
- assert f'session work {session} (tty, detached)' in listed, listed
+ assert f'session work {session} {listed_as("detached")}' in listed, listed
os.write(term.master, f'echo {typed}\r'.encode())
wait_for('its keys in the shell', lambda: typed.encode() in client.read(f'/pane/{shell}/body'))
return c
@@ -2934,7 +2978,9 @@ def main(binary, cycles):
wait_for('the client\'s first frame', lambda: b'\x1b[?1049h' in term.text())
listed = wait_for('the client in --ps', lambda: (lambda out: f'client {stub.pid} ' in out and out)(
subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode()))
- assert f'session fresh {session} (tty, detached)' in listed, listed
+ # (Under the variable the killed stub was the pair's client: a loss,
+ # the session still a pair's, P36.)
+ assert f'session fresh {session} {"(tty)" if WITH_PAIR else listed_as("detached")}' in listed, listed
print('daemon: a session whose stub was killed outright detached, and was attached again, as a client')
# The end: the session quits, its shells hang up, its client and
@@ -2977,7 +3023,7 @@ def gui(binary, cycles):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rtg-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
(root / 'caps').mkdir()
env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_TEST='1', PARDES_TEST_CAPTURE_DIR=str(root / 'caps'),
@@ -2997,6 +3043,9 @@ def gui(binary, cycles):
wait_for('the window session', sock.exists, timeout=20)
client = Client(sock)
shell = terminals(client)[0]
+ # The window's own process, or under the variable its child (a
+ # pair: the window a client of it).
+ session = int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid'])
assert not sized(client), 'a window owns the size'
# With its window: another window is a client of the session (its
# own process, its captures its own), listed by --ps; closed, it
@@ -3005,22 +3054,23 @@ def gui(binary, cycles):
wait_for('the second window drawn', lambda: (root / 'second' / 'latest.ppm').exists(), timeout=20)
assert f'client {second.pid} ' in listed(), listed()
second.close()
- wait_for('the client gone from --ps', lambda: 'client ' not in listed())
+ # (a pair's own window is a client too: the second's pid is what goes)
+ wait_for('the client gone from --ps', lambda: f'client {second.pid} ' not in listed())
assert not sized(client), 'the first window stays'
- assert proc.poll() is None
+ assert alive(session)
print('daemon: a second window on a window session a client of it (in --ps), closed alone')
# Detached: the window closed, the process on; every attach after it
# a window client, the session detached still.
client.write(f'/pane/{shell}/exec', b'Detach\n')
wait_for('the window closed', lambda: sized(client))
- assert proc.poll() is None, 'the process carries on with no window'
- assert f'session win {proc.pid} (gui, detached)' in listed(), listed()
+ assert alive(session), 'the session carries on with no window'
+ assert f'session win {session} {listed_as("detached", "gui")}' in listed(), listed()
baseline = None
for cycle in range(cycles):
w = Window(root, f'w{cycle}', [binary, 'attach'] if cycle % 2 else [binary, '--attach=win'], env)
wait_for('the client window drawn', lambda: (root / f'w{cycle}' / 'latest.ppm').exists(), timeout=20)
wait_for('the client in --ps', lambda: f'client {w.pid} ' in listed())
- assert f'session win {proc.pid} (gui, detached)' in listed(), listed()
+ assert f'session win {session} {listed_as("detached", "gui")}' in listed(), listed()
now = (fds(proc.pid), len(processes(root)))
baseline = baseline or now
assert now == baseline, (cycle, now, baseline)
@@ -3037,14 +3087,14 @@ def gui(binary, cycles):
tty_attach.terminate()
tty_attach.wait(timeout=10)
term.close()
- assert proc.poll() is None
+ assert alive(session)
print('daemon: a terminal attached to a window session by name, as a client')
nobody = subprocess.run([binary, '--attach=nobody'], env=env, cwd=root, timeout=10,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
assert nobody.returncode == 1 and b"no session called 'nobody'" in nobody.stderr, nobody.stderr
# Detached and told to end: it ends.
client.write(f'/pane/{shell}/exec', b'Exit\n')
- proc.wait(timeout=10)
+ wait_for('the session ended', lambda: not alive(session))
client.socket.close()
wait_for('the daemon gone once idle', lambda: not [p for p in processes(root) if alive(p)], timeout=5)
print('daemon: window session ended, nothing left behind')
@@ -3072,7 +3122,7 @@ def gui_pair(gui_binary):
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 = base_env()
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)
@@ -3100,7 +3150,7 @@ def gui_pair(gui_binary):
try:
w, nine, session, pane = started('gp', env)
- wait_for('the window listed its client', lambda: f'session gp {session} (tty)' in listed()
+ wait_for('the window listed its client', lambda: f'session gp {session} (gui)' 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'))
@@ -3118,7 +3168,7 @@ def gui_pair(gui_binary):
os.kill(w.pid, signal.SIGKILL)
w.p.wait(timeout=10)
wait_for('the client unlisted', lambda: f'client {w.pid} ' not in listed())
- assert alive(session) and f'session gl {session} (tty)' in listed(), listed()
+ assert alive(session) and f'session gl {session} (gui)' 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)
@@ -3243,7 +3293,7 @@ def upgrades(old, new):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rtu-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
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)
@@ -3344,6 +3394,10 @@ def upgrades(old, new):
# (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
+ # (Under the variable a pair's session of a build that keeps its
+ # client's terminal, P48, lets it go: close-on-exec, not carried;
+ # such a build's put-back turns the in-band resize off.)
+ gone += 1 if WITH_PAIR and b'\x1b[?2048l\x1b[0m' in Path(old).read_bytes() else 0
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)
@@ -3553,7 +3607,7 @@ def upgrade_clients(old, new):
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 = base_env()
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)
@@ -3655,7 +3709,7 @@ def gui_upgrades(old, new):
another build."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
root = Path(tempfile.mkdtemp(prefix='rtgu-', dir=scratch))
- env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env = base_env()
display = Path(os.environ.get('WAYLAND_DISPLAY', 'wayland-0'))
if not display.is_absolute():
display = Path(os.environ.get('XDG_RUNTIME_DIR', f'/run/user/{os.getuid()}')) / display
@@ -3746,6 +3800,9 @@ def gui_upgrades(old, new):
if __name__ == '__main__':
+ WITH_PAIR = sys.argv[1:2] == ['--with-pair']
+ if WITH_PAIR:
+ del sys.argv[1]
# A session's state file is its HOME's, never the user's: the dumps a
# test makes there would push the user's out.
os.environ.pop('XDG_DATA_HOME', None)
diff --git a/test/panes.zig b/test/panes.zig
index 32cfd530..7d0b6396 100644
--- a/test/panes.zig
+++ b/test/panes.zig
@@ -4316,6 +4316,61 @@ const PdfAddon = struct {
try std.testing.expect(a.core.panes[c.id] == null and win.core().panes[c.id] == null);
try std.testing.expect(win.diverged == null);
}
+
+ test "Addon load <path> typed in a session lands on its client too, which runs the kind from that path while its bytes are the session's and shows its line once they are not" {
+ const R = pardes.replica;
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable });
+ defer a.deinit();
+ const r = try R.Replica.init(gpa, 1, try a.unit(0, 0));
+ defer r.deinit();
+ const Land = struct {
+ a: *R.Authority,
+ r: *R.Replica,
+ fn step(l: @This(), ev: pardes.Event) !void {
+ l.r.confirm(try l.a.local(ev));
+ }
+ };
+ const land: Land = .{ .a = a, .r = r };
+ // The image addon at a path of its own, in no addons directory.
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const lib = try std.Io.Dir.cwd().readFileAlloc(io, addons.image, gpa, .limited(256 << 20));
+ defer gpa.free(lib);
+ try tmp.dir.writeFile(io, .{ .sub_path = "libpic.so", .data = lib });
+ try tmp.dir.writeFile(io, .{ .sub_path = "dot.ppm", .data = "P6\n1 1\n255\n\x01\x02\x03" });
+ var buf: [4096]u8 = undefined;
+ const dir = buf[0..try tmp.dir.realPath(io, &buf)];
+ var line: [4200]u8 = undefined;
+ try land.step(.{ .command = try std.fmt.bufPrint(&line, "Addon load {s}/libpic.so", .{dir}) });
+ try std.testing.expect(r.diverged == null);
+ try std.testing.expect(a.core.kinds.byName("image") != null and r.core().kinds.byName("image") != null);
+ // A picture: the client runs the kind from the session's path.
+ try land.step(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/dot.ppm", .{dir}) });
+ try jobs(a.core, land);
+ const id = for (a.core.panes, 0..) |slot, i| {
+ if (slot) |pane| if (pane.addon != null) break i;
+ } else return error.NoPicture;
+ try std.testing.expect(r.core().panes[id].?.addon.?.ops != null);
+ r.settle();
+ try std.testing.expect(r.diverged == null);
+ // The file written over since (one byte more): a client joining
+ // now finds other bytes there and shows the kind's line.
+ const longer = try std.mem.concat(gpa, u8, &.{ lib, "\x00" });
+ defer gpa.free(longer);
+ try tmp.dir.writeFile(io, .{ .sub_path = "libpic.so", .data = longer });
+ const was = pardes.tape.on;
+ pardes.tape.on = &a.t;
+ const bytes = try pardes.dump.byteDump(a.core);
+ pardes.tape.resync(&a.t);
+ pardes.tape.on = was;
+ defer a.core.gpa.free(bytes);
+ const late = try R.Replica.initDump(gpa, 2, 0, bytes, .{ .cols = 80, .rows = 24 });
+ defer late.deinit();
+ try std.testing.expect(late.loaded(pardes.tape.digestOf(a.core)));
+ try std.testing.expect(late.core().panes[id].?.addon.?.ops == null);
+ }
};
test {