From 4bcf2055cb97d0c69fc94643b3e43b579d6fa30c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 00:51:28 -0300 Subject: term: a kitty image's medium (a file, a temporary file, shared memory) is the session's read and a recorded answer on the tape, so every replica's emulator is handed the bytes the session read, or its failure, and never reads its own machine: ghostty's loader gets the bytes through `LoadingImage.read_medium` (an Edit in build/patches.zig, ghostty's own read handed to it, the report in docs/ghostty-kitty-medium.md), which the terminal module sets to the core's `Term.media`, a `tape.valueIn(.medium, ...)` site (a new Site; `valueIn` is `value` with the answer's slices in the loader's allocator, no yield inside a feed), so a read crosses to a client as a file read does (inline under 1 MiB, by hash at or over it), a temporary file is deleted and shared memory unlinked once, on the session, and the program is answered by the session alone; a replica no longer loads by direct data only: `Term.direct`, `State.direct` and the `direct` entry go (`media` in their place); under screen state the read stays the authority's (a screen-state replica feeds no emulator); FIRST the test through the replica's surface (a session and a bytes replica, four images shown, by a file, a temporary file, shared memory and a missing file): on the base the digests parted (expected 8810391091473565423, found 2236913079067993401: the replica's loader said "unsupported medium" and did not move its cursor), now they agree, the terminals dump the same bytes, the temporary file and the object are gone and the replica read nothing (ghostty's FileNotFound warned once); tui term-test 17/17, kitty-test 45/45, core-test 856/1007 (151 skipped), shell-test 1043/1046, unit-test -Dtest-filter=bytes: 23/23 (the perf check's BaselineHarnessMismatch, as on the base) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- abi/term.zig | 13 ++++++++-- build/patches.zig | 37 ++++++++++++++++++++++++++ build/patches/ghostty_kitty.zig | 21 +++++++++++++++ core/Term.zig | 22 ++++++++++++---- core/replica.zig | 49 +++++++++++++++++++++++++++++++++++ core/tape.zig | 9 +++++++ core/term/term.zig | 2 +- core/term/terminal.zig | 27 +++++++------------ docs/ghostty-kitty-medium.md | 57 +++++++++++++++++++++++++++++++++++++++++ 9 files changed, 211 insertions(+), 26 deletions(-) create mode 100644 docs/ghostty-kitty-medium.md diff --git a/abi/term.zig b/abi/term.zig index 37519309..187b99e5 100644 --- a/abi/term.zig +++ b/abi/term.zig @@ -308,6 +308,14 @@ pub const Parts = struct { /// What reading its text can fail with. pub const TextError = error{ OutOfMemory, WriteFailed, UnknownPoint }; +/// How a kitty image's medium is had (a file, a temporary file, shared +/// memory: things of the session's machine): `read(ctx)` is the emulator's +/// own read (which deletes a temporary file and unlinks shared memory), +/// its bytes `gpa`'s (core/Term.zig `media`). +pub const Media = *const fn (ctx: *const anyopaque, read: *const fn (ctx: *const anyopaque) MediumError![]u8, gpa: std.mem.Allocator) MediumError![]u8; +/// What ghostty's loader fails a medium's read with. +pub const MediumError = error{ OutOfMemory, InvalidData, UnsupportedMedium, DimensionsTooLarge, TemporaryFileNotInTempDir, TemporaryFileNotNamedCorrectly }; + /// The entries, as `term.ops` gives them. An error set named here is what /// the core's callers name (the tape's `Failure` reads `open`'s, the text /// readers' are edit.zig's); `anyerror` where the core only passes one on @@ -347,8 +355,9 @@ pub const Ops = struct { /// Its emulator made again from its own snapshot where it is (a join: /// every side does it); the snapshot's hash. reload: *const fn (s: *State) anyerror!u64, - /// Its program's kitty images by direct data alone (a replica's). - direct: *const fn (s: *State) void, + /// How every terminal in the process has a kitty image's medium from + /// now on (the core's: a recorded answer). + media: *const fn (read: Media) void, // ---- output and view ---- /// One read of its program's output (`Told` says where the tracked diff --git a/build/patches.zig b/build/patches.zig index 3d956d26..7c7b2d60 100644 --- a/build/patches.zig +++ b/build/patches.zig @@ -213,7 +213,44 @@ pub fn zstbi(b: *std.Build, patch: *std.Build.Step.Compile, zstbi_dep: *std.Buil /// - an image may be no larger than a screen's storage /// (TerminalImages.storage_limit) rather than ghostty's 400 MB, which a /// program could make pardes read and hold before refusing it. +/// - a medium's bytes (t=f, t=t, t=s) are had through `read_medium` when +/// the host sets one, which is handed ghostty's own read: pardes makes +/// that read a recorded answer, so a session reads a file once (deletes +/// a temporary file, unlinks shared memory, once) and every replica of +/// it is handed the same bytes or the same failure, never reading its +/// own machine (core/Term.zig `media`; docs/ghostty-kitty-medium.md). const ghostty_kitty = [_]Edit{ + .{ + .old = " /// Initialize a chunked immage from the first image transmission.\n", + .new = + \\ /// pardes (build/patches.zig): how a file's, a temporary file's or + \\ /// shared memory's bytes are had: `read(ctx)` is ghostty's own read + \\ /// (which deletes a temporary file and unlinks shared memory), its + \\ /// bytes `alloc`'s; null, it is made as it is. + \\ pub var read_medium: ?*const fn (ctx: *const anyopaque, read: *const fn (ctx: *const anyopaque) MediumError![]u8, alloc: Allocator) MediumError![]u8 = null; + \\ pub const MediumError = error{ OutOfMemory, InvalidData, UnsupportedMedium, DimensionsTooLarge, TemporaryFileNotInTempDir, TemporaryFileNotNamedCorrectly }; + \\ + \\ /// Initialize a chunked immage from the first image transmission. + \\ + , + }, + .{ + .old = + \\ switch (t.medium) { + \\ .direct => unreachable, // handled above + \\ .file => try result.readFile(.file, io, alloc, t, cmd.data), + \\ .temporary_file => try result.readFile(.temporary_file, io, alloc, t, cmd.data), + \\ .shared_memory => try result.readSharedMemory(io, alloc, t, cmd.data), + \\ } + \\ + , + .new = + \\ // pardes (build/patches.zig): through the host's `read_medium`. + \\ const medium: PardesMedium = .{ .loading = &result, .io = io, .alloc = alloc, .t = t, .path = cmd.data }; + \\ result.data = .fromOwnedSlice(if (read_medium) |read| try read(&medium, PardesMedium.read, alloc) else try PardesMedium.read(&medium)); + \\ + , + }, .{ .old = "const max_size = 400 * 1024 * 1024; // 400MB", .new = "const max_size = 64 * 1024 * 1024; // pardes (build.zig): a screen's storage, TerminalImages.storage_limit", diff --git a/build/patches/ghostty_kitty.zig b/build/patches/ghostty_kitty.zig index a86d62d3..870c51e1 100644 --- a/build/patches/ghostty_kitty.zig +++ b/build/patches/ghostty_kitty.zig @@ -13,3 +13,24 @@ fn pardesOpenRegular(io: std.Io, path: []const u8) !std.Io.File { const same = std.fmt.bufPrint(&buf, "/proc/self/fd/{d}", .{probe.handle}) catch unreachable; return std.Io.Dir.cwd().openFile(io, same, .{}); } + +/// pardes (build.zig): a medium's read as ghostty makes it, handed to the +/// host's `LoadingImage.read_medium`: its bytes, the caller's. +const PardesMedium = struct { + loading: *LoadingImage, + io: std.Io, + alloc: Allocator, + t: command.Transmission, + path: []const u8, + + fn read(ctx: *const anyopaque) LoadingImage.MediumError![]u8 { + const m: *const PardesMedium = @ptrCast(@alignCast(ctx)); + switch (m.t.medium) { + .direct => unreachable, // read by the caller + .file => try m.loading.readFile(.file, m.io, m.alloc, m.t, m.path), + .temporary_file => try m.loading.readFile(.temporary_file, m.io, m.alloc, m.t, m.path), + .shared_memory => try m.loading.readSharedMemory(m.io, m.alloc, m.t, m.path), + } + return m.loading.data.toOwnedSlice(m.alloc); + } +}; diff --git a/core/Term.zig b/core/Term.zig index 89773f77..aa05a68f 100644 --- a/core/Term.zig +++ b/core/Term.zig @@ -102,10 +102,9 @@ pub const State = struct { var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const parts = try walk.load(iface.Parts, arena.allocator(), bytes[8..][0..n], null); + o.media(media); out.* = .{ .impl = try o.load(gpa, bytes[8 + n ..], &parts) }; writes +%= 1; - // A replica's (a join's, a closed terminal brought back in a step). - if (tape.replaying() or dump.terminal_gpa != null) o.direct(out.impl); } }; @@ -125,14 +124,27 @@ pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State { const o = ops orelse return error.NoTerminal; const s = try gpa.create(State); errdefer gpa.destroy(s); + o.media(media); s.* = .{ .impl = try o.open(gpa, cols, rows) }; writes +%= 1; - // A replica's emulator loads its program's images by direct data alone - // (P32): what is read off the session's machine is the session's. - if (tape.replaying()) o.direct(s.impl); return s; } +/// A kitty image's medium (a file, a temporary file, shared memory: the +/// session's machine's) as its emulator reads it, made the tape's answer +/// (P30: the device's answer as it was, as a file's bytes are): the session +/// reads it, a temporary file deleted and shared memory unlinked there once, +/// and every replica is handed the same bytes, or the same failure. Under +/// screen state a replica feeds no emulator: the read is the session's. +fn media(ctx: *const anyopaque, read: *const fn (*const anyopaque) iface.MediumError![]u8, gpa: std.mem.Allocator) iface.MediumError![]u8 { + if (tape.screenState()) return read(ctx); + return tape.valueIn(.medium, gpa, readMedium, .{ read, ctx }); +} + +fn readMedium(read: *const fn (*const anyopaque) iface.MediumError![]u8, ctx: *const anyopaque) iface.MediumError![]u8 { + return read(ctx); +} + /// It and what it holds, freed, all of it with its own allocator (the /// one it was opened with): the allocator a caller hands is not used. pub fn close(s: *State, _: std.mem.Allocator) void { diff --git a/core/replica.zig b/core/replica.zig index a52061f4..14757d9a 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -4427,6 +4427,55 @@ test "bytes: a session's output past a unit's bound is cut into units under it, try sameTerminals(b.a, b.r); } +test "bytes: a kitty image shown by a file, a temporary file or shared memory is the session's read, and the replica is handed its bytes: the same image, the cursor moved past it, the temporary file and the shared memory gone once, a missing file refused alike" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const shm = struct { + extern "c" fn shm_open(name: [*:0]const u8, flag: c_int, mode: std.c.mode_t) c_int; + extern "c" fn shm_unlink(name: [*:0]const u8) c_int; + extern "c" fn ftruncate(fd: c_int, len: i64) c_int; + }; + // ghostty warns of the missing file, on the session alone. + const level = std.testing.log_level; + std.testing.log_level = .err; + defer std.testing.log_level = level; + const b = try BytesPair.init(); + defer b.deinit(); + const pixels: [12]u8 = @splat(0x7f); // 2 by 2, RGB + const pid = std.c.getpid(); + var names: [4][80]u8 = undefined; + const file = try std.fmt.bufPrintSentinel(&names[0], "/tmp/pardes-replica-{d}-file.rgb", .{pid}, 0); + const temp = try std.fmt.bufPrintSentinel(&names[1], "/tmp/tty-graphics-protocol-pardes-replica-{d}.rgb", .{pid}, 0); + const object = try std.fmt.bufPrintSentinel(&names[2], "/pardes-replica-{d}", .{pid}, 0); + const missing = try std.fmt.bufPrintSentinel(&names[3], "/tmp/pardes-replica-{d}-missing.rgb", .{pid}, 0); + for ([_][:0]const u8{ file, temp }) |path| { + const fd = std.c.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(std.c.mode_t, 0o600)); + try std.testing.expect(fd >= 0); + defer _ = std.c.close(fd); + try std.testing.expectEqual(@as(isize, pixels.len), std.c.write(fd, &pixels, pixels.len)); + } + defer for ([_][:0]const u8{ file, temp }) |path| { + _ = std.c.unlink(path); + }; + { + const fd = shm.shm_open(object, @bitCast(std.c.O{ .ACCMODE = .RDWR, .CREAT = true, .TRUNC = true }), 0o600); + try std.testing.expect(fd >= 0); + defer _ = std.c.close(fd); + try std.testing.expectEqual(@as(c_int, 0), shm.ftruncate(fd, pixels.len)); + try std.testing.expectEqual(@as(isize, pixels.len), std.c.write(fd, &pixels, pixels.len)); + } + defer _ = shm.shm_unlink(object); + const enc = std.base64.standard.Encoder; + var line: [256]u8 = undefined; + var b64: [128]u8 = undefined; + for ([_][:0]const u8{ file, temp, object, missing }, "ftsf", 7..) |path, medium, id| + try b.output(try std.fmt.bufPrint(&line, "\x1b_Ga=T,t={c},i={d},f=24,s=2,v=2;{s}\x1b\\ shown\r\n", .{ medium, id, enc.encode(&b64, path) })); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); + try std.testing.expect(std.c.access(file, std.c.F_OK) == 0); + try std.testing.expect(std.c.access(temp, std.c.F_OK) != 0); + try std.testing.expect(shm.shm_open(object, @bitCast(std.c.O{ .ACCMODE = .RDONLY }), 0) < 0); +} + test "a replica joined from the session's dump replays the units after it" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); diff --git a/core/tape.zig b/core/tape.zig index d977b53e..f705636f 100644 --- a/core/tape.zig +++ b/core/tape.zig @@ -135,6 +135,9 @@ pub const Site = enum(u16) { /// join (panes.reloadTerminals), which every replica's own reload /// compares. reload, + /// 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, }; /// What the sites return. wire.semantics hashes their shape with the @@ -1296,6 +1299,12 @@ pub fn authority(comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn" return (on orelse &none).authority(f, args); } +/// `value` whose answer's slices are `a`'s on a replay, as `site`'s are: +/// what its caller keeps (a kitty image's medium, Term.media). +pub fn valueIn(comptime s: Site, a: std.mem.Allocator, comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? { + return (on orelse &none).call(s, a, f, args, false); +} + /// What `authority` was asked: `f` and its arguments as they are. fn question(comptime f: anytype, args: anytype) u64 { var h = std.hash.Wyhash.init(@intFromPtr(&f)); diff --git a/core/term/term.zig b/core/term/term.zig index b18f5875..59511727 100644 --- a/core/term/term.zig +++ b/core/term/term.zig @@ -32,7 +32,7 @@ pub const ops: iface.Ops = .{ .snapshot = cast(iface.Ops, "snapshot", terminal_.snapshot), .load = cast(iface.Ops, "load", terminal_.load), .reload = cast(iface.Ops, "reload", terminal_.reload), - .direct = cast(iface.Ops, "direct", terminal_.direct), + .media = terminal_.media, .feed = cast(iface.Ops, "feed", terminal_.feed), .grid = cast(iface.Ops, "grid", terminal_.grid), .viewTo = cast(iface.Ops, "viewTo", terminal_.viewTo), diff --git a/core/term/terminal.zig b/core/term/terminal.zig index 055c8981..e57193a6 100644 --- a/core/term/terminal.zig +++ b/core/term/terminal.zig @@ -195,11 +195,6 @@ pub const State = struct { /// the step reads the grid it had, as its replicas' replays do, and the /// rows sent them for it (Screens.fill) are of that grid's numbering. resize_to: ?struct { cols: u16, rows: u16 } = null, - /// Its program's kitty images by direct data alone (`direct`): a - /// replica's emulator, which is not the session's. A file, a temporary - /// file or shared memory is the session's machine's (and a temporary - /// one is deleted by its first reader): its image is absent here. - direct: bool = false, /// The stream over the emulator, its answers to the program and its /// size reports routed here, PNG decoded: what `create` and a dump's @@ -343,11 +338,11 @@ pub fn reload(s: *State) !u64 { var reply: [@typeInfo(@FieldType(State, "reply")).array.len]u8 = undefined; @memcpy(reply[0..saved.reply.len], saved.reply); saved.reply = reply[0..saved.reply.len]; - const kept = .{ s.changes, s.read, s.resize_to, s.direct }; + const kept = .{ s.changes, s.read, s.resize_to }; if (comptime images_enabled) s.images.deinit(gpa); s.stream.deinit(); s.vt.deinit(gpa); - s.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined, .changes = kept[0] +% 1, .read = kept[1], .resize_to = kept[2], .direct = kept[3] }; + s.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined, .changes = kept[0] +% 1, .read = kept[1], .resize_to = kept[2] }; // Short of room for its sequence in flight it goes on without it (lost // at the next cut), as ghostty's stream does: not worth a terminal. _ = install(s, decoded.continuation, &saved); @@ -357,8 +352,8 @@ pub fn reload(s: *State) !u64 { /// What a join compares of a snapshot (`reload`): every record of it but /// its kitty images' (tags 8 to 10, which ghostty's framing makes optional: /// snapshot/record.zig, a u16 tag, a u32 length, a u32 CRC and the payload, -/// after a 10-byte envelope): an image by file or shared memory is the -/// session's alone (P32, `direct`), and no digest reads an image. +/// after a 10-byte envelope): an animation's current frame is stepped by +/// each side's own draws, and no digest reads an image. fn joinHash(bytes: []const u8) u64 { const envelope = 10; const head = 10; @@ -379,7 +374,7 @@ fn joinHash(bytes: []const u8) u64 { /// whether its stream had all the room it wanted (`wire`). fn install(out: *State, continuation: ghostty_vt.snapshot.Continuation, saved: *const Term.Parts) bool { if (comptime images_enabled) inline for (.{ .primary, .alternate }) |which| { - if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = if (out.direct) .direct else .allWithTempDir(tempDir()); + if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .allWithTempDir(tempDir()); }; const whole = out.wire(); switch (continuation) { @@ -409,14 +404,10 @@ fn install(out: *State, continuation: ghostty_vt.snapshot.Continuation, saved: * return whole; } -/// Its program's kitty images by direct data alone from now on: the -/// emulator of a replica that is not the session (P32). -pub fn direct(s: *State) void { - if (comptime !images_enabled) return; - s.direct = true; - inline for (.{ .primary, .alternate }) |which| { - if (s.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .direct; - } +/// How every terminal's kitty loader has a medium's bytes from now on +/// (ghostty's `read_medium`, build/patches.zig). +pub fn media(read: Term.Media) void { + if (comptime images_enabled) ghostty_vt.kitty.graphics.LoadingImage.read_medium = read; } /// The allocator it was opened with, its own from then on. diff --git a/docs/ghostty-kitty-medium.md b/docs/ghostty-kitty-medium.md new file mode 100644 index 00000000..c990ea6d --- /dev/null +++ b/docs/ghostty-kitty-medium.md @@ -0,0 +1,57 @@ +# ghostty: a host cannot be the one that reads a kitty image's medium + +A note for upstream (https://github.com/ghostty-org/ghostty), against the +commit pardes pins (83fb95624b04, 1.4.0, `build.zig.zon`). pardes patches +its fetched copy at build time (build/patches.zig, `ghostty_kitty`, and +build/patches/ghostty_kitty.zig) until upstream has a way, if it wants one. + +## What a host cannot do + +A kitty graphics transmission by file (`t=f`), temporary file (`t=t`) or +shared memory (`t=s`) is read inside `LoadingImage.init` +(`src/terminal/kitty/graphics_image.zig`): `readFile` opens, checks and +reads the path, and deletes a temporary file; `readSharedMemory` opens, +maps, copies and unlinks the object. A host of libghostty-vt can allow or +refuse each medium (`LoadingImage.Limits`), and nothing else: it cannot +be the one that has the bytes. + +pardes needs to. A session's terminal is parsed by its own emulator and, +the same bytes in the same order, by the emulator of every client of the +session, each on its own machine. A file or a shared memory object names +something on the session's machine, and a temporary file or an object is +gone once its first reader has read it. So a client must not read the +medium: it must be handed the bytes the session read, or the failure the +session met, and the program must be answered once, by the session. If a +client refuses the medium instead, a shown image (`a=T`) moves the +session's cursor past it and not the client's, and the two terminals part. + +## The patch + +`LoadingImage.read_medium`, a hook a host may set (null: ghostty's read +as it is). When set, `init` hands it ghostty's own read as a function and +a context, and the allocator the bytes are to be in; what it returns +becomes the image's data: + +```zig +pub var read_medium: ?*const fn (ctx: *const anyopaque, read: *const fn (ctx: *const anyopaque) MediumError![]u8, alloc: Allocator) MediumError![]u8 = null; +``` + +The read itself is ghostty's, unchanged (`readFile`, `readSharedMemory`, +their checks, the deletion and the unlink), behind a small struct appended +to the file (`PardesMedium.read`). pardes's hook calls it on the session +and records what it returned; a client's hook returns the recorded bytes +(or error) without calling it. Everything before the read (the limits, +the PNG check, the path's NUL check) and after it (decompression, +decoding, the size checks of `complete`, the answer) runs on every side +alike. + +## Why not rewrite the transmission instead + +The other way is to turn `t=f`, `t=t` and `t=s` into direct data before +the emulator sees it. That parses the APC outside ghostty, repeats its +rules (the temporary directory and the name a temporary file must have, +the `/proc`, `/sys` and device refusals, the shared memory range by +format, offset and size, `S` meaning an exact length), and re-encodes the +bytes as base64 a third larger, chunked to the protocol's limits. It also +changes what the emulator sees, so its answer to the program has to be +checked to match. The hook keeps all of that in ghostty. -- cgit v1.3 From f8bc2dfb5c26b034643b22232624defe87517c20 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 00:51:28 -0300 Subject: test/replicas: --bytes shows kitty images by direct data, a file, a temporary file and shared memory at the end of the flood, twice: answered (ids 5 to 8, each OK counted once on the session's pty, with the query's) and kept (ids 15 to 18, q=1: the soak's tty echoes an answer back as output, and an echoed `ESC _ G i=5;OK ESC \` is a failed transmission of image 5 that takes it away), the kept shared-memory image 600x600 RGBA so its read crosses by hash; at quiescence every client's kept images hashed pixel for pixel against the session's, and every temporary file and object gone (the session's read deleted them, no client read them); the file image stored only (a=t) before, which no client loaded, goes; --clients 5 --bytes --seeds 8 at 30/80/207 ms (load 11): diverged 0, unequal 0, quiet checks 1513/0 1120/0 1691/0, 84/92/92 kitty images in clients at quiescence, each the session's pixels, corpus 22 of 22, no leak, stops off may_wait 1/0/0 (seed 2 at 30 ms, a client's key d stopped at the host's `now`: Del's question reads the host clock, exec.clockNow; the same stop once in the 4-seed run; the core change alone under the old soak: 0 over 8 seeds); the screen-state soak beside it: diverged 0, unequal 0, deltas 1874/0 1937/0 1828/0, quiet 597/0 673/0 792/0, stops off may_wait 0, corpus 22 of 22 Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- test/replicas.zig | 141 +++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 118 insertions(+), 23 deletions(-) diff --git a/test/replicas.zig b/test/replicas.zig index 70edea75..4994d9a5 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -246,6 +246,9 @@ const Totals = struct { /// Deltas the replicas applied while the flood ran. flood_deltas: u64 = 0, flood_us: u64 = 0, + /// Kitty images a client held at quiescence, the session's pixels + /// (`--bytes`, `images`). + images_equal: u64 = 0, flood_delta_bytes: u64 = 0, flood_unit_bytes: u64 = 0, fetched: u64 = 0, @@ -795,9 +798,13 @@ const Soak = struct { /// encoding cost. framed: bool = false, encode_ns: u64 = 0, - /// The session's pty told the answer to the program's kitty query - /// (`questions`): once, whatever the clients. - kitty_answers: u32 = 0, + /// The session's pty told the answers to the program's kitty query and + /// its four images (`questions`, `images`, `kitty_oks`): each once, whatever the + /// clients. + kitty_answers: [kitty_oks.len]u32 = @splat(0), + /// The temporary file and the shared memory object an image was shown + /// by (`images`): gone once the session read them. + media: *const Media = undefined, /// A Peer's queue, swapped out as its writer swaps it (the Peers' /// allocator's). sending: std.ArrayListUnmanaged(u8) = .empty, @@ -818,7 +825,9 @@ const Soak = struct { const s = of(ctx); // Only the session's emulator answers its program: a client's // answers are its tape's, never written (`questions`). - if (std.mem.indexOf(u8, bytes, "\x1b_Gi=31;OK") != null) s.kitty_answers += 1; + for (kitty_oks, &s.kitty_answers) |ok, *n| if (std.mem.indexOf(u8, bytes, ok) != null) { + n.* += 1; + }; s.echo.append(gpa, .{ .pane = pane, .bytes = gpa.dupe(u8, bytes) catch return }) catch {}; } @@ -1469,10 +1478,16 @@ const Soak = struct { for (s.flood_deltas[0..s.clients.len]) |d| totals.flood_deltas += d; const want = pardes.tape.digestOf(core); if (bytes_kind) std.debug.print("seed {d} rtt {d} ms: a join's step at worst {d} us (the session's reloads and its dump), the last dump {d} KB ({d} KB of state)\n", .{ s.r.seed, s.r.rtt_ms, s.l.peers.join_ns / 1000, s.l.peers.dump_bytes >> 10, s.l.peers.state_bytes >> 10 }); - if (bytes_kind and s.kitty_answers != 1) { + if (bytes_kind) for (kitty_oks, s.kitty_answers) |ok, n| if (n != 1) { totals.unequal += 1; - std.debug.print("seed {d} rtt {d} ms: the program's kitty query was answered {d} times on the session's pty\n", .{ s.r.seed, s.r.rtt_ms, s.kitty_answers }); - } + std.debug.print("seed {d} rtt {d} ms: the program's kitty {f} was answered {d} times on the session's pty\n", .{ s.r.seed, s.r.rtt_ms, std.ascii.hexEscape(ok, .lower), n }); + }; + if (bytes_kind) for (&s.media.temp, &s.media.object) |*temp, *object| { + for ([_][:0]const u8{ temp, object }, [_]bool{ libc.access(temp, libc.F_OK) == 0, shm.shm_open(object, @bitCast(libc.O{ .ACCMODE = .RDONLY }), 0) >= 0 }) |name, left| if (left) { + totals.unequal += 1; + std.debug.print("seed {d} rtt {d} ms: {s}, an image's medium, is still there\n", .{ s.r.seed, s.r.rtt_ms, name }); + }; + }; for (s.clients, 1..) |*cl, id| { totals.resizes += cl.resizes; totals.wakes += cl.wakes; @@ -1499,7 +1514,8 @@ const Soak = struct { totals.unequal += 1; std.debug.print("seed {d} rtt {d} ms: client {d} at quiescence: {s}\n", .{ s.r.seed, s.r.rtt_ms, id, if (rp.quiet()) "another digest" else "inputs still pending" }); } - // At quiescence, every terminal the session's, cell for cell. + // At quiescence, every terminal the session's, cell for cell, + // and its kitty images the session's, pixel for pixel. for (core.panes, 0..) |slot, pid| { const pane = slot orelse continue; const state = pane.terminal orelse continue; @@ -1511,6 +1527,13 @@ const Soak = struct { totals.unequal += 1; std.debug.print("seed {d} rtt {d} ms: client {d}'s terminal {d} at quiescence is not the session's\n", .{ s.r.seed, s.r.rtt_ms, id, pid }); } + const theirs = imagesHash(state); + if (!std.mem.eql(u64, &theirs, &imagesHash(mine))) { + totals.unequal += 1; + std.debug.print("seed {d} rtt {d} ms: client {d}'s kitty images in terminal {d} are not the session's\n", .{ s.r.seed, s.r.rtt_ms, id, pid }); + } else for (theirs) |h| { + if (h != 0) totals.images_equal += 1; + } } // ...and every file's text the session's, byte for byte: a digest // takes a text of 4 KiB and up by its length (core/walk.zig). @@ -1586,11 +1609,20 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { defer gpa.free(tui); const session_only = try screen_state.shellStream(gpa); defer gpa.free(session_only); - const asked = if (bytes_kind) try questions(dir) else ""; - defer if (bytes_kind) gpa.free(asked); - const shell_session = try std.mem.concat(gpa, u8, &.{ session_only, asked }); + const shell_session = try std.mem.concat(gpa, u8, &.{ session_only, if (bytes_kind) questions else "" }); defer gpa.free(shell_session); - const yes = try screen_state.yesStream(gpa, @intCast(r.flood_mb * (1 << 20) / 3)); + var media: Media = undefined; + const shown = if (bytes_kind) try images(dir, r.seed, &media) else ""; + defer if (bytes_kind) { + gpa.free(shown); + for (&media.temp, &media.object) |*temp, *object| { + _ = libc.unlink(temp); + _ = shm.shm_unlink(object); + } + }; + const yes_only = try screen_state.yesStream(gpa, @intCast(r.flood_mb * (1 << 20) / 3)); + defer gpa.free(yes_only); + const yes = try std.mem.concat(gpa, u8, &.{ yes_only, shown }); defer gpa.free(yes); var soak: Soak = .{ @@ -1606,27 +1638,90 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { .yes = yes, .own_left = r.steps, .typing = r.clients + 1, + .media = &media, }; // The session: THE session loop, from its start to its end. try SessionLoop.run(init, .{ .cols = 100, .rows = 30, .boot = .tty }, &soak); if (soak.err) |err| return err; } +/// What `questions`'s kitty query and `images`'s four are answered with. +const kitty_oks = [_][]const u8{ "\x1b_Gi=31;OK", "\x1b_Gi=5;OK", "\x1b_Gi=6;OK", "\x1b_Gi=7;OK", "\x1b_Gi=8;OK" }; + +/// The temporary files and the shared memory objects `images` shows its +/// images by, which the session's emulator removes when it reads them. +const Media = struct { temp: [2][300:0]u8, object: [2][64:0]u8 }; + +const shm = struct { + extern "c" fn shm_open(name: [*:0]const u8, flag: c_int, mode: libc.mode_t) c_int; + extern "c" fn shm_unlink(name: [*:0]const u8) c_int; + extern "c" fn ftruncate(fd: c_int, len: i64) c_int; +}; + +/// The pixels of each of `images`'s kept images a terminal holds, hashed +/// (0: not held). +fn imagesHash(state: *pardes.Term.State) [4]u64 { + var out: [4]u64 = @splat(0); + const screen = pardes.Term.emulatorOf(state).vt.screens.active; + for (&out, 15..) |*h, id| if (screen.kitty_images.imageById(@intCast(id))) |img| { + h.* = std.hash.Wyhash.hash(1, img.data.bytes() orelse continue); + }; + return out; +} + /// What the shell's program asks its terminal at the end of its session /// (`--bytes`): device attributes, the cursor's place, the cell's size in -/// pixels, a kitty query; then a kitty image by direct data, shown, and one -/// by a file of the session's machine, stored (a=t), which no client loads -/// (P32): absent there, as every live terminal's image is under screen -/// state. Shown (a=T) it would move the session's cursor past it and not a -/// client's: a divergence until the file's bytes are taped (a later step). -fn questions(dir: []const u8) ![]u8 { +/// pixels, a kitty query. +const questions = "\x1b[c\x1b[6n\x1b[16t\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\\r\n$ "; + +/// What the flood's program shows at its end (`--bytes`; after it, so the +/// clients still hold them at quiescence): kitty images shown (a=T) by +/// direct data, by a file of the session's machine, by a temporary file +/// (which its reader deletes) and by shared memory (which its reader +/// unlinks), twice: answered (ids 5 to 8, `kitty_oks`), and kept (ids 15 +/// to 18, q=1: the soak's tty echoes an answer back as output, and an +/// echoed `ESC _ G i=5;OK` is a transmission of image 5 that fails and +/// takes it away), the kept one by shared memory 1.4 MB, so its read +/// crosses to a client by hash. Each medium is the session's to read and +/// every client is handed its bytes (Term.media): each image in every +/// client, pixel for pixel; the program answered once; each temporary file +/// and object gone once. +fn images(dir: []const u8, seed: u64, media: *Media) ![]u8 { var path_buf: [300]u8 = undefined; const path = try std.fmt.bufPrintSentinel(&path_buf, "{s}/pixels.rgb", .{dir}, 0); try writeText(path, &@as([12]u8, @splat(0x7f))); - var b64: [400]u8 = undefined; - const name = std.base64.standard.Encoder.encode(&b64, path); - return std.fmt.allocPrint(gpa, "\x1b[c\x1b[6n\x1b[16t\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\\r\n" ++ - "\x1b_Ga=T,i=5,f=24,s=2,v=2;AAAAAAAAAAAAAAAA\x1b\\\r\n\x1b_Ga=t,i=6,t=f,f=24,s=2,v=2;{s}\x1b\\\r\n$ ", .{name}); + var out: std.ArrayListUnmanaged(u8) = .empty; + errdefer out.deinit(gpa); + var b64: [3][400]u8 = undefined; + const enc = std.base64.standard.Encoder; + for (0..2, [_]u32{ 2, 600 }, [_][]const u8{ "", ",q=1" }) |round, side, quiet| { + const temp = try std.fmt.bufPrintSentinel(&media.temp[round], "{s}/tty-graphics-protocol-{d}-{d}.rgb", .{ dir, seed, round }, 0); + try writeText(temp, &@as([12]u8, @splat(0x3f))); + const object = try std.fmt.bufPrintSentinel(&media.object[round], "/pardes-soak-{d}-{d}-{d}", .{ libc.getpid(), seed, round }, 0); + const fd = shm.shm_open(object, @bitCast(libc.O{ .ACCMODE = .RDWR, .CREAT = true, .TRUNC = true }), 0o600); + if (fd < 0) return error.ShmOpenFailed; + defer _ = libc.close(fd); + // Sized first: FreeBSD's write does not grow a shared memory object. + if (shm.ftruncate(fd, side * side * 4) != 0) return error.WriteFailed; + var row: [600 * 4]u8 = undefined; + for (0..side) |y| { + for (row[0 .. side * 4], 0..) |*c, i| c.* = @truncate(i * 7 + y * 13 + seed); + if (libc.write(fd, &row, side * 4) != side * 4) return error.WriteFailed; + } + const id = 5 + 10 * round; + try out.print(gpa, "\x1b_Ga=T,i={d},f=24,s=2,v=2{s};AAAAAAAAAAAAAAAA\x1b\\\r\n\x1b_Ga=T,i={d},t=f,f=24,s=2,v=2{s};{s}\x1b\\\r\n" ++ + "\x1b_Ga=T,i={d},t=t,f=24,s=2,v=2{s};{s}\x1b\\\r\n\x1b_Ga=T,i={d},t=s,f=32,s={d},v={d},c=8,r=4{s};{s}\x1b\\\r\n", .{ + id, quiet, + id + 1, quiet, + enc.encode(&b64[0], path), id + 2, + quiet, enc.encode(&b64[1], temp), + id + 3, side, + side, quiet, + enc.encode(&b64[2], object), + }); + } + try out.appendSlice(gpa, "$ "); + return out.toOwnedSlice(gpa); } /// A typist: keys 50-200 ms apart, a pause now and then. @@ -2838,7 +2933,7 @@ pub fn main(init: std.process.Init) !void { var t: Totals = .{}; pardes.Term.reloads = .{}; for (first..first + seeds) |seed| try run(init, .{ .seed = seed, .rtt_ms = rtt, .steps = steps, .clients = clients, .flood_mb = flood_mb }, dir, &t); - if (bytes_kind) std.debug.print("rtt {d}: {d} reloads of a terminal at joins, every side (the session's own too), {d} us each, {d} us at worst\n", .{ rtt, pardes.Term.reloads.n, pardes.Term.reloads.ns / @max(1, pardes.Term.reloads.n) / 1000, pardes.Term.reloads.worst_ns / 1000 }); + if (bytes_kind) std.debug.print("rtt {d}: {d} reloads of a terminal at joins, every side (the session's own too), {d} us each, {d} us at worst; {d} kitty images in clients at quiescence, each the session's pixels\n", .{ rtt, pardes.Term.reloads.n, pardes.Term.reloads.ns / @max(1, pardes.Term.reloads.n) / 1000, pardes.Term.reloads.worst_ns / 1000, t.images_equal }); const rollbacks = t.mispredicted + t.foreign; std.debug.print("{d:>4} {d:>6} {d:>7} {d:>7} {d:>6} {d:>6} {d:>6} ({d}+{d}) {d:>5.1}% {d:>6} {d:>5}/{d:<6} {d:>5}/{d:<5} ({d}) {d:>7}/{d:<7} {d:>8} {d:>7}\n", .{ rtt, t.inputs, t.speculated, -- cgit v1.3 From 6905c00e44c781741c37ca28fd68b96112eb71f4 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 03:27:51 -0300 Subject: test/daemon.py: a session told to Exit is given 60 s to end, not 10: its last act is the dump into the state database, whose fsync waits on the disk (the session's main thread in fsync under Db.putDump <- host_io.writeDump <- the write_dump effect, state D: the stack taken by gdb at two slow exits, 10.7 s and 20.4 s, on a disk six builders were writing; reorg/far27/loop-45.log); the wait is the durability the dump is for, not a hang: alone the exit takes 0.0 to 0.2 s (6 of 6), and --far failed at this wait once in the coordinator's gate of pardes-merge27 and 2 times in 49 in a loop under load, at the end of far and of by_hash; the six waits follow; no product change Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- test/daemon.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test/daemon.py b/test/daemon.py index e600beb7..6ae74c01 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -507,7 +507,7 @@ def clients(binary): f'one killed, the other typed on and detached; a third typed into a shell, agreed ' f'{len(checks(root / "c.check"))} times, and was hung up') exit_session(nine, pane) - sess.wait(timeout=10) + sess.wait(timeout=60) nine.socket.close() wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10) print('daemon: replica clients\' session ended, nothing left behind') @@ -704,7 +704,7 @@ def pdf_window(binary, gui_binary): print(f'daemon: a PDF in a detached session, a window client\'s wheel over it: the session at page {page()}, ' f'the window\'s digest the session\'s {len(checks(check))} times') exit_session(nine, pdf) - sess.wait(timeout=10) + sess.wait(timeout=60) nine.socket.close() finally: for pid in started: @@ -850,7 +850,7 @@ def window_clients(binary, gui_binary): f'{agreements} and {len(checks(root / "a.check"))} times; one put off the session\'s state joined again, ' f'joined again across an Upgrade, agreed {len(checks(dcheck))} times and detached (far: its joins {joins(root / "wd.stats")})') exit_session(nine, pane) - sess.wait(timeout=10) + sess.wait(timeout=60) nine.socket.close() # A window's session (its daemon on, as a desktop's is), served to a # terminal's client and a window's, the window typing as they do. @@ -1086,7 +1086,7 @@ def far(binary): b_joins[1]['blobs'], c_join['from_disk'], c_join['blobs'], d_join['sent_kb'], sum(len(checks(root / f'{n}.check')) for n in 'abcdef'))) exit_session(nine, pane) - sess.wait(timeout=10) + sess.wait(timeout=60) nine.socket.close() wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10) finally: @@ -1169,7 +1169,7 @@ def by_hash(binary): os.write(t.master, b' sD') wait_for('a client let go', lambda: c.poll() is not None, timeout=20) exit_session(nine, pane) - sess.wait(timeout=10) + sess.wait(timeout=60) nine.socket.close() finally: for t in terms: @@ -1282,7 +1282,7 @@ def games(binary, libs, secs=10): f'{got["c"]["foreign"]} (the third typing text), every digest agreed; a kind whose tick reads the clock was caught and its ' f'client joined again once') exit_session(nine, text) - sess.wait(timeout=10) + sess.wait(timeout=60) nine.socket.close() finally: for t in terms: -- cgit v1.3 From 969369d4b84fa1847dc3dee0e737dcd58e56c5e7 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 01:46:17 -0300 Subject: attach: `pardes attach [NAME]` is a client always, from a terminal a terminal's and from `pardes-gui` a window's, whatever the session was born with (the ruling of 2026-11-17: a session's own frontend is only the one it was born with), and the in-place attach deleted with what only it used (305 lines deleted, 94 added): the daemon's `attach` request and its `find` that chose (runtime/daemon.zig), `daemon.attach` and its `Answer`, `Note.attach`, the stub's second use (`stubWait`'s `child` and its `r`/`x` words, `tellStubExit`), `attachTo`'s two hand-offs and `crossAttach` (runtime/main.zig: a named attach goes straight to the replica socket, where the daemon refuses a name nobody has; a bare one takes the one detached session, else the one session, from the daemon's `list`, else names them: `bareAttach`, with a test), the terminal handed to a session (`attachTerminal`, `refuse`, the `.attach` message and its three arms: dev/tui/tui.zig), the window opened again in place (`openTheWindow`, `Shell.detached`, the queue's `.window` and its arms: dev/gui/gui.zig, dev/Inbox.zig, runtime/macos.zig), and `setState(false)`, which nothing says now (`setDetached`); test/daemon.py's attach cases expect a client (a Detach in its own terminal once, then each attach a client in `--ps`, the session detached still, its Detach exit 1 "let this client go"; the window cycles as window clients, offscreen); tui shell-test 1046/1049 (3 skipped, as the base), core-test 855/1005 (the base's less the deleted `find` test), daemon.py plain passing (gated with the next change) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- dev/Inbox.zig | 4 +- dev/gui/gui.zig | 37 ++------- dev/tui/tui.zig | 59 ++------------ runtime/daemon.zig | 206 +++++++---------------------------------------- runtime/macos.zig | 2 +- runtime/main.zig | 89 +++++++++++---------- runtime/session.zig | 7 +- test/daemon.py | 224 ++++++++++++++++++++++++++++++---------------------- 8 files changed, 223 insertions(+), 405 deletions(-) diff --git a/dev/Inbox.zig b/dev/Inbox.zig index ed3a9835..4df02013 100644 --- a/dev/Inbox.zig +++ b/dev/Inbox.zig @@ -23,8 +23,6 @@ pub const Msg = union(enum) { kind_job: *KindJob, files_changed, fs_ready, - /// The daemon asks for the window again (`pardes-gui --attach`). - window, /// A shell a dead session left, its pty's master (Adopt); pid 0 is /// the last of them told. adopted: struct { pid: libc.pid_t, fd: c_int }, @@ -44,7 +42,7 @@ pub const Msg = union(enum) { .adopted => |a| if (a.fd >= 0) { _ = libc.close(a.fd); }, - .eof, .files_changed, .fs_ready, .window => {}, + .eof, .files_changed, .fs_ready => {}, } } }; diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index c3272957..81d58137 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -990,8 +990,9 @@ fn closeWindow(g: *Gui) void { }; } -/// `pardes-gui --attach`: a window again, as the first was made, at the -/// size the last one had. False when the display will not give one. +/// A window again, as the first was made, at the size the last one had +/// (a transparent one: syncWindowOpacity). False when the display will not +/// give one. fn reopenWindow(g: *Gui) bool { const window = c.SDL_CreateWindow("pardes", g.window_w, g.window_h, g.win_flags) orelse return false; if (comptime builtin.os.tag == .macos) c.ui_macos_trackpad_attach(window); @@ -2395,10 +2396,8 @@ fn pollGamepad(g: *Gui, in: *Input) void { const Shell = struct { core: *pardes.Pardes, - /// The window's, while one is open; null while detached (`detached` has - /// it). + /// The window's, while one is open; null once detached. gui: ?*Gui = null, - detached: ?*Gui = null, io: std.Io, gpa: std.mem.Allocator, fs: ?*ninep_io.Listener = null, @@ -2452,7 +2451,7 @@ const Shell = struct { } /// Detach: the window closed, the session left running with no - /// window, for `pardes-gui --attach` to open one again. + /// window, detached for good: an attach shows it as a client. fn detachWindow(ctx: ?*anyopaque) void { const s = shellOf(ctx); // A replica client's: its link ends. @@ -2499,29 +2498,13 @@ const Shell = struct { fn closeTheWindow(s: *Shell) void { const g = s.gui orelse return; closeWindow(g); - s.detached = g; s.gui = null; s.presented = false; s.surface = null; // Its clients look at it still (Peers keeps it attended). s.peers.detached = true; s.core.unattended = s.peers.count() == 0; - daemon.setState(true); - } - - fn openTheWindow(s: *Shell) void { - const g = s.detached orelse return; - if (!reopenWindow(g)) { - log.err("--attach: no window: {s}", .{c.SDL_GetError()}); - return daemon.setState(true); - } - s.gui = g; - s.detached = null; - s.peers.detached = false; - s.core.unattended = false; - s.core.needs_frame = true; - resetScroll(g); - daemon.setState(false); + daemon.setDetached(); } fn watched(ctx: ?*anyopaque) bool { @@ -2686,7 +2669,6 @@ const Shell = struct { }, .files_changed => check_files = true, .fs_ready => {}, - .window => if (s.gui == null) s.openTheWindow(), .adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd), }; if (check_files and file_watch.reloadChanged(s.core, s.io, s.gpa, s.watches)) @@ -3200,13 +3182,6 @@ fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { const s: *Shell = @ptrCast(@alignCast(ctx)); const q = s.queue; switch (note) { - .attach => |a| { - // A terminal for a window session: the daemon refuses that kind - // before it is sent, so only an old one's would be here. - if (a.tty >= 0) _ = libc.close(a.tty); - if (a.stub >= 0) daemon.tellStub(a.stub, "r{s}", .{"a window session takes no terminal"}); - if (a.tty < 0) q.push(.window); - }, .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 } }); diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index 5c1945e6..42f73559 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -104,9 +104,6 @@ const Msg = union(enum) { /// The terminal's input ended: its end of file, a hangup. A session /// a daemon keeps carries on detached; any other ends. quit, - /// A terminal for this detached session, and its stub's pipe - /// (daemon.Note.attach). - attach: struct { tty: posix.fd_t, stub: posix.fd_t }, /// 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. @@ -573,7 +570,7 @@ fn surfaceHasKittyKey(surface: *const pardes.Surface, key: u64) bool { /// Where a session's terminal comes from: /dev/tty, as a plain `pardes` /// opens it; one open already (a session forked off its stub, -/// daemon.forkSession); or none, detached until one is attached (`--detach`). +/// 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 }; @@ -811,9 +808,9 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, /// A terminal a session draws on, while it has one: entered (raw, the /// alternate screen, mouse and paste reports) and left (all of it put back, -/// the terminal closed) at the session's start and end, and at a detach and -/// a reattach in between (daemon.zig), its stub `daemon.stub`. One a -/// process: a second terminal on a session is a replica client of it. +/// the terminal closed) at the session's start and end, or at a detach +/// (daemon.zig), its stub `daemon.stub`. One a process, the one the session +/// was born with: an attach is a replica client of it. const Screen = struct { io: std.Io, gpa: std.mem.Allocator, @@ -1019,10 +1016,6 @@ const Own = struct { }, .search_rows => |b| b.deinit(gpa), .kind_job => |j| j.drop(), - .attach => |a| { - _ = libc.close(a.tty); - if (a.stub >= 0) _ = libc.close(a.stub); - }, .adopted => |a| _ = libc.close(a.fd), else => {}, }; @@ -1108,12 +1101,6 @@ fn clearNativeImages( fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { const loop: *Loop = @ptrCast(@alignCast(ctx)); switch (note) { - .attach => |a| if (a.tty < 0) { - if (a.stub >= 0) daemon.tellStub(a.stub, "r{s}", .{"a terminal session takes a terminal"}); - } else loop.postEvent(.{ .attach = .{ .tty = a.tty, .stub = a.stub } }) catch { - _ = libc.close(a.tty); - _ = libc.close(a.stub); - }, .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); @@ -1324,42 +1311,7 @@ const Shell = struct { if (null_fd > 2) _ = libc.close(null_fd); } daemon.tellStubDetached(); - daemon.setState(true); - } - - /// `pardes --attach`'s terminal, for a detached session: its own again, - /// entered as the first one was, sized, asked what it can do, and drawn - /// whole. One attached already takes no other (the daemon makes a second - /// a replica client). - fn attachTerminal(s: *Shell, fd: posix.fd_t, stub: posix.fd_t, cooked: ?posix.termios) void { - const screen = s.screen orelse { - _ = libc.close(fd); - return refuse(stub, "that session has no terminal of its own to attach to"); - }; - if (screen.on) { - _ = libc.close(fd); - return refuse(stub, "that session has a terminal: join it as a client, `pardes --attach=:`"); - } - const tty = Screen.ttyOn(s.io, screen.buf, fd, cooked) catch { - _ = libc.close(fd); - daemon.setState(true); - return refuse(stub, "that terminal would not go raw"); - }; - screen.enter(tty) catch { - daemon.setState(true); - return refuse(stub, "that terminal would not take the screen"); - }; - daemon.stub = stub; - s.setAttended(true); - startInput(s.loop, screen) catch {}; - screen.vx.queryTerminalSend(screen.tty.writer()) catch {}; - s.core.needs_frame = true; - daemon.setState(false); - } - - /// A terminal refused: its stub told why (a test's has none). - fn refuse(stub: posix.fd_t, why: []const u8) void { - if (stub >= 0) daemon.tellStub(stub, "r{s}", .{why}); + daemon.setDetached(); } const PtyCalls = host_io.Ptys.Calls(Shell); @@ -1662,7 +1614,6 @@ const Shell = struct { core.quit = true; return true; }, - .attach => |a| s.attachTerminal(a.tty, a.stub, null), .adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd), .replica => |j| { s.peers.handed(j.fd, j.view); diff --git a/runtime/daemon.zig b/runtime/daemon.zig index 0d860918..1b9149b6 100644 --- a/runtime/daemon.zig +++ b/runtime/daemon.zig @@ -10,9 +10,9 @@ //! - a dup of every pty master it forks (`pty`), so a session killed //! outright never hangs its shells up, and which ones it closed; //! - whether a terminal or a window shows it (`state`). -//! It hands a terminal (`pardes --attach`) or a window request -//! (`pardes-gui --attach`) to a detached session, and a crashed session's -//! masters to the one that asks for them (Adopt). +//! It lists the sessions (`pardes ps`), hands a crashed session's masters +//! to the one that asks for them (Adopt), and a client's connection to the +//! session it names (below). //! //! Messages are SOCK_SEQPACKET datagrams: a line of words, and the fds it //! carries (SCM_RIGHTS). @@ -359,8 +359,10 @@ pub fn closed(pid: libc.pid_t) void { tell(std.fmt.bufPrint(&buf, "close {d}", .{pid}) catch unreachable, &.{}); // a pid fits 32 } -pub fn setState(detached: bool) void { - tell(if (detached) "state detached" else "state attached", &.{}); +/// Its own frontend let go (Detach, its terminal's end): detached for +/// good, an attach after it a client. +pub fn setDetached() void { + tell("state detached", &.{}); } /// This session's replica clients now, each its process's pid (0 when its @@ -398,9 +400,6 @@ pub fn resumeLink(fd: c_int, stub_fd: c_int, k: Kind, named: []const u8, detache } pub const Note = union(enum) { - /// A terminal for a detached tui session (`pardes --attach`), and the - /// stub's pipe; for a window session, both -1: open a window. - attach: struct { tty: c_int, stub: c_int }, adopted: struct { pids: [max_fds]libc.pid_t, fds: [max_fds]c_int, n: usize }, /// A replica's connection, its hello taken (core/replica.zig `Peers`), /// and the view it joins again for, if it does. @@ -426,15 +425,8 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no while (recv(fd, &buf)) |got| { var words = std.mem.tokenizeScalar(u8, got.words, ' '); const verb = words.next() orelse ""; - if (std.meta.stringToEnum(enum { ok, attach, replica, adopted }, verb)) |v| switch (v) { + if (std.meta.stringToEnum(enum { ok, replica, adopted }, verb)) |v| switch (v) { .ok => up.store(true, .release), - .attach => { - deliver(ctx, .{ .attach = .{ - .tty = if (got.nfds >= 2) got.fds[0] else -1, - .stub = if (got.nfds >= 2) got.fds[1] else -1, - } }); - for (got.fds[@min(got.nfds, 2)..got.nfds]) |f| _ = libc.close(f); - }, .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 } }); @@ -501,37 +493,13 @@ pub fn quit() void { link = -1; } -// ---- `pardes --attach`: a terminal, or a window, for a detached session ---- - -/// `other`: the session is the other kind (a window's for a terminal, or a -/// terminal's for a window), named so: joined as a replica client instead -/// (`replicaSocket`). -pub const Answer = union(enum) { ok: libc.pid_t, no: []const u8, other: []const u8 }; +// ---- `pardes attach`: a client, by the replica socket ---- /// This machine's replica socket, which joins a session of either kind. pub fn replicaSocket(buf: *[sun_path_len:0]u8) ?[:0]const u8 { return place(buf, "pardes-replica.sock"); } -/// Asks the daemon to hand `fds` (a terminal and a stub's pipe, or none for -/// a window) to the detached session `named` (any one, when empty), and -/// answers how it went; the words are `buf`'s. -pub fn attach(k: Kind, named: []const u8, fds: []const c_int, buf: []u8) Answer { - const fd = connect(false) orelse return .{ .no = "no detached session is running" }; - defer _ = libc.close(fd); - var line: [256]u8 = undefined; - const words = std.fmt.bufPrint(&line, "attach {t} {s}", .{ k, named }) catch return .{ .no = "that name is too long" }; - if (!send(fd, words, fds) or !readable(fd, 2000)) return .{ .no = "the daemon does not answer" }; - const got = recv(fd, buf) orelse return .{ .no = "the daemon hung up" }; - for (got.fds[0..got.nfds]) |f| _ = libc.close(f); - if (std.mem.startsWith(u8, got.words, "ok ")) { - const pid = std.fmt.parseInt(libc.pid_t, got.words[3..], 10) catch return .{ .no = "the daemon answered nonsense" }; - return .{ .ok = pid }; - } - if (std.mem.startsWith(u8, got.words, "other ")) return .{ .other = got.words["other ".len..] }; - return .{ .no = if (std.mem.startsWith(u8, got.words, "no ")) got.words[3..] else got.words }; -} - /// The daemon's answer to `words` (`list`, `kill `, `killall`), in /// `buf`; null with no daemon running, or none answering. pub fn ask(words: []const u8, buf: []u8) ?[]const u8 { @@ -558,13 +526,11 @@ fn forward(sig: posix.SIG) callconv(.c) void { } } -/// The job the shell waits on, for a session that is not its child any -/// more (`pardes --attach`) or that it forked (`child`, reaped here): what -/// a terminal sends the job goes on to the session (its size, an end +/// The job the shell waits on, for the session it forked (reaped here): +/// what a terminal sends the job goes on to the session (its size, an end /// asked for), and it ends when the session is gone from the terminal -- -/// detached (`d`), exited (`x`, or the pipe's end and the -/// child's status), or refused (`r`). -pub fn stubWait(session: libc.pid_t, child: bool, pipe: c_int) noreturn { +/// detached (`d`), or exited (the pipe's end and the child's status). +fn stubWait(session: libc.pid_t, pipe: c_int) noreturn { stub_child = session; const on: posix.Sigaction = .{ .handler = .{ .handler = forward }, .mask = posix.sigemptyset(), .flags = posix.SA.RESTART }; for ([_]posix.SIG{ .WINCH, .TERM, .INT, .QUIT, .HUP }) |sig| posix.sigaction(sig, &on, null); @@ -587,31 +553,21 @@ pub fn stubWait(session: libc.pid_t, child: bool, pipe: c_int) noreturn { if (said.len > 0 and said[0] == 'd') { var text: [700]u8 = undefined; const who = said[1..]; - out.writeStreamingAll(io, std.fmt.bufPrint(&text, "pardes: detached from '{s}', which is still running; come back with `pardes --attach={s}`\n", .{ who, who }) catch "pardes: detached\n") catch {}; + out.writeStreamingAll(io, std.fmt.bufPrint(&text, "pardes: detached from '{s}', which is still running; come back with `pardes attach {s}`\n", .{ who, who }) catch "pardes: detached\n") catch {}; libc._exit(0); } - if (said.len > 0 and said[0] == 'r') { - var text: [700]u8 = undefined; - out.writeStreamingAll(io, std.fmt.bufPrint(&text, "pardes: --attach: {s}\n", .{said[1..]}) catch "pardes: --attach refused\n") catch {}; - libc._exit(1); + var status: c_int = 0; + while (libc.waitpid(session, &status, 0) < 0) { + if (libc.errno(-1) != .INTR) libc._exit(1); } - if (child) { - var status: c_int = 0; - while (libc.waitpid(session, &status, 0) < 0) { - if (libc.errno(-1) != .INTR) libc._exit(1); - } - const s: u32 = @bitCast(status); - if (libc.W.IFEXITED(s)) libc._exit(@intCast(libc.W.EXITSTATUS(s))); - if (libc.W.IFSIGNALED(s)) { - const sig = libc.W.TERMSIG(s); - const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 }; - posix.sigaction(sig, &default, null); - _ = libc.raise(sig); - } - libc._exit(1); + const s: u32 = @bitCast(status); + if (libc.W.IFEXITED(s)) libc._exit(@intCast(libc.W.EXITSTATUS(s))); + if (libc.W.IFSIGNALED(s)) { + const sig = libc.W.TERMSIG(s); + const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 }; + posix.sigaction(sig, &default, null); + _ = libc.raise(sig); } - if (said.len > 0 and said[0] == 'x') libc._exit(std.fmt.parseInt(u8, said[1..], 10) catch 1); - out.writeStreamingAll(io, "pardes: the session ended without a word\n") catch {}; libc._exit(1); } @@ -642,16 +598,8 @@ pub fn tellStubDetached() void { stub = -1; } -/// The session's end, `code` its exit status: the stub is told (and goes). -pub fn tellStubExit(code: u8) void { - tellStub(stub, "x{d}", .{code}); - stub = -1; -} - -/// The stub on `fd` told how its terminal's session went, what stubWait -/// reads, and its pipe let go: `d` detached (one of a session's -/// several terminals, views.zig), `x` exited, `r` refused (an -/// attach that came too late). +/// The stub on `fd` told that its terminal's session detached +/// (`d`), what stubWait reads, and its pipe let go. pub fn tellStub(fd: c_int, comptime fmt: []const u8, args: anytype) void { if (fd < 0) return; var buf: [256]u8 = undefined; @@ -694,7 +642,7 @@ pub fn forkSession(conn: c_int) ?void { _ = libc.close(conn); // Off the session's way: it is drawing already, its hello queued. startPending(true); - stubWait(pid, true, pipe[0]); + stubWait(pid, pipe[0]); } // ---- the daemon ---- @@ -815,7 +763,7 @@ const Daemon = struct { }; const c = &d.conns[i]; var words = std.mem.tokenizeScalar(u8, got.words, ' '); - const Verb = enum { hello, state, clients, pty, close, quit, upgrade, list, kill, killall, adopt, attach }; + const Verb = enum { hello, state, clients, pty, close, quit, upgrade, list, kill, killall, adopt }; switch (std.meta.stringToEnum(Verb, words.next() orelse return) orelse return) { .hello => { const v = std.fmt.parseInt(u32, words.next() orelse "", 10) catch 0; @@ -880,95 +828,7 @@ const Daemon = struct { if (!send(c.fd, w.buffered(), fds[0..n])) return d.hangUp(i); for (given[0..n]) |h| h.owner = i; }, - .attach => { - const k = std.meta.stringToEnum(Kind, words.next() orelse "") orelse return d.reply(i, "no bad attach", &.{}); - const wanted_name = std.mem.trim(u8, words.rest(), " "); - var why: [512]u8 = undefined; - // "other ": the client joins it through the replica socket. - const target = d.find(k, wanted_name, &why) orelse return d.reply(i, std.mem.sliceTo(&why, 0), &.{}); - const t = &d.conns[target]; - if (!send(t.fd, "attach", got.fds[0..got.nfds])) { - d.hangUp(target); - return d.reply(i, "no that session does not answer", &.{}); - } - t.detached = false; - var line: [32]u8 = undefined; - return d.reply(i, std.fmt.bufPrint(&line, "ok {d}", .{t.pid}) catch unreachable, &.{}); // a pid fits 32 - }, - } - } - - /// The detached session of kind `k` called `wanted_name`, or the one - /// there is when it is empty; else null, and why not in `why` - /// (0-terminated): "other " for one to join as a replica - /// client (of the other kind, or attached already: a session shows one - /// frontend of its own). - fn find(d: *Daemon, k: Kind, wanted_name: []const u8, why: *[512]u8) ?u8 { - @memset(why, 0); - const other: []const u8 = switch (k) { - .tty => "a window: attach it with `pardes-gui --attach", - .gui => "a terminal session: attach it with `pardes --attach", - }; - if (wanted_name.len != 0) { - for (&d.conns, 0..) |*s, i| if (s.fd >= 0 and s.kind != null and std.mem.eql(u8, s.named(), wanted_name)) { - if (s.kind.? != k or !s.detached) { - _ = std.fmt.bufPrint(why, "other {s}", .{wanted_name}) catch {}; - return null; - } - return @as(u8, @intCast(i)); - }; - _ = std.fmt.bufPrint(why, "no no session called '{s}'", .{wanted_name}) catch {}; - return null; } - var found: ?u8 = null; - var count: usize = 0; - var others: usize = 0; - var w: std.Io.Writer = .fixed(why[0 .. why.len - 1]); - for (&d.conns, 0..) |*s, i| if (s.fd >= 0 and s.detached and s.kind != null) { - if (s.kind.? != k) { - others += 1; - continue; - } - count += 1; - found = @intCast(i); - }; - if (count == 1) return found.?; - // None detached: the one session there is, joined as a client. - if (count == 0) { - for (&d.conns, 0..) |*s, i| if (s.fd >= 0 and s.kind == k) { - count += 1; - found = @intCast(i); - }; - if (count == 1) { - _ = std.fmt.bufPrint(why, "other {s}", .{d.conns[found.?].named()}) catch unreachable; // a [128]u8 field's name fits 512 - return null; - } - count = 0; - // None of this kind at all: the one session there is, the other kind's. - var only: ?*Conn = null; - var sessions: usize = 0; - for (&d.conns) |*s| if (s.fd >= 0 and s.kind != null) { - sessions += 1; - only = s; - }; - if (found == null and sessions == 1) { - _ = std.fmt.bufPrint(why, "other {s}", .{only.?.named()}) catch unreachable; // a [128]u8 field's name fits 512 - return null; - } - } - if (count == 0 and others == 0) { - w.writeAll("no no detached session is running") catch unreachable; // a literal fits 511 - return null; - } - if (count == 0) { - w.print("no the detached session{s} running {s} {s}=`", .{ if (others == 1) " is" else "s are", if (others == 1) "is" else "are each", other }) catch {}; // cut short, still 0-terminated - return null; - } - w.print("no {d} detached sessions are running; say which with --attach=:", .{count}) catch unreachable; // a usize fits 511 - for (&d.conns) |*s| if (s.fd >= 0 and s.detached and s.kind == k) { - w.print(" {s}", .{s.named()}) catch {}; - }; - return null; } /// More of a replica's hello; once it is whole, the connection refused @@ -1239,13 +1099,3 @@ test "a message carries its words and its fds, and the peer's end is null" { _ = libc.close(pair[1]); try std.testing.expect(recv(pair[0], &buf) == null); } - -test "an attach by a name longer than any session's is refused in words, never an empty reason" { - var d: Daemon = .{}; - var why: [512]u8 = undefined; - const long: []const u8 = &@as([600]u8, @splat('n')); - try std.testing.expect(d.find(.tty, long, &why) == null); - const said = std.mem.sliceTo(&why, 0); - try std.testing.expect(std.mem.startsWith(u8, said, "no ")); - try std.testing.expect(said.len > "no ".len); -} diff --git a/runtime/macos.zig b/runtime/macos.zig index dc12a6fb..cfe93b13 100644 --- a/runtime/macos.zig +++ b/runtime/macos.zig @@ -835,7 +835,7 @@ fn drainInbox(st: *State) bool { // No daemon on macOS (daemon.supported): neither ever comes. // ponytail: no `job` host entry here either: a kind's jobs run // on the loop (host_io.KindJob.runHere), so none comes. - .files_changed, .fs_ready, .handed, .window, .adopted, .kind_job => {}, + .files_changed, .fs_ready, .handed, .adopted, .kind_job => {}, } } for (0..pardes.MAX_PANES) |pane| { diff --git a/runtime/main.zig b/runtime/main.zig index 448dfa57..563461ed 100644 --- a/runtime/main.zig +++ b/runtime/main.zig @@ -1595,7 +1595,6 @@ fn nativeMain(std_init: std.process.Init) !void { } } defer daemon.quit(); - errdefer daemon.tellStubExit(1); switch (pardes.platform) { .tui => @import("dev").tui.run(init, opts, term) catch |err| switch (err) { // No controlling terminal (a detached pty, a daemon): said, not @@ -1609,7 +1608,6 @@ fn nativeMain(std_init: std.process.Init) !void { .gui => try @import("dev").gui.run(init, opts, detached), .macos => unreachable, } - daemon.tellStubExit(0); } extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; @@ -1803,50 +1801,61 @@ fn attachClient(init: std.process.Init, opts: pardes.Options, where: []const u8, std.process.exit(0); } -/// `pardes --attach[=name]` in a terminal: this terminal handed (through -/// the daemon) to the detached session of that name, or the only one, and -/// this process its stub until the session leaves it. `pardes-gui -/// --attach`: the session asked to open its window again, and done. A -/// session attached already, or of the other kind, is joined as a replica -/// client, through this machine's replica socket. +/// `pardes attach [NAME]` (`pardes-gui` too): a client of the session of +/// that name on this machine, through its replica socket (the daemon +/// refuses a name no session has); bare, of the one `bareAttach` finds. fn attachTo(init: std.process.Init, opts: pardes.Options, name: []const u8) noreturn { const io = init.io; - var words: [600]u8 = undefined; if (comptime !daemon.supported) die(io, "--attach: this system has no pardes daemon to attach through", .{}); - if (pardes.platform == .gui) switch (daemon.attach(.gui, name, &.{}, &words)) { - .ok => std.process.exit(0), - .no => |why| die(io, "--attach: {s}", .{why}), - .other => |named| crossAttach(init, opts, named), - }; - const fd = std.c.open("/dev/tty", .{ .ACCMODE = .RDWR, .CLOEXEC = true, .NOCTTY = true }, @as(std.c.mode_t, 0)); - if (fd < 0) die(io, "--attach: no terminal to attach: /dev/tty will not open", .{}); - if (std.posix.tcgetattr(fd)) |tio| std.posix.tcsetattr(fd, .NOW, tio) catch {} else |_| {} - var pipe: [2]std.c.fd_t = undefined; - if (std.c.pipe(&pipe) != 0) die(io, "--attach: no pipe for the session to say when it leaves", .{}); - ninep_io.setCloexec(pipe[0]); - ninep_io.setCloexec(pipe[1]); - switch (daemon.attach(.tty, name, &.{ fd, pipe[1] }, &words)) { - .ok => |pid| { - _ = std.c.close(fd); - _ = std.c.close(pipe[1]); - daemon.stubWait(pid, false, pipe[0]); - }, - .no => |why| die(io, "--attach: {s}", .{why}), - .other => |named| { - _ = std.c.close(fd); - _ = std.c.close(pipe[0]); - _ = std.c.close(pipe[1]); - crossAttach(init, opts, named); - }, + var list: [4096]u8 = undefined; + var names_buf: [600]u8 = undefined; + var names: std.Io.Writer = .fixed(&names_buf); + const said = daemon.ask("list", &list) orelse die(io, "--attach: no pardes daemon is running", .{}); + const named = if (name.len != 0) name else bareAttach(said, &names) orelse if (names.end == 0) + die(io, "--attach: no session is running", .{}) + else + die(io, "--attach: say which session:{s}", .{names.buffered()}); + var sock_buf: [ninep_io.sun_path_len:0]u8 = undefined; + const sock = daemon.replicaSocket(&sock_buf) orelse die(io, "--attach: no runtime directory for the replica socket", .{}); + attachClient(init, opts, sock, named); +} + +/// The session a bare attach takes, from the daemon's `list`: the one +/// detached, else the one there is; null with none or several, every +/// session's name in `names`. +fn bareAttach(list: []const u8, names: *std.Io.Writer) ?[]const u8 { + var one: ?[]const u8 = null; + var detached: ?[]const u8 = null; + var n: usize = 0; + var n_detached: usize = 0; + var lines = std.mem.tokenizeScalar(u8, list, '\n'); + while (lines.next()) |line| { + var words = std.mem.tokenizeScalar(u8, line, ' '); + if (!std.mem.eql(u8, words.next() orelse "", "session")) continue; + _ = words.next(); // its pid + _ = words.next(); // its kind + const state = words.next() orelse continue; + one = std.mem.trim(u8, words.rest(), " "); + n += 1; + names.print(" {s}", .{one.?}) catch {}; // cut short + if (!std.mem.eql(u8, state, "detached")) continue; + detached = one; + n_detached += 1; } + if (n_detached == 1) return detached; + return if (n == 1) one else null; } -/// A session attached already or of the other kind (`--attach`'s): a -/// replica client of it here. -fn crossAttach(init: std.process.Init, opts: pardes.Options, name: []const u8) noreturn { - var sock_buf: [ninep_io.sun_path_len:0]u8 = undefined; - const sock = daemon.replicaSocket(&sock_buf) orelse die(init.io, "--attach: no runtime directory for the replica socket", .{}); - attachClient(init, opts, sock, name); +test "a bare attach takes the one detached session, else the one there is, else names them" { + var buf: [600]u8 = undefined; + 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).?); + names = .fixed(&buf); + try std.testing.expect(bareAttach("daemon 1\norphan 4\n", &names) == null); + try std.testing.expectEqual(@as(usize, 0), names.end); + try std.testing.expect(bareAttach("session 2 tty detached a\nsession 3 tty detached b c\n", &names) == null); + try std.testing.expectEqualStrings(" a b c", names.buffered()); } /// Where Recent's file (0.24) and the store before it were kept: diff --git a/runtime/session.zig b/runtime/session.zig index 3942aa83..55b42b60 100644 --- a/runtime/session.zig +++ b/runtime/session.zig @@ -23,8 +23,8 @@ //! listener's wake, a detached 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 (a terminal, an adopted shell, a -//! client's connection), onto its queue. +//! - `note(n)`: what the daemon says (an adopted shell, a client's +//! connection), onto its queue. //! - `watched()`: the files it watches (a Restore stops watching them). //! - `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 @@ -119,8 +119,7 @@ pub fn Loop(comptime Frontend: type) type { // Asked in the step (the word), done between steps: the // session whole. fe.upgradeAsked(); - // A terminal (`pardes --attach`), a window asked for again, - // an adopted shell or a client's connection, handed on by + // An adopted shell or a client's connection, handed on by // the daemon's thread; started after the first frame, off a // start's way. l.watch(); diff --git a/test/daemon.py b/test/daemon.py index e600beb7..31806863 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -2,8 +2,8 @@ """The per-user daemon end to end (docs/next-daemon.md, phase 3), under a private HOME and runtime directory: -- a terminal's session detached (the stub ends, exit 0) and attached again - from another terminal, N times; +- a terminal's session detached (the stub ends, exit 0), then attached + from another terminal N times, each a client (an attach is always one); - a session killed outright: its shells live on, held by the daemon, and another session adopts them as terminal panes; - a replica's hello on the daemon's stream socket (phase 5): one of this @@ -16,8 +16,8 @@ private HOME and runtime directory: - nothing left behind: no session, shell, daemon or socket. python3 -B test/daemon.py [cycles] - python3 -B test/daemon.py --gui [cycles] (a hidden window; - needs a Wayland display, and a pardes beside it for the refusal) + python3 -B test/daemon.py --gui [cycles] (hidden windows, + offscreen, and a pardes beside it for the terminal's client) python3 -B test/daemon.py --ping [n] a hello of 's build and n pings on a replica socket (one `ssh -L` forwards, say), timed @@ -428,8 +428,8 @@ def clients(binary): wait_for('both clients out of insert mode', lambda: normal_again(ta) and normal_again(tb)) wait_for('client A agrees once quiet', lambda: agreed(root / 'a.check', 0)) wait_for('client B agrees once quiet', lambda: agreed(root / 'b.check', 0)) - # A terminal attached while a client's view is live (its input the - # last): it takes the session's own and is drawn. + # A terminal attached by the session's name alone while a client's + # view is live (its input the last): a client too, drawn. tt = Term(24, 80) terms.append(tt) stub = tt.spawn([binary, '--attach=files'], env) @@ -1395,70 +1395,90 @@ def main(binary, cycles): shell = terminals(client)[0] shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1]) started.append(shell_pid) + # Detach in the terminal it was born with: the stub ends (exit 0, + # its words), the terminal put back; the session runs on detached, + # for good: every attach after it is a client. + client.write(f'/pane/{shell}/exec', b'Detach\n') + assert stub.wait(timeout=10) == 0, stub.returncode + # The stub's last words are in its terminal before it ends, but + # this side's reader may not have them yet. + wait_for('the stub says it detached', lambda: b'detached from \'work\', which is still running; come back with `pardes attach work`' in term.text()) + assert b'\x1b[?1049l' in term.text(), 'the terminal is put back' + term.close() + assert alive(session) and alive(shell_pid) + assert run(client, shell, b'echo still\n').startswith(b'exit 0\nstill'), 'the shell runs on, detached' + + def attach(term, argv, typed): + """A client: its own process, drawn, listed by --ps under the + session, detached still, and its keys in the shell.""" + c = term.spawn(argv, env) + started.append(c.pid) + 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 + 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 + + def let_go(how, c, term): + """Detach in it (its view the live one: it typed last), or its + terminal closed: it ends; the session and its shell run on.""" + if how == 'detach': + client.write(f'/pane/{shell}/exec', b'Detach\n') + assert c.wait(timeout=10) == 1, c.returncode + wait_for('the client says it was let go', lambda: b'let this client go' in term.text()) + else: + term.close() + c.wait(timeout=10) + if how == 'detach': + term.close() + assert alive(session) and alive(shell_pid) + baseline = None for cycle in range(cycles): - client.write(f'/pane/{shell}/exec', b'Detach\n') - assert stub.wait(timeout=10) == 0, stub.returncode - # The stub's last words are in its terminal before it ends, but - # this side's reader may not have them yet. - wait_for('the stub says it detached', lambda: b'detached from \'work\'' in term.text()) - said = term.text() - assert b'\x1b[?1049l' in said, 'the terminal is put back' - term.close() - assert alive(session) and alive(shell_pid) - assert run(client, shell, b'echo still\n').startswith(b'exit 0\nstill'), 'the shell runs on, detached' term = Term(30, 100) - stub = term.spawn([binary, '--attach=work'], env) - wait_for('the attached terminal\'s first frame', lambda: b'\x1b[?1049h' in term.text()) - wait_for('the session sized to its new terminal', - lambda: client.screen()['cols'] == 100 and client.screen()['rows'] == 30) + c = attach(term, [binary, '--attach=work'] if cycle % 2 else [binary, 'attach'], f'cycle-{cycle}') now = (fds(session), fds(daemon), len(list(root.iterdir())), len(processes(root))) if baseline is None: baseline = now assert now == baseline, (cycle, now, baseline) - print(f'daemon: {cycles} detach/attach cycles, fds/sockets/processes level: {baseline}') - - # Another terminal while one is attached: a replica client of the - # session (a session shows one frontend of its own), listed under - # it by --ps, drawn beside the first, typed into as the first is. - # Detached from inside, it ends and the first draws on; closed - # outright, the same. + let_go('detach' if cycle % 2 else 'close', c, term) + print(f'daemon: a Detach in its own terminal, then {cycles} attaches as clients (Detach in each, or its terminal closed), ' + f'fds/sockets/processes level: {baseline}') + + # Two clients at once, both listed by --ps, both typed into and + # drawn; the second let go by a Detach in it, or its terminal + # closed, and the first draws on. + term = Term(30, 100) + first = attach(term, [binary, 'attach', 'work'], 'first-in') for how in ('detach', 'close'): - # Bigger than the first: the shell, sized for the first (its - # last typist), shows whole in it. term2 = Term(40, 120) - stub2 = term2.spawn([binary, '--attach=work'], env) - started.append(stub2.pid) - wait_for('the second terminal\'s first frame', lambda: b'\x1b[?1049h' in term2.text()) - wait_for('the second terminal\'s view live', lambda: client.screen()['cols'] == 120) - listed = subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode() - assert f'client {stub2.pid} ' in listed, listed + second = attach(term2, [binary, 'attach', 'work'], f'two-typed-{how}') os.write(term.master, f'echo one-typed-{how}\r'.encode()) wait_for('the first terminal\'s keys in the shell', lambda: f'one-typed-{how}'.encode() in client.read(f'/pane/{shell}/body')) - os.write(term2.master, f'echo two-typed-{how}\r'.encode()) - wait_for('the second terminal\'s keys in the shell', lambda: f'two-typed-{how}'.encode() in client.read(f'/pane/{shell}/body')) + # (Words no line before has a letter of in the same place: a + # terminal is sent the cells that changed.) + drawn = f'{how.upper()}BOTHDRAWN' seen = len(term.text()) - run(client, shell, f'echo both-drawn-{how}\n'.encode()) - wait_for('the first terminal drawn', lambda: f'both-drawn-{how}'.encode() in term.text()[seen:]) - wait_for('the second terminal drawn', lambda: f'both-drawn-{how}'.encode() in term2.text()) - assert stub.poll() is None and stub2.poll() is None - if how == 'detach': - # Its view is the live one (its terminal spoke last). - client.write(f'/pane/{shell}/exec', b'Detach\n') - stub2.wait(timeout=10) - term2.close() - else: - term2.close() - stub2.wait(timeout=10) - wait_for('the first terminal\'s view live again', lambda: client.screen()['cols'] == 100) - wait_for('the client gone from --ps', lambda: 'client ' not in subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode()) + run(client, shell, f'echo {drawn}\n'.encode()) + wait_for('the first terminal drawn', lambda: drawn.encode() in term.text()[seen:]) + wait_for('the second terminal drawn', lambda: drawn.encode() in term2.text()) + assert first.poll() is None and second.poll() is None + # Its view the live one: it typed last. + os.write(term2.master, f'echo two-last-{how}\r'.encode()) + wait_for('the second terminal\'s keys in the shell', lambda: f'two-last-{how}'.encode() in client.read(f'/pane/{shell}/body')) + let_go(how, second, term2) + wait_for('the client gone from --ps', lambda: f'client {second.pid} ' not in subprocess.run([binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode()) + drawn = f'{how.upper()}FIRSTON' seen = len(term.text()) - run(client, shell, f'echo first-on-{how}\n'.encode()) - wait_for('the first terminal drawn on', lambda: f'first-on-{how}'.encode() in term.text()[seen:]) - assert stub.poll() is None, 'the first terminal stays attached' + run(client, shell, f'echo {drawn}\n'.encode()) + wait_for('the first terminal drawn on', lambda: drawn.encode() in term.text()[seen:]) + assert first.poll() is None, 'the first client stays' now = (fds(session), fds(daemon), len(list(root.iterdir())), len([p for p in processes(root) if alive(p)])) assert now[:3] == baseline[:3], (how, now, baseline) - print('daemon: a second terminal on an attached session a client of it (in --ps), both typed into and drawn, then detached and closed; the first drew on') + print('daemon: two clients at once, each in --ps, both typed into and drawn; the second detached, then closed; the first drew on') + stub = first # Killed outright: its shells live on, their masters the daemon's, # and a replica client of it hears so at once, in words (one froze @@ -1507,22 +1527,33 @@ def main(binary, cycles): shell.kill() shell.wait(timeout=10) term.close() - term = Term() - stub = term.spawn([binary, '--attach=fresh'], env) - wait_for('the attached terminal\'s first frame', lambda: b'\x1b[?1049h' in term.text()) - wait_for('the session sized to its new terminal', lambda: not sized(client)) - print('daemon: a session whose stub was killed outright detached, and was attached again') before = set(terminals(client)) client.write(f'/pane/{min(before)}/exec', b'Adopt\n') adopted = wait_for('the adopted pane', lambda: set(terminals(client)) - before) pane = adopted.pop() + # Sized twice (Ptys.take): a run into a prompt redrawn under it + # reads as not run (core/ninep/pty.zig). + wait_for('the adopted shell answers', lambda: run(client, pane, b'true\n') == b'exit 0\n') said = run(client, pane, b'echo $$\n') assert said.split(b'\n')[1] == str(shell_pid).encode(), said print(f'daemon: shell {shell_pid} outlived kill -9 of its session and was adopted') - - # The end: the session quits, its shells hang up, the daemon goes. - client.write(f'/pane/{pane}/exec', b'Exit\n') - stub.wait(timeout=10) + # Attached again: a client. (After the runs: a pty/run under a + # client puts it off the session's state, and it joins again; one + # that tries as the session ends says it could not.) + term = Term() + stub = term.spawn([binary, 'attach', 'fresh'], env) + started.append(stub.pid) + 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 + 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 + # the daemon go. + exit_session(client, pane) + assert stub.wait(timeout=10) == 1, stub.returncode + wait_for('the client says it was let go', lambda: b'let this client go' in term.text()) client.socket.close() term.close() wait_for('the adopted shell hung up', lambda: not alive(shell_pid)) @@ -1551,62 +1582,67 @@ def sized(client): def gui(binary, cycles): - """A window's Detach closes it and keeps the process; `pardes-gui - --attach` opens it again. Test mode: a hidden window, its stdin the - test feed.""" + """A window's Detach closes it and keeps the process, detached for good: + `pardes-gui attach` is a window client of it, a process of its own, + and so is a terminal's `pardes attach`. Test mode: hidden windows, + offscreen, the session's stdin the test feed.""" 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} - 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 (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'), - SDL_VIDEODRIVER='wayland', WAYLAND_DISPLAY=str(display), PARDES_DAEMON='on') + SDL_VIDEO_DRIVER='offscreen', PARDES_DAEMON='on', TERM='xterm-256color') (root / 'config' / 'pardes').mkdir(parents=True) (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') feed_r, feed_w = os.pipe() proc = subprocess.Popen([binary, '--9p=win'], env=env, cwd=root, stdin=feed_r, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) os.close(feed_r) + + def listed(): + return subprocess.run([binary, '--ps'], env=env, cwd=root, capture_output=True, timeout=30).stdout.decode() + try: sock = root / 'pardes-9p-win.sock' wait_for('the window session', sock.exists, timeout=20) client = Client(sock) shell = terminals(client)[0] assert not sized(client), 'a window owns the size' - baseline = None - for cycle in range(cycles): - 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' - attach = subprocess.run([binary, '--attach=win'], env=env, cwd=root, timeout=10, - stdout=subprocess.PIPE, stderr=subprocess.PIPE) - assert attach.returncode == 0, attach.stderr - wait_for('the window open again', lambda: not sized(client)) - now = (fds(proc.pid), len(processes(root))) - baseline = baseline or now - assert now == baseline, (cycle, now, baseline) - print(f'daemon: {cycles} window detach/attach cycles, fds/processes level: {baseline}') - # Attached already: another window is a replica client of the - # session (its own process, its captures its own), listed by --ps; - # closed, it ends alone. + # With its window: another window is a client of the session (its + # own process, its captures its own), listed by --ps; closed, it + # ends alone. second = Window(root, 'second', [binary, '--attach=win'], env) wait_for('the second window drawn', lambda: (root / 'second' / 'latest.ppm').exists(), timeout=20) - listed = subprocess.run([binary, '--ps'], env=env, cwd=root, capture_output=True, timeout=30).stdout.decode() - assert f'client {second.pid} ' in listed, listed + assert f'client {second.pid} ' in listed(), listed() second.close() - wait_for('the client gone from --ps', lambda: 'client ' not in subprocess.run([binary, '--ps'], env=env, cwd=root, capture_output=True, timeout=30).stdout.decode()) + wait_for('the client gone from --ps', lambda: 'client ' not in listed()) assert not sized(client), 'the first window stays' assert proc.poll() is None - print('daemon: a second window on an attached window session a client of it (in --ps), closed alone') - # Another kind joins as a replica client: a terminal of the window's - # session, by its name alone. A name nobody has is refused in words. + 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() + 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() + now = (fds(proc.pid), len(processes(root))) + baseline = baseline or now + assert now == baseline, (cycle, now, baseline) + w.close() + wait_for('the client gone from --ps', lambda: 'client ' not in listed()) + print(f'daemon: a window Detach, then {cycles} window attaches as clients, fds/processes level: {baseline}') + # A terminal's client of the window's session, by its name alone. A + # name nobody has is refused in words. term = Term() - tty_attach = term.spawn([binary.replace('pardes-gui', 'pardes'), '--attach=win'], env) + tty_attach = term.spawn([binary.replace('pardes-gui', 'pardes'), 'attach', 'win'], env) wait_for('the window session drawn in the terminal', lambda: b'\x1b[?1049h' in term.text()) time.sleep(1) assert tty_attach.poll() is None, term.text()[-400:] -- cgit v1.3 From 1967cf64dc6d7490d386db874cf1866b764f235c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 02:21:52 -0300 Subject: daemon: a session registers again with a daemon that was restarted: its link's reader, woken by the link's end alone (no timer, no poll: an idle session stays at 0 wakeups), dials the next daemon, starting one if none answers, and says its hello again on the link's own fd (dup3, so the session's own sends never race a new fd); the session loop, woken once by the note, tells it its shells' masters (`Ptys.tellDaemon`) and its clients again (`relinked`); a link the daemon never took (another build's) or the session's own end (`quit`) is not dialled again; test/daemon.py's `relink` (in plain, and alone as `--relink`), first failing on the base ("a daemon again" timed out: nothing dialled), now: the daemon killed, its two sessions (one detached, one with its terminal) start the next and are listed again with their shells, a client attaches, the detached one killed outright leaves its shell to another's Adopt, 0 and 0 wakeups in 2 s before and after; and the killed-session words in daemon.py read once the test's terminal has them (a race of the test's own); gated with the previous change, Debug: tui core-test 855/1005, shell-test 1046/1049, term 17/17, pane 183/184, kitty 45/45, behaviour 275/275 and its replay, process-test 0 of 144 failed, both soaks diverged 0 unequal 0 at 30/80/207 ms (corpus 22 scenes the same), daemon.py plain (50 cycles), far, games, window-clients, gui, upgrade both ways with clients attached pass; gui unit-test 1643/1647 (BaselineHarnessMismatch only); macOS x86_64 and aarch64, FreeBSD cross-builds pass; the frame and perf gate against tree2 PASS: 77/77 frames, perfab-corpus2x -0.114% (threshold 0.4%), 121 per-operation counts within 0.1% (largest +0.014%) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- dev/Ptys.zig | 6 +++ dev/gui/gui.zig | 1 + dev/tui/tui.zig | 2 + runtime/daemon.zig | 124 ++++++++++++++++++++++++++++++++-------------- runtime/session.zig | 6 ++- test/daemon.py | 138 +++++++++++++++++++++++++++++++++++++++++++++++++++- 6 files changed, 237 insertions(+), 40 deletions(-) diff --git a/dev/Ptys.zig b/dev/Ptys.zig index 97c5cfde..16a31939 100644 --- a/dev/Ptys.zig +++ b/dev/Ptys.zig @@ -156,6 +156,12 @@ pub fn signal(p: *Ptys, id: pardes.Pane.Id, sig: pardes.PtySignal) void { if (p.slots[id.index()]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.fd, sig, pt.cmd.watched); } +/// A daemon started since the last one died: every master told it again, +/// as `spawn` tells the first (host_io.forkShell). +pub fn tellDaemon(p: *const Ptys) void { + for (p.slots) |slot| if (slot) |pt| daemon.pty(pt.pid, pt.fd); +} + /// The pane is gone, or its shell is: its reader out of the queue first /// (which lets go one waiting for room there) and canceled; its pty hung /// up, which the kernel passes on to the shell as SIGHUP; the daemon's diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index 81d58137..2aaa8bcc 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -3182,6 +3182,7 @@ 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 } }); diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index 42f73559..c54447c7 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -1101,6 +1101,8 @@ fn clearNativeImages( 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); diff --git a/runtime/daemon.zig b/runtime/daemon.zig index 1b9149b6..80e1cc09 100644 --- a/runtime/daemon.zig +++ b/runtime/daemon.zig @@ -12,7 +12,8 @@ //! - whether a terminal or a window shows it (`state`). //! It lists the sessions (`pardes ps`), hands a crashed session's masters //! to the one that asks for them (Adopt), and a client's connection to the -//! session it names (below). +//! session it names (below). A session whose daemon died dials the next +//! one and registers again (`readNotes`). //! //! Messages are SOCK_SEQPACKET datagrams: a line of words, and the fds it //! carries (SCM_RIGHTS). @@ -290,9 +291,17 @@ fn hello(fd: c_int, k: Kind, pid: libc.pid_t, named: []const u8, detached: bool) /// 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. +/// `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 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. +var kind: Kind = .tty; +var detached_now = std.atomic.Value(bool).init(false); /// What it is called (its 9P name). var name_buf: [128]u8 = undefined; var name_len: usize = 0; @@ -328,6 +337,8 @@ fn setName(named: []const u8) void { pub fn register(fd: ?c_int, k: Kind, named: []const u8, detached: bool) bool { if (comptime !supported) return false; setName(named); + kind = k; + detached_now.store(detached, .release); const c = fd orelse connect(true) orelse return false; startPending(true); if (!hello(c, k, libc.getpid(), name(), detached)) { @@ -362,19 +373,33 @@ 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); tell("state detached", &.{}); } +/// The last `clients` line, kept to be told to a new daemon (`relinked`). +var clients_line: ["clients".len + max_clients * " -2147483648".len]u8 = undefined; +var clients_len: usize = 0; + /// This session's replica clients now, each its process's pid (0 when its /// socket's peer is not known), for `--ps`. pub fn clients(pids: []const libc.pid_t) void { - var buf: ["clients".len + max_clients * " -2147483648".len]u8 = undefined; - var w: std.Io.Writer = .fixed(&buf); - w.writeAll("clients") catch unreachable; // a literal, its .len in buf's - for (pids[0..@min(pids.len, max_clients)]) |pid| w.print(" {d}", .{pid}) catch unreachable; // max_clients i32s, in buf's type + var w: std.Io.Writer = .fixed(&clients_line); + w.writeAll("clients") catch unreachable; // a literal, its .len in clients_line's + for (pids[0..@min(pids.len, max_clients)]) |pid| w.print(" {d}", .{pid}) catch unreachable; // max_clients i32s, in clients_line's type + clients_len = w.end; tell(w.buffered(), &.{}); } +/// Whether a new daemon took this session's hello since the last call +/// (the session loop's, each pass): its clients told it again here, its +/// ptys the caller's to tell (`pty`). +pub fn relinked() bool { + if (!retell.swap(false, .acq_rel)) return false; + if (clients_len > 0) tell(clients_line[0..clients_len], &.{}); + return true; +} + /// Asks for the masters of sessions that died holding them; they come back /// as an `adopted` note. pub fn adopt() void { @@ -396,10 +421,15 @@ pub fn resumeLink(fd: c_int, stub_fd: c_int, k: Kind, named: []const u8, detache 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); } pub const Note = union(enum) { + /// A new daemon took the hello (`readNotes`): the session loop is woken + /// to tell it the rest (`relinked`). + relinked, adopted: struct { pids: [max_fds]libc.pid_t, fds: [max_fds]c_int, n: usize }, /// A replica's connection, its hello taken (core/replica.zig `Peers`), /// and the view it joins again for, if it does. @@ -417,39 +447,58 @@ pub fn watch(ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) v fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void { var buf: [msg_max]u8 = undefined; - // The end of the link (a daemon gone, a hello refused): not kept. - defer { - up.store(false, .release); - gone.store(true, .release); - } - 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), - .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 } }); - for (got.fds[@min(got.nfds, 1)..got.nfds]) |f| _ = libc.close(f); - }, - .adopted => { - var note: Note = .{ .adopted = .{ .pids = undefined, .fds = undefined, .n = 0 } }; - const a = ¬e.adopted; - for (got.fds[0..got.nfds]) |f| { - const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch { - _ = libc.close(f); - continue; - }; - a.pids[a.n] = pid; - a.fds[a.n] = f; - a.n += 1; - } - deliver(ctx, note); - }, - } else for (got.fds[0..got.nfds]) |f| { - _ = libc.close(f); + 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), + .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 } }); + for (got.fds[@min(got.nfds, 1)..got.nfds]) |f| _ = libc.close(f); + }, + .adopted => { + var note: Note = .{ .adopted = .{ .pids = undefined, .fds = undefined, .n = 0 } }; + const a = ¬e.adopted; + for (got.fds[0..got.nfds]) |f| { + const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch { + _ = libc.close(f); + continue; + }; + a.pids[a.n] = pid; + a.fds[a.n] = f; + a.n += 1; + } + deliver(ctx, note); + }, + } else for (got.fds[0..got.nfds]) |f| { + _ = libc.close(f); + } } + // The end of the link. One whose daemon took the hello (it died, or + // let the session go) is dialled again, a daemon started if none + // answers, and the hello said, here, off the session's way: the + // 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; + retell.store(true, .release); + deliver(ctx, .relinked); } + // Not kept, until the session's end. + gone.store(true, .release); +} + +/// A new connection in the place of `fd`, the link (its number kept, so +/// the session's own sends never race a new fd), and the hello said on it. +fn redial(fd: c_int) bool { + if (comptime !supported) return false; + const c = connect(true) orelse return false; + 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)); } /// `bytes` sent whole on a socket, never raising SIGPIPE: false when the @@ -485,6 +534,7 @@ pub fn hangUp() void { /// link closed, the reader joined. pub fn quit() void { if (link < 0) return; + quitting.store(true, .release); tell("quit", &.{}); _ = libc.shutdown(link, 2); if (reader) |r| r.join(); diff --git a/runtime/session.zig b/runtime/session.zig index 55b42b60..4172ba8d 100644 --- a/runtime/session.zig +++ b/runtime/session.zig @@ -24,7 +24,7 @@ //! - `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), onto its queue. +//! connection, a new daemon's hello taken), onto its queue. //! - `watched()`: the files it watches (a Restore stops watching them). //! - `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 @@ -139,8 +139,10 @@ pub fn Loop(comptime Frontend: type) type { } /// What the daemon says, onto the frontend's queue (once: its - /// reader is started by the first call). + /// 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); } diff --git a/test/daemon.py b/test/daemon.py index 31806863..d9706f04 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -4,6 +4,8 @@ private HOME and runtime directory: - a terminal's session detached (the stub ends, exit 0), then attached from another terminal N times, each a client (an attach is always one); +- the daemon killed: its sessions start the next and register again with + it, their shells too, and a client attaches (`relink`); - a session killed outright: its shells live on, held by the daemon, and another session adopts them as terminal panes; - a replica's hello on the daemon's stream socket (phase 5): one of this @@ -23,6 +25,8 @@ private HOME and runtime directory: `ssh -L` forwards, say), timed python3 -B test/daemon.py --clients the replica clients alone + python3 -B test/daemon.py --relink + the daemon killed: its sessions register again with the next python3 -B test/daemon.py --far the far clients and their blob cache alone, and a file by its hash python3 -B test/daemon.py --games [seconds] @@ -606,6 +610,132 @@ def manage(binary): shutil.rmtree(root, ignore_errors=True) +def wakeups(pid, secs): + """Its threads' context switches over `secs` (Linux's /proc): none for + a process nothing wakes.""" + def count(): + n = 0 + for task in os.listdir(f'/proc/{pid}/task'): + try: + for line in open(f'/proc/{pid}/task/{task}/status'): + if line.split(':')[0] in ('voluntary_ctxt_switches', 'nonvoluntary_ctxt_switches'): + n += int(line.split()[1]) + except OSError: + pass + return n + before = count() + time.sleep(secs) + return count() - before + + +def relink(binary): + """The daemon killed outright (docs/next-run.md, "A session registering + again"): a detached session and a terminal's, each with a shell, dial + the next daemon themselves (the first to find none starts it) and + register again with their shells' masters, so `--ps` lists both and + their shells, a client attaches, and the session then killed outright + leaves its shell to an Adopt. An idle session stays idle before and + after.""" + 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'), + 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') + + def listed(): + out = subprocess.run([binary, '--ps'], env=env, cwd=root, capture_output=True, timeout=30) + return out.stdout.decode() if out.returncode == 0 else '' + + def daemons(): + return [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon'] and alive(p)] + + started = [] + terms = [] + try: + (root / 'notes.txt').write_text('notes\n') + started.append(subprocess.Popen([binary, '--detach=work', str(root / 'notes.txt')], env=env, cwd=root, + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True).pid) + wait_for('the detached session\'s 9P socket', (root / 'pardes-9p-work.sock').exists) + work = Client(root / 'pardes-9p-work.sock') + session = int(dict(line.split(maxsplit=1) for line in work.read('/status').decode().splitlines())['pid']) + started.append(session) + work.write('/pane/1/exec', b'Term\n') + wait_for('its shell', lambda: terminals(work)) + shell = terminals(work)[0] + wait_for('its shell answers', lambda: run(work, shell, b'true\n') == b'exit 0\n') + shell_pid = int(run(work, shell, b'echo $$\n').split(b'\n')[1]) + started.append(shell_pid) + term = Term() + terms.append(term) + stub = term.spawn([binary, '--tty', '--9p=own'], env) + started.append(stub.pid) + wait_for('the terminal\'s session', (root / 'pardes-9p-own.sock').exists) + own = Client(root / 'pardes-9p-own.sock') + own_pid = int(dict(line.split(maxsplit=1) for line in own.read('/status').decode().splitlines())['pid']) + started.append(own_pid) + wait_for('its first frame', lambda: b'\x1b[?1049h' in term.text()) + 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)', + f'shell {shell_pid}', f'shell {own_shell_pid}'] + assert all(row in listed() for row in expected), listed() + daemon = daemons()[0] + idle = wakeups(session, 2) if procfs else 0 + os.kill(daemon, signal.SIGKILL) + wait_for('the daemon gone', lambda: not alive(daemon)) + # Nobody runs pardes again: the sessions start the next one. + again = wait_for('a daemon again', daemons)[0] + started.append(again) + wait_for('both sessions and their shells listed again', lambda: all(row in listed() for row in expected)) + idle_after = wakeups(session, 2) if procfs else 0 + assert idle <= 2 and idle_after <= 2, ('an idle session woke', idle, idle_after) + print(f'relink: daemon {daemon} killed, {again} started by its sessions, both listed again with their shells; ' + f'the detached one idle before and after ({idle} and {idle_after} wakeups in 2 s)') + tc = Term(30, 100) + terms.append(tc) + c = tc.spawn([binary, 'attach', 'work'], env) + started.append(c.pid) + wait_for('the client\'s first frame', lambda: b'notes' in tc.text(), timeout=30) + wait_for('the client in --ps', lambda: f'client {c.pid} ' in listed()) + c.send_signal(signal.SIGHUP) + c.wait(timeout=10) + os.kill(session, signal.SIGKILL) + wait_for('the killed session gone', lambda: not alive(session)) + wait_for('its shell no session\'s', lambda: 'no session holds' in listed()) + assert alive(shell_pid), 'the new daemon held its master' + before = set(terminals(own)) + own.write(f'/pane/{min(before)}/exec', b'Adopt\n') + pane = wait_for('the adopted pane', lambda: set(terminals(own)) - before).pop() + assert run(own, pane, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode() + print(f'relink: a client attached to the session through the new daemon; killed outright, its shell {shell_pid} was adopted') + exit_session(own, pane) + stub.wait(timeout=10) + own.socket.close() + work.socket.close() + wait_for('the shells hung up', lambda: not alive(shell_pid) and not alive(own_shell_pid)) + wait_for('the daemon gone once idle', lambda: not alive(again), timeout=5) + left = [p for p in processes(root) if alive(p)] + assert not left, [cmdline(p) for p in left] + print('relink: nothing left behind') + finally: + 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 @@ -1392,6 +1522,7 @@ def main(binary, cycles): far(binary) by_hash(binary) manage(binary) + relink(binary) shell = terminals(client)[0] shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1]) started.append(shell_pid) @@ -1490,7 +1621,10 @@ def main(binary, cycles): os.kill(session, signal.SIGKILL) killed = time.monotonic() wait_for('the replica client ended with its session', lambda: rc.poll() is not None, timeout=10) - assert time.monotonic() - killed < 2 and b'let this client go' in tr.text(), (time.monotonic() - killed, tr.text()[-300:]) + assert time.monotonic() - killed < 2, time.monotonic() - killed + # Its words are in its terminal before it ends, but this side's + # reader may not have them yet. + wait_for('the replica client says it was let go', lambda: b'let this client go' in tr.text()) tr.close() stub.wait(timeout=10) client.socket.close() @@ -2097,6 +2231,8 @@ if __name__ == '__main__': clients(sys.argv[2]) elif sys.argv[1:2] == ['--manage']: manage(sys.argv[2]) + elif sys.argv[1:2] == ['--relink']: + relink(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']: -- cgit v1.3 From a6c258bec5808ac2b6ef9d3362134e34e759c1c9 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 03:20:39 -0300 Subject: docs: an attach is always a client, and a session registers again with a restarted daemon, in the documents: the manual's "How pardes runs" (docs/typ/running.typ: one Attach section, its figure of the in-place attach deleted from figures.typ, the glance and survival tables, the words), the guide's Sessions, the reference's /sessions and command line, the building chapter's daemon, the cheatsheet's line, `pardes help attach` (runtime/main.zig, docs/typ/command-line.txt from builtins-json), the Detach word's doc (core/builtins.zig, both builtins JSONs), docs/next-run.md as built (what went, counted on the change: 305 lines deleted, 94 added; the re-registration as built; --detach forking still not) with its figure (Before / Now), and the changelog's Unreleased; the book and the cheatsheet render (typst), tui shell-test 1046/1049 (3 skipped), core-test 855/1005 (150 skipped: the base's 856/1006 less the deleted `find` test) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/CHANGELOG.md | 20 ++++++ core/builtins.zig | 2 +- docs/next-run.md | 157 +++++++++++++++++++++++++-------------------- docs/next-run.svg | 2 +- docs/next-run.typ | 4 +- docs/typ/building.typ | 17 +++-- docs/typ/builtins-gui.json | 2 +- docs/typ/builtins-tui.json | 2 +- docs/typ/cheatsheet.typ | 2 +- docs/typ/command-line.txt | 21 +++--- docs/typ/figures.typ | 46 +++---------- docs/typ/guide.typ | 27 ++++---- docs/typ/reference.typ | 18 +++--- docs/typ/running.typ | 148 ++++++++++++++++++++---------------------- runtime/main.zig | 21 +++--- 15 files changed, 247 insertions(+), 242 deletions(-) diff --git a/core/CHANGELOG.md b/core/CHANGELOG.md index 9b551e9b..fe9adec8 100644 --- a/core/CHANGELOG.md +++ b/core/CHANGELOG.md @@ -2,6 +2,26 @@ ## Unreleased +- `pardes attach NAME` (and `pardes-gui attach NAME`) is always a client: + a process of its own with its own view, whatever the session was + started in. A session's own terminal or window is only the one it was + born with: once a Detach or its terminal let it go, it never takes one + back. Before, an attach to a detached terminal's session handed it this + terminal (the attach waiting as its stub), and `pardes-gui attach` asked + a detached window's session to open its own window again and exited 0. + A client's Detach ends it with "'NAME' let this client go" and exit 1, + where the stub said "detached from 'NAME'" and exited 0. Bare, `pardes + attach` takes the one detached session, else the one session, of either + kind; with several it names them all. + +- A session whose daemon was killed starts the next one itself and + registers with it again, its shells' terminals and its clients with it: + `pardes ps` lists it, an attach and Adopt find it, and Detach works. It + ran on unlisted for good before, and its terminal closing ended it. + +- The words `pardes` says at a Detach name `pardes attach NAME`, the + command's spelling now, not `--attach=NAME`. + - On a client, and so on a far one, what changes only the editor is applied at once and only what touches the session's machine waits for it (a save, a shell's keys, a file read from disk, a program run, a diff --git a/core/builtins.zig b/core/builtins.zig index 1a0b4ce7..2740e05a 100644 --- a/core/builtins.zig +++ b/core/builtins.zig @@ -532,7 +532,7 @@ pub const Restore = struct { }; /// Detach this pardes from its terminal or window, leaving the session -/// running: `pardes --attach` (or `pardes-gui --attach`) takes it back. +/// running: `pardes attach` (or `pardes-gui attach`) shows it as a client. pub const Detach = struct { pub const scope: Scope = .session; pub const enabled = pardes.can_attach; diff --git a/docs/next-run.md b/docs/next-run.md index 06941026..74eab197 100644 --- a/docs/next-run.md +++ b/docs/next-run.md @@ -1,4 +1,4 @@ -# Running pardes: an attach is always a client (ruled, not built) +# Running pardes: an attach is always a client (ruled; built 2026-11-20, all but `--detach` forking) > the way it's distributed with client/server and detached and stuff, it's > confusing to me now and I think it must be confusing in the code too, @@ -7,69 +7,84 @@ Ruled by the user on 2026-11-17, answering the reorganisation plan's questions: the words of distribution (*session*, *client*, *far*, *frontend*, *detached*, *attach*); "attach is always a client"; the daemon -stays as built; the vocabulary and the manual's page first, no code moved -yet. Nothing in this note is built. What runs today, with a figure for each -way of starting pardes, is the manual's "How pardes runs" +stays as built; the vocabulary and the manual's page first, the code +after. Built on 2026-11-20 (agent pardes-attach, report +`.scratch/sketch/reports/pardes-attach.md`): an attach is always a client, +the in-place attach deleted, and a session registering again with a +restarted daemon. Not built: `--detach` forking (below). What runs, with a +figure for each way of starting pardes, is the manual's "How pardes runs" (`docs/typ/running.typ`); the daemon's history is `docs/next-daemon.md`. -Line numbers are this tree's, 2026-11-19. ## The ruling A session's own frontend is only the one it was born with. Once it has let that go (a Detach, its terminal or window closing), it stays detached, and every attach after that is a client: a process of its own with a -replica core, as the second attach to a session is today. +replica core, as the second attach to a session already was. Two more things go with it (the coordinator's, put to the user with the question): - a session registers again with a daemon that was restarted, so a daemon's - death no longer leaves its sessions unlisted for good; + death no longer leaves its sessions unlisted for good (built); - `--detach` forks as a terminal's session does, so the process you typed - returns at once and `ps` always shows a session the same way. + returns at once and `ps` always shows a session the same way (not + built). -## Today, and after +## Before, and now -![What `pardes attach` does today, and after](next-run.svg) +![What `pardes attach` did before, and does now](next-run.svg) The figure is `docs/next-run.typ`, drawn by `docs/typ/figures.typ` (`typst compile --root . --ignore-system-fonts -f svg docs/next-run.typ docs/next-run.svg`). -Today `pardes attach` is four mechanisms, picked by the daemon's `find` -(`runtime/daemon.zig:901-972`) and by `main.zig`'s `attachTo` -(`runtime/main.zig:1806-1842`): a terminal handed to a detached terminal's -session, which draws on it in its own process while the attach process -waits as its stub; a window's detached session asked to open its own -window again, while the attach process exits; a client here, when the -session has a frontend or is of the other kind; a far client through -`ssh -L`. After, it is the last two only: a client, here or far. - -## What it removes - -The reorganisation plan's option b, checked against this tree: - -| What goes | Where today | Lines, about | +Before, `pardes attach` was four mechanisms, picked by the daemon's `find` +and by `main.zig`'s `attachTo`: a terminal handed to a detached terminal's +session, which drew on it in its own process while the attach process +waited as its stub; a window's detached session asked to open its own +window again, while the attach process exited; a client here, when the +session had a frontend or was of the other kind; a far client through +`ssh -L`. Now it is the last two only: a client, here or far. +`runtime/main.zig`'s `attachTo` goes to this machine's replica socket with +the name (the daemon refuses one no session has); bare, `bareAttach` takes +the one detached session from the daemon's `list`, else the one session, +else names them and asks which. + +What a user who relied on the in-place attach does now: `pardes attach +work` (or `pardes-gui attach work`) is a client of the detached session, +its own process in this terminal or window. What differs from having the +session's own frontend back: the client is a second process (a terminal's +10-16 MB, a window's about 110 MB); an addon that is not plain runs in the +session alone (its panes show a line saying so); its Detach, or its +terminal closing, ends the client with "'work' let this client go" and exit +1, where the stub said "detached from 'work'" and exit 0 (the last word a +session sends its client, and exit codes, are the next steps: "B" in +`.scratch/sketch/reports/pardes-last-step-design.md`). + +## What it removed + +Counted on the change itself (deleted lines, comments with them; a +function's added replacement in brackets): + +| What went | Where | Lines | |---|---|---| -| A terminal handed to a session: the daemon's `attach` request and answer, the session's `attachTerminal`, the `attach` note and message | `runtime/daemon.zig:400-403`, `:431-437`, `:504-533`, `:883-897`; `dev/tui/tui.zig:107-109`, `:1037-1040`, `:1135-1140`, `:1354-1387`, `:1711`; `runtime/main.zig:1821-1842` | 110 | -| A window opened again in place | `dev/gui/gui.zig:550-557` (what it reopens with), `:1004-1022` (`reopenWindow`), `:2588-2601` (`openTheWindow`), `:2823`, `:3388-3394` | 50 | -| The daemon choosing which session takes a frontend: `find`, its `other` answer, the use of `daemon.Kind` to match | `runtime/daemon.zig:901-972`, `:506-509` | 75 | -| The stub's second use: an attach process waiting on a session that is not its child (`stubWait`'s `child = false`, its `r` refusals) | `runtime/daemon.zig:561-616` in part (`:593-597`, `:613-615`) | 10 | - -What does not go, against the plan's list: the upgrade record's terminal -and window fields. A session born with a terminal still takes it across an -Upgrade (`dev/tui/tui.zig:1438-1446`, `runtime/upgrade.zig:101-117`), and a window's still -says whether it had its window (`dev/gui/gui.zig:2656`). Only the record's other -terminals (`dev/tui/tui.zig:1487-1506`, a build's from before 2026-11-06, when a -second local terminal stopped being the session's) are already dead weight. -Detach of the session's own frontend stays too (`dev/tui/tui.zig:1327-1352`, -`dev/gui/gui.zig:2530-2539`, `:2575-2586`): it is how a session becomes detached. -`daemon.Kind` stays in the hello and in `pardes ps` (`tty` or `gui`). - -The plan counted 87 + about 60 + 67 lines for the first three rows; the -counts above include each piece's comments and its callers' lines. - -## What a client lacks today, which the change makes work +| The daemon choosing which session takes a frontend: `find`, its `other` answer, the `attach` verb and its test | `runtime/daemon.zig` `Daemon.find`, `Daemon.take` | 99 | +| The attach request: `daemon.attach`, `Answer`, `Note.attach` and the reader's arm | `runtime/daemon.zig` | 36 | +| The stub's second use: `stubWait`'s `child` and its `r` and `x` words, `tellStubExit` | `runtime/daemon.zig`, `runtime/main.zig` | 37 | +| `attachTo`'s two hand-offs and `crossAttach` | `runtime/main.zig` | 41 (+16: `attachTo`; +33: `bareAttach` and its test, what `find` chose, done here) | +| A terminal handed to a session: `attachTerminal`, `refuse`, the `.attach` message and its three arms | `dev/tui/tui.zig` | 52 | +| A window opened again in place: `openTheWindow`, `Shell.detached`, the queue's `.window` and its arms | `dev/gui/gui.zig`, `dev/Inbox.zig`, `runtime/macos.zig` | 34 | +| `setState(false)`, which nothing says now | `runtime/daemon.zig` (`setDetached`) | 2 | +| **in all** | | **305 deleted, 94 added** | + +What did not go: the upgrade record's terminal and window fields (a +session born with a terminal still takes it across an Upgrade); Detach of +the session's own frontend (it is how a session becomes detached); +`reopenWindow`, which a WindowOpacity under 100 makes a window again with; +`daemon.Kind` in the hello and in `pardes ps` (`tty` or `gui`). + +## What a client lacked, which the change made work The ruling turns these from objections into work. Each is checked here: what is true, and whether it was measured. @@ -86,7 +101,7 @@ what is true, and whether it was measured. terminal's client and is four or five times too small for a window's; what would shed it is a lighter way to draw, not a lighter core. A client adds about 1.3 MB to its session (a terminal's), 13 MB (a - window's with addon panes). Today only a second attach pays it; after, every attach to a detached + window's with addon panes). Before, only a second attach paid it; now every attach to a detached session does, which is the tmux habit (`pardes --detach=work`, then `pardes attach work`). - **An addon's code does not run in a replica.** No longer so for an @@ -121,23 +136,31 @@ what is true, and whether it was measured. Not measured here: a keystroke to its frame, local client against own frontend, on the soak gate. -## A session registering again - -Today a session says hello once, at its start (`runtime/main.zig:1567-1595`), or -on its link after an Upgrade (`runtime/daemon.zig:392-398`). When the daemon dies -the session's reader sees the link end (`runtime/daemon.zig:419-425`) and nothing -dials again, so the session runs on unlisted: `pardes ps` and attach do not -find it, Detach and Adopt refuse, and its frontend closing ends it -(`dev/tui/tui.zig:1699-1709`, `dev/gui/gui.zig:1839`). The next daemon knows only the -sessions that start after it. - -The work: when `gone` is set, the session's loop (which calls -`daemon.watch` each iteration already, `runtime/session.zig:115`, `:133-135`) -dials again, starting a daemon if none answers (`daemon.connect(true)`), -says its hello with its state, sends a dup of every pty master it holds -(at most 64 fds a message, `runtime/daemon.zig:37`), and its clients' pids. What -cannot come back: the shells of sessions killed earlier, which only the -dead daemon held. +## A session registering again (built) + +Before, a session said hello once, at its start, or on its link after an +Upgrade; when the daemon died the session's reader saw the link end and +nothing dialled again, so the session ran on unlisted: `pardes ps` and +attach did not find it, Detach and Adopt refused, and its frontend closing +ended it. With "an attach is always a client" that would have meant no +attach to any session after a daemon's death. + +Now (`runtime/daemon.zig` `readNotes`, `redial`, `relinked`; +`runtime/session.zig` `watch`; `dev/Ptys.zig` `tellDaemon`): the reader +thread, blocked in its read, is woken by the link's end alone. If the +daemon had taken the hello (an `ok` came) and the session is not ending, +it dials the next daemon, starting one if none answers +(`daemon.connect(true)`: the lock decides which of several sessions starts +it), puts the new connection on the link's own fd (`dup3`, so the session +loop's own sends never race a new fd) and says the hello with its kind, +name and whether it is detached. It then posts a note that wakes the +session loop once, which tells the new daemon a dup of every pty master it +holds and its clients' pids. Nothing polls and nothing waits on a timer: an +idle session is at 0 wakeups before and after (`test/daemon.py --relink`, +2 s each). A link the daemon never took (another build's daemon refuses +the hello) is not dialled again, so two builds cannot loop. What cannot +come back: the shells of sessions killed earlier, which only the dead +daemon held. ## `--detach` forking @@ -166,10 +189,10 @@ binary's strings (`/usr/sbin/rex` links libghostty); Rex was not run. | Who holds the programs | one server an account holds every session and runs every program (`skill-show.txt`) | each session is its own process, with the truth; the daemon holds a dup of each pty master and a list | | What starts it | any command starts a missing server (`--autostart`) | the first session starts the daemon; what you start is the session | | A client | "one program connected to the server" (`help-client.txt`); not a thin view: it replays the server's stream into its own libghostty and draws locally (the binary links libghostty; the help text does not say so, and this row first called it a view of the server's state: the user's correction, 2026-11-17) | the same principle, the stream shipped and the state derived where it is shown, into a whole replica core with its own view; what pardes adds is a client applying its own input before the session confirms it (speculation, rolled back when the session ordered things otherwise) and a predicted echo | -| Attach | no user's verb; in the API "start receiving its events and get its current view" | today four mechanisms; after this note, one: a client | +| Attach | no user's verb; in the API "start receiving its events and get its current view" | one: a client (four mechanisms until 2026-11-20) | | The last client leaves | "the session keeps running" (`api-session.detach.txt`) | the same for a client; today a session's own frontend closing depends on its kind and the daemon | | Another machine | the same commands with `-S HOST` | `attach HOST:NAME`; a far session's 9P is not reached that way | -| The server or daemon dies | "Stopping the server ends every program" (`help-server-stop.txt`) | a killed daemon ends nothing; today its sessions run on unlisted | +| The server or daemon dies | "Stopping the server ends every program" (`help-server-stop.txt`) | a killed daemon ends nothing; its sessions start the next and register with it again | What pardes bought that Rex does not have: a deterministic core replicated in each client, so a far session feels local (a key is applied @@ -182,8 +205,6 @@ session takes back. ## Open questions -- Re-registration: dial again at once and back off, or only when - something needs the daemon (a Detach, an Adopt, the frontend closing)? - `--detach` with no daemon starts a session nothing can attach to (`runtime/main.zig:1567-1569` ignores the failed registration). Refuse, or keep it as a 9P-only session? @@ -191,6 +212,6 @@ session takes back. own (the daemon's list, and so /sessions, still says `attached`, a wire word). After the change that frontend can only be the first one: is "has a frontend" the word, or "with its first frontend"? -- When: the order the user ruled is this vocabulary and the page first, - and the code after sketchbook's steps land (`.scratch/sketch/PARDES.md`, - ruling 4). +- A client's Detach exits 1 with "let this client go", where the stub's + said "detached from" and exited 0: the session's last word to a client + (step B of the last-step design) would let it say which. diff --git a/docs/next-run.svg b/docs/next-run.svg index fdfc705a..b46d94fa 100644 --- a/docs/next-run.svg +++ b/docs/next-run.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/next-run.typ b/docs/next-run.typ index 91461b25..5d972f0e 100644 --- a/docs/next-run.typ +++ b/docs/next-run.typ @@ -1,5 +1,5 @@ -// The figure of docs/next-run.md: what `pardes attach` does today beside -// what it does once "an attach is always a client" is built. Drawn by +// The figure of docs/next-run.md: what `pardes attach` did before beside +// what it does since "an attach is always a client" was built. Drawn by // docs/typ/figures.typ, the one file of the docs that imports cetz. // typst compile --root . --ignore-system-fonts -f svg docs/next-run.typ docs/next-run.svg #import "typ/style.typ": palette diff --git a/docs/typ/building.typ b/docs/typ/building.typ index 9350b484..8bfcb85b 100644 --- a/docs/typ/building.typ +++ b/docs/typ/building.typ @@ -501,10 +501,13 @@ life; the first session that finds none starts it (a double fork and an exec) and it exits a second after it holds nothing. It is nobody's parent: a session registers on one connection, sends it a dup of every pty master it forks (so a session killed outright never hangs its shells up, and -#word("Adopt") takes them into another), says whether a terminal or a -window shows it, and is handed a terminal (`pardes --attach`) or a window -request (`pardes-gui --attach`) through it. Messages are `SOCK_SEQPACKET` -datagrams: a line of words and the fds it carries. +#word("Adopt") takes them into another), says whether it has let its own +terminal or window go, and is handed each client's connection through it +(`pardes attach`, below). A daemon that dies is started again by the +sessions: each one's link's reader, woken by the link's end, dials the +next, says the hello again and tells it its masters and its clients. +Messages are `SOCK_SEQPACKET` datagrams: a line of words and the fds it +carries. `pardes` in a terminal forks its session off before anything starts: the session, in a session of its own (`setsid`), draws on the terminal it @@ -512,9 +515,9 @@ opened, and the process the shell waits on stays as its stub, passing it `SIGWINCH`, `SIGTERM`, `SIGINT` and `SIGQUIT` and ending with its status. #word("Detach"), or the terminal's end (EIO, a hangup), puts the terminal back and lets it go; the stub ends (exit 0) and the session -runs on with nothing drawn, until `pardes --attach` hands it another -terminal. A window's #word("Detach") closes the window and keeps the -process; `pardes-gui --attach` opens one again. `PARDES_DAEMON=off` (the +runs on with nothing drawn, detached for good: `pardes attach` is a client +of it. A window's #word("Detach") closes the window and keeps the +process, the same. `PARDES_DAEMON=off` (the process tests) runs a session as before the daemon: in the terminal's own process, ended by its hangup. diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index 732e66a7..34a46fa6 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -24,7 +24,7 @@ {"name": "DelAbove", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane above it."}, {"name": "DelBelow", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane below it."}, {"name": "Delcol", "leader": "SPC c d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close this column and its panes, refusing once over unsaved text."}, - {"name": "Detach", "leader": "SPC s D", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Detach this pardes from its terminal or window, leaving the session running: `pardes --attach` (or `pardes-gui --attach`) takes it back."}, + {"name": "Detach", "leader": "SPC s D", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Detach this pardes from its terminal or window, leaving the session running: `pardes attach` (or `pardes-gui attach`) shows it as a client."}, {"name": "Diagnostics", "leader": "SPC l d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the file's diagnostics from the language server."}, {"name": "Diff", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text."}, {"name": "Down", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane below, off a tag onto the pane under it."}, diff --git a/docs/typ/builtins-tui.json b/docs/typ/builtins-tui.json index 0a074c44..5919a77a 100644 --- a/docs/typ/builtins-tui.json +++ b/docs/typ/builtins-tui.json @@ -23,7 +23,7 @@ {"name": "DelAbove", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane above it."}, {"name": "DelBelow", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane below it."}, {"name": "Delcol", "leader": "SPC c d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close this column and its panes, refusing once over unsaved text."}, - {"name": "Detach", "leader": "SPC s D", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Detach this pardes from its terminal or window, leaving the session running: `pardes --attach` (or `pardes-gui --attach`) takes it back."}, + {"name": "Detach", "leader": "SPC s D", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Detach this pardes from its terminal or window, leaving the session running: `pardes attach` (or `pardes-gui attach`) shows it as a client."}, {"name": "Diagnostics", "leader": "SPC l d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the file's diagnostics from the language server."}, {"name": "Diff", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text."}, {"name": "Down", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane below, off a tag onto the pane under it."}, diff --git a/docs/typ/cheatsheet.typ b/docs/typ/cheatsheet.typ index e931effa..2df92b00 100644 --- a/docs/typ/cheatsheet.typ +++ b/docs/typ/cheatsheet.typ @@ -122,7 +122,7 @@ Helix-style: motions *select*, then an edit acts on the selection. Mode box: bla - A query pane under the pane: line 1 the query, its first word the source: `/pat`, `Find name` (fuzzy), `Grep text` (literal), `Recent`, `Panes`, `Symbols`, `All`. #keys("Ctrl-n", "Ctrl-p") step, #key("Enter") lands and keeps the rows, #key("Esc") puts things back. #word("Help"), #word("Tutor"). == Sessions -`pardes --detach=work`; `--attach=work` (`pardes-gui --attach=work`) takes it back; #word("Detach") leaves it running; #word("Adopt") takes in a killed session's shells. #doc("detached") +`pardes --detach=work`; `pardes attach work` shows it here, as a client (`pardes-gui attach work`: in a window); #word("Detach") leaves it running; #word("Adopt") takes in a killed session's shells. #doc("detached") == Config #word("Config") (#key("SPC f c")): `~/.config/pardes/init`, a builtin a line (#word("Theme") `atelier`). #word("DumpConfig"): every setting. #word("Dump") / #word("Restore"): the workspace. #doc("config") diff --git a/docs/typ/command-line.txt b/docs/typ/command-line.txt index 0b06275e..3c73fed4 100644 --- a/docs/typ/command-line.txt +++ b/docs/typ/command-line.txt @@ -12,7 +12,7 @@ Open: Sessions: ps the daemon's sessions, their clients and shells - attach [NAME] show a detached session here (HOST:NAME: over ssh) + attach [NAME] show a session here, as a client (HOST:NAME: over ssh) kill NAME end a session and its shells (--all: every one) new [flags] [FILE] start one: --detach=NAME --9p=NAME -n 3 (help new) @@ -54,15 +54,16 @@ See also: attach, kill, /sessions == pardes help attach -Show a detached session here: in this terminal for pardes, a window -for pardes-gui. Bare, the one detached session (with none, the one -session). One with a frontend already, or of the other kind, is joined -as a client. HOST:NAME is a client of session NAME on another machine, -over `ssh -L` to its pardes-replica.sock ($PARDES_SSH: the ssh -command, default ssh; $PARDES_REMOTE_RUNTIME: its runtime directory, -if not this one's path); SOCK:NAME goes through a socket forwarded -already (a path, with a '/'). Returns when the session detaches or -ends. +Show a session here as a client: a process of its own, with a copy of +the session's core and a view of its own, in this terminal for pardes, +a window for pardes-gui, whatever the session was started in. Bare, +the one detached session (with none, the one session). HOST:NAME is a +client of session NAME on another machine, over `ssh -L` to its +pardes-replica.sock ($PARDES_SSH: the ssh command, default ssh; +$PARDES_REMOTE_RUNTIME: its runtime directory, if not this one's +path); SOCK:NAME goes through a socket forwarded already (a path, with +a '/'). Returns when it is let go: its Detach or its terminal or window +closing (the session runs on), or the session's end. Usage: pardes attach [NAME] diff --git a/docs/typ/figures.typ b/docs/typ/figures.typ index 4ca51c1a..15364e47 100644 --- a/docs/typ/figures.typ +++ b/docs/typ/figures.typ @@ -201,37 +201,9 @@ wire((14.1, 3.0), (14.1, 1.67), ends: none, dash: "dotted", label: [keeps each \ one open], at: (15.15, 2.33), width: 1.6) }) -/// `pardes attach work` to a session with no frontend: a terminal's and a -/// window's. -#let run-attach-detached() = drawn(alt: "pardes attach to a detached session: the terminal handed to the session through the daemon; for a window, the session opens its own again", { - import cetz.draw: * - // A terminal's session. - content((0, 8.75), anchor: "west", text(size: 8pt, weight: "bold")[a terminal's session: `pardes attach work`]) - screen(0, 6.4, 3.4, 1.7, [this terminal]) - proc(0, 3.9, 3.4, 2.0, "stub", "pardes attach work", - ("plain", [now the job your shell waits on]), ("plain", [holds nothing])) - daemon-box(5.5, 3.9) - proc(11.0, 3.9, 5.0, 4.2, "session", "pardes --detach=work", - core-truth, ptys, ninep("work"), - ("plain", [draws on this terminal now]), - ("plain", [the same process as before])) - wire((3.4, 4.8), (5.5, 4.8), label: [① this terminal \ and a pipe], at: (4.45, 5.32), width: 1.8) - wire((8.9, 4.8), (11.0, 4.8), dash: "dashed", label: [② handed on], at: (9.95, 5.15)) - wire((3.4, 7.25), (11.0, 7.25), ends: "both", label: [③ keys in, frames out], at: (7.2, 7.6)) - line((-0.1, 3.3), (16.1, 3.3), stroke: (paint: palette.rule, thickness: 0.6pt)) - // A window's session. - content((0, 2.85), anchor: "west", text(size: 8pt, weight: "bold")[a window's session: `pardes-gui attach work`]) - proc(0, 0, 3.4, 2.0, "other", "pardes-gui attach work", ("plain", [asks, then exits: no stub]), dash: "dashed") - daemon-box(5.5, 0) - proc(11.0, 0, 5.0, 2.3, "session", "pardes-gui --detach=work", - core-truth, ("plain", [opens its own window again])) - wire((3.4, 0.9), (5.5, 0.9), label: [① asks], at: (4.45, 1.25)) - wire((8.9, 0.9), (11.0, 0.9), dash: "dashed", label: [② "attach"], at: (9.95, 1.25)) -}) - -/// `pardes attach work` to a session that has a frontend (or is of the -/// other kind): a client. -#let run-attach-client() = drawn(alt: "pardes attach to a session with a frontend: a client process with its own replica core, joined through the daemon", { +/// `pardes attach work`: a client, whether or not the session still has +/// the frontend it was born with (here it has). +#let run-attach-client() = drawn(alt: "pardes attach: a client process with its own replica core, joined through the daemon", { import cetz.draw: * screen(0, 3.4, 3.0, 1.7, [its own terminal]) proc(0, 0, 4.8, 2.9, "session", "pardes", @@ -283,12 +255,12 @@ wire((10.6, 0.7), (12.2, 0.7), ends: "both", label: [a pty's bytes], at: (11.4, 1.05)) }) -// ---- docs/next-run.md: the ruled direction, not built ---- +// ---- docs/next-run.md: the ruling, built ---- -/// What `pardes attach` does today (four things) beside what it does once -/// "an attach is always a client" is built (one). Drawn by +/// What `pardes attach` did before 2026-11-20 (four things) beside what it +/// does since "an attach is always a client" was built (one). Drawn by /// docs/next-run.typ for the design note; no chapter shows it. -#let run-attach-before-after() = drawn(alt: "pardes attach today: four mechanisms; after: always a client", { +#let run-attach-before-after() = drawn(alt: "pardes attach before: four mechanisms; now: always a client", { import cetz.draw: * let row(x, y, when, typed, kind, said) = { content((x, y + 1.2), anchor: "west", text(size: small, style: "italic", fill: palette.tag-fg, when)) @@ -299,13 +271,13 @@ rect((x + 3.9, y), (x + 7.5, y + 0.95), fill: tint(c), stroke: 1.3pt + c, radius: 3pt) content((x + 5.7, y + 0.475), box(width: 3.4cm, align(center, text(size: small, said)))) } - content((0, 8.15), anchor: "west", text(size: 9pt, weight: "bold")[Today: four mechanisms]) + content((0, 8.15), anchor: "west", text(size: 9pt, weight: "bold")[Before: four mechanisms]) row(0, 6.0, [a terminal's session, detached], [pardes attach work], "session", [the session draws here; this process becomes its stub]) row(0, 4.3, [a window's session, detached], [pardes-gui attach work], "session", [the session opens its own window; this process exits]) row(0, 2.6, [it has a frontend, or is the other kind], [pardes attach work], "client", [a client: this process, with a replica]) row(0, 0.9, [on another machine], [pardes attach box:work], "client", [a client, through `ssh -L`]) line((7.95, -0.1), (7.95, 8.4), stroke: (paint: palette.rule, thickness: 0.8pt)) - content((8.45, 8.15), anchor: "west", text(size: 9pt, weight: "bold")[After: always a client]) + content((8.45, 8.15), anchor: "west", text(size: 9pt, weight: "bold")[Now: always a client]) row(8.45, 6.0, [any session on this machine], [pardes attach work], "client", [a client: this process, with a replica]) row(8.45, 4.3, [on another machine], [pardes attach box:work], "client", [a client, through `ssh -L`]) content((8.45, 2.85), anchor: "west", box(width: 7.5cm, text(size: small)[A session's own frontend is only the one it was born with: a Detach, or its terminal or window closing, leaves it detached for good, and each attach after is a client.])) diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index e69c756a..3dd8107c 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -352,28 +352,29 @@ cheatsheet (#doc("cheatsheet")) say so. ``` pardes --detach=work & a session with no screen of its own -pardes --attach=work show it here -pardes-gui --attach=work a window session's window again -pardes --ps every session the daemon lists, and its shells -pardes --kill=work end it and its shells (--kill-all: every one) +pardes attach work show it here, as a client +pardes-gui attach work show it in a window, as a client +pardes ps every session the daemon lists, and its shells +pardes kill work end it and its shells (kill --all: every one) ``` #word("Detach") (#key("SPC s D")) lets the terminal or the window go and leaves the session running, its panes, shells and files kept; so does a terminal that closes, while the daemon (below) is there. A window that -closes ends its session, unless the session has clients. -`pardes --attach` takes it back in any terminal, -`pardes-gui --attach` a window session's window: a terminal session takes -a terminal, a window session a window. Attached already, it takes another -view: each terminal or window has its own columns, focus, cursors and -scroll over the same panes, texts and registers, and a terminal shown in -two takes the size of the one that last typed into it. #word("Detach") in -one lets only that one go. A session is named by `--9p=` or +closes ends its session, unless the session has clients. Once let go, a +session's own terminal or window never comes back: `pardes attach` shows +it in any terminal, `pardes-gui attach` in a window, either kind of +session, each as a client, a process of its own. Each terminal or window +has its own view (columns, focus, cursors, scroll) over the same panes, +texts and registers, and a terminal shown in two takes the size of the +one that last typed into it. #word("Detach") in one lets only that one +go. A session is named by `--9p=` or `--detach=`, else its pid. A session killed outright leaves its shells running; #word("Adopt") in another takes them in as terminal panes, what they showed gone. One `pardes --daemon` per user lists the sessions and holds their shells' terminals open; the first session starts it, it is -nobody's parent, and it leaves once it holds nothing. Which processes +nobody's parent, and it leaves once it holds nothing; killed, the +sessions start it again. Which processes run, and what survives what, is in #doc("running"). After a rebuild, #word("Upgrade") (#key("SPC s U")) moves a running session onto the pardes now installed diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index 4c193e0f..425209a0 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -1014,7 +1014,7 @@ at 200, ending in `…`. Control characters become spaces. of its own, a terminal or window; `pardes ps` says "has a frontend") with a `client ` line for each of its clients and a `shell ` line for each shell it holds, then `orphan ` for each shell no session holds. Any of the - names attaches (`pardes --attach=`, either kind). Read fails `no + names attaches (`pardes attach `, either kind, as a client). Read fails `no pardes daemon answers` with none, or one too old to list (Upgrade it). - #file("/os/"): existing regular files take read, write and truncation to zero; create, remove, rename and mode changes are refused as not @@ -1350,15 +1350,13 @@ to its end before the write is answered, and one that finds nothing fails, which #word("Adopt") takes. `--kill=NAME` ends that session and its shells (a TERM, then a KILL 2 s later; unsaved changes are lost), `--kill-all` every session and every kept shell; with no daemon running - each says so and exits 1. Bare `--detach` names the session after its pid; bare - `--attach` needs exactly one detached session of its kind (a terminal's - for `pardes`, a window's for `pardes-gui`), or with none detached the - only session of that kind, joined as a client (with none of that kind, - the only session there is); a second `--detach=NAME` - while NAME runs (a plain session is named by its pid) says so in words - and exits 1. A session with a frontend already is joined as a client, as one of - the other kind is, and one on another machine (`--attach=HOST:NAME`, over - `ssh -L`; `--attach=SOCKET:NAME` through a socket forwarded already): its + each says so and exits 1. Bare `--detach` names the session after its pid; a + second `--detach=NAME` while NAME runs (a plain session is named by its + pid) says so in words and exits 1. `attach NAME` (`--attach=NAME`) is + always a client of session NAME, either kind, here or on another machine + (`attach HOST:NAME`, over `ssh -L`; `attach SOCKET:NAME` through a socket + forwarded already); bare, of the one detached session, else the only + session (with several, it names them and exits 1): its own process, listed under the session by `--ps`, up to three clients (four views at once, the session's own among them): each terminal or window its own layout, focus, cursors, selections, modes, diff --git a/docs/typ/running.typ b/docs/typ/running.typ index 1500845e..74eb8cbd 100644 --- a/docs/typ/running.typ +++ b/docs/typ/running.typ @@ -4,31 +4,32 @@ // attach); the direction not built yet is docs/next-run.md. The file:line // that says each fact is in a comment beside it. #import "style.typ": word, doc, pairs, file -#import "figures.typ": run-legend, run-terminal, run-window, run-detach, run-attach-detached, run-attach-client, run-far, run-no-daemon +#import "figures.typ": run-legend, run-terminal, run-window, run-detach, run-attach-client, run-far, run-no-daemon A running pardes is up to four kinds of process. Which of them there are, and what each holds, depends only on how it was started. -// runtime/daemon.zig:8-16 (nobody's parent; dups; hands terminals, -// windows, replicas); core/replica.zig:1-19, :747-794 (a client's core +// runtime/daemon.zig:8-17 (nobody's parent; dups; lists the sessions, +// hands a client's connection on); core/replica.zig:1-19, :747-794 (a client's core // from the dump); dev/host_io.zig:548-551 (the shells are the session's -// children); runtime/9p_io.zig:57 (the socket); runtime/daemon.zig:546-698 -// (the stub). +// children); runtime/9p_io.zig:57 (the socket); runtime/daemon.zig forkSession, +// stubWait (the stub). #pairs( [*session*], [the process with the truth: the one core every other copy follows, the shells' pty masters (the shells are its children) and the 9P socket. There is one a session, always.], [*client*], [any further terminal or window on a session: a process of its own, with a copy of the session's core (a replica) loaded from the session's dump and kept in step with the session's tape. It has its own view (columns, focus, cursors, scroll) and draws it. It holds no shells and no 9P socket. A client on another machine is *far*.], - [*daemon*], [`pardes --daemon`, one per user per machine: a switchboard. It spawns nothing and is nobody's parent. It keeps the list of sessions and a dup of every pty master, so that a session killed outright never hangs its shells up; clients dial its replica socket; it hands a terminal, a window's request or a client's connection to the session that takes it. The first session that finds none starts it, and it exits a second after it holds nothing.], + [*daemon*], [`pardes --daemon`, one per user per machine: a switchboard. It spawns nothing and is nobody's parent. It keeps the list of sessions and a dup of every pty master, so that a session killed outright never hangs its shells up; clients dial its replica socket, and it hands each client's connection to the session it names. The first session that finds none starts it, and it exits a second after it holds nothing. Killed, it is started again by its sessions, which register with the next one.], [*stub*], [the process your shell waits on when the session is not it. It holds nothing: it passes signals on, and ends when the session leaves its terminal.], ) -// dev/tui/tui.zig:590 (a session's terminal: one or none); -// dev/gui/gui.zig:2433-2436 (the window, or none while detached); -// runtime/daemon.zig:901-905 ("a session shows one frontend of its own"). +// dev/tui/tui.zig Screen (a session's terminal: the one it was born +// with, or none); dev/gui/gui.zig Shell.gui (the window, or none once +// detached); runtime/main.zig attachTo (an attach is a client). A *frontend* is what draws: the terminal (`pardes`), the window (`pardes-gui`), or the Mac's own build. A session draws at most one -frontend of its own: the one it was started with, or one attached to it -later. A session with none is *detached*; it may still have clients. -To *attach* is to show a session here. +frontend of its own: the one it was started with. Once it lets that one go +(a #word("Detach"), its terminal closing) it is *detached*, for good; it +may still have clients. To *attach* is to show a session here, and an +attach is always a client. In the figures a box with a heavy edge is a process: its kind, then the command `ps` shows for it, then what it holds. The core with the truth is @@ -41,11 +42,11 @@ travels on it. #run-terminal() -// runtime/main.zig:1570-1595, runtime/daemon.zig:663-698 (the fork, -// setsid, the stub); runtime/daemon.zig:550-559, :567-616 (what the stub -// forwards and how it ends); dev/tui/tui.zig:1685-1709 (the terminal's -// end: detached while kept, else the end); runtime/daemon.zig:305-314 -// (kept: the daemon answered and is still there). +// runtime/main.zig, the fork (daemon.forkSession: setsid, the stub); +// runtime/daemon.zig forward, stubWait (what the stub forwards and how it +// ends); dev/tui/tui.zig, the `.quit` arm (the terminal's end: detached +// while kept, else the end); runtime/daemon.zig kept (the daemon +// answered and is still there). `pardes` forks the session off and stays as its stub. The session runs in a POSIX session of its own, so it can outlive the job your shell waits on. It reads the keys from the terminal and draws on it itself; the stub only @@ -54,7 +55,7 @@ session too) and exits when the session leaves the terminal, with the session's status, or 0 after a #word("Detach"). Closing the terminal detaches the session while a daemon keeps it. With no -daemon, or after the daemon has died, it ends the session and its shells. +daemon it ends the session and its shells. = `pardes-gui` @@ -80,9 +81,9 @@ terminal hangs up. // process). The process you started is the session: nothing is forked, so the `&` that puts it in the background is yours to type (`pardes new --detach=work` is -the same). It draws nothing and is 160×50 until an attach or the root -#file("ctl")'s `size` sizes it. Until something attaches, 9P is the only -way in (#doc("scripting")). +the same). It draws nothing and is 160×50 until the root #file("ctl")'s +`size` sizes it; a client shows its own view, at its own size. Until a +client attaches, 9P is the only way in (#doc("scripting")). // runtime/main.zig, the --detach branch (the exec of the pardes beside it). `pardes-gui --detach` runs the `pardes` installed beside it in its place: @@ -95,55 +96,42 @@ a daemon keeps it; a window's binary's ends on it, as any job does. With no daem `--detach` still starts a session, which nothing can attach to: only 9P reaches it. -= Attach, to a detached session - -#run-attach-detached() - -// runtime/main.zig:1812-1842 (attachTo); runtime/daemon.zig:883-897 -// (handed on); dev/tui/tui.zig:1354-1382 (the terminal entered as the -// first was); dev/gui/gui.zig:3384-3402, :2588-2601 (the window opened -// again). -For a terminal's session, `pardes attach work` hands its terminal and a -pipe to the session through the daemon, and stays as the stub. For a -window's, `pardes-gui attach work` asks, then exits, and the session opens -its own window again. Either way the frontend is the session's own again, -in the process that has been the session all along: what happens when -it closes is what the first two sections say. - -// runtime/daemon.zig:901-972 (find: the bare attach, and `other`). -The kind has to match. A terminal's session attached from `pardes-gui`, -or a window's from `pardes`, is joined as a client (the next section). -Bare, `pardes attach` takes the one detached session of its kind; with -none, the one session of its kind, as a client; with no session of its -kind, the only session there is, as a client. `--attach=work` is the older -spelling of `attach work`. - -= Attach, to a session that has a frontend += Attach #run-attach-client() -// runtime/main.zig:1844-1850 (crossAttach); runtime/daemon.zig:974-1008 -// (the hello, the same build, handed on); core/replica.zig:1-19 -// (speculation and rollback); core/replica.zig:2204-2214, core/views.zig:31, +// runtime/main.zig attachTo, bareAttach (a client, through the replica +// socket; bare: the one detached session, else the one session); +// runtime/daemon.zig hear (the hello, the same build, handed on); +// core/replica.zig:1-19 (speculation and rollback); core/views.zig:31, // core/Core.zig:1163-1203 (four views, the session's own among them); -// core/replica.zig:2303-2325 (a client leaving); core/replica.zig initDump, -// core/Addon.zig plainOps (a plain kind's code runs in the client that has -// it; another's in the session alone); dev/gui/gui.zig:2200-2214 (a -// client's notch: whole rows sent), :3673 (glideFrame: the picture on the -// client's clock); dev/gui/gui.zig:595-623 (a client's font: the session's -// request, by the face's name on this machine). Measured 2026-11-17 +// core/replica.zig closeViewOf (a client leaving); core/replica.zig +// initDump, core/Addon.zig plainOps (a plain kind's code runs in the +// client that has it; another's in the session alone); +// dev/gui/gui.zig:2200-2214 (a client's notch: whole rows sent), +// glideFrame (the picture on the client's clock); dev/gui/gui.zig +// syncReplicaFont (a client's font: the session's request, by the face's +// name on this machine). Measured 2026-11-17 // (.scratch/sketch/reports/pardes-measure.md sections A, C and E): a // client's notch glides as the session's window does (5 frames, 0 to // -22 px); a terminal's client 10-16 MB PSS idle, a window's about 110 MB // (187 MB RSS), as a window session's, three quarters of it the GPU and // display libraries. -A session draws one frontend of its own, so the second attach is a client. -The daemon checks the client's hello (the session's name, and the client's -build: a client must be the build its session is) and hands its -connection to the session; from then on the two talk directly. The client -loads the session's dump into its own core, applies its own keys at once, -and takes the session's tape (each step as the session took it) as the -truth, rolling back when the session ordered things differently. +`pardes attach work` is a client of session work, whatever the session was +started in and whether or not it still has its own frontend: in a terminal +for `pardes`, a window for `pardes-gui`. A session never takes a frontend +of its own back: the one it was born with is the only one it ever has. +Bare, `pardes attach` takes the one detached session; with none detached, +the only session there is; with several, it names them and asks which. +`--attach=work` is the older spelling of `attach work`. + +The client says its hello on the daemon's replica socket: the session's +name, and the client's build (a client must be the build its session is). +The daemon refuses a name no session has, and hands the connection to the +session; from then on the two talk directly. The client loads the +session's dump into its own core, applies its own keys at once, and takes +the session's tape (each step as the session took it) as the truth, +rolling back when the session ordered things differently. // core/replica.zig:5316-5395 (may_wait: what a client waits for, each // row's why); core/tape.zig:1163-1193 (keeps_stopping); core/Core.zig:1763-1778 @@ -163,7 +151,7 @@ opens here. A session takes three clients: four views at once, its own among them. A client's #word("Detach"), or its terminal or window closing, ends that -client only; the last client of a detached session leaves its layout as +client only (it says the session let it go, and exits 1); the last client of a detached session leaves its layout as the session's, for the next one to find. In a client, an addon whose state is plain (`PA_PLAIN`: the games, the picture, the PDF) runs in the client that shows it, from that client's own addons; one the client lacks @@ -202,18 +190,18 @@ of the session or a divergence of its own. `pardes attach /run/x.sock:work` #run-no-daemon() -// runtime/daemon.zig:52-61 (PARDES_DAEMON, PARDES_TEST), :34 (Linux and -// FreeBSD only); runtime/main.zig:1576-1592 (no daemon reached: no fork); -// dev/tui/tui.zig:1333-1334, dev/gui/gui.zig:2537, dev/host_io.zig:85 -// (Detach and Adopt refused); core/replica.zig:2087-2092 (a client only -// through the daemon); core/root.zig:118 (can_attach); -// runtime/main.zig:1513-1515 (a far attach needs no daemon here). +// runtime/daemon.zig wanted (PARDES_DAEMON, PARDES_TEST), supported +// (Linux and FreeBSD only); runtime/main.zig, the fork (no daemon reached: +// no fork); dev/tui/tui.zig detach, dev/gui/gui.zig detachWindow, +// dev/host_io.zig (Detach and Adopt refused); runtime/main.zig attachTo (a +// client only through the daemon); core/root.zig can_attach; +// runtime/main.zig, `attach HOST:NAME` (a far attach needs no daemon here). With `PARDES_DAEMON=off`, in a window under test (`PARDES_TEST`), where none could start, and in the Mac's own build, the session is the process you started, with no stub. #word("Detach") and #word("Adopt") refuse, no client can join (a client comes only through the daemon), and closing the terminal or the window ends the session and its shells. A session whose -daemon died is in the same place (#link()[below]). +daemon died is not: it starts the next one itself (#link()[below]). `pardes-gui` built for a Mac has no daemon either, but can still be a far client. @@ -234,8 +222,7 @@ client. [`pardes`], [stub, session, daemon], [`pardes` twice (the stub, and its child the session), `pardes --daemon`], [the session], [the session, on your terminal], [the session detaches while a daemon keeps it; else it ends], [`pardes-gui`], [session, daemon], [`pardes-gui`, the daemon], [the session], [the session, its window], [the session ends, unless it has clients and a daemon: then it runs on, detached], [`pardes --detach=work &`], [session, daemon], [`pardes --detach=work`, the daemon], [the session], [nothing], [it has none; its terminal's hangup ends a window's, not a terminal's while a daemon keeps it], - [`pardes attach work`, detached], [stub, session, daemon (a window's attach exits)], [`pardes attach work` (the stub), the session as it was], [the session], [the session, on this terminal (or its window)], [as for `pardes` (or `pardes-gui`)], - [`pardes attach work`, it has a frontend], [client, session, daemon], [`pardes attach work` (the client), the session], [the session; the client has a replica], [each its own: the session its frontend, the client this terminal], [the client ends; the session runs on], + [`pardes attach work`], [client, session, daemon], [`pardes attach work` (the client), the session as it was], [the session; the client has a replica], [the client, this terminal (`pardes-gui`: a window); the session its own frontend, if it still has it], [the client ends; the session runs on], [`pardes attach box:work`], [here: client, ssh; on box: daemon, session], [`pardes attach box:work`, `ssh -tt -q -o ExitOnForwardFailure=yes -L … box exec sleep 2147483647`], [the far session], [the client, here], [the client ends, and its ssh], [no daemon], [session], [`pardes` (or `pardes-gui`)], [the session], [the session], [the session ends, with its shells], ) @@ -247,13 +234,14 @@ started it. After an #word("Upgrade"), a session's command line starts with = What survives what -// core/replica.zig:2303-2325 (a client leaving); runtime/daemon.zig:485-502, +// core/replica.zig closeViewOf (a client leaving); runtime/daemon.zig hangUp, quit, // runtime/9p_io.zig:704-729, dev/tui/tui.zig:928-940 (TERM, HUP, INT: the -// shells go); runtime/daemon.zig:755-765, :770-789 (killed outright: kept +// shells go); runtime/daemon.zig Daemon.hangUp, Daemon.kill (killed outright: kept // for Adopt; `kill`: not); dev/tui/tui.zig:598-600 (a HUP kept by a daemon -// is a terminal's end, not the session's); runtime/daemon.zig:397, -// runtime/main.zig:1566-1593 (registered at the start and at an Upgrade -// only); runtime/upgrade.zig:1-15, core/replica.zig:2370-2393, :2988-3008 +// is a terminal's end, not the session's); runtime/daemon.zig readNotes, +// redial, relinked, dev/Ptys.zig tellDaemon (the next daemon dialled by +// the link's end alone, the hello and the shells' masters told it +// again); runtime/upgrade.zig:1-15, core/replica.zig:2370-2393, :2988-3008 // (Upgrade); core/Db.zig:1-17, :385-410 (the state file: Recent, the dumps). #{ set text(size: 0.85em) @@ -268,7 +256,7 @@ started it. After an #word("Upgrade"), a session's command line starts with [#word("Detach") in its own frontend], [runs on, detached (refused with no daemon)], [stay], [stay], [it ends (#word("Exit"), `pardes kill`, a TERM or an INT)], [gone; a terminal's stub exits with its status], [hang up with it], [each told, and exits], [it is killed outright (KILL) or crashes], [gone, its text with it unless dumped (#word("Dump"))], [run on while a daemon holds their terminals, and #word("Adopt") in another session takes them (what they showed is lost)], [each exits], - [the daemon is killed], [runs on, but no daemon lists it again, this one or the next: `pardes ps` and attach do not find it, #word("Detach") and #word("Adopt") refuse, and its frontend closing ends it], [stay; the shells of sessions killed earlier, held only by the daemon, hang up], [the ones joined stay; no new one can join], + [the daemon is killed], [runs on, and dials the next daemon at once, starting it if none answers: `pardes ps` lists it again, clients attach, #word("Detach") and #word("Adopt") work], [stay, their terminals held by the next daemon too; the shells of sessions killed earlier, held only by the dead daemon, hang up], [the ones joined stay; new ones join through the next daemon], [#word("Upgrade")], [the same pid on the new build, its dump loaded again; every view, terminal and stub kept; the daemon moves too. A build that cannot load the dump hands it back to the one before], [stay, the session's children still], [let go, and each joins again by itself (it tries for 20 s)], [a reboot], [gone; what is on disk stays: saved files and the state file (`pardes.xitdb`: Recent and the dumps, which #word("Restore") brings back)], [gone], [gone], ) @@ -282,8 +270,8 @@ started it. After an #word("Upgrade"), a session's command line starts with [*client*], [any further terminal or window on a session: its own process, a replica core], [*far*], [a client on another machine], [*frontend*], [what draws: the terminal, the window, the Mac's own], - [*detached*], [a session with no frontend of its own (it may have clients)], - [*attach*], [show a session here], + [*detached*], [a session with no frontend of its own, for good once it has let go the one it was born with (it may have clients)], + [*attach*], [show a session here: always a client], [*daemon*], [the per-user switchboard, `pardes --daemon`], [*stub*], [the process your shell waits on when the session is not it], ) @@ -295,7 +283,7 @@ and `headless` for detached): // core/replica.zig:1-19 (authority); core/replica.zig:2006-2062, :3013 // (Peers, Link, Joining); dev/tui/tui.zig:1162, dev/gui/gui.zig:2431 // (Shell); core/Core.zig:313-315, core/replica.zig:2028-2030 (unattended -// against detached); runtime/daemon.zig:283, :363, :799 (the daemon's +// against detached); runtime/daemon.zig hello, setDetached, Daemon.list (the daemon's // attached and detached), runtime/main.zig:1647 (`ps` says "has a // frontend"); runtime/session.zig:1-30, runtime/client.zig:1-35 (the // loops and what a frontend gives each). diff --git a/runtime/main.zig b/runtime/main.zig index 563461ed..a791ffec 100644 --- a/runtime/main.zig +++ b/runtime/main.zig @@ -280,17 +280,18 @@ const cmds = std.EnumArray(Cmd, Doc).init(.{ .attach = .{ .group = .Sessions, .args = "[NAME]", - .line = "show a detached session here (HOST:NAME: over ssh)", + .line = "show a session here, as a client (HOST:NAME: over ssh)", .doc = - \\Show a detached session here: in this terminal for pardes, a window - \\for pardes-gui. Bare, the one detached session (with none, the one - \\session). One with a frontend already, or of the other kind, is joined - \\as a client. HOST:NAME is a client of session NAME on another machine, - \\over `ssh -L` to its pardes-replica.sock ($PARDES_SSH: the ssh - \\command, default ssh; $PARDES_REMOTE_RUNTIME: its runtime directory, - \\if not this one's path); SOCK:NAME goes through a socket forwarded - \\already (a path, with a '/'). Returns when the session detaches or - \\ends. + \\Show a session here as a client: a process of its own, with a copy of + \\the session's core and a view of its own, in this terminal for pardes, + \\a window for pardes-gui, whatever the session was started in. Bare, + \\the one detached session (with none, the one session). HOST:NAME is a + \\client of session NAME on another machine, over `ssh -L` to its + \\pardes-replica.sock ($PARDES_SSH: the ssh command, default ssh; + \\$PARDES_REMOTE_RUNTIME: its runtime directory, if not this one's + \\path); SOCK:NAME goes through a socket forwarded already (a path, with + \\a '/'). Returns when it is let go: its Detach or its terminal or window + \\closing (the session runs on), or the session's end. , .examples = &.{ .{ "pardes attach", "the one detached session" }, -- cgit v1.3