From a73697397ee3f2b7fa7cba08c96f6f81ff7ee04c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 29 Oct 2026 10:03:35 -0300 Subject: docs/next-daemon.md: the daemon and multi-client design, argued 2026-10-29 (deterministic replicated core, kakoune-style views, one daemon per user, phases) Co-Authored-By: Claude Opus 5.5 --- docs/next-daemon.md | 171 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 docs/next-daemon.md (limited to 'docs') diff --git a/docs/next-daemon.md b/docs/next-daemon.md new file mode 100644 index 00000000..8bc9b38c --- /dev/null +++ b/docs/next-daemon.md @@ -0,0 +1,171 @@ +# The daemon: one pardes per machine, many clients per session + +> I want to have a global pardes daemon ... holding file descriptors for +> ptys, files, etc. ... like kakoune or emacs, or as in plan9 terms a +> cpu+file server ... the main test: multiple clients to a single session, +> and a client here and the session on freebsd and very deep and thorough +> performance testing and optimizations to make it feel like its local and +> snappy. + +Designed 2026-10-29 in discussion (the user, the coordinator, a survey +agent). Nothing here is built yet. Paths are relative to the repo. + +## Decided by the user + +- **A deterministic core, replicated.** The session is the authority: it + orders every client's input and every host result, and only it performs + effects. Each client runs a full core replica, applies its own input at + once, and rolls back and replays when the order differs. Visible rollback + is acceptable. +- **Kakoune-style clients.** Each client has its own view (layout, focus, + selections, scroll) over shared buffers and terminals. Registers are + session-wide. A terminal shown at two sizes is sized by its last typist. +- **Performance order.** First, the regular tty and GUI get no slower. + Then the detached and remote clients reach that local performance, with + the session on the FreeBSD box included. +- **A host step may show up one RTT late, but is never wrong.** This + covers Look, open and exec, as sam's hostlock does. +- **Join is complete.** The joining client pays for it in time; the + authority and the other clients do not. +- **One long-lived daemon per user per machine.** It supervises one child + process per session, postgres-style. Nothing is left dangling, and the + core is not de-globalised. + +## What today's seam is, and why it goes + +`src/detached/server.zig` is a third Host: it runs the core and the ptys +in a single poll loop and sends cell frames to the frontends, at the +smallest common grid across them. + +- **The frames are mostly not diffed.** Every layer's cells are re-sent on + each frame (wire.zig:734, :755). +- **Several things never cross the wire.** Images, PDF pixels, rail ticks + and pane animations stay behind (surface.zig:483-509). +- **Every keystroke is a round trip,** which no amount of optimisation can + make feel local at 30-80 ms. +- **Each remote 9P operation dials afresh,** costing about 6 RTTs + (9p_io.zig:2361-2385). + +## The design + +- **Processes.** + - The daemon is subreaper, spawner, fd holder, registry and 9P root. + - Every session is a child of the daemon: a GUI window, a tty session + behind a stub, or a headless session. + - A session is always an in-process authority with its own local view, + so the regular path does not change. Replicas exist only for extra + clients or remote ones. +- **The tty stub.** + - `pardes` in a terminal passes its terminal fd to the daemon + (SCM_RIGHTS), along with cwd, env and argv. + - The session child drives that fd directly. The stub forwards SIGWINCH + and exits with the session's status. + - Detach: the session drops the fd and the stub exits. No fork happens. +- **GUI detach.** The window is destroyed and the process carries on + headless. Closing a window that has no other client attached quits it. +- **Shells survive a session crash.** After each `forkShell`, the session + sends the daemon a dup of the pty master, so the shells do not get + SIGHUP. Being subreaper only decides who reaps them. +- **The recorder.** It is null when no client is attached. When one is, + it appends what the authority consumed, in order: + - every step's host tape (the results of the ~30 `turn.yield()` sites); + - each `serveFs` mutation. + + Turn order is log order, so the local path changes by one null check. +- **The protocol.** One ordered stream: events, host tapes, digests and + terminal state. Framing, the hello and the Event codec are kept from + wire.zig; the frames go. +- **Terminals cross as authoritative screen state,** not as pty bytes: + - metadata plus immutable row blobs, assigned in absolute terms; + - scrollback fetched on demand. + + A `cat` of 1 GB costs screens, not bytes. ghostty stays exact on the + authority, and the local path keeps reading ghostty directly. +- **The reflective walker.** One comptime `@typeInfo` walk gives: + - the digest; + - the complete dump, which also serves join, Restore and Handover; + - the rollback copy. + + Fields are annotated local, authority-only or derived. A hash of the + type graph versions it. The hello carries a semantics hash (version, + features, grammars), and a mismatched build is refused. +- **Rollback.** + - When the first speculative event goes pending, the replica copies what + speculation can write: views, buffers, registers, counters and terminal + metadata. Blobs are pinned rather than copied. + - On a divergence it restores that copy, then replays the confirmed + events and its own pending ones. + - The authority never rolls back. +- **Join.** The authority forks a writer child at a step boundary; the + child streams the dump. The authority buffers the events after it for + the joiner. +- **Remote.** + - `ssh -L` of the daemon's one socket. + - The daemon hands a replication connection's socket to its session. + - A remote daemon mounts as `/n/`. + +## Determinism leaks (the survey's census) + +| Leak | Where | Fix | +|---|---|---| +| Render writes core state | body_layer.zig:181-187, File.zig:1923-1957 | view geometry in a lazy cache, render pure; the worst leak | +| 9P mutating between steps | pardes.zig:6060, pump :6016 | sequenced; turn order is log order | +| Host syscalls in a step | the ~30 `turn.yield()` sites | host tape | +| Wall-clock budgets | Names.zig:150, Places.zig:480, Tables.zig:519 | tape the work done | +| Ticks off the host clock | pardes.zig:6014/7850 | session ticks stamped, presentation ticks local | +| Clock and TZ in messages | Messages.zig:129-145 | event stamp, session TZ | +| Worker results polled in render | image.zig:1103, pdf_view.zig:1991, Stream.zig:482 | consumed at step boundaries, sequenced | +| getenv in the core (~30) | e.g. fs.zig:798 | env captured once into session state | +| Frontend kind / build flags | `windowed`/`native_images`; 223 comptime branches | moved into View; semantics hash | +| ghostty media reads, its pages outside the arenas | terminal.zig:629, PageList.zig:580 | authority-only under screen-state terminals | + +## Phases + +Each phase ships on its own and keeps `zig build perf --base` level (with +an A/A run). All 110 snapshots stay green throughout. + +1. **Determinism and the replay-divergence harness.** + - Work: the recorder and tape; the leak fixes, the render one first; the + semantics hash; the walker's digest. + - Check: replay each recorded log into two cores at different addresses + and one headless core. + - Gate: zero divergences on the snapshot scripts and on N monkey seeds. +2. **A complete dump on the walker.** It replaces dump.zig for Restore and + Handover. + - Gates: `digest(load(dump(x))) == digest(x)`, and dump is a fixpoint. +3. **The daemon and the tty stub.** + - Work: in-place detach and reattach; pty master dups; the frame wire + deleted. + - Gates: keystroke-to-present unchanged; a session `kill -9`'d leaves + its shells adoptable; no stale sockets after N cycles. +4. **Views.** A second window on the same session, in one process. + - Gate: logs with several views replay without divergence. +5. **Replicas.** + - Work: speculation, rollback, screen-state terminals, join, socket + handoff, `ssh -L`. + - Gates: + - a 30/80 ms delay relay keeps remote within noise of local; + - the rollback rate stays low under the fuzzer; + - a lagging client leaves the authority flat; + - a join costs the authority under one frame. +6. **Remote amortisation.** A content cache by hash, prefetch, zstd, + predicted echo in TTY mode, and session upgrade by re-exec. + +New measurements to add before phase 1 lands: keystroke-to-present in the +tty and the GUI, `yes | head -c 1G` through a real pty, and a big-file +open. + +## Still open (the coordinator's position in brackets) + +1. Delete the frame wire at phase 3, leaving no remote attach until + phase 5. [yes: it was never used daily] +2. The stream as its own framed protocol, or as a 9P file. [framed: one + ordered stream with no per-read round trip; 9P stays for scripting and + the relay] +3. Rollback by walker copy or by arena copy-on-write. [whichever + measurement of the mutable state's size decides] +4. How the daemon starts: spawning itself or socket activation. [itself, + by double fork; FreeBSD has no systemd. A user unit can be added if a + terminal's scope ever kills it] +5. The join writer: a fork child, or a metadata copy serialised on a + worker. [fork first, measure the page-table copy] -- cgit v1.3 From 4ffe5c93b3087f245f5b57a822ab0ecf41cc085c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 29 Oct 2026 10:48:56 -0300 Subject: sessions register with the daemon: a terminal's session forked off its stub, Detach and --attach in place for terminals and windows, pty masters kept, Adopt pardes in a terminal reaches (or starts) the daemon, opens /dev/tty and forks: the child is the session, in a session of its own (setsid), drawing on that terminal (tty.Term.fd, a raw vaxis Tty made from the fd); the parent stays as its stub, the job the shell waits on. Not the daemon spawning it from a passed fd, env and argv: the user's terminals each run in a 9ns user and mount namespace, which a session spawned by a per-user daemon would not share, and a fork costs one small process's page tables where the spawn cost an IPC and an exec. GUI windows and --detach sessions just register. tty: Detach (and a terminal's end: EOF, EIO, a hangup the stub passes on, taken on the signal thread) puts the terminal back, drops it and the stub's stdio, tells the stub (which ends, exit 0), and leaves the session running with nothing drawn (Host.watched), its messages on the clock and `size` its own. pardes --attach[=name] hands its terminal through the daemon; the session enters it as the first one, sized, queried and drawn whole, and that process is its stub until it leaves. A hangup never ends a kept session; TERM and INT do, telling the daemon so the shells go with it (one async-signal-safe send). gui: Detach closes the window (its swapchain or renderer) and keeps the device, atlas and pipelines; the loop sleeps on SDL's queue; pardes-gui --attach[=name] opens a window again. Closing a window still quits. --detach is a session started detached: the tty host with no terminal yet, the GUI with a hidden window closed at once. forkShell sends the daemon a dup of every master and the hosts tell it what they close, so a session killed outright leaves its shells running; the new Adopt word takes them in as terminal panes (the Tty word's pane, its spawn taking the pty, a 1x1 size then the pane's to make it redraw). The Attach word, which switched a session's own terminal to a detached session through the frames, goes, with its effect and request in the core. PARDES_DAEMON=off (the e2e harness's) runs a session as before. test/daemon.py: 50 detach/attach cycles at a level fd count with no stale socket, kill -9 and Adopt, and nothing left; --gui the same for a window. test/fs.py: a forked session's socket is found by its own pid, and a hangup leaves a kept session running. Co-Authored-By: Claude Opus 5.5 --- docs/typ/builtins-gui.json | 4 +- docs/typ/builtins-tty.json | 4 +- docs/typ/cheatsheet.typ | 3 +- docs/typ/guide.typ | 14 +- src/9p_io.zig | 22 +- src/builtins.zig | 49 +--- src/config.zig | 4 +- src/file_watch.zig | 2 +- src/gui/gui.zig | 487 +++++++++++++++++---------------- src/host_io.zig | 37 ++- src/macos.zig | 3 +- src/main.zig | 137 +++++++--- src/pardes.zig | 72 +---- src/tty/tty.zig | 650 +++++++++++++++++++++------------------------ src/tutor.txt | 4 +- test/daemon.py | 322 ++++++++++++++++++++++ test/e2e_harness.zig | 4 + test/fs.py | 40 ++- 18 files changed, 1100 insertions(+), 758 deletions(-) create mode 100644 test/daemon.py (limited to 'docs') diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index db1031a0..9db9e396 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -1,6 +1,6 @@ [ + {"name": "Adopt", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Take in the shells of a session that died holding them, each as a terminal pane here: the pardes daemon kept their terminals open."}, {"name": "Ascii", "leader": "SPC t a", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "add the printable ASCII bitmaps to the matcher's glyph set"}, - {"name": "Attach", "leader": "SPC s a", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Attach this terminal to a detached pardes session by name."}, {"name": "Back", "leader": "SPC j o", "also": ["C-o"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Ctrl-o: one step back into the history."}, {"name": "Bloom", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off, 0-3", "doc": "The brightest ink glows a little: a level, 0 (off) through 3."}, {"name": "BootShell", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "keep, replace", "doc": "A document dropped where a lone untouched shell stands: keep the shell, or replace it."}, @@ -29,7 +29,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, leaving the session running."}, + {"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": "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": false, "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": "DiffLook", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "hunks, text", "doc": "A .diff or .patch looked at: hunks, a +Diff stacking its hunks, or text, the file itself; Diff goes from one to the other."}, diff --git a/docs/typ/builtins-tty.json b/docs/typ/builtins-tty.json index 6bdca598..151c04a6 100644 --- a/docs/typ/builtins-tty.json +++ b/docs/typ/builtins-tty.json @@ -1,6 +1,6 @@ [ + {"name": "Adopt", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Take in the shells of a session that died holding them, each as a terminal pane here: the pardes daemon kept their terminals open."}, {"name": "Ascii", "leader": "SPC t a", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "add the printable ASCII bitmaps to the matcher's glyph set"}, - {"name": "Attach", "leader": "SPC s a", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Attach this terminal to a detached pardes session by name."}, {"name": "Back", "leader": "SPC j o", "also": ["C-o"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Ctrl-o: one step back into the history."}, {"name": "BootShell", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "keep, replace", "doc": "A document dropped where a lone untouched shell stands: keep the shell, or replace it."}, {"name": "Callees", "leader": "SPC l C", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the functions the function under the cursor calls."}, @@ -26,7 +26,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, leaving the session running."}, + {"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": "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": false, "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": "DiffLook", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "hunks, text", "doc": "A .diff or .patch looked at: hunks, a +Diff stacking its hunks, or text, the file itself; Diff goes from one to the other."}, diff --git a/docs/typ/cheatsheet.typ b/docs/typ/cheatsheet.typ index 43162f52..11f7c6fc 100644 --- a/docs/typ/cheatsheet.typ +++ b/docs/typ/cheatsheet.typ @@ -105,7 +105,6 @@ Helix-style: motions *select*, then an edit acts on the selection. Mode box: bla key("SPC c p"), word("Placement"), key("SPC s d"), word("Dump"), key("SPC s r"), word("Restore"), - key("SPC s a"), word("Attach"), key("SPC s D"), word("Detach"), key("SPC h t"), word("Tutor"), key("SPC h m"), word("Messages"), @@ -124,7 +123,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` or #word("Attach") `work`; #word("Detach") leaves it running. #doc("detached") +`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") == 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/guide.typ b/docs/typ/guide.typ index 58e5d907..5dea0522 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -343,12 +343,18 @@ 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 ``` -The session owns the panes, shells and files; frontends come and go, and -all of them see the same screen. #word("Attach") `work` (#key("SPC s a")) -switches this window to it; #word("Detach") (#key("SPC s D")) leaves it -running. +#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. `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. 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 keeps all of it, and +leaves once nothing is kept. = Config diff --git a/src/9p_io.zig b/src/9p_io.zig index a089a7cf..2a0061fd 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -975,13 +975,14 @@ pub fn unlinkOwnSocket() void { _ = libc.unlink(own_socket[0..n :0]); } -/// SIGTERM and SIGHUP with no handler of their own (a GUI's): the socket -/// goes, then the signal's own death. A host that handles them itself (the -/// terminal's Killed, the detached server's quit) removes it its own way. +/// SIGTERM, SIGHUP and SIGINT with no handler of their own (a GUI's, a +/// detached session's): the socket goes, then the signal's own death. A +/// host that handles them itself (the terminal's Killed, SDL's quit) +/// removes it its own way. fn armSocketCleanup() void { const sig = std.posix.SIG; const on: std.posix.Sigaction = .{ .handler = .{ .handler = onFatalSignal }, .mask = std.posix.sigemptyset(), .flags = std.posix.SA.RESETHAND }; - for ([_]std.posix.SIG{ sig.TERM, sig.HUP }) |s| { + for ([_]std.posix.SIG{ sig.TERM, sig.HUP, sig.INT }) |s| { var was: std.posix.Sigaction = undefined; std.posix.sigaction(s, null, &was); if (was.handler.handler == sig.DFL) std.posix.sigaction(s, &on, null); @@ -995,6 +996,8 @@ pub var fatal_cleanup: ?*const fn () void = null; fn onFatalSignal(s: std.posix.SIG) callconv(.c) void { unlinkOwnSocket(); if (fatal_cleanup) |cleanup| cleanup(); + // Its shells go with it, the daemon's dups let go. + @import("daemon.zig").hangUp(); // SA_RESETHAND put the default back: the same signal, now fatal. _ = std.c.raise(s); } @@ -1204,6 +1207,17 @@ pub fn listen(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes, named: [ const alive = transport.isListening; +/// Whether a live session listens under `name` already: a second +/// `--detach=` is refused before anything is made. +pub fn taken(name: []const u8) bool { + if (comptime !supported) return false; + var dir_buf: [sun_path_len:0]u8 = undefined; + const dir = socketDir(&dir_buf) orelse return false; + var buf: [sun_path_len]u8 = undefined; + const p = socketPath(&buf, dir, name) orelse return false; + return statNoFollow(p) != null and alive(p); +} + /// What is at a socket path, in cloud9's three answers (`post.Probe`). /// Asked here with libc rather than through `cloud9.post.probe`, whose /// raw Linux syscalls darwin cannot compile, but the classification is diff --git a/src/builtins.zig b/src/builtins.zig index 1f1e674e..3a66a316 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -737,51 +737,28 @@ pub const Restore = struct { } }; -/// Attach this terminal to a detached pardes session by name. -pub const Attach = struct { +/// Detach this pardes from its terminal or window, leaving the session +/// running: `pardes --attach` (or `pardes-gui --attach`) takes it back. +pub const Detach = struct { pub const scope: Scope = .session; - pub const takes_arg = true; pub const enabled = pardes.can_attach; pub fn run(c: Ctx) void { - if (comptime enabled) ask(c) else unreachable; - } - fn ask(c: Ctx) void { - const name = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); - if (name.len > pardes.attach_name_max) - return c.p.reportError(c.id, comptime word(@This()), error.NameTooLong); - // A detached session has no terminal to move: bare, there is no - // "the one session there" but itself; a name is said for what it is. - if (c.p.opts.detached_session) { - if (name.len == 0) return c.p.reportFailure(c.id, "wrong #args in control message \"Attach\": a detached session names the session"); - // A session is its socket, `pardes-detached-.sock` beside - // the 9P ones (detached/server.zig socketPath); not imported, as - // the core links no frontend's code. - const ninep_io = @import("9p_io.zig"); - var dir_buf: [ninep_io.sun_path_len:0]u8 = undefined; - var path_buf: [ninep_io.sun_path_len + 64:0]u8 = undefined; - const exists = if (ninep_io.socketDir(&dir_buf)) |dir| - (if (std.fmt.bufPrintSentinel(&path_buf, "{s}/pardes-detached-{s}.sock", .{ dir, name }, 0)) |path| ninep_io.statNoFollow(path) != null else |_| false) - else - false; - var said: [pardes.attach_name_max + 96]u8 = undefined; - return c.p.reportFailure(c.id, if (exists) - std.fmt.bufPrint(&said, "Attach: {s}: a detached session has no terminal to attach; Attach from a frontend", .{name}) catch "Attach: a detached session has no terminal to attach" - else - std.fmt.bufPrint(&said, "Attach: {s}: no such session", .{name}) catch "Attach: no such session"); - } - c.p.emit(.{ .attach = .{ .pane = @intCast(c.id), .name = .from(name) } }); + if (comptime enabled) + c.p.emit(.{ .detach = .{ .pane = @intCast(c.id) } }) + else + unreachable; } }; -/// Detach this pardes from its terminal, leaving the session running. -pub const Detach = struct { +/// Take in the shells of a session that died holding them, each as a +/// terminal pane here: the pardes daemon kept their terminals open. +pub const Adopt = struct { pub const scope: Scope = .session; pub const enabled = pardes.can_attach; pub fn run(c: Ctx) void { - if (comptime enabled) - c.p.emit(.{ .detach = .{ .pane = @intCast(c.id) } }) - else - unreachable; + if (comptime !enabled) unreachable; + const adopt = c.p.host.vtable.adopt orelse return c.p.reportFailure(c.id, "Adopt: no pardes daemon is keeping shells for this session"); + adopt(c.p.host.ctx, @intCast(c.id)); } }; diff --git a/src/config.zig b/src/config.zig index 988f634d..66b11c72 100644 --- a/src/config.zig +++ b/src/config.zig @@ -217,8 +217,8 @@ pub const leader_path = paths: { table.set(.Unmount, null); } if (pardes.can_attach) { - table.set(.Attach, "sa"); table.set(.Detach, "sD"); + table.set(.Adopt, null); } if (builtins.Peek.enabled) { table.set(.Peek, null); @@ -2306,6 +2306,8 @@ test "docs/typ names only words, keys and default tags that exist" { var dir = try std.Io.Dir.cwd().openDir(io, @import("doc_typ").dir, .{ .iterate = true }); defer dir.close(io); var found: [3]std.ArrayList([]const u8) = @splat(.empty); + // The arena's: gone with this test, so no later test reads it. + defer doc_typ.other_build = ""; for ([_][]const u8{ "builtins-tty.json", "builtins-gui.json" }) |f| { const text = dir.readFileAlloc(io, f, gpa, .limited(1 << 20)) catch continue; doc_typ.other_build = try std.mem.concat(gpa, u8, &.{ doc_typ.other_build, text }); diff --git a/src/file_watch.zig b/src/file_watch.zig index ab902e5b..e3fe9963 100644 --- a/src/file_watch.zig +++ b/src/file_watch.zig @@ -98,7 +98,7 @@ const wake_ident: usize = std.math.maxInt(usize); /// /// `polled` is the only flag that survives the port. On linux it adds /// IN_NONBLOCK, because a host that finds this descriptor ready in its own -/// `poll(2)` (detached/server.zig) must be able to stop draining it, while a +/// `poll(2)` must be able to stop draining it, while a /// host that parks a thread in `wait` (tty.zig, gui.zig) wants the blocking /// read. On macos neither host needs either flag: a kqueue is not inherited /// across `fork(2)`, so there is no CLOEXEC to ask for, and whether a wait diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 01272b41..a1590b48 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -22,7 +22,7 @@ const c_heap = @import("c_heap"); const ninep_io = @import("../9p_io.zig"); -const detached_client = @import("../detached/client.zig"); +const daemon = @import("../daemon.zig"); const tracy = @import("../tracy.zig"); pub const c = @import("gui_c"); // SDL3 and font.h, translated by build.zig @@ -1434,8 +1434,6 @@ const Gui = struct { tagline_percent: u8, tagline_width: u32, tagline_height: u32, - attached_layers: ?*const [pardes.MAX_PANES]pardes.Layer = null, - attached_tag_layers: ?*const [pardes.MAX_TAG_LAYERS]pardes.Layer = null, cell_w: u32, cell_h: u32, ascent: i32, @@ -1533,6 +1531,14 @@ const Gui = struct { applied_window_opacity: u8 = 100, soft_renderer: ?*c.SDL_Renderer = null, soft_texture: ?*c.SDL_Texture = null, + /// What a window is opened again with (reopenWindow): the flags (not + /// hidden), the present mode, its size when it was closed. + win_flags: c.SDL_WindowFlags = 0, + present_mode: c.SDL_GPUPresentMode = c.SDL_GPU_PRESENTMODE_VSYNC, + window_w: c_int = 1120, + window_h: c_int = 720, + /// The window runNative destroys at the end: the one open then, if any. + window_slot: ?*?*c.SDL_Window = null, soft_tex_w: u32 = 0, soft_tex_h: u32 = 0, @@ -1895,16 +1901,10 @@ fn setTransitionFields( pub const run = runNative; -fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u8) !void { +fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool) !void { const gpa = init.gpa; const env = init.environ_map; - if (env.get("PARDES_TEST_GRID") != null) { - if (attach != null) { - log.err("--attach needs a window; PARDES_TEST_GRID is headless", .{}); - return error.AttachNeedsWindow; - } - return runGrid(init, opts_in); - } + if (env.get("PARDES_TEST_GRID") != null) return runGrid(init, opts_in); const test_mode = env.get("PARDES_TEST") != null; const capture_dir = env.get("PARDES_TEST_CAPTURE_DIR"); @@ -1950,6 +1950,9 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u // opacity would dim the text as well. SDL requires this flag at creation. const surface_opacity = native_wayland; if (surface_opacity) win_flags |= c.SDL_WINDOW_TRANSPARENT; + const reopen_flags = win_flags; + // `--detach`: a window never shown, closed once the session is up. + if (headless) win_flags |= c.SDL_WINDOW_HIDDEN; // `--geometry=WxH[+X+Y]`, as X11 programs take it. var want_w: c_int = 1120; var want_h: c_int = 720; @@ -1969,7 +1972,8 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u log.err("SDL_CreateWindow: {s}", .{c.SDL_GetError()}); return error.SdlInit; }; - defer c.SDL_DestroyWindow(window); + var window_slot: ?*c.SDL_Window = window; + defer if (window_slot) |open| c.SDL_DestroyWindow(open); if (want_at) |at| _ = c.SDL_SetWindowPosition(window, at[0], at[1]); updateDisplayScale(window); if (native_wayland) log.info("Wayland opacity: background-only transparent surface", .{}); @@ -2173,6 +2177,11 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u .demo_next = if (env.get("PARDES_FRAMES_DEMO")) |name| (if (pardes.FrameStats.named(name) != null) @as(?usize, 0) else null) else null, .surface_opacity = surface_opacity, .soft_renderer = soft_renderer, + .win_flags = reopen_flags, + .present_mode = present_mode, + .window_w = want_w, + .window_h = want_h, + .window_slot = &window_slot, }; // The pipelines, textures and buffers the Gui holds, whatever they were // regrown to; the image ones are released below. @@ -2221,10 +2230,48 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u // compositor moves it, as it does a title bar. if (!test_mode and !c.SDL_SetWindowHitTest(window, hitTest, &g)) log.warn("SDL_SetWindowHitTest: {s}", .{c.SDL_GetError()}); - if (attach) |requested| return attachRequested(gpa, &g, requested); - var attached: ?detached_client.Client = null; - try localSession(init, &g, opts_in, test_mode, &attached); - if (attached) |*client| return attachedLoop(gpa, &g, client); + try localSession(init, &g, opts_in, test_mode, headless); +} + +/// Detach: the window closed (and with it its swapchain or renderer); the +/// device, the atlas and the pipelines stay for the next one. +fn closeWindow(g: *Gui) void { + _ = c.SDL_GetWindowSize(g.window, &g.window_w, &g.window_h); + _ = c.SDL_StopTextInput(g.window); + if (g.soft_renderer) |renderer| { + if (g.soft_texture) |texture| c.SDL_DestroyTexture(texture); + g.soft_texture = null; + g.soft_tex_w = 0; + g.soft_tex_h = 0; + c.SDL_DestroyRenderer(renderer); + g.soft_renderer = null; + } else c.SDL_ReleaseWindowFromGPUDevice(g.device, g.window); + c.SDL_DestroyWindow(g.window); + if (g.window_slot) |slot| slot.* = null; +} + +/// `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. +fn reopenWindow(g: *Gui) bool { + const window = c.SDL_CreateWindow("pardes", g.window_w, g.window_h, g.win_flags) orelse return false; + if (g.soft_present) { + g.soft_renderer = c.SDL_CreateRenderer(window, null) orelse { + c.SDL_DestroyWindow(window); + return false; + }; + } else { + if (!c.SDL_ClaimWindowForGPUDevice(g.device, window)) { + c.SDL_DestroyWindow(window); + return false; + } + _ = c.SDL_SetGPUSwapchainParameters(g.device, window, c.SDL_GPU_SWAPCHAINCOMPOSITION_SDR, g.present_mode); + } + g.window = window; + if (g.window_slot) |slot| slot.* = window; + updateDisplayScale(window); + if (!g.capture) _ = c.SDL_SetWindowHitTest(window, hitTest, g); + _ = c.SDL_StartTextInput(window); + return true; } fn localSession( @@ -2232,7 +2279,7 @@ fn localSession( g: *Gui, opts_in: pardes.Options, test_mode: bool, - attached: *?detached_client.Client, + headless: bool, ) !void { const io = init.io; const gpa = init.gpa; @@ -2359,25 +2406,19 @@ fn localSession( defer pardes.lsp.setStatusSink(null, null); host_io.setExitWake(&queue, Queue.wakeForExit); defer host_io.setExitWake(null, null); + if (headless) { + shell.closeTheWindow(); + // Nothing else may wake the first wait. + daemon.watch(&queue, deliverNote); + } while (!core.quit) { pardes.turn.bump(&pardes.turn.restores); try core.pump(host); + // A window asked for again, or an adopted shell, from the daemon's + // thread through the queue; started after the first frame. + daemon.watch(&queue, deliverNote); if (core.quit) break; // a session that ended does not restore into one - if (core.takeAttach()) |req| { - const geom = windowCells(g); - const outcome = detached_client.attempt(gpa, req.name, geom.cols, geom.rows); - switch (outcome) { - .greeted => |client| { - attached.* = client; - break; - }, - else => { - var mbuf: [256]u8 = undefined; - core.setMessage(req.pane, attachFailure(&mbuf, outcome, req.name)); - }, - } - } if (core.takeRestore()) |rp| blk: { const bytes = filesystem.readRestore(gpa, rp, core.settings.dump_dir.get()) catch |err| { core.reportError(core.active, "Restore", err); @@ -2426,198 +2467,6 @@ fn localSession( } } -fn attachFailure(buf: []u8, outcome: detached_client.Attempt, requested: []const u8) []const u8 { - return switch (outcome) { - .greeted => unreachable, - .no_session => if (requested.len != 0) - std.fmt.bufPrint(buf, "Attach: no detached session called '{s}'", .{requested}) catch - "Attach: no detached session under that name" - else - "Attach: nothing is detached (start one with `pardes --detach`)", - .ambiguous => |n| std.fmt.bufPrint(buf, "Attach: {d} detached sessions; say which one", .{n}) catch - "Attach: several detached sessions; say which one", - .refused => |why| switch (why) { - .version => "Attach: that session speaks a different wire version — it is another build of pardes", - .full => "Attach: that session already has every frontend slot taken", - .quitting => "Attach: that session is ending", - }, - .silent => "Attach: that session took the connection and never greeted us", - .lost => |err| std.fmt.bufPrint(buf, "Attach: lost the connection ({t})", .{err}) catch - "Attach: lost the connection", - }; -} - -fn attachRequested(gpa: std.mem.Allocator, g: *Gui, requested: []const u8) !void { - const geom = windowCells(g); - const outcome = detached_client.attempt(gpa, requested, geom.cols, geom.rows); - switch (outcome) { - .greeted => |greeted| { - var client = greeted; - return attachedLoop(gpa, g, &client); - }, - else => { - var mbuf: [256]u8 = undefined; - log.err("{s}", .{attachFailure(&mbuf, outcome, requested)}); - return switch (outcome) { - .no_session => error.NoSession, - .ambiguous => error.AmbiguousSession, - .refused => error.Refused, - .silent => error.NoGreeting, - .lost => |err| err, - .greeted => unreachable, - }; - }, - } -} - -fn attachedResize(client: *detached_client.Client, g: *const Gui, cols: u16, rows: u16) !void { - try client.send(.{ .event = .{ .resize = .{ .cols = cols, .rows = rows, .row_metrics = .{ - .body_w = @intCast(g.cell_w), - .body_h = @intCast(g.cell_h), - .tagline_w = @intCast(g.tagline_width), - .tagline_h = @intCast(g.tagline_height), - } } } }); -} - -fn attachedLoop(gpa: std.mem.Allocator, g: *Gui, client: *detached_client.Client) !void { - defer client.detach(); - _ = c.SDL_StartTextInput(g.window); - - var in: Input = .{ .client = client }; - g.attached_layers = &client.body_layers; - g.attached_tag_layers = &client.tag_layers; - var dirty = false; - var geom = windowCells(g); - try attachedResize(client, g, geom.cols, geom.rows); - while (true) { - const link = client.wait(detached_client.poll_ms); - while (true) { - const msg = (try client.next()) orelse break; - switch (msg) { - .welcome => {}, - .refuse => |why| { - log.err("session refused an already-greeted frontend: {t}", .{why}); - return error.Refused; - }, - .frame => dirty = true, - .quit => return, - .detach => return, - .set_clipboard => |text| putClipboard(gpa, text), - .read_clipboard => if (takeClipboard()) |text| { - defer c.SDL_free(text.ptr); - in.post(.{ .paste = text }); - }, - .open_link => |url| look.openLink(url), - .post => dirty = true, - } - } - try link; - - var sev = std.mem.zeroes(c.SDL_Event); - while (c.SDL_PollEvent(&sev)) dispatch(g, &in, &sev); - pollGamepad(g, &in); - if (in.lost) |err| return err; - if (in.quit) return; - - const now = windowCells(g); - if (now.cols != geom.cols or now.rows != geom.rows) { - geom = now; - try attachedResize(client, g, now.cols, now.rows); - } - // The session's chain, its files compiled there. - g.post.sync(gpa, g.device, g.swapchain_format, client.post.list(), client.post_key, null); - if (!dirty) { - // As a local window does: a chain that moves on its own redraws - // alone, once a refresh. - if (g.post.animating(client.post.animation) and g.scene_tex != null and - c.SDL_GetTicksNS() -| g.post.last_ns + std.time.ns_per_ms >= refreshNs(g)) redrawPost(g, gpa); - continue; - } - dirty = false; - paintAttached(g, gpa, client); - } -} - -fn paintAttached(g: *Gui, gpa: std.mem.Allocator, client: *detached_client.Client) void { - var surface = attachedSurface(client); - _ = renderFrame( - g, - gpa, - null, - &surface, - false, - ) catch |err| blk: { - log.err("render: {t}", .{err}); - break :blk false; - }; -} - -/// The session's frame as a surface: its cells, layers, regions and palette, -/// so its chrome is drawn from them as a local one's is. -fn attachedSurface(client: *const detached_client.Client) pardes.Surface { - var surface: pardes.Surface = .{ - .cols = client.cols, - .rows = client.rows, - .cells = client.grid.items, - .cursor = if (client.cursor) |cu| .{ .x = cu.x, .y = cu.y, .bar = cu.bar } else null, - .pointer_shape = client.pointer_shape, - .body_layers = client.body_layers, - .tag_layers = client.tag_layers, - .chrome = client.chrome, - }; - const placed = client.regions.items[0..@min(client.regions.items.len, surface.regions.len)]; - @memcpy(surface.regions[0..placed.len], placed); - surface.nregions = @intCast(placed.len); - return surface; -} - -test "an attached frontend draws the session's chrome from its frame alone" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - // A gui-shaped core, whose tags and notices are layers. - core.update(.{ .resize = .{ .cols = 80, .rows = 24, .row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 6, .tagline_h = 12 } } }); - _ = try core.newShell(1, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - core.settings.focus_tint = true; - try std.testing.expect(core.executeBuiltinLine(0, "Msg a notice with a rule under it")); - core.sync(); - // Past its slide into place, where its rule shows. - for (0..30) |_| core.update(.tick); - const s = try core.render(core.scratch.allocator()); - - const wire = @import("../detached/wire.zig"); - var client: detached_client.Client = .{ .gpa = gpa }; - defer client.deinit(); - var welcome: [64]u8 = undefined; - try client.in.appendSlice(gpa, try wire.encodeServer(&welcome, .{ .welcome = .{ .slot = 0, .cols = s.cols, .rows = s.rows } })); - const out = try gpa.alloc(u8, wire.frameBound(s.cols, s.rows) + wire.layersBound(&s.body_layers, &s.tag_layers, s.regionList())); - defer gpa.free(out); - try client.in.appendSlice(gpa, try wire.encodeFrameLayers(out, s.cols, s.rows, null, s.pointer_shape, s.cells, &.{}, &s.body_layers, &s.tag_layers, s.regionList(), s.chrome)); - _ = try client.next(); - _ = try client.next(); - const attached = attachedSurface(&client); - - var g: Gui = undefined; - g.cell_w = 10; - g.cell_h = 20; - g.tagline_width = 6; - g.tagline_height = 12; - g.decor = .empty; - g.glide = .{}; - g.scroll_pane = null; - g.scroll_lag = 0; - defer g.decor.deinit(gpa); - var groups = makeGroups(&.{}, false); - try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 800, 480, true); - const local = try gpa.dupe(CellInstance, g.decor.items); - defer gpa.free(local); - try std.testing.expect(local.len > 8); - try std.testing.expect(groups.items[groups.notices].decor_count != 0); - try buildDecor(&g, gpa, &attached, &groups, fixedCellLayout(&g), 800, 480, true); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(local), std.mem.sliceAsBytes(g.decor.items)); -} - fn runGrid(init: std.process.Init, opts_in: pardes.Options) !void { const io = init.io; const gpa = init.gpa; @@ -2691,6 +2540,7 @@ fn runGrid(init: std.process.Init, opts_in: pardes.Options) !void { .inotify_fd = -1, .watches = &watches, .fs = fs, + .grid = true, }; defer shell.shutdownPtys(); const host = shell.host(); @@ -3125,18 +2975,10 @@ test "the window's function and editing keys reach a terminal as its cursor keys const Input = struct { core: ?*pardes.Pardes = null, - client: ?*detached_client.Client = null, quit: bool = false, - lost: ?anyerror = null, fn post(in: *Input, ev: pardes.Event) void { if (in.core) |core| return core.update(ev); - const client = in.client orelse return; - if (in.lost != null) return; - client.send(.{ .event = ev }) catch |err| switch (err) { - error.Overlong, error.WriteFailed => {}, - else => in.lost = err, - }; } fn close(in: *Input) void { @@ -3526,18 +3368,6 @@ fn gridCellAtPixels(g: *const Gui, core: ?*const pardes.Pardes, x: f32, y: f32) break; } }; - if (core == null) if (g.attached_layers) |layers| for (layers) |*layer| { - if (layer.bodyHit(x, y, @floatFromInt(g.cell_w), @floatFromInt(g.cell_h), @floatFromInt(g.tagline_width), @floatFromInt(g.tagline_height))) |body_hit| { - point.body_hit = body_hit; - break; - } - }; - if (core == null) if (g.attached_tag_layers) |layers| for (layers) |*layer| { - if (layer.tagHit(x, y, @floatFromInt(g.cell_w), @floatFromInt(g.cell_h), @floatFromInt(g.tagline_width), @floatFromInt(g.tagline_height))) |hit| { - point.tag_hit = hit; - break; - } - }; return point; } @@ -3805,7 +3635,17 @@ fn pollGamepad(g: *Gui, in: *Input) void { const Shell = struct { core: *pardes.Pardes, + /// The window's, while one is open; null while detached (`parked` has + /// it) and in the headless test grid. gui: ?*Gui = null, + parked: ?*Gui = null, + /// The headless test grid (runGrid): its own loop, no window ever. + grid: bool = false, + /// Shells a dead session left (Adopt), each waiting for the spawn of + /// the terminal pane made for it. + adoptions: [pardes.MAX_PANES]Adoption = undefined, + adoptions_len: usize = 0, + adopted: usize = 0, io: std.Io, gpa: std.mem.Allocator, fs: ?*ninep_io.Listener = null, @@ -3863,6 +3703,7 @@ const Shell = struct { } _ = libc.close(pt.fd); pt.fd = -1; + daemon.closed(pt.pid); const now = std.Io.Clock.awake.now(s.queue.io).toMilliseconds(); host_io.reapRetired(&pt.pid, &pt.kill_at, now); if (pt.pid == 0) { @@ -3917,7 +3758,83 @@ const Shell = struct { } fn host(s: *Shell) pardes.Host { - return .{ .ctx = s, .vtable = if (s.gui == null) &grid_vtable else &vtable }; + return .{ .ctx = s, .vtable = if (s.grid) &grid_vtable else &vtable }; + } + + /// Detach: the window closed, the session left running with no + /// window, for `pardes-gui --attach` to open one again. + fn detachWindow(ctx: ?*anyopaque) void { + const s = shellOf(ctx); + if (s.gui == null) return s.core.reportFailure(s.core.active, "Detach: no window is open"); + if (!daemon.kept()) return s.core.reportFailure(s.core.active, "Detach: no pardes daemon keeps this session; closing its window ends it"); + s.closeTheWindow(); + } + + fn closeTheWindow(s: *Shell) void { + const g = s.gui orelse return; + closeWindow(g); + s.parked = g; + s.gui = null; + s.presented = false; + s.surface = null; + s.core.unattended = true; + daemon.setState(true); + } + + fn openTheWindow(s: *Shell) void { + const g = s.parked orelse return; + if (!reopenWindow(g)) { + log.err("--attach: no window: {s}", .{c.SDL_GetError()}); + return daemon.setState(true); + } + s.gui = g; + s.parked = null; + s.core.unattended = false; + s.core.needs_frame = true; + resetScroll(g); + daemon.setState(false); + } + + fn watched(ctx: ?*anyopaque) bool { + return shellOf(ctx).gui != null; + } + + fn adopt(ctx: ?*anyopaque, pane: u8) void { + const s = shellOf(ctx); + if (!daemon.kept()) return s.core.reportFailure(pane, "Adopt: no pardes daemon is keeping shells for this session"); + s.adopted = 0; + daemon.adopt(); + } + + /// One shell of a dead session (`pid` 0: the last of them was told): + /// a terminal pane made for it, as the Tty word makes one, whose spawn + /// takes this pty (spawnPane). + fn adoptShell(s: *Shell, pid: libc.pid_t, fd: c_int) void { + const core = s.core; + if (pid == 0) { + var buf: [96]u8 = undefined; + return core.setMessage(core.active, if (s.adopted == 0) "Adopt: no shell of a session that died is waiting" else std.fmt.bufPrint(&buf, "Adopt: {d} shell{s} taken in; what they showed is gone", .{ s.adopted, if (s.adopted == 1) "" else "s" }) catch "Adopt: shells taken in"); + } + var newest: u32 = 0; + for (core.panes) |slot| if (slot) |pn| { + newest = @max(newest, pn.serial); + }; + if (s.adoptions_len < s.adoptions.len) { + s.adoptions[s.adoptions_len] = .{ .pid = pid, .fd = fd, .pane = null }; + s.adoptions_len += 1; + _ = core.executeBuiltinLine(core.active, "Tty"); + for (core.panes, 0..) |slot, id| if (slot) |pn| if (pn.serial > newest and pn.isTerminal()) { + // Its shell is up already: nothing to greet with `ls`. + pn.greet = false; + s.adoptions[s.adoptions_len - 1].pane = @intCast(id); + s.adopted += 1; + return; + }; + s.adoptions_len -= 1; + } + _ = libc.close(fd); + var buf: [96]u8 = undefined; + core.setMessage(core.active, std.fmt.bufPrint(&buf, "Adopt: no room for shell {d}; it ends with this session", .{pid}) catch "Adopt: no room for a shell"); } const vtable: pardes.Host.VTable = .{ @@ -3926,6 +3843,9 @@ const Shell = struct { .present = present, .post_present = postPresent, .poll_frame = pollFrame, + .watched = watched, + .detach = detachWindow, + .adopt = adopt, .spawn = spawnPane, .pty_write = ptyWrite, .pty_resize = ptyResize, @@ -3957,6 +3877,9 @@ const Shell = struct { v.post_present = gridPostPresent; v.set_clipboard = null; v.read_clipboard = null; + v.watched = null; + v.detach = null; + v.adopt = null; break :vt v; }; @@ -4051,6 +3974,14 @@ const Shell = struct { }, .files_changed => check_files = true, .fs_ready => {}, + .window => { + s.openTheWindow(); + s.saw_event = true; + }, + .adopted => |a| { + s.adoptShell(a.pid, a.fd); + s.saw_event = true; + }, }; if (check_files) s.shaders.recheck(); if (check_files and file_watch.reloadChanged(s.core, s.io, s.gpa, s.watches)) @@ -4214,7 +4145,7 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { } s.paced_ns = if (paced) tick else null; if (paced) g.pace_ns = tick; - } + } else waitDetached(core, timeout_ms); if (s.test_mode) { const r = s.feed.pump(s.gpa, &in, s.gui) catch { core.quit = true; @@ -4229,6 +4160,26 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { if (s.gui) |g| pollGamepad(g, &in); } +/// Detached: no window, asleep until the queue's wake (an SDL user event: +/// a pty's output, the daemon's window request), the core's next wake, or a +/// quit (SDL makes SIGTERM and SIGINT one). With nobody to dismiss them, +/// messages go on the clock. +fn waitDetached(core: *pardes.Pardes, timeout_ms: u32) void { + pardes.Messages.expireUnattended(core); + var ms: c_int = if (timeout_ms != 0) @intCast(@min(timeout_ms, std.math.maxInt(c_int))) else -1; + for (core.panes) |slot| if (slot) |pane| if (pane.msg_len > 0) { + ms = if (ms < 0) 100 else @min(ms, 100); + break; + }; + var sev = std.mem.zeroes(c.SDL_Event); + pardes.turn.rest(); + var got = c.SDL_WaitEventTimeout(&sev, ms); + pardes.turn.wake(); + while (got) : (got = c.SDL_PollEvent(&sev)) { + if (sev.type == c.SDL_EVENT_QUIT) core.quit = true; + } +} + fn pollFrame(ctx: ?*anyopaque) void { const s = shellOf(ctx); s.reconcilePtys(); @@ -4545,6 +4496,11 @@ fn gridPostPresent(ctx: ?*anyopaque) void { fn spawnPane(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { const s = shellOf(ctx); s.reap(); + for (s.adoptions[0..s.adoptions_len], 0..) |a, i| if (a.pane == pane) { + std.mem.copyForwards(Adoption, s.adoptions[i .. s.adoptions_len - 1], s.adoptions[i + 1 .. s.adoptions_len]); + s.adoptions_len -= 1; + return takeShell(s, pane, a); + }; // The new shell starts before a running one goes: one that cannot // start leaves the running one be (pty/ctl's exec). const running = s.ptys[pane] != null; @@ -4571,6 +4527,46 @@ fn spawnPane(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { }; } +const Adoption = struct { pid: libc.pid_t, fd: c_int, pane: ?u8 }; + +/// An adopted shell, running already, as pane `pane`'s: told the size twice +/// (one it never had, then the pane's), which makes it redraw. +fn takeShell(s: *Shell, pane: u8, a: Adoption) void { + s.closePty(pane); + s.gens[pane] +%= 1; + s.ptys[pane] = .{ .fd = a.fd, .pid = a.pid, .serial = s.core.panes[pane].?.serial, .cmd = .{} }; + var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + s.core.acknowledgeShell(pane, host_io.processExe(a.pid, &exe_buf) orelse "sh", host_io.marksPrompts(a.pid)); + var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + if (host_io.shellCwd(a.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); + const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 }; + _ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny)); + if (s.core.panes[pane]) |pn| ptyResize(s, pane, @max(pn.cols, 1), @max(pn.rows, 1)); + if (!s.threads_ok) return; + s.ptys[pane].?.reader = s.queue.startReader(.{ .handle = a.fd, .flags = .{ .nonblocking = false } }, pane, s.gens[pane]) catch |err| { + s.closePty(pane); + return s.core.reportError(pane, "terminal reader", err); + }; +} + +/// The daemon's thread: what it says, onto the queue (drainQueue). +fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { + const q: *Queue = @ptrCast(@alignCast(ctx)); + 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.refuseStub(a.stub, "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 } }); + }, + } +} + fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void { const s = shellOf(ctx); if (s.ptys[pane]) |pt| if (pt.fd >= 0) { @@ -4704,6 +4700,7 @@ test "the headless grid host round-trips a yank back as a paste" { .pipe_tasks = &pipe_tasks, .inotify_fd = -1, .watches = &watches, + .grid = true, }; core.host = shell.host(); try std.testing.expect(core.host.vtable == &Shell.grid_vtable); diff --git a/src/host_io.zig b/src/host_io.zig index af284e84..96c790d7 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -24,7 +24,11 @@ pub const Host = struct { /// client attached draws none (a /screen read draws its own), and /// the frame owed is drawn when one attaches. Absent: always. watched: ?*const fn (ctx: ?*anyopaque) bool = null, + /// Detach: the terminal or window let go, the session left running + /// for the daemon to attach again (daemon.zig). detach: ?*const fn (ctx: ?*anyopaque) void = null, + /// Adopt: the shells a dead session left, asked of the daemon. + adopt: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null, spawn: ?*const fn (ctx: ?*anyopaque, pane: u8, cwd: []const u8) void = null, pty_write: ?*const fn (ctx: ?*anyopaque, pane: u8, bytes: []const u8) void = null, pty_resize: ?*const fn (ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void = null, @@ -143,6 +147,11 @@ pub const Inbox = struct { handed: struct { seq: u32, ok: bool, words: []u8 }, 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 }, pub fn deinit(m: Msg, gpa: std.mem.Allocator, lsp_allocator: std.mem.Allocator) void { switch (m) { @@ -155,7 +164,10 @@ pub const Inbox = struct { }, .search => |b| b.deinit(gpa), .handed => |h| gpa.free(h.words), - .eof, .files_changed, .fs_ready => {}, + .adopted => |a| if (a.fd >= 0) { + _ = libc.close(a.fd); + }, + .eof, .files_changed, .fs_ready, .window => {}, } } }; @@ -2097,6 +2109,9 @@ pub fn forkShell( }; } ninep_io.setCloexec(master); + // The daemon keeps a dup: this session killed outright never hangs the + // shell up (daemon.zig). + @import("daemon.zig").pty(pid, master); if (core) |c| c.acknowledgeShell(pane, std.mem.span(spawn.path), one_line == null and spawn.argv[1] != null); return .{ .file = .{ .handle = master, .flags = .{ .nonblocking = false } }, .pid = pid }; } @@ -2208,6 +2223,26 @@ const proc_vnodepathinfo = extern struct { const PROC_PIDVNODEPATHINFO: c_int = 9; extern "c" fn proc_pidinfo(pid: c_int, flavor: c_int, arg: u64, buffer: *anyopaque, buffersize: c_int) c_int; +/// Whether an adopted shell marks its prompts: one pardes started with its +/// prompt files (bash, zsh, fish), which a pane's runs wait on. +pub fn marksPrompts(pid: libc.pid_t) bool { + var buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + const exe = std.fs.path.basename(processExe(pid, &buf) orelse return false); + for ([_][]const u8{ "bash", "zsh", "fish" }) |shell| if (std.mem.eql(u8, exe, shell)) return true; + return false; +} + +/// The program `pid` runs, where the system says (an adopted shell's, for +/// its pane's Tty word); null elsewhere. +pub fn processExe(pid: libc.pid_t, buf: []u8) ?[]const u8 { + if (comptime builtin.os.tag != .linux) return null; + var pbuf: [64]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&pbuf, "/proc/{d}/exe", .{pid}, 0) catch return null; + const n = libc.readlink(path, buf.ptr, buf.len); + if (n <= 0 or n >= buf.len) return null; + return buf[0..@intCast(n)]; +} + pub fn shellCwd(pid: libc.pid_t, buf: []u8) ?[]const u8 { switch (builtin.os.tag) { .linux => { diff --git a/src/macos.zig b/src/macos.zig index 8d372432..e07955a1 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -1105,7 +1105,8 @@ fn drainInbox(st: *State) bool { .search => |b| st.core.update(.{ .search = b }), // The SDL shell's: this one's file watches and 9P are its own. // ponytail: no hand_over host entry on macOS yet, so none comes. - .files_changed, .fs_ready, .handed => {}, + // No daemon on macOS (daemon.supported): neither ever comes. + .files_changed, .fs_ready, .handed, .window, .adopted => {}, } } for (0..pardes.MAX_PANES) |pane| { diff --git a/src/main.zig b/src/main.zig index 4e6b49bb..803ff4da 100644 --- a/src/main.zig +++ b/src/main.zig @@ -2,6 +2,7 @@ const std = @import("std"); const builtin = @import("builtin"); const pardes = @import("pardes.zig"); const ninep_io = @import("9p_io.zig"); +const daemon = @import("daemon.zig"); const is_emscripten = builtin.os.tag == .emscripten; @@ -84,22 +85,20 @@ const help_text = \\ --9p-quic= also serve at quic!! (-Dquic=true). \\ --mount== mount a 9P session or Unix/TCP/QUIC endpoint under /n/. \\ Repeat for more mounts; os and self are reserved. - \\ --detach run this session with NO terminal of its own, - \\ serving frontends over a unix socket beside its - \\ 9P socket. The core, the panes and the - \\ undo history outlive every frontend that attaches - \\ --detach= ...named rather than this process's pid, so - \\ a frontend can say which session it wants. One - \\ path component: no '/' and nothing empty - \\ --attach become a frontend of the one detached session - \\ that is running: draw its screen and send it - \\ input, and nothing else — the session owns its - \\ pane shells, its files and its watches. Works in - \\ both the terminal and the SDL window build. - \\ Several frontends may be attached at once and all - \\ see the same screen - \\ --attach= ...of the session called , which is what to - \\ use when more than one is running + \\ --detach run this session with no terminal (no window) + \\ until one attaches; its panes, shells and files + \\ stay. Detach, or a terminal that closes, leaves + \\ any session so. One `pardes --daemon` per user + \\ keeps them (PARDES_DAEMON=off: none) + \\ --detach= ...named rather than this process's pid, + \\ as --9p names it. One path component: no '/' + \\ and nothing empty + \\ --attach show the one detached session here: this + \\ terminal for `pardes`, a window again for + \\ `pardes-gui`, each of its own kind. Returns when + \\ the session detaches or ends + \\ --attach= ...the session called (its --9p or + \\ --detach name, else its pid) \\ --geometry=WxH[+X+Y] the window's size in points, and where it goes \\ where the display lets a window say (X11) \\ -h, --help show this help and exit @@ -316,7 +315,7 @@ fn emscriptenMain(argc: c_int, argv: [*]?[*:0]u8) callconv(.c) c_int { // no argv in the browser: options stay default, state comes from the dump, and // there is no session to attach to — a browser tab has no unix socket. fn webMain() !void { - try @import("gui/gui.zig").run(.{}, .{}, null); + try @import("gui/gui.zig").run(.{}, .{}, false); } // init.gpa, what the tty, gui and detached shells allocate from, is their @@ -335,6 +334,8 @@ fn nativeMain(std_init: std.process.Init) !void { var mounts_len: usize = 0; const arena = init.arena.allocator(); const args = try init.minimal.args.toSlice(arena); + // The per-user daemon a session started (daemon.zig): nothing else. + if (comptime daemon.supported) if (args.len == 2 and std.mem.eql(u8, args[1], "--daemon")) daemon.serve(); var session_only = true; var new_session = false; var explicit_tty = false; @@ -713,30 +714,57 @@ fn nativeMain(std_init: std.process.Init) !void { opts.config_dir = found.dir; opts.store_path = storePath(init.io, arena, init.environ_map); if (found.dir) |d| @import("crash.zig").setDir(d); + if (attach) |name| attachTo(init.io, name); if (detach) |name| { - const named = if (name.len != 0) - name - else - try std.fmt.allocPrint(arena, "{d}", .{@as(u32, @intCast(std.c.getpid()))}); - // Said plainly, never a Zig error trace: a name another session's + // Said plainly, never a Zig error trace: a name a live session's // socket holds already (a plain session is named by its pid too). - return @import("detached/server.zig").run(init, opts, named) catch |err| { - var words: [128]u8 = undefined; + if (name.len != 0 and ninep_io.taken(name)) { var said: [512]u8 = undefined; - const why = if (err == error.ListenFailed) - "its socket is taken: another session (a plain one is named by its pid) holds that name; choose another" - else - pardes.Messages.errorWords(err, &words); - std.Io.File.stderr().writeStreamingAll(init.io, std.fmt.bufPrint(&said, "pardes: --detach={s}: {s}\n", .{ named, why }) catch "pardes: --detach failed\n") catch {}; + std.Io.File.stderr().writeStreamingAll(init.io, std.fmt.bufPrint(&said, "pardes: a session named {s} is already running\n", .{name}) catch "pardes: a session of that name is already running\n") catch {}; std.process.exit(1); - }; + } + if (opts.ninep_name.len == 0) opts.ninep_name = name; + // Nobody's size yet: one roomy enough for a script's panes; `size` + // sets another, and an attached terminal or window its own. + opts.cols = 160; + opts.rows = 50; } - if (attach != null and pardes.platform != .tty and pardes.platform != .gui) { - try std.Io.File.stderr().writeStreamingAll(init.io, "pardes: --attach needs the tty or gui shell\n"); - std.process.exit(1); + const kind: daemon.Kind = if (pardes.platform == .gui) .gui else .tty; + var term: @import("tty/tty.zig").Term = if (detach != null) .none else .open; + if (daemon.wanted()) { + if (detach != null or pardes.platform == .gui) { + _ = daemon.register(null, kind, opts.ninep_name, detach != null); + } else if (pardes.platform == .tty) fork: { + // A terminal's session is forked off its stub, which stays the + // job the shell waits on: Detach (or the terminal's end) ends + // the job and leaves the session running (daemon.forkSession). + // The daemon is reached or started first, from this small + // process, and the terminal opened while it is this one's. + const conn = daemon.connect(true) orelse break :fork; + const fd = std.c.open("/dev/tty", .{ .ACCMODE = .RDWR, .CLOEXEC = true, .NOCTTY = true }, @as(std.c.mode_t, 0)); + if (fd < 0) { + daemon.startPending(true); + _ = std.c.close(conn); + break :fork; + } + // Started in the background, the job stops here until it is + // brought to the foreground, as one making its terminal raw does. + // std.posix's termios, not std.c's: glibc's is the bigger struct. + if (std.posix.tcgetattr(fd)) |tio| std.posix.tcsetattr(fd, .NOW, tio) catch {} else |_| {} + daemon.forkSession(conn) orelse { + daemon.startPending(true); + _ = std.c.close(fd); + _ = std.c.close(conn); + break :fork; + }; + _ = daemon.register(conn, .tty, opts.ninep_name, false); + term = .{ .fd = fd }; + } } + defer daemon.quit(); + errdefer daemon.tellStubExit(1); switch (pardes.platform) { - .tty => @import("tty/tty.zig").run(init, opts, attach) catch |err| switch (err) { + .tty => @import("tty/tty.zig").run(init, opts, term) catch |err| switch (err) { // No controlling terminal (a detached pty, a daemon): said, not // an error trace. error.NoDevice => { @@ -745,9 +773,45 @@ fn nativeMain(std_init: std.process.Init) !void { }, else => return err, }, - .gui => try @import("gui/gui.zig").run(init, opts, attach), + .gui => try @import("gui/gui.zig").run(init, opts, detach != null), .web, .macos, .esp32p4 => unreachable, } + daemon.tellStubExit(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. +fn attachTo(io: std.Io, name: []const u8) noreturn { + var words: [600]u8 = undefined; + const Say = struct { + fn no(o: std.Io, why: []const u8) noreturn { + var buf: [700]u8 = undefined; + std.Io.File.stderr().writeStreamingAll(o, std.fmt.bufPrint(&buf, "pardes: --attach: {s}\n", .{why}) catch "pardes: --attach failed\n") catch {}; + std.process.exit(1); + } + }; + if (comptime !daemon.supported) Say.no(io, "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| Say.no(io, why), + }; + const fd = std.c.open("/dev/tty", .{ .ACCMODE = .RDWR, .CLOEXEC = true, .NOCTTY = true }, @as(std.c.mode_t, 0)); + if (fd < 0) Say.no(io, "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) Say.no(io, "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| Say.no(io, why), + } } fn parseCtrlKey(raw: []const u8) ?u21 { @@ -774,8 +838,7 @@ test { _ = @import("detached/wire.zig"); _ = @import("ShaderBuild.zig"); _ = @import("vaxis_input.zig"); - _ = @import("detached/server.zig"); - _ = @import("detached/client.zig"); + _ = @import("daemon.zig"); _ = @import("9p_io.zig"); _ = @import("9p_io.zig").Client; _ = @import("host_io.zig"); diff --git a/src/pardes.zig b/src/pardes.zig index c7ae6704..2bee1f98 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -538,53 +538,8 @@ fn drainForSavePath(p: *Pardes, buf: []u8) ?[]const u8 { return if (len) |n| buf[0..n] else null; } -fn drainForAttach(p: *Pardes) ?AttachRequest { - while (p.nextEffect()) |effect| p.perform(effect); - return p.takeAttach(); -} - -test "Attach asks for a session and tears nothing down" { - if (comptime !can_attach) return; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - - // Bare means whichever session is there, and that is an EMPTY name rather - // than an absent request: the frontend still has to go and look. - try std.testing.expect(p.executeBuiltinLine(0, "Attach")); - const bare = drainForAttach(p) orelse return error.NoAttachAsked; - try std.testing.expectEqualStrings("", bare.name); - try std.testing.expectEqual(@as(u8, 0), bare.pane); - - // ...and the named form carries its tail, the way `Theme ` does. - try std.testing.expect(p.executeBuiltinLine(0, "Attach work")); - const named = drainForAttach(p) orelse return error.NoAttachAsked; - try std.testing.expectEqualStrings("work", named.name); - try std.testing.expect(p.takeAttach() == null); // taken once, then gone - - // The word only ASKS. A core that tore itself down here could not be handed - // back intact when the connect fails, and that is the entire guarantee. - try std.testing.expect(!p.quit); - try std.testing.expect(p.panes[0] != null); -} - -test "Attach in a detached session: bare is wrong #args, a name no session has says so, and nothing is asked" { - if (comptime !can_attach) return; - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .detached_session = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try std.testing.expect(p.executeBuiltinLine(0, "Attach")); - try std.testing.expect(drainForAttach(p) == null); - try std.testing.expectStringStartsWith(pane.msg[0..pane.msg_len], "wrong #args"); - try std.testing.expect(p.executeBuiltinLine(0, "Attach zz-no-such-session-qq")); - try std.testing.expect(drainForAttach(p) == null); - try std.testing.expectEqualStrings("Attach: zz-no-such-session-qq: no such session", pane.msg[0..pane.msg_len]); -} - -test "Detach asks the frontend to leave, and says so when there is nothing to leave" { - if (comptime !can_attach) return; // compiled out where nothing polls `takeAttach` — see `can_attach` +test "Detach asks the host to let its terminal go, and says so when there is nothing to leave" { + if (comptime !can_attach) return; // the word is compiled out elsewhere: see `can_attach` const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); @@ -3753,10 +3708,6 @@ pub const Event = union(enum) { tick, }; -pub const attach_name_max = 256; - -pub const AttachRequest = struct { pane: u8, name: []const u8 }; - pub const PendingWrite = struct { bytes: []u8, off: usize = 0 }; /// `command` is Kill's: SIGTERM to the terminal's foreground job, and never @@ -3807,7 +3758,6 @@ pub const Effect = union(enum) { /// Write the build-time theme ring below the per-user config directory. /// The pane receives the completion/error message from the native host. dump_themes: struct { pane: u8 }, - attach: struct { pane: u8, name: Buf(attach_name_max) }, detach: struct { pane: u8 }, quit, @@ -4387,9 +4337,6 @@ pub const Options = struct { /// window opens one as big as that, Handover.zig). geometry: ?[]const u8 = null, nested: bool = false, - /// The core of a `--detach` session (detached/server.zig): it has no - /// terminal of its own, so Attach there is refused with why. - detached_session: bool = false, startup_config: ?[]const u8 = null, ninep_name: []const u8 = "", ninep_tcp: ?[]const u8 = null, @@ -4738,8 +4685,6 @@ pub const Pardes = struct { /// shell consumes it via takeRestore each frame (restore contents stay host-fed) restore_req: ?[]const u8 = null, restore_buf: [1024]u8 = undefined, - attach_req: ?AttachRequest = null, - attach_buf: [attach_name_max]u8 = undefined, surface: Surface = .{}, /// per-update scratch (paneCursorLines, selection text); reset each update @@ -5088,14 +5033,6 @@ pub const Pardes = struct { return r; } - /// the shell polls this each frame beside takeRestore: a pending Attach's - /// session and reporting pane, or null - pub fn takeAttach(p: *Pardes) ?AttachRequest { - const a = p.attach_req; - p.attach_req = null; - return a; - } - /// The workspace tag's height: one row while the setting keeps it, as /// acme's row tag is, zero once a native shell takes its commands over. /// Layout and hit testing read this rather than the constant, the way @@ -5981,11 +5918,6 @@ pub const Pardes = struct { }, .theme_file => |t| if (v.watch_theme) |f| f(p.host.ctx, t.generation, t.on), .dump_themes => |d| if (v.dump_themes) |f| f(p.host.ctx, d.pane), - .attach => |a| { - const name = a.name.slice(); - @memcpy(p.attach_buf[0..name.len], name); - p.attach_req = .{ .pane = a.pane, .name = p.attach_buf[0..name.len] }; - }, .detach => |d| if (v.detach) |f| f(p.host.ctx) else diff --git a/src/tty/tty.zig b/src/tty/tty.zig index a358051e..37f66456 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -14,9 +14,7 @@ const file_watch = @import("../file_watch.zig"); const selection_pipe = @import("../selection_pipe.zig"); const ninep_io = @import("../9p_io.zig"); const panel_compositor = @import("panel_compositor.zig"); -const detached_client = @import("../detached/client.zig"); -const detached_server = @import("../detached/server.zig"); -const wire = @import("../detached/wire.zig"); +const daemon = @import("../daemon.zig"); const host_io = @import("../host_io.zig"); extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; @@ -78,7 +76,14 @@ fn kittyShmProbe(w: *std.Io.Writer) void { pub const Command = struct { pub var value: union(enum) { nop, + /// The terminal's input ended: its end of file, a hangup. A session + /// a daemon keeps carries on detached; any other ends. quit, + /// A 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. wake, key_press: vaxis.Key, @@ -1166,78 +1171,99 @@ fn nativePdfWheelTarget(core: *const pardes.Pardes, mouse: vaxis.Mouse) ?PdfWhee return null; } -pub fn run(init: std.process.Init, opts: pardes.Options, attach: ?[]const u8) !void { +/// 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, until one is attached (`--detach`). +pub const Term = union(enum) { open, fd: posix.fd_t, none }; + +pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void { const io = init.io; const gpa = init.gpa; - var attach_end: AttachEnd = .none; - defer attach_end.report(io); - - var name_buf: [detached_server.path_max]u8 = undefined; - var attach_name: []const u8 = &.{}; - if (attach) |requested| switch (detached_client.resolve(&name_buf, requested)) { - .name => |resolved| attach_name = resolved, - .none => { - attach_end = if (requested.len != 0) .{ .no_session = requested } else .nothing_detached; - return; - }, - .ambiguous => |found| { - attach_end = .{ .ambiguous = found }; - return; - }, - }; - var winch_set = posix.sigemptyset(); posix.sigaddset(&winch_set, posix.SIG.WINCH); + // Kept by a daemon, a hangup is the terminal's end, not the session's: + // winchWatch takes it, and the session carries on detached. + if (daemon.link >= 0) posix.sigaddset(&winch_set, posix.SIG.HUP); posix.sigprocmask(posix.SIG.BLOCK, &winch_set, null); var tty_buf: [0x10000]u8 = undefined; - var tty = try vaxis.Tty.init(io, &tty_buf); - defer tty.deinit(); // restore cooked termios LAST, after vx flushed its resets - var vx = try vaxis.init(io, gpa, init.environ_map, .{ .system_clipboard_allocator = gpa }); - defer vx.deinit(gpa, tty.writer()); - try vx.enterAltScreen(tty.writer()); - defer vx.exitAltScreen(tty.writer()) catch {}; - try vx.setMouseMode(tty.writer(), true); - try vx.setBracketedPaste(tty.writer(), true); - Killed.arm(tty.fd.handle, tty.termios); - defer Killed.disarm(); - - if (attach != null) { - attach_end = attachSession(init, attach_name, &tty, &vx); - return; + var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf }; + switch (term) { + .open => try screen.enter(try vaxis.Tty.init(io, &tty_buf)), + .fd => |fd| try screen.enter(try Screen.ttyOn(io, &tty_buf, fd)), + .none => {}, } + defer screen.leave(); var kitty_handles = std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image).init(gpa); defer { - clearNativeImages(&kitty_handles, &vx, &tty); + if (screen.on) clearNativeImages(&kitty_handles, &screen.vx, &screen.tty); kitty_handles.deinit(); } var paste_buf: std.Io.Writer.Allocating = .init(gpa); defer paste_buf.deinit(); - var loop: Loop = .init(io, &tty, &vx); + var loop: Loop = .init(io, &screen.tty, &screen.vx); var input_cache: vaxis.GraphemeCache = .{}; - var attached: ?detached_client.Client = null; - defer if (attached != null) { - stopInput(&loop); - drainAttachedQueue(&loop, gpa); - }; - try localSession(init, opts, &tty, &vx, &loop, &input_cache, &kitty_handles, &paste_buf, &attached); - if (attached) |*client| { - defer client.detach(); - var a: Attach = .{ - .gpa = gpa, - .client = client, - .loop = &loop, - .vx = &vx, - .tty = &tty, - .paste_buf = &paste_buf, - }; - attach_end = attachLoop(&a); - } + try localSession(init, opts, &screen, &loop, &input_cache, &kitty_handles, &paste_buf); } +/// Whether a terminal is there to ask its size (winchWatch): none while +/// detached, when the descriptor it had may be another's. +var terminal_on = std.atomic.Value(bool).init(false); + +/// The 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). +const Screen = struct { + io: std.Io, + gpa: std.mem.Allocator, + env: *std.process.Environ.Map, + buf: []u8, + tty: vaxis.Tty = undefined, + vx: vaxis.Vaxis = undefined, + on: bool = false, + + /// `fd` made raw, as vaxis.Tty.init makes /dev/tty: the terminal of a + /// forked session is no controlling terminal of its, which /dev/tty is. + fn ttyOn(io: std.Io, buf: []u8, fd: posix.fd_t) !vaxis.Tty { + if (comptime builtin.is_test) unreachable; // vaxis.Tty is its TestTty + const termios = try vaxis.Tty.makeRaw(fd); + const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; + return .{ .io = io, .fd = file, .termios = termios, .tty_writer = file.writerStreaming(io, buf) }; + } + + fn enter(sc: *Screen, tty: vaxis.Tty) !void { + sc.tty = tty; + errdefer sc.tty.deinit(); + sc.vx = try vaxis.init(sc.io, sc.gpa, sc.env, .{ .system_clipboard_allocator = sc.gpa }); + errdefer sc.vx.deinit(sc.gpa, sc.tty.writer()); + try sc.vx.enterAltScreen(sc.tty.writer()); + try sc.vx.setMouseMode(sc.tty.writer(), true); + try sc.vx.setBracketedPaste(sc.tty.writer(), true); + if (comptime !builtin.is_test) { + Killed.arm(sc.tty.fd.handle, sc.tty.termios); + // What a panic puts back (vaxis.recover). + vaxis.tty.global_tty = sc.tty; + } + sc.on = true; + terminal_on.store(true, .release); + } + + fn leave(sc: *Screen) void { + if (!sc.on) return; + sc.on = false; + terminal_on.store(false, .release); + Killed.disarm(); + sc.vx.exitAltScreen(sc.tty.writer()) catch {}; + sc.vx.deinit(sc.gpa, sc.tty.writer()); + if (comptime !builtin.is_test) vaxis.tty.global_tty = null; + sc.tty.deinit(); // restore cooked termios LAST, after vx flushed its resets + } +}; + /// SIGTERM or SIGHUP: the terminal put back as a clean exit leaves it -- /// the main screen, no mouse, paste or keyboard modes, the cursor shown, /// cooked termios -- and then the signal's own death. A nested editor @@ -1247,19 +1273,20 @@ const Killed = struct { var fd: posix.fd_t = -1; var cooked: posix.termios = undefined; const reset = "\x1b[ |b| b.deinit(gpa), + .attach => |a| { + _ = libc.close(a.tty); + _ = libc.close(a.stub); + }, + .adopted => |a| _ = libc.close(a.fd), else => {}, }; } const host = sh.host(); core.host = host; + // Nobody to see it, and nobody to size it: `size` sets it (ctl.zig). + core.unattended = !screen.on; while (core.nextEffect()) |effect| core.perform(effect); - try startInput(loop, input_cache); - defer if (attached.* == null) stopInput(loop); + if (screen.on) try startInput(loop, input_cache); + defer stopInput(loop); (try std.Thread.spawn(.{}, winchWatch, .{ loop, vx, tty })).detach(); (try std.Thread.spawn(.{}, wakeWatch, .{ io, loop })).detach(); if (fs) |f| try f.watch(loop, wakeFs); - try vx.queryTerminalSend(tty.writer()); + if (screen.on) try vx.queryTerminalSend(tty.writer()); + // Detached from the start, nothing else may wake the first wait. + if (!screen.on) daemon.watch(loop, deliverNote); sh.threads_ok = true; for (&sh.ptys, 0..) |*slot, id| if (slot.*) |*pt| { @@ -1413,9 +1449,13 @@ fn localSession( if (kittyShmName(&name_buf, n)) |name| _ = libc.shm_unlink(name) else |_| {} } } - frames: while (!core.quit) { + while (!core.quit) { pardes.turn.bump(&pardes.turn.restores); try core.pump(host); + // A terminal (`pardes --attach`) or an adopted shell, handed on by + // the daemon's thread to this loop; started after the first frame, + // off a startup's way. + daemon.watch(loop, deliverNote); if (core.takeRestore()) |rp| blk: { const bytes = filesystem.readRestore(gpa, rp, core.settings.dump_dir.get()) catch |err| { core.reportError(core.active, "Restore", err); @@ -1435,6 +1475,7 @@ fn localSession( for (&sh.ptys) |*slot| if (slot.*) |*pt| { pt.reader.cancel(io) catch {}; _ = libc.close(pt.file.handle); + daemon.closed(pt.pid); host_io.retireShell(pt.pid); slot.* = null; }; @@ -1447,28 +1488,16 @@ fn localSession( .{ .text = 0 }, ); _ = file_watch.applyThemeEffect(core, gpa, sh.inotify_fd, &sh.watches, 0, false, false); - clearNativeImages(kitty_handles, vx, tty); - nc.native_images = vx.caps.kitty_graphics; + if (screen.on) clearNativeImages(kitty_handles, vx, tty); + nc.native_images = screen.on and vx.caps.kitty_graphics; + nc.unattended = !screen.on; if (fs) |f| f.reset(nc); core.deinit(); core = nc; sh.core = nc; - if (comptime pardes.pdf_enabled) { + if (comptime pardes.pdf_enabled) if (screen.on) { updateCoreTerminalSize(core, vx.screen.width, vx.screen.height, vx.screen.width_pix, vx.screen.height_pix); - } - } - if (core.takeAttach()) |req| { - var attempt = detached_client.attempt(gpa, req.name, core.screen_w, core.screen_h); - switch (attempt) { - .greeted => |client| { - attached.* = client; - break :frames; - }, - else => { - var mbuf: [256]u8 = undefined; - core.setMessage(req.pane, attemptEnd(&attempt, req.name).row(&mbuf)); - }, - } + }; } } if (fs) |f| { @@ -1488,11 +1517,25 @@ fn clearNativeImages( kitty_handles.clearRetainingCapacity(); } -fn drainAttachedQueue(loop: *Loop, gpa: std.mem.Allocator) void { - while (loop.tryEvent() catch null) |ev| switch (ev) { - .paste => |b| gpa.free(@constCast(b)), - else => {}, - }; +const Adoption = struct { pid: posix.pid_t, fd: posix.fd_t, pane: ?u8 }; + +/// The daemon's thread: what it says, onto the loop's queue. +fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { + const loop: *Loop = @ptrCast(@alignCast(ctx)); + switch (note) { + .attach => |a| if (a.tty < 0) { + if (a.stub >= 0) daemon.refuseStub(a.stub, "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); + }; + loop.postEvent(.{ .adopted = .{ .pid = 0, .fd = -1 } }) catch {}; + }, + } } const Shell = struct { @@ -1504,10 +1547,18 @@ const Shell = struct { loop: *Loop, vx: *vaxis.Vaxis, tty: *vaxis.Tty, + /// The terminal, while there is one (Screen.on); null in tests. + screen: ?*Screen = null, + input_cache: ?*vaxis.GraphemeCache = null, kitty: *std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image), frame: *std.heap.ArenaAllocator, paste_buf: *std.Io.Writer.Allocating, inotify_fd: c_int, + /// Shells a dead session left (Adopt), each waiting for the spawn of + /// the terminal pane made for it. + adoptions: [pardes.MAX_PANES]Adoption = undefined, + adoptions_len: usize = 0, + adopted: usize = 0, fs: ?*ninep_io.Listener = null, ptys: [pardes.MAX_PANES]?Pty = @splat(null), gens: [pardes.MAX_PANES]u32 = @splat(0), @@ -1557,6 +1608,9 @@ const Shell = struct { .present = present, .post_present = postPresent, .poll_frame = pollFrame, + .watched = watched, + .detach = detach, + .adopt = adopt, .spawn = spawn, .pty_write = ptyWrite, .pty_resize = ptyResize, @@ -1583,6 +1637,112 @@ const Shell = struct { return s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); } + fn attached(s: *const Shell) bool { + const screen = s.screen orelse return true; + return screen.on; + } + + /// Drawn only while a terminal shows it. + fn watched(ctx: ?*anyopaque) bool { + return of(ctx).attached(); + } + + /// Detach: the terminal put back and let go, the stub told (it ends, + /// and the shell has its terminal again), the session left running. + fn detach(ctx: ?*anyopaque) void { + const s = of(ctx); + if (!s.attached()) return s.core.reportFailure(s.core.active, "Detach: no terminal is attached"); + if (!daemon.kept()) return s.core.reportFailure(s.core.active, "Detach: no pardes daemon keeps this session (it is its terminal's job)"); + s.leaveTerminal(); + } + + fn leaveTerminal(s: *Shell) void { + const screen = s.screen orelse return; + stopInput(s.loop); + clearNativeImages(s.kitty, s.vx, s.tty); + screen.leave(); + s.core.native_images = false; + s.core.unattended = true; + // The stub's stdin, stdout and stderr were its terminal too. + const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(libc.mode_t, 0)); + if (null_fd >= 0) { + for (0..3) |i| _ = libc.dup2(null_fd, @intCast(i)); + if (null_fd > 2) _ = libc.close(null_fd); + } + daemon.tellStubDetached(); + daemon.setState(true); + } + + /// `pardes --attach`'s terminal, for this detached session: entered as + /// the first one was, sized, asked what it can do, and drawn whole. + fn attachTerminal(s: *Shell, fd: posix.fd_t, stub: posix.fd_t) void { + const screen = s.screen orelse return; + if (screen.on) { + _ = libc.close(fd); + return daemon.refuseStub(stub, "that session has a terminal already"); + } + const tty = Screen.ttyOn(s.io, screen.buf, fd) catch { + _ = libc.close(fd); + daemon.setState(true); + return daemon.refuseStub(stub, "that terminal would not go raw"); + }; + screen.enter(tty) catch { + daemon.setState(true); + return daemon.refuseStub(stub, "that terminal would not take the screen"); + }; + daemon.stub = stub; + FrameAck.waiting.store(false, .release); + FrameAck.off.store(false, .release); + kitty_shm.store(false, .release); + s.caps_pending = true; + s.core.unattended = false; + startInput(s.loop, s.input_cache.?) catch {}; + s.vx.queryTerminalSend(s.tty.writer()) catch {}; + s.core.needs_frame = true; + daemon.setState(false); + } + + /// Adopt: the daemon is asked for the shells of sessions that died + /// holding them; each comes back (`adopted`) as a terminal pane here. + fn adopt(ctx: ?*anyopaque, pane: u8) void { + const s = of(ctx); + if (!daemon.kept()) return s.core.reportFailure(pane, "Adopt: no pardes daemon is keeping shells for this session"); + s.adopted = 0; + daemon.adopt(); + } + + /// One shell of a dead session (`pid` 0: the last of them was told). + fn adoptShell(s: *Shell, pid: posix.pid_t, fd: posix.fd_t) void { + const core = s.core; + if (pid == 0) { + var buf: [96]u8 = undefined; + return core.setMessage(core.active, if (s.adopted == 0) "Adopt: no shell of a session that died is waiting" else std.fmt.bufPrint(&buf, "Adopt: {d} shell{s} taken in; what they showed is gone", .{ s.adopted, if (s.adopted == 1) "" else "s" }) catch "Adopt: shells taken in"); + } + var newest: u32 = 0; + for (core.panes) |slot| if (slot) |pn| { + newest = @max(newest, pn.serial); + }; + if (s.adoptions_len < s.adoptions.len) { + // A terminal pane, as the Tty word makes one; its spawn takes + // this pty instead of forking a shell (`spawn`). + s.adoptions[s.adoptions_len] = .{ .pid = pid, .fd = fd, .pane = null }; + s.adoptions_len += 1; + _ = core.executeBuiltinLine(core.active, "Tty"); + for (core.panes, 0..) |slot, id| if (slot) |pn| if (pn.serial > newest and pn.isTerminal()) { + // Its shell is up already: nothing to greet with `ls`. + pn.greet = false; + s.adoptions[s.adoptions_len - 1].pane = @intCast(id); + s.adopted += 1; + return; + }; + s.adoptions_len -= 1; + } + // No room for it: its master goes, and the shell with this session. + _ = libc.close(fd); + var buf: [96]u8 = undefined; + core.setMessage(core.active, std.fmt.bufPrint(&buf, "Adopt: no room for shell {d}; it ends with this session", .{pid}) catch "Adopt: no room for a shell"); + } + fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { const s = of(ctx); // The wait is the 9P connections' turn with the core. A timeout (the @@ -1593,6 +1753,14 @@ const Shell = struct { // ends the wait at once and its frame is drawn then; the ticks after // it run from it. var wait = timeout_ms; + // Detached, nobody's key dismisses a message: they go on the clock. + if (!s.attached()) { + pardes.Messages.expireUnattended(s.core); + for (s.core.panes) |slot| if (slot) |pane| if (pane.msg_len > 0) { + wait = if (wait == 0) 100 else @min(wait, 100); + break; + }; + } const paced = s.test_clock == null and s.core.continuous(); var tick: u64 = 0; if (paced) { @@ -1685,15 +1853,23 @@ const Shell = struct { virtual.* = @max(virtual.*, s.wake_to); }, .quit => { + // The terminal went: a session the daemon keeps carries on + // without it, to be attached again. + if (daemon.kept()) { + if (s.attached()) s.leaveTerminal(); + return true; + } core.quit = true; return true; }, + .attach => |a| s.attachTerminal(a.tty, a.stub), + .adopted => |a| s.adoptShell(a.pid, a.fd), .focus_in => core.update(.{ .focus = true }), .focus_out => { core.update(.pointer_leave); core.update(.{ .focus = false }); }, - .winsize => |ws| { + .winsize => |ws| if (s.attached()) { s.vx.resize(s.gpa, s.tty.writer(), ws) catch {}; if (comptime pardes.pdf_enabled) updateCoreTerminalSize(core, ws.cols, ws.rows, ws.x_pixel, ws.y_pixel) @@ -1820,7 +1996,7 @@ const Shell = struct { if (host_io.ttyCwd(pt.pid, pt.file.handle, s.core.settings.shell.effective.get(), &lbuf)) |cwd| s.core.setCwd(id, cwd); }; - if (s.caps_pending and s.vx.queries_done.load(.unordered)) { + if (s.caps_pending and s.attached() and s.vx.queries_done.load(.unordered)) { s.caps_pending = false; s.vx.enableDetectedFeatures(s.tty.writer()) catch {}; s.core.native_images = s.vx.caps.kitty_graphics; @@ -1965,6 +2141,11 @@ const Shell = struct { fn spawn(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { const s = of(ctx); + for (s.adoptions[0..s.adoptions_len], 0..) |a, i| if (a.pane == pane) { + std.mem.copyForwards(Adoption, s.adoptions[i .. s.adoptions_len - 1], s.adoptions[i + 1 .. s.adoptions_len]); + s.adoptions_len -= 1; + return s.takeShell(pane, a); + }; // The new shell starts before a running one goes: one that cannot // start leaves the running one be (pty/ctl's exec). const running = s.ptys[pane] != null; @@ -1988,6 +2169,25 @@ const Shell = struct { } } + /// An adopted shell, running already, as pane `pane`'s: told the size + /// twice (a size it never had, then the pane's), which makes it redraw. + fn takeShell(s: *Shell, pane: u8, a: Adoption) void { + closePty(s, pane); + s.gens[pane] +%= 1; + const file: std.Io.File = .{ .handle = a.fd, .flags = .{ .nonblocking = false } }; + s.ptys[pane] = .{ .file = file, .pid = a.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{} }; + var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + s.core.acknowledgeShell(pane, host_io.processExe(a.pid, &exe_buf) orelse "sh", host_io.marksPrompts(a.pid)); + var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + if (host_io.shellCwd(a.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); + const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 }; + _ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny)); + if (s.core.panes[pane]) |pn| ptyResize(s, pane, @max(pn.cols, 1), @max(pn.rows, 1)); + if (s.threads_ok) if (s.ptys[pane]) |*pt| { + pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader; + }; + } + fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void { const s = of(ctx); if (s.ptys[pane]) |pt| _ = host_io.writeFd(pt.file.handle, bytes); @@ -2018,6 +2218,7 @@ const Shell = struct { s.gens[pane] +%= 1; pt.reader.cancel(s.io) catch {}; _ = libc.close(pt.file.handle); + daemon.closed(pt.pid); host_io.retireShell(pt.pid); } @@ -2078,11 +2279,14 @@ const Shell = struct { fn setClipboard(ctx: ?*anyopaque, text: []const u8) void { const s = of(ctx); + // Detached, the session keeps it (a 9P read, a paste here). + if (!s.attached()) return s.core.fallback.setClipboard(text); copyToClipboard(s.vx, s.tty, s.gpa, text); } fn readClipboard(ctx: ?*anyopaque) void { const s = of(ctx); + if (!s.attached()) return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); requestClipboard(s.vx, s.tty); } @@ -2262,19 +2466,20 @@ fn watchFiles(io: std.Io, fd: c_int, loop: *Loop) anyerror!void { } fn winchWatch(loop: *Loop, vx: *vaxis.Vaxis, tty: *vaxis.Tty) void { - winchWatchUntil(loop, vx, tty, null); -} - -/// A SIGWINCH watcher that ends: `stop` set, then a SIGWINCH sent to its -/// thread, wakes its sigwait and it returns, so whoever owns `loop` can join -/// it before the loop goes (attachSession's loop is on its stack). -fn winchWatchUntil(loop: *Loop, vx: *vaxis.Vaxis, tty: *vaxis.Tty, stop: ?*const std.atomic.Value(bool)) void { var set = posix.sigemptyset(); posix.sigaddset(&set, posix.SIG.WINCH); + if (daemon.link >= 0) posix.sigaddset(&set, posix.SIG.HUP); while (true) { var sig: c_int = 0; if (libc.sigwait(&set, &sig) != 0) continue; - if (stop) |flag| if (flag.load(.acquire)) return; + // The terminal hung up (its stub passes the hangup on): as its + // input's end. + if (sig == @backingInt(posix.SIG.HUP)) { + loop.postEvent(.quit) catch {}; + continue; + } + // Detached, the descriptor the terminal had may be another's now. + if (!terminal_on.load(.acquire)) continue; if (vx.state.in_band_resize) continue; // terminal reports via CSI 48 const ws = tty.getWinsize() catch continue; loop.postEvent(.{ .winsize = ws }) catch {}; @@ -2869,243 +3074,6 @@ fn vaxisColor(c: pardes.Color) vaxis.Color { }; } -const AttachEnd = union(enum) { - none, - no_session: []const u8, - nothing_detached, - ambiguous: usize, - refused: wire.Refusal, - lost: anyerror, - rejected, - silent, - detached: []const u8, - - fn report(e: AttachEnd, io: std.Io) void { - var buf: [512]u8 = undefined; - var ok = false; - const text: []const u8 = switch (e) { - .none => return, - .detached => |name| blk: { - ok = true; - break :blk if (name.len != 0) std.fmt.bufPrint( - &buf, - "pardes: detached from '{s}', which is still running — come back with `pardes --attach={s}`\n", - .{ name, name }, - ) catch "pardes: detached; that session is still running\n" else "pardes: detached; that session is still running — come back with `pardes --attach`\n"; - }, - .no_session => |name| std.fmt.bufPrint( - &buf, - "pardes: no detached session called '{s}' (start one with `pardes --detach={s}`)\n", - .{ name, name }, - ) catch "pardes: no detached session under that name\n", - .nothing_detached => "pardes: no detached session is running (start one with `pardes --detach`)\n", - .ambiguous => |n| std.fmt.bufPrint( - &buf, - "pardes: {d} detached sessions are running; say which with --attach=\n", - .{n}, - ) catch "pardes: several detached sessions are running; say which with --attach=\n", - .refused => |why| switch (why) { - .version => "pardes: that session speaks a different wire version — it is another build of pardes\n", - .full => "pardes: that session already has every frontend slot taken\n", - .quitting => "pardes: that session is ending\n", - }, - .lost => |err| std.fmt.bufPrint(&buf, "pardes: detached session lost: {t}\n", .{err}) catch - "pardes: detached session lost\n", - .rejected => "pardes: that session hung up on the connect — every frontend slot is taken (32), or it is shutting down. `PARDES_LOG=1` on the session names which\n", - .silent => "pardes: that session accepted the connection and then never greeted it — it is wedged inside its own loop, or something else is listening at that path. `PARDES_LOG=1` on the session says which\n", - }; - const out = if (ok) std.Io.File.stdout() else std.Io.File.stderr(); - out.writeStreamingAll(io, text) catch {}; - if (!ok) std.process.exit(1); - } - - fn row(e: AttachEnd, buf: []u8) []const u8 { - return switch (e) { - .none => "attach: that session ended", - .no_session => |name| std.fmt.bufPrint(buf, "attach: no session '{s}'", .{name}) catch - "attach: no session under that name", - .nothing_detached => "attach: no detached session is running", - .ambiguous => |n| std.fmt.bufPrint(buf, "attach: {d} sessions running, name one", .{n}) catch - "attach: several sessions running, name one", - .refused => |why| switch (why) { - .version => "attach: that session is another build of pardes", - .full => "attach: that session has every frontend slot taken", - .quitting => "attach: that session is ending", - }, - .lost => |err| std.fmt.bufPrint(buf, "attach: {t}", .{err}) catch "attach: link lost", - .rejected => "attach: that session hung up on the connect", - .silent => "attach: that session accepted and never greeted", - .detached => "attach: detached from that session", - }; - } -}; - -const Attach = struct { - gpa: std.mem.Allocator, - client: *detached_client.Client, - loop: *Loop, - vx: *vaxis.Vaxis, - tty: *vaxis.Tty, - paste_buf: *std.Io.Writer.Allocating, - session: []const u8 = &.{}, - caps_pending: bool = true, - in_paste: bool = false, - dirty: bool = false, - - fn send(a: *Attach, ev: pardes.Event) ?AttachEnd { - a.client.send(.{ .event = ev }) catch |err| switch (err) { - error.Overlong, error.WriteFailed => return null, - else => return .{ .lost = err }, - }; - return null; - } - - fn handle(a: *Attach, msg: wire.ServerMsg) ?AttachEnd { - switch (msg) { - .welcome => {}, - .refuse => |why| return .{ .refused = why }, - .frame => a.dirty = true, - .quit => return .none, - .detach => return .{ .detached = a.session }, - .set_clipboard => |text| copyToClipboard(a.vx, a.tty, a.gpa, text), - .read_clipboard => requestClipboard(a.vx, a.tty), - .open_link => |url| look.openLink(url), - // A terminal has no post chain to draw through. - .post => {}, - } - return null; - } - - fn apply(a: *Attach, event: @TypeOf(Command.value)) ?AttachEnd { - switch (event) { - .nop, .wake, .fs_ready, .lsp_done, .lsp_status, .pipe_done, .search_rows, .pty_read, .pty_eof, .files_changed => {}, - .quit => return .none, - .focus_in => return a.send(.{ .focus = true }), - .focus_out => { - if (a.send(.pointer_leave)) |end| return end; - return a.send(.{ .focus = false }); - }, - .winsize => |ws| { - a.vx.resize(a.gpa, a.tty.writer(), ws) catch {}; - a.dirty = true; - a.client.resize(ws.cols, ws.rows) catch |err| return .{ .lost = err }; - }, - .key_press => |key| if (a.in_paste) { - const bytes = pasteBytes(key); - const room = max_paste_bytes -| a.paste_buf.written().len; - a.paste_buf.writer.writeAll(bytes[0..@min(bytes.len, room)]) catch {}; - } else return a.send(vaxis_input.keyEvent(key)), - .mouse => |m| if (mouseEvent(m)) |ev| return a.send(ev), - .paste => |bytes| { - defer a.gpa.free(@constCast(bytes)); - return a.send(.{ .paste = bytes }); - }, - .paste_start => { - a.in_paste = true; - a.paste_buf.clearRetainingCapacity(); - }, - .paste_end => { - a.in_paste = false; - defer a.paste_buf.clearRetainingCapacity(); - const pasted = a.paste_buf.written(); - if (pasted.len > 0) return a.send(.{ .paste = pasted }); - }, - } - return null; - } - - fn enableCaps(a: *Attach) void { - if (!a.caps_pending or !a.vx.queries_done.load(.unordered)) return; - a.caps_pending = false; - a.vx.enableDetectedFeatures(a.tty.writer()) catch {}; - a.vx.queueRefresh(); - a.dirty = true; - } - - fn paint(a: *Attach) void { - a.dirty = false; - const win = a.vx.window(); - paintCells(win, a.client.grid.items, a.client.cols, a.client.rows); - if (a.client.cursor) |cur| paintCursor(win, cur.x, cur.y, cur.bar); - a.vx.render(a.tty.writer()) catch {}; - } -}; - -fn attemptEnd(a: *const detached_client.Attempt, requested: []const u8) AttachEnd { - return switch (a.*) { - .greeted => .none, - .no_session => if (requested.len != 0) .{ .no_session = requested } else .nothing_detached, - .ambiguous => |found| .{ .ambiguous = found }, - .refused => |why| .{ .refused = why }, - .silent => .silent, - .lost => |err| if (err == error.Closed) .rejected else .{ .lost = err }, - }; -} - -fn attachLoop(a: *Attach) AttachEnd { - while (true) { - const link = a.client.wait(detached_client.poll_ms); - while (true) { - const msg = (a.client.next() catch |err| return .{ .lost = err }) orelse break; - if (a.handle(msg)) |end| return end; - } - link catch |err| return .{ .lost = err }; - var batch: usize = 0; - while (a.in_paste or batch < 64) { - const ev = (a.loop.tryEvent() catch |err| return .{ .lost = err }) orelse break; - batch += 1; - if (a.apply(ev)) |end| return end; - } - a.enableCaps(); - if (a.dirty) a.paint(); - } -} - -fn attachSession(init: std.process.Init, name: []const u8, tty: *vaxis.Tty, vx: *vaxis.Vaxis) AttachEnd { - const io = init.io; - const gpa = init.gpa; - - const ws = tty.getWinsize() catch |err| return .{ .lost = err }; - if (ws.cols == 0 or ws.rows == 0) return .{ .lost = error.NoWinsize }; - vx.resize(gpa, tty.writer(), ws) catch |err| return .{ .lost = err }; - - var attempt = detached_client.attempt(gpa, name, ws.cols, ws.rows); - var client = switch (attempt) { - .greeted => |c| c, - else => return attemptEnd(&attempt, name), - }; - defer client.detach(); - - var loop: Loop = .init(io, tty, vx); - var input_cache: vaxis.GraphemeCache = .{}; - var paste_buf: std.Io.Writer.Allocating = .init(gpa); - defer paste_buf.deinit(); - - var a: Attach = .{ - .gpa = gpa, - .client = &client, - .loop = &loop, - .vx = vx, - .tty = tty, - .paste_buf = &paste_buf, - .session = name, - }; - defer drainAttachedQueue(&loop, gpa); - - startInput(&loop, &input_cache) catch |err| return .{ .lost = err }; - defer stopInput(&loop); - var winch_stop: std.atomic.Value(bool) = .init(false); - const winch = std.Thread.spawn(.{}, winchWatchUntil, .{ &loop, vx, tty, &winch_stop }) catch |err| return .{ .lost = err }; - defer { - winch_stop.store(true, .release); - _ = libc.pthread_kill(winch.getHandle(), posix.SIG.WINCH); - winch.join(); - } - vx.queryTerminalSend(tty.writer()) catch {}; - - return attachLoop(&a); -} - test "a jump leaves a trail of a few cells behind the cursor that fades in 120 ms" { const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); diff --git a/src/tutor.txt b/src/tutor.txt index 3f153ebd..5cfb245b 100644 --- a/src/tutor.txt +++ b/src/tutor.txt @@ -144,7 +144,7 @@ run at start. 2. In a shell, pardes --detach=work starts a session with no screen; pardes --attach=work shows it; `Detach` (SPC s D) leaves it - running. + running, as a terminal that closes does. -> Guide: Sessions, Config @@ -292,7 +292,7 @@ typed SPC y yank to the clipboard SPC p paste from it SPC w window mode: h/j/k/l, Enter; d Del, c Collapse SPC j j `Last` SPC j o / SPC j i back / forward - SPC s a `Attach` SPC s D `Detach` + SPC s D `Detach` SPC t ... the toggles SPC l ... the language SPC h t this tutor diff --git a/test/daemon.py b/test/daemon.py new file mode 100644 index 00000000..bf3d237c --- /dev/null +++ b/test/daemon.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python3 +"""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 session killed outright: its shells live on, held by the daemon, and + another session adopts them as terminal panes; +- 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) +""" +import fcntl +import os +import shutil +import signal +import struct +import subprocess +import sys +import tempfile +import termios +import threading +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent)) +from ninep import Client # noqa: E402 + + +def wait_for(what, check, timeout=10): + deadline = time.monotonic() + timeout + while True: + got = check() + if got: + return got + if time.monotonic() > deadline: + raise TimeoutError(what) + time.sleep(.01) + + +class Term: + """A terminal: a pty whose other end is read and kept, its frame + requests answered (CSI 5 n), as a terminal emulator does.""" + + def __init__(self, rows=24, cols=80): + self.master, self.slave = os.openpty() + fcntl.ioctl(self.slave, termios.TIOCSWINSZ, struct.pack('HHHH', rows, cols, 0, 0)) + self.out = bytearray() + self.lock = threading.Lock() + self.reader = threading.Thread(target=self.drain, daemon=True) + self.reader.start() + + def drain(self): + while True: + try: + got = os.read(self.master, 65536) + except OSError: + return + if not got: + return + with self.lock: + self.out += got + if b'\x1b[5n' in got: + try: + os.write(self.master, b'\x1b[0n') + except OSError: + return + + def spawn(self, argv, env): + slave = self.slave + return subprocess.Popen(argv, env=env, stdin=slave, stdout=slave, stderr=slave, + start_new_session=True, + preexec_fn=lambda: fcntl.ioctl(0, termios.TIOCSCTTY, 0)) + + def text(self): + with self.lock: + return bytes(self.out) + + def close(self): + os.close(self.slave) + os.close(self.master) + self.reader.join(timeout=2) + + +def run(client, serial, line): + """pty/run: a line in, `exit N` and its output out.""" + fid = client.open(f'/pane/{serial}/pty/run', 2) + try: + client.rpc(118, struct.pack('