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 ++++++++++---- 4 files changed, 15 insertions(+), 10 deletions(-) (limited to 'docs/typ') 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 -- cgit v1.3 From 9be47b76e4edf4ddb56e4d572c14b54bf45fdd39 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 29 Oct 2026 10:48:56 -0300 Subject: docs: the daemon, Detach, --attach and Adopt; phase 3 notes in docs/next-daemon.md building.typ's detached sessions are the daemon and its sessions; the guide, cheatsheet and reference say what Detach, a closing terminal, --attach of each kind and Adopt do, and that attaching from another machine waits for phase 5. docs/next-daemon.md records the forks taken (sessions register and are not the daemon's children, and why; how it starts; masters; Adopt as a word; the stub's signals and job control; --detach; the Attach word; the harness switch), the known gaps, and the termios trap. Co-Authored-By: Claude Opus 5.5 --- docs/next-daemon.md | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++ docs/typ/building.typ | 55 ++++++++++++++++------------ docs/typ/reference.typ | 22 ++++++------ src/CHANGELOG.md | 23 ++++++++++++ 4 files changed, 165 insertions(+), 33 deletions(-) (limited to 'docs/typ') diff --git a/docs/next-daemon.md b/docs/next-daemon.md index 8bc9b38c..d164eced 100644 --- a/docs/next-daemon.md +++ b/docs/next-daemon.md @@ -169,3 +169,101 @@ open. 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] + +## Phase 3 notes + +Built 2026-10-29 (`src/daemon.zig`, the tty and GUI hosts, `main.zig`). +Decisions taken at the forks, with the ponytail lens: + +- **Sessions are not the daemon's children; every one registers.** The + design had the daemon spawn a terminal's session from the fd, cwd, env + and argv the stub passes. That proved wrong here: + - the user's terminals each run in a `9ns --mntgen` user and mount + namespace (`unshare(CLONE_NEWUSER|CLONE_NEWNS)`); a session the daemon + spawned would run in whichever namespace the daemon was started from, + its `/mnt/9p` served by a 9ns that may be gone. Its cgroup, rlimits, + umask and stdin (`pardes -`) would be the daemon's too, or have to be + carried and re-execed; + - startup would pay an IPC round trip and an exec of a 100+ MB binary; + - the snapshot harness's idleness probe walks the launched process's + tree, and a daemon-spawned session is outside it. + + So `pardes` in a terminal forks its session off itself before anything + starts (`daemon.forkSession`): the child calls `setsid` and draws on the + `/dev/tty` the parent opened; the parent stays as its stub. GUI windows + and `--detach` sessions just register. The daemon spawns nothing, so it + is no subreaper: a detached session is reparented to the system's reaper + (systemd --user or init), which reaps it, as it reaps a crashed + session's shells. Nothing dangles: the daemon lists every session (its + connection) and holds every master, and exits a second after it holds + neither. +- **Starting the daemon.** The first session takes the flock, binds and + listens itself and queues its own connection; `pardes --daemon` is then + double-forked and exec'd onto that listener and lock (fds 3 and 4), by + a terminal's stub after the session's fork, so no session waits for it: + its hello sits queued until the daemon runs, and is not waited on (the + daemon's `ok` is the reader thread's; Detach waits for it, up to 2 s). + With the spawn before the fork, a cold start measured +0.38 ms (+7.6%). + The daemon's reader thread likewise starts after the first frame. + Another starter waits on the lock; a stale socket is the lock holder's + to replace. Messages are `SOCK_SEQPACKET` datagrams, a line of words and + the fds it carries. +- **pty masters.** `forkShell` sends a dup; a host's close sends `close`; + a session's end sends `quit` (its shells hang up); a master whose shell + is gone (`POLLHUP`, polled with no events) is dropped. TERM, HUP and INT + handlers send `quit` too (one `send`, async-signal-safe), so only a + session killed outright or crashed leaves shells behind. +- **Adoption is a word, `Adopt`,** calling the host through a vtable entry + (no Effect): the daemon hands over every orphaned master, and each + becomes a pane through the `Tty` word, its spawn taking the pty instead + of forking; a 1x1 size then the pane's makes it redraw. Adopting at + startup was rejected: an `EDITOR='pardes --wait'` session would take the + shells and hang them up when the editor exits. +- **The stub.** It forwards WINCH, TERM, INT, QUIT and HUP by `kill`, and + ends with the session's status (a forked stub `waitpid`s; an attaching + one reads `x`). A HUP is the terminal's end: kept by a daemon, a + session takes HUP on its signal thread (sigwait, beside WINCH) and + detaches, as on EIO; HUP never ends a kept session, since the terminal's + own EIO and HUP arrive in either order. Ctrl-Z stays a key for the pane + (the terminal is raw, as before); a TSTP sent to the stub is ignored, + since a stopped stub hands the terminal back under a session still + drawing; a background start stops at a `tcsetattr` before the fork, as + the old raw mode did. `--wait`, nested forwarding and `--tty` run before + any of this and are unchanged. +- **`--detach` is a session started detached:** the tty host with no + terminal, the GUI with a hidden window closed at once. With the frames + gone, `detached/server.zig` was a third host with nothing left to do + that the other two could not. +- **`Attach` (the word) is deleted:** it switched a session's own terminal + to another session through the frames. +- **Harnesses.** `PARDES_DAEMON=off` (the e2e harness sets it) runs a + session as before: in the terminal's own process, ended by its hangup, + for a harness that kills by pid and closes the terminal. A GUI test + window (`PARDES_TEST`) has none unless `PARDES_DAEMON=on`. +- **Known gaps.** A stub killed with SIGKILL while its terminal stays open + leaves the session drawing there until the terminal closes or Detach. A + reattached terminal keeps the first one's environment (TERM, COLORTERM); + vaxis queries its capabilities again. A daemon killed outright leaves + its sessions unregistered, and Detach then refuses. A daemon of an older + protocol answers `version`, and a session then runs without one. A + GUI started in a terminal's foreground stays that terminal's job. + +Measured (ReleaseFast, base main a7369739 against these changes, both +live at once and their samples alternating A, B, A, B; A/A the base +against itself; p50 ratio new/base): + +| | tty | A/A | GUI (test mode) | A/A | +|---|---|---|---|---| +| startup, no daemon running | 1.017 (4.73 to 4.81 ms) | 0.998 | 0.982 (295 to 290 ms) | 0.999 | +| startup, daemon running | 1.014 (4.66 to 4.72 ms) | | 1.014 (noisy) | | +| key in a file, to its frame | 0.992 | 1.009 | 1.003 | 0.986 | +| key echoed by bash, to its frame | 1.016 | 1.005 | | | + +What is left of the tty's startup is the stub's fork (about 70 us), which +the design cannot do without: the job the shell waits on must be able to +end while the session runs on. + +Trap found on the way: glibc's `tcgetattr` writes its 60-byte `struct +termios` into Zig's `std.c.termios`, which is 44 (the kernel's layout), +and overran the stack, clobbering a neighbouring local in the forked +child; `std.posix.tcgetattr` (an ioctl on that layout) is the right one. diff --git a/docs/typ/building.typ b/docs/typ/building.typ index d551c251..152be838 100644 --- a/docs/typ/building.typ +++ b/docs/typ/building.typ @@ -1,6 +1,6 @@ // Building pardes, for contributors: platforms, options, tests, the // release gates and sending patches, then how the pieces fit: the core -// and its shells, the threads, detached sessions, the 9P engine, the +// and its shells, the threads, the daemon and its sessions, the 9P engine, the // listeners and mounts. #import "style.typ": key, keys, btn, chord, word, tag, addr, file, cmd, doc, pairs @@ -177,8 +177,9 @@ Code map: `src/panes.zig` and the pane kinds it names (`src/File.zig`, `src/Terminal.zig`, ...), `src/layout.zig`, `src/fs.zig` (host access, mounts and resolution) and `src/pardes.zig` (input), with one file per thing beside them (`edit.zig`, `normal.zig`, `look.zig`, `exec.zig`, -`mouse.zig`, ...). `src/ninep/` is the control tree, `src/detached/` the -wire, the detached core and the frontend client, `src/lsp/` the +`mouse.zig`, ...). `src/ninep/` is the control tree, `src/daemon.zig` the +per-user daemon and a terminal's stub, `src/detached/wire.zig` the input +wire a remote client will speak, `src/lsp/` the language-server client; `test/` holds harnesses, goldens and helix cases, `build/` the snapshot suite's build step. @@ -197,26 +198,34 @@ reading the live core, and a request id, the pane's serial and (for an edit) the file's revision reject a stale reply. A process that never calls `turn.start` (the tests, the ESP32-P4, the browser) has no second thread. -== Detached sessions - -One poll loop in `src/detached/server.zig` owns core mutation, frontend -connections, pty I/O and file watches. The frontend socket is -`pardes-detached-.sock` beside the session's 9P socket; a second -session cannot take a live name. Up to 32 frontends attach; frames go to -every one, while clipboard reads, browser opens and #word("Detach") go to -the frontend that asked (else the first attached). Frames are full grids -or changes against what each frontend last received, never queued: a -frontend with unsent bytes skips that frame, and one that stops draining -past 1 MiB of control backlog is closed, its peers untouched. Frontends -never spawn shells, write session files or watch files. #word("Attach") -connects first and swaps second: only after the handshake does a shell -give up its own core. #word("Restore") builds the replacement core before touching -the current one. - -`src/detached/wire.zig` is the versioned protocol (version 10): fixed-width -little-endian fields, a 5-byte header (tag, then a u32 length), payloads up -to 16 MiB and grids up to 512 by 128. A comptime hash of `pardes.Chrome` -forces a version bump when that struct changes. +== The daemon and detached sessions + +One `pardes --daemon` per user (`src/daemon.zig`) listens on +`pardes-daemon.sock` in the runtime directory, its `.lock` flocked for its +life; the first session that finds none starts it (a double fork and an +exec) and it exits a second after it holds nothing. It is nobody's parent: +a session registers on one connection, sends it a dup of every pty master +it forks (so a session killed outright never hangs its shells up, and +#word("Adopt") takes them into another), says whether a terminal or a +window shows it, and is handed a terminal (`pardes --attach`) or a window +request (`pardes-gui --attach`) through it. Messages are `SOCK_SEQPACKET` +datagrams: a line of words and the fds it carries. + +`pardes` in a terminal forks its session off before anything starts: the +session, in a session of its own (`setsid`), draws on the terminal it +opened, and the process the shell waits on stays as its stub, passing it +`SIGWINCH`, `SIGTERM`, `SIGINT` and `SIGQUIT` and ending with its status. +#word("Detach"), or the terminal's end (EIO, a hangup), puts +the terminal back and lets it go; the stub ends (exit 0) and the session +runs on with nothing drawn, until `pardes --attach` hands it another +terminal. A window's #word("Detach") closes the window and keeps the +process; `pardes-gui --attach` opens one again. `PARDES_DAEMON=off` (the +snapshot harness) runs a session as before the daemon: in the terminal's +own process, ended by its hangup. + +`src/detached/wire.zig` is the input half of the protocol a remote client +will speak (version 13): fixed-width little-endian fields, a 5-byte header +(tag, then a u32 length), the hello and its version, the input events. = 9P diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index b83b4a83..c95a574a 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -386,9 +386,9 @@ Writes take settings and session builtins (`scope = .session` in record for why. A #word("ThemeFile") the dump names that fails to load changes nothing. - #word("Kill") `[word...]` (above), #word("Mount") `name dial`, #word("Unmount") `name`, #word("Theme") `x`. -- `size C R` sizes a `--detach` session no frontend is attached to (160x50 - until then): from 20x6 to 4096x4096, else `invalid size`; refused while a - frontend owns the size, and when a column would lose its panes' minimum +- `size C R` sizes a session no terminal or window is attached to (160x50 + for a `--detach` one until then): from 20x6 to 4096x4096, else `invalid + size`; refused while a terminal or window owns the size, and when a column would lose its panes' minimum rows (`size: too small for the panes, each its tag and 2 rows`). A bad `size` is refused quoting the value it got (`"5 2"`). @@ -454,8 +454,7 @@ turning it off: #word("PanelSlide"), #word("PanelZoom"), #word("PanelDissolve"), #word("PanelAscii"), #word("PanelVertical"), #word("PanelEdges"), #word("PanelFall"), #word("PanelWave"), #word("PanelCurtain"), #word("PanelScramble"), #word("PanelType"); all -start off, and the web shell has none. Scene passes (the SDL window, and -one attached to a detached session), each at a level 0-3 (`on` is 2), all +start off, and the web shell has none. Scene passes (the SDL window), each at a level 0-3 (`on` is 2), all off: #word("Crt"), #word("Bloom"), #word("Vignette"), #word("Grain"). #word("Shader") `` adds a Shadertoy file written for ghostty to the chain (#word("Shader") `off` removes it; it recompiles when saved); @@ -1011,11 +1010,14 @@ to its end before the write is answered, and one that finds nothing fails, git's `a/` `b/` (and `c/ i/ w/ o/`) prefixes are dropped; a `--no-prefix` diff's paths are kept. - *Sessions.* Bare `--detach` names the session after its pid; bare - `--attach` needs exactly one session; a second `--detach=NAME` while NAME - runs (a plain session is named by its pid) says so in words and exits 1. Frontends share the smallest common size. With - none attached, `size C R` sets the screen, messages clear by the clock, - and a pty reports its size in pixels at the last frontend's cell size - (8×16 before any), as CSI 14, 16 and 18 t do. + `--attach` needs exactly one detached session of its kind (a terminal's + for `pardes`, a window's for `pardes-gui`); a second `--detach=NAME` + while NAME runs (a plain session is named by its pid) says so in words + and exits 1. One terminal or window shows a session at a time. With none + attached, `size C R` sets the screen, messages clear by the clock, and a + pty reports its size in pixels at the last cell size (8×16 before any), + as CSI 14, 16 and 18 t do. Attaching from another machine is gone until + the replicated clients (docs/next-daemon.md, phase 5). - *Config.* The startup file is `$XDG_CONFIG_HOME/pardes/init` when that is absolute, else `~/.config/pardes/init` (macOS: `~/Library/Application Support/pardes/init`). A line that fails is a diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index 4466ad26..10cc451d 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,29 @@ ## Unreleased +- One `pardes --daemon` per user keeps sessions, started by the first + session and gone once it keeps nothing. `pardes` in a terminal forks + its session off and stays as its stub: `Detach` (`SPC s D`), or a + terminal that closes, puts the terminal back and leaves the session + running in place (no fork of the core, no dump), and the stub ends. + `pardes --attach[=name]` in any terminal takes it back there. A + window's Detach closes the window and keeps the process; + `pardes-gui --attach[=name]` opens it again. A terminal session takes a + terminal and a window session a window, and the other is refused in + words. The daemon holds a dup of every shell's pty: a session killed + outright leaves its shells running, and `Adopt` in another session + takes them in as terminal panes (what they showed is gone; a resize + makes them redraw). A hangup never ends a session the daemon keeps (it + is the terminal's end); TERM and INT do, its shells with it. + `PARDES_DAEMON=off` runs a session as before. +- The frame wire goes: `src/detached/server.zig`, `client.zig` and the + cell frames of `wire.zig`, the frontends that drew a session's screen + from them, the smallest-common-grid rule, and the `Attach` word that + switched a session's own terminal to another. A `--detach` session is + now a terminal (or window) session with none attached yet. Attaching + from another machine is gone until the replicated clients + (docs/next-daemon.md, phase 5); `wire.zig` keeps the framing, the hello + and the input events for them. - One PNG and one JPEG decoder in a binary: images decode through wuffs, the decoders ghostty uses (ghostty-vt already links them), and stb_image keeps only the other formats. stb's own inflate and image writer go, as -- cgit v1.3 From 74286e81e88a6df7586ead9e8bcd503d44446a85 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 29 Oct 2026 17:58:06 -0300 Subject: docs: views in the guide and reference (a session attached already takes another view, up to four; Detach lets one go); phase 4 notes in docs/next-daemon.md; tty: Screen.hungUp reads a test terminal's fd as the test build has it Co-Authored-By: Claude Opus 5.5 --- docs/next-daemon.md | 124 +++++++++++++++++++++++++++++++++++++++++++++++++ docs/typ/guide.typ | 6 ++- docs/typ/reference.typ | 11 ++++- src/tty/tty.zig | 3 +- 4 files changed, 140 insertions(+), 4 deletions(-) (limited to 'docs/typ') diff --git a/docs/next-daemon.md b/docs/next-daemon.md index e3be6af8..b5939b9d 100644 --- a/docs/next-daemon.md +++ b/docs/next-daemon.md @@ -271,6 +271,130 @@ termios` into Zig's `std.c.termios`, which is 44 (the kernel's layout), and overran the stack, clobbering a neighbouring local in the forked child; `std.posix.tcgetattr` (an ioctl on that layout) is the right one. +## Phase 4 notes + +Built 2026-10-29 (`src/views.zig`, the tty and GUI hosts, `daemon.zig`, +the snapshot harness and the monkey). Decisions taken at the forks, with +the ponytail lens: + +- **A view is swapped in, not pointed at.** The ~1,900 references to the + core's layout, focus and pane state stay as they are: the core sees one + view, the live one, in the fields it always had. A view's share of the + session is a list of field names (`views.fields`, ~60) made into a struct + by one comptime `@Struct` (`Part`), and of each pane a struct beside it + (`PaneView`, in `Pane.pv`); going into view `k` copies the live one's out + (`park`) and `k`'s in (`unpark`). Copies, not swaps: a slot is stale + while its view is live and written whenever it goes out, so no two places + own a selection's heap. One view never parks: the single client pays + `views.several` (an AND and a compare) in the pump, the step's sync and an + edit, and one store a key (`typedInto`). Rejected: a `*View` the core + reads through (every reference rewritten, an indirection on every + access); a twin pane per view (Zerox exists only for files, and a + terminal's pty is its pane's slot). +- **Where each piece of state went.** + - Each view's own (`views.fields`): the screen size and cell metrics; + the columns, their weights, panes, serials, tags and the finder; rects; + `active`, `active_column` and the header focus; the jump list (kakoune's + is per client); the pointer, hover, drag, mouse grab, clicks and chords; + key prefixes (`"x` register name, leader, Ctrl-w, window pick); a + pending clipboard read; the presentation and the animations (lifts, + cursor glide); `windowed`, `native_images` and `native_image_patches`, + which the census had as watched host writes: a tty view on kitty and + one on a plain terminal differ. The 223 comptime platform branches stay + comptime: a session is one build, which the semantics hash says. + - Each pane's, each view's own (`PaneView`): `vweight`, `collapsed` and + `attached_to` (a layout's); `focus`; the body's mode, cursor, + selections, sticky column, pending normal command and find; a document's + scroll, `hscroll` and size; and what the step measured for that view + (`tag_rows`, `tag_top`, `tag_scroll`, `view`, `notices`), so a view drawn + without a step of its own draws its own geometry. + - The session's, every view's: the panes' text, undo, terminals and + their scroll (tmux shares a pane's copy mode too), tags (acme's are + per window; one tag per buffer is one text, its caret included), the + workspace tag, prompts, messages, registers (decided), the macro being + recorded, look-hover (one pointer at a time), mouse sweeps, query + panes, search state, settings and theme, the effect and input queues, + `needs_frame` (any change draws every view). +- **A terminal shown at two sizes** takes the size of the view that typed + into it last (`Pane.sized_by`, set by a key or a paste; a new pane's is + its maker's; a closed view's goes to the next to sync it). The others show + it at that size: `sync` resizes no pty for them, and `pane.cols/rows` + stay the terminal's own, so the terminal code's invariant (pane size is + the emulator's) holds. ponytail: a smaller view sees its top rows, cut; + panning to the cursor as tmux does is the upgrade, if a small view must + follow a shell it never types into. +- **Panes come and go under parked views.** A view keeps the serial of + each slot when it goes out; unparked, the ids whose serial changed leave + its layout and its keyboard moves to its first pane left. A pane focused + in a view that does not show it (a Look at a file another view opened, a + jump, a 9P focus) is placed in the view's active column (`views.show`, + kakoune's buffer shown in the window that asked). A text edited in one + view moves every other view's cursor and scroll with the splice, as a + Zerox twin's (`File.ParkedPlaces`); their selections go, as a twin's do. +- **Drawing the other views stays out of the digest.** The pump draws each + other view by unparking it, rendering and presenting, and restores the + live one exactly (`drawOthers`): no digested field moves, so the headless + replica, which draws nothing and skips it, agrees. What drawing a view + makes of its own (its animations, its presentation) is kept; what its + unpark normalised (a cursor clamped inside a changed text, a pruned + layout) is not, and is done again when it next goes live by an input, + in every replica alike. `parked` and `pv` are `.local`: a parked view is + checked when it is live again. Found by `pardes-monkey --views=3 --tape`: + a drawn view's `post_present` (acknowledgePanelPresentation, which moves + the pointer's hover) was applied by the headless replica to the live view; + other views take no post_present, their panels acknowledged when they + are live and drawn. +- **Inputs.** `toView`, `openView` and `closeView` are taped. A host goes + into a view before the input its client sent: the tty's terminal readers + post through a `Poster` that puts a `from` ahead of a terminal's input + whenever another terminal posted last (so one terminal posts none, and + coalesced motions never cross views); the GUI asks SDL which window an + event is for (`route`), which also takes a window's resize to its view + (the GUI sizes the live view from its window each frame). +- **The tty.** Each terminal is a `Screen` of its own: its vaxis, input + reader, frame answer (`FrameAck`, was global), kitty images and shm probe + (were global), glide, trail and flash, its stub and its Killed slot. The + primary's stub stays `daemon.stub`. A SIGWINCH asks every terminal its + size (attach stubs forward theirs; another view's terminal is no one's + controlling terminal); a SIGHUP asks each whether its terminal or stub's + pipe hung up, where it used to mean the one terminal. Detach, or a + terminal's end, with views left closes only that view and tells its stub + `d`; the session's end tells every stub. ponytail: a bracketed paste in + progress is the shell's, not a terminal's: keys from another terminal + during it join it. +- **The GUI.** One `Gui` (device, atlas, fonts, pipelines) and its + window's share swapped like the core's (`window_fields`: the SDL window + and its presenting, scroll and glide, scene and post chain, pointer, + blink, captures); `Shell.follow` keeps the Gui on the core's live view. + Closing a window while others stay closes its view; Restore closes the + others. ponytail: a second window's compositor hit test reads whichever + window's state is in the Gui (the workspace tag is in the same place in + every view). +- **The daemon.** `attach` names an attached session too: it takes another + view (a terminal, or a window). With no name, the detached sessions are + asked first, then the only session of that kind. +- **Harnesses, extended not new.** A snapshot script's `start ... views=N` + gives the app N-1 more ptys (PARDES_TEST_VIEWS, opened as attached ones + from the start), `view ` types into and captures terminal k, and every + wait reads all of them (a pty nobody reads would block the session's + frame); a `resize` there SIGWINCHes the app, as a stub would. + `pardes-monkey --views=N` switches among N terminals a quarter of its + steps, each with its own size; `zig build replay` runs its seeds at one + view and at three. The GUI's test feed takes `ESC]777;view;BEL`, and + PARDES_TEST_VIEWS=N opens N more hidden windows, captured under view-k. +- **What proved wrong in the design.** "Views" in the design were a + struct the core reads through; the swap made them cheaper and kept every + reference. Its rollback copy (phase 5) is the same list of fields. The + design's view-local state assumed a step per view; the step's + measurements (`tag_rows`, `notices`, the pane's geometry key) had to + become per view too, or a view drawn after another's step drew the + other's tag heights. And the census's single "frontend kind" leak is not + per process but per client: kitty graphics are a terminal's. + +Measured: PERF_TABLE + +Gates: GATES_TABLE + ## FreeBSD notes Groundwork for phase 5's main test, a client here and the session on the diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index 5dea0522..40802ed9 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -350,7 +350,11 @@ pardes-gui --attach=work a window session's window again 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 +a terminal, a window session a window. Attached already, it takes another +view: each terminal or window has its own columns, focus, cursors and +scroll over the same panes, texts and registers, and a terminal shown in +two takes the size of the one that last typed into it. #word("Detach") in +one lets only that one go. A session is named by `--9p=` or `--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 diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index c95a574a..190adba7 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -1011,9 +1011,16 @@ to its end before the write is answered, and one that finds nothing fails, `--no-prefix` diff's paths are kept. - *Sessions.* Bare `--detach` names the session after its pid; bare `--attach` needs exactly one detached session of its kind (a terminal's - for `pardes`, a window's for `pardes-gui`); a second `--detach=NAME` + for `pardes`, a window's for `pardes-gui`), or with none detached the + only session of that kind; a second `--detach=NAME` while NAME runs (a plain session is named by its pid) says so in words - and exits 1. One terminal or window shows a session at a time. With none + and exits 1. A session attached already takes another view, up to four: + each terminal or window its own layout, focus, cursors, selections, + modes, scroll and jumps, over the panes, texts, tags, terminals, + messages and registers they share. A terminal pane shown in two takes the + size of the view that typed into it last; a smaller view shows its top + rows. #word("Detach"), or a terminal closing, lets that view go and + leaves the others. With none attached, `size C R` sets the screen, messages clear by the clock, and a pty reports its size in pixels at the last cell size (8×16 before any), as CSI 14, 16 and 18 t do. Attaching from another machine is gone until diff --git a/src/tty/tty.zig b/src/tty/tty.zig index f949d571..b56e74b1 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -1329,8 +1329,9 @@ const Screen = struct { /// Its terminal hung up, or the stub that waits on it is gone. fn hungUp(sc: *const Screen) bool { const stub = if (sc.primary) daemon.stub else sc.stub; + const handle = if (@TypeOf(sc.tty.fd) == std.Io.File) sc.tty.fd.handle else sc.tty.fd; var fds = [_]posix.pollfd{ - .{ .fd = sc.tty.fd.handle, .events = 0, .revents = 0 }, + .{ .fd = handle, .events = 0, .revents = 0 }, .{ .fd = stub, .events = 0, .revents = 0 }, }; _ = posix.poll(fds[0..if (stub >= 0) 2 else 1], 0) catch return false; -- cgit v1.3 From 32b80ad0393321d44f929e501e5515bbf6e51c12 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 29 Oct 2026 19:52:55 -0300 Subject: views: a terminal shown in a view shorter than it is passed down to its cursor, a shell's prompt never out of sight, an arrow in the gutter where rows are above; a name drafted in a tag is the view's that opened it A terminal takes the size of the view that typed into it last; a shorter view used to show its top rows, the prompt below them cut. It now passes over as many as keep the cursor's row in sight, as tmux pans a bigger window in a smaller client: `Pane.pan` (per view, derived) is made in the step's sync and again when a view is drawn out of turn (views.unpark), by terminal.panFor (0 in the view that sizes it, in one tall enough, or folded), and read where the body's rows start: `Pane.scroll`, the body walk in tty mode, the visible cursor. One view never pans: the view that sizes a terminal returns 0 at its first test. A `.name` prompt (a file's name drafted in its tag) is the view's that opened it (`Pane.prompt_view`): another view's step, where that pane has not the keyboard, no longer drops it; its view closing does. views-pan.snap: a shell sized for a 24-row view, its last lines and prompt in a 12-row one under the arrow, then typed into from the short view and sized for it. A unit test: the short view's frame has the cursor's row, and the line on it, inside the pane. docs: the notes, the reference. Co-Authored-By: Claude Opus 5.5 --- docs/next-daemon.md | 41 +++++++++++++++++++------------- docs/typ/reference.typ | 4 ++-- src/draw.zig | 3 +++ src/panes.zig | 11 +++++++-- src/pardes.zig | 11 +++++---- src/tagline.zig | 1 + src/terminal.zig | 24 ++++++++++++++++--- src/views.zig | 49 +++++++++++++++++++++++++++++++++++++- test/snapshots/views-pan.golden | 52 +++++++++++++++++++++++++++++++++++++++++ test/snapshots/views-pan.snap | 27 +++++++++++++++++++++ 10 files changed, 194 insertions(+), 29 deletions(-) create mode 100644 test/snapshots/views-pan.golden create mode 100644 test/snapshots/views-pan.snap (limited to 'docs/typ') diff --git a/docs/next-daemon.md b/docs/next-daemon.md index 3d4c8a08..e7ddcf5f 100644 --- a/docs/next-daemon.md +++ b/docs/next-daemon.md @@ -314,15 +314,23 @@ the ponytail lens: workspace tag, prompts, messages, registers (decided), the macro being recorded, look-hover (one pointer at a time), mouse sweeps, query panes, search state, settings and theme, the effect and input queues, - `needs_frame` (any change draws every view). + `needs_frame` (any change draws every view). A `.name` prompt (a + file's name drafted in its tag) is the view's that opened it + (`Pane.prompt_view`): only that view's focus leaving the pane drops it, + and its closing. - **A terminal shown at two sizes** takes the size of the view that typed into it last (`Pane.sized_by`, set by a key or a paste; a new pane's is its maker's; a closed view's goes to the next to sync it). The others show it at that size: `sync` resizes no pty for them, and `pane.cols/rows` stay the terminal's own, so the terminal code's invariant (pane size is - the emulator's) holds. ponytail: a smaller view sees its top rows, cut; - panning to the cursor as tmux does is the upgrade, if a small view must - follow a shell it never types into. + the emulator's) holds. A view shorter than the terminal is passed down + its top rows as far as keeps its cursor's row in sight, as tmux shows a + bigger window in a smaller client (`Pane.pan`, terminal.panFor: per view, + made in the step and again when a view is drawn out of turn, read where + the body's rows start, `Pane.scroll` and the body walk), an arrow in its + gutter's first row saying rows are above; a shell's prompt, at the + bottom, is never out of sight. ponytail: a panned view's mouse reports to + the terminal's program and its kitty images are placed as unpanned. - **Panes come and go under parked views.** A view keeps the serial of each slot when it goes out; unparked, the ids whose serial changed leave its layout and its keyboard moves to its first pane left. A pane focused @@ -390,8 +398,6 @@ the ponytail lens: named in a path yet (a script's focus or layout is that view's). - Every change draws every view (`needs_frame` is the session's); a view's own dirtiness waits for a measurement that wants it. - - Prompts are the pane's: a `.name` prompt drafted in one view is - closed by another view's step, where that pane has not the keyboard. - Dump, Restore and Handover keep one view, the live one. - **What proved wrong in the design.** "Views" in the design were a struct the core reads through; the swap made them cheaper and kept every @@ -433,21 +439,24 @@ Two views (not gated): every frame draws both, so a change costs two renders; a view switch copies ~60 fields and each pane's share, a few microseconds. -Gates, on the line rebased onto main's tty throughput fix (qzsouslm): +Gates, on the line rebased onto main's screen-state terminals (mnlwlpvk): -- `zig build replay -Dplatform=tty`: 112 snapshot scripts pass (the 110, - views.snap and views-term.snap), their 130 tapes replay in all three - replicas (390 runs, 29,355 digests); 20 monkey seeds at one view (60 - runs, 14,010 digests) and 20 at three views (60 runs, 9,720 digests); - no divergence, no panic. views.snap: 75 digests a replica, - views-term.snap 35. -- Unit tests: tty 1478 of 1498 pass, 20 skipped; GUI 1549 of 1560, 9 +- `zig build replay -Dplatform=tty`: 113 snapshot scripts pass (the 110, + views.snap, views-term.snap and views-pan.snap), their 131 tapes replay + in all three replicas (393 runs, 29,436 digests); 20 monkey seeds at one + view (60 runs, 14,004 digests) and 20 at three views (60 runs, 9,666 + digests); no divergence, no panic. views.snap: 75 digests a replica, + views-term.snap 35. core-test: 1117 of 1135, 18 skipped. +- Unit tests (on qzsouslm): tty 1478 of 1498 pass, 20 skipped; GUI 1549 of 1560, 9 skipped and 2 failed, the same two that fail on phase 1's line (`tagline pointer mapping retains physical grips...` and `a tag caret past its - row's end glides...`). The views' own: 7 (own cursor, scroll, mode, + row's end glides...`). The views' own: 8 (own cursor, scroll, mode, layout and focus; an edit and a register shared; a terminal sized by its last typist; views closing; the other views drawn leave the digest; a - view keeps its place in a text another edits). + view keeps its place in a text another edits; a short view keeps a tall + terminal's cursor in sight). views-pan.snap: a shell sized for the tall + view, its prompt and last lines in the short one under an arrow, then + typed into from the short one and sized for it. - test/fs.py passes (with a TMPDIR short enough for the 9P sockets' paths). test/daemon.py: 20 detach and attach cycles, then a second terminal on the attached session, both drawn, detached from inside and diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index 190adba7..ce2a45f1 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -1018,8 +1018,8 @@ to its end before the write is answered, and one that finds nothing fails, each terminal or window its own layout, focus, cursors, selections, modes, scroll and jumps, over the panes, texts, tags, terminals, messages and registers they share. A terminal pane shown in two takes the - size of the view that typed into it last; a smaller view shows its top - rows. #word("Detach"), or a terminal closing, lets that view go and + size of the view that typed into it last; a shorter view shows the + rows down to its cursor, an arrow in the gutter when rows are above. #word("Detach"), or a terminal closing, lets that view go and leaves the others. With none attached, `size C R` sets the screen, messages clear by the clock, and a pty reports its size in pixels at the last cell size (8×16 before any), diff --git a/src/draw.zig b/src/draw.zig index 4f9c6c87..0cc5c80d 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -958,6 +958,9 @@ fn renderPane(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: } try body_layer.joinBody(p, s, arena, pane, r, id, active, rail.*); + // A terminal panned to its cursor in a view shorter than it: an arrow + // in the gutter's first body row says rows are above (views.zig). + if (pane.pan > 0) s.set(r.x, p.bodyTop(pane, r), "↑", .{ .fg = .{ .rgb = chrome.box } }); // A query's places' ticks, each in the track's cell of its row: chrome, // painted with the rail (a pixel shell draws its own from the same list). for (s.rail_ticks[0..s.nrail_ticks]) |tick| { diff --git a/src/panes.zig b/src/panes.zig index 71a04464..89f24eb6 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -30,7 +30,7 @@ pub const Pane = struct { /// the pane's opens and readers; the other views' share of it (views.zig). pub const replica = .{ .local = .{ "pv", "pv_known" }, - .derived = .{ "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "view", "notices" }, + .derived = .{ "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "view", "notices", "pan" }, .authority = .{"fs"}, .len = .{ .{ "msg", "msg_len" }, .{ "msg_older", "msg_older_len" }, .{ "question", "question_len" }, .{ "shell_tail", "shell_tail_len" }, .{ "sel_snap", "nsel_snap" } }, }; @@ -309,6 +309,13 @@ pub const Pane = struct { /// The view that last typed into it: a terminal shown at two sizes takes /// that view's (Pardes.sync). sized_by: u8 = 0, + /// A terminal shown in a view shorter than it (one that does not size + /// it): the rows its top is passed over by, so its cursor stays in + /// sight (terminal.panFor); 0 everywhere else. + pan: u16 = 0, + /// The view whose step a `.name` prompt is (tagline.draftName): only + /// that view's focus leaving the pane drops it. + prompt_view: u8 = 0, pub const MessagePhase = enum { entering, shown, lingering, leaving }; /// One message line's animation: falling in, shown, lingering after the @@ -543,7 +550,7 @@ pub const Pane = struct { pub fn scroll(pane: *Pane) i32 { if (pane.file) |f| return @intCast(f.scroll); if (comptime Pdf.enabled) if (pane.pdf) |pv| return @intCast(pv.text_scroll); - return pane.surfRow(terminal.gridOffset(pane)); + return pane.surfRow(terminal.gridOffset(pane) + pane.pan); } pub fn wrapAt(pane: *Pane, vr: i32) struct { line: i32, at: i32, pad: i32 = 0 } { diff --git a/src/pardes.zig b/src/pardes.zig index 59233347..75e91ee9 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -7729,7 +7729,7 @@ pub const Pardes = struct { // hands it back to its body, and a name drafted there is dropped. if (id != p.active or p.header_focus) { pane.focus = .body; - if (pane.prompt == .name) pane.closePrompt(); + if (pane.prompt == .name and pane.prompt_view == p.view) pane.closePrompt(); } // A sweep over the tag is the tag's while it has the keyboard. const swept = pane.sel[sel_slot]; @@ -7822,6 +7822,7 @@ pub const Pardes = struct { pane.rows = rows; if (pane.file) |*file| file.syntax_dirty = true; } + pane.pan = panes.terminal.panFor(p, pane, r); // A directory pane's entries follow its width, as acme's // columns do (Dir.fit). if (pane.file) |file| if (file.listing != null and r.h > pane.tag_rows) panes.Dir.fit(p, pane, pane.cols); @@ -7856,10 +7857,10 @@ pub const Pardes = struct { /// Whether the live view sizes terminal `pane`: a terminal shown at two /// sizes takes the size of the view that typed into it last, and any - /// view's once that one is gone. The others show it at that size. - // ponytail: a view smaller than the terminal shows its top rows, the - // rest cut; panning to its cursor, as tmux does, when a small view must - // follow a busy shell it never types into. + /// view's once that one is gone. The others show it at that size, a + /// shorter one passed down to its cursor (`Pane.pan`, terminal.panFor). + // ponytail: a panned view's pointer reports to a terminal's program and + // its kitty images are placed as the unpanned rows are. fn sizes(p: *Pardes, pane: *Pane) bool { if (pane.sized_by == p.view) return true; if (views.isOpen(p, pane.sized_by)) return false; diff --git a/src/tagline.zig b/src/tagline.zig index 79c2c09b..f669e98b 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -361,6 +361,7 @@ pub fn draftName(p: *Pardes, pane: *Pane, col: usize) void { const name = p.gpa.dupe(u8, f.path) catch return; pane.closePrompt(); pane.prompt = .name; + pane.prompt_view = p.view; pane.input = .{ .what = .input, .own = name, .mode = .insert, .cur_pinned = true, .cur_col = @intCast(@min(name.len, panes.File.rawAtDisplay(name, col))) }; } diff --git a/src/terminal.zig b/src/terminal.zig index 0afbe43a..e737a831 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -395,8 +395,26 @@ pub fn visibleCursor(pane: *const Pane) ?GridCursor { const cur = state.vt.screens.active.cursor; const sb = scrollbar(pane); const row = sb.total - sb.len + cur.y; - if (row < sb.offset or row - sb.offset >= sb.len) return null; - return .{ .x = @intCast(cur.x), .y = @intCast(row - sb.offset) }; + if (row < sb.offset + pane.pan or row - sb.offset >= sb.len) return null; + return .{ .x = @intCast(cur.x), .y = @intCast(row - sb.offset - pane.pan) }; +} + +/// The rows terminal `pane`'s top is passed over by in a view whose rect +/// `r` is shorter than it, one that does not size it (Pardes.sizes): as +/// many as keep its cursor's row in sight, as tmux pans a bigger window in +/// a smaller client. 0 in the view that sizes it, and in one tall enough. +pub fn panFor(p: *const Pardes, pane: *const Pane, r: pardes.Rect) u16 { + if (comptime !enabled) return 0; + if (pane.sized_by == p.view or pane.collapsed or !pane.isTerminal()) return 0; + const shown = r.h -| pane.tag_rows; + if (shown == 0 or shown >= pane.rows) return 0; + const state = pane.terminal orelse return 0; + const sb = scrollbar(pane); + // The cursor's row in the viewport; past its end (scrolled back), its + // last row. + const row = sb.total - sb.len + state.vt.screens.active.cursor.y; + const at: usize = if (row < sb.offset) 0 else @min(row - sb.offset, pane.rows - 1); + return @intCast(@min(pane.rows - shown, (at + 1) -| shown)); } /// Move the emulator's viewport by `delta` shell rows (negative scrolls back). @@ -1886,7 +1904,7 @@ const BodyWalk = struct { return .{ .pane = pane, .goff = goff, - .g = if (pane.body.mode == .tty) goff else pane.gridRow(off), + .g = if (pane.body.mode == .tty) goff + pane.pan else pane.gridRow(off), .skip = if (pane.ovl) |o| @intCast(@max(0, off - pane.surfRow(o.row))) else 0, }; } diff --git a/src/views.zig b/src/views.zig index e3ba5b4e..c847b987 100644 --- a/src/views.zig +++ b/src/views.zig @@ -53,7 +53,7 @@ pub const fields = [_][:0]const u8{ /// A pane's fields that are each view's own: where it is in the view's /// layout, which of its texts has the keyboard, how far it is scrolled, and /// what the view's step measured of it (its tag's rows, its bands). -const pane_fields = [_][:0]const u8{ "focus", "vweight", "collapsed", "attached_to", "hscroll", "tag_scroll", "tag_top", "tag_rows", "view", "notices" }; +const pane_fields = [_][:0]const u8{ "focus", "vweight", "collapsed", "attached_to", "hscroll", "tag_scroll", "tag_top", "tag_rows", "view", "notices", "pan" }; /// The body's: its cursor, selections and mode. Its undo stays the pane's. const body_fields = [_][:0]const u8{ "mode", "cur_pinned", "cur_row", "cur_col", "msel", "vsel", "sels", "nsel", "select", "sticky_col", "restore_cursor", "last_edit", "reg_wait", "normal", "find_op", "find_ch" }; @@ -72,6 +72,7 @@ pub const PaneView = struct { tag_rows: u16 = 1, view: Pane.SessionView = .{}, notices: Pane.Notices = .{}, + pan: u16 = 0, body: Part(Text, &body_fields) = .{}, /// A document's scroll and size; a terminal's size is its pty's, which /// every view shows (sized by its last typist, `Pardes.sync`). @@ -216,6 +217,10 @@ fn unpark(p: *Pardes, k: u8) void { }; } layout.compute(p); + // Its terminals' cursors moved while it was out: each pan follows. + for (p.panes, 0..) |s, id| if (s) |pane| { + pane.pan = pardes.panes.terminal.panFor(p, pane, p.rects[id]); + }; } /// The pane with the keyboard is one the live view shows: focused where its @@ -285,6 +290,8 @@ pub fn close(p: *Pardes, k: u8) void { if (sels.len > 0) p.gpa.free(sels); pane.pv[k].body.sels = &.{}; pane.pv_known &= ~(@as(u8, 1) << @intCast(k)); + // A name it was drafting goes with it. + if (pane.prompt == .name and pane.prompt_view == k) pane.closePrompt(); }; p.views_open &= ~(@as(u8, 1) << @intCast(k)); } @@ -555,3 +562,43 @@ test "a view not live keeps its place in a text another view edits" { try testing.expectEqual(scrolled + 3, pane.file.?.scroll); try testing.expect(std.mem.startsWith(u8, pardes.panes.File.sourceLine(pane, 103), "line 101")); } + +test "a terminal shown in a view shorter than it keeps its cursor in sight" { + const gpa = testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 20 }); + defer p.deinit(); + const id = p.active; + const term = p.panes[id].?; + const k = p.openView().?; + p.toView(k); + p.update(.{ .resize = .{ .cols = 100, .rows = 50 } }); + p.update(.{ .key = .{ .cp = Key.right } }); + const rows = term.rows; + try testing.expect(rows > 30); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(gpa); + for (1..rows) |i| try out.print(gpa, "row-{d}\r\n", .{i}); + try out.appendSlice(gpa, "LAST$ "); + p.update(.{ .output = .{ .pane = @intCast(id), .bytes = out.items } }); + // Sized for the tall view, it fits there whole: nothing is passed over. + try testing.expectEqual(@as(u16, 0), term.pan); + p.toView(0); + p.sync(); + try testing.expectEqual(rows, term.rows); + try testing.expect(term.pan > 0); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const s = try p.render(arena.allocator()); + const r = p.rects[id]; + // The cursor's row, the last, is on screen in the short view, inside + // the pane, and so is the line it is on. + const cursor = s.cursor.?; + try testing.expect(cursor.y >= r.y and cursor.y < r.y + r.h); + var row_text: std.ArrayList(u8) = .empty; + defer row_text.deinit(gpa); + for (0..s.cols) |x| try row_text.appendSlice(gpa, s.cells[@as(usize, cursor.y) * s.cols + x].grapheme()); + try testing.expect(std.mem.indexOf(u8, row_text.items, "LAST$") != null); + // Back in the tall view, its top is where it was. + p.toView(k); + try testing.expectEqual(@as(u16, 0), term.pan); +} diff --git a/test/snapshots/views-pan.golden b/test/snapshots/views-pan.golden new file mode 100644 index 00000000..db63d29c --- /dev/null +++ b/test/snapshots/views-pan.golden @@ -0,0 +1,52 @@ +== snap tall grid=80x24 cursor=4,16 +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/views-pan/cwd Tty+bash Save Mode Filter Collapse Del +| 18 +| 19 +| 20 +| 21 +| 22 +| 23 +| 24 +| 25 +| 26 +| 27 +| 28 +| 29 +| 30 +| $ +| /tmp/pardes-snap/views-pan/cwd/+New Save Tty Collapse Del +| 1 +== snap short-pans grid=60x12 cursor=4,8 +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/views-pan/cwd Tty+bash Save Mode Filter C +| ollapse Del +|↑ 27 +| 28 +| 29 +| 30 +| $ +| /tmp/pardes-snap/views-pan/cwd/+New Save Tty Collapse Del +| 1 +== snap short-typed grid=60x12 cursor=4,8 +|4: 29 +|5: 30 +|6: $ echo typed-in-short +|7: typed-in-short +== snap tall-sees grid=80x24 cursor=4,7 +|3: 29 +|4: 30 +|5: $ echo typed-in-short +|6: typed-in-short +|7: $ +|8: +|9: +|10: +|11: +|12: +|13: +|14: +|15: +|16: diff --git a/test/snapshots/views-pan.snap b/test/snapshots/views-pan.snap new file mode 100644 index 00000000..3ba1ac5b --- /dev/null +++ b/test/snapshots/views-pan.snap @@ -0,0 +1,27 @@ +# A terminal shown in a view shorter than it (src/views.zig): sized for the +# tall view that typed into it, the short one passes over its top rows so +# its cursor and prompt stay in sight, an arrow in the gutter saying rows +# are above. +config Verbose off +start 24 80 views=2 +wait 8000 $ +stable 700 20000 +view 2 +resize 12 60 +stable 500 10000 +view 1 +text seq 1 30 +key enter +wait 8000 30 +stable 500 10000 +snap tall +view 2 +stable 500 10000 +snap short-pans +text echo typed-in-short +key enter +stable 500 10000 +snap short-typed +view 1 +stable 500 10000 +snap tall-sees -- cgit v1.3 From 6a6e1b2cb3e328d5abd4435c1c2659f4e4e31eb8 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 29 Oct 2026 16:55:47 -0300 Subject: the replica socket: the daemon listens on pardes-replica.sock, a stream `ssh -L` can forward, refuses another build's hello in words and hands the connection to its session, which welcomes it and answers pings The daemon binds `pardes-replica.sock` beside its own (SOCK_STREAM, so ssh can forward it; the SEQPACKET socket that carries fds stays local) once it holds its lock. A replica's first message is a hello (detached/wire.zig, now version 14): the protocol version at offset 0, the client's semantics hash and the session's name. The daemon reads exactly that much and no further, so whatever the client sends next is the session's, keeps up to 16 hellos still on their way (ponytail: one that never comes holds its slot until it hangs up), and refuses in words another protocol, a session nobody has, or another build: every session now says its own hash in its registration (daemon protocol 2), so a mismatch never reaches it. An accepted connection goes to the session over its link (SCM_RIGHTS) and the daemon keeps no copy; the session welcomes it with its pid and name on a thread of its own and answers each ping with a pong, until bye or a hangup. ponytail: that stub is all a session does with a replica until phase 5 proper; it is what times a round trip through the handoff and `ssh -L`. The semantics hash (wire.semantics) is phase 1's undone item: the protocol, the release and commit, the platform, the build options, every dependency the manifest pins by its content hash (grammars, ghostty, the Unicode tables: build.zig's new `deps` option) and the walker codec's assumptions (pointer width, byte order). Not the OS: a Linux client of a FreeBSD session is the main case. ponytail: an unstamped build has no commit, so two dev trees of one release with the same options are not told apart. `pardes --version` prints it on a second line. The hello lost its grid (a replica's view takes a resize like any other input). test/daemon.py: a hello of this build welcomed by the session itself (its pid, one fd more in the session and none in the daemon, and back once it hangs up), 50 pings, another build's hello and an unknown session's refused, and `--ping [n]`, which times a hello and n pings on any replica socket (a forwarded one, say). Co-Authored-By: Claude Opus 5.5 --- build.zig | 13 ++++ docs/typ/building.typ | 17 ++++-- src/CHANGELOG.md | 6 ++ src/daemon.zig | 166 ++++++++++++++++++++++++++++++++++++++++++++++++-- src/detached/wire.zig | 157 ++++++++++++++++++++++++++++++++++++----------- src/main.zig | 6 +- test/daemon.py | 110 ++++++++++++++++++++++++++++++++- 7 files changed, 427 insertions(+), 48 deletions(-) (limited to 'docs/typ') diff --git a/build.zig b/build.zig index 5e337dfc..24476753 100644 --- a/build.zig +++ b/build.zig @@ -13,6 +13,18 @@ const display_version = if (std.mem.endsWith(u8, zon.version, ".0") and std.mem. else zon.version; +/// Every dependency the manifest pins, by its content hash: a grammar, +/// ghostty or the Unicode tables steps a core differently, so they are part +/// of a replica's semantics hash (src/detached/wire.zig `semantics`). +const deps_text = blk: { + var text: []const u8 = ""; + for (@typeInfo(@TypeOf(zon.dependencies)).@"struct".field_names) |name| { + const dep = @field(zon.dependencies, name); + text = text ++ name ++ " " ++ (if (@hasField(@TypeOf(dep), "hash")) dep.hash else "path") ++ "\n"; + } + break :blk text; +}; + pub const Platform = enum { tty, gui, web, macos, esp32p4 }; const PerfBuild = struct { @@ -2120,6 +2132,7 @@ fn shellOptions(b: *std.Build, cfg: ShellConfig, platform: Platform) *std.Build. // ...and the commit it was built from, when there is one and the build // is stamped at all (see `stamp_commit`). Read at configure time. o.addOption(?[]const u8, "commit", cfg.commit); + o.addOption([]const u8, "deps", deps_text); return o; } diff --git a/docs/typ/building.typ b/docs/typ/building.typ index 152be838..00088d7b 100644 --- a/docs/typ/building.typ +++ b/docs/typ/building.typ @@ -31,7 +31,8 @@ leaves that copy out. Zig 0.17 keeps the prefix from the build script, so so always pass `-Dplatform` while developing. Test, benchmark and run steps build what they need without installing. `pardes --version` prints `pardes ` (from `build.zig.zon`), plus the commit for release builds and the `~/.local` -install; `pardes --help` lists every flag. +install, and on a second line the build's semantics hash, which a replica +must share with its session; `pardes --help` lists every flag. The ESP32-P4 firmware is linked in the sibling `../05-zig-p4` toolchain, which needs ESP-IDF register headers: after building the editor object @@ -223,9 +224,17 @@ process; `pardes-gui --attach` opens one again. `PARDES_DAEMON=off` (the snapshot harness) runs a session as before the daemon: in the terminal's own process, ended by its hangup. -`src/detached/wire.zig` is the input half of the protocol a remote client -will speak (version 13): fixed-width little-endian fields, a 5-byte header -(tag, then a u32 length), the hello and its version, the input events. +A replica (a client running its own copy of the core, phase 5 of +`docs/next-daemon.md`) connects to `pardes-replica.sock`, a stream socket +beside it that `ssh -L` can forward. `src/detached/wire.zig` is its +protocol (version 14): fixed-width little-endian fields, a 5-byte header +(tag, then a u32 length), the hello, a ping, the input events. The hello +names a session and carries the client's semantics hash (the protocol, +release, commit, platform, build options and every dependency's hash); the +daemon refuses another build's, or a session nobody has, in words, and +hands an accepted connection to its session (`SCM_RIGHTS`), which welcomes +it and from then on is the one it talks to. Today the session answers +pings and nothing more. = 9P diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index 10cc451d..27337781 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- The daemon also listens on `pardes-replica.sock`, a stream socket `ssh + -L` can forward, for the replicated clients to come (docs/next-daemon.md, + phase 5): a hello names a session and the client's build, another + build is refused in words, and an accepted connection is handed to its + session, which so far only welcomes it and answers pings. + `pardes --version` prints that build's semantics hash on a second line. - One `pardes --daemon` per user keeps sessions, started by the first session and gone once it keeps nothing. `pardes` in a terminal forks its session off and stays as its stub: `Detach` (`SPC s D`), or a diff --git a/src/daemon.zig b/src/daemon.zig index ac9e6eb4..702d11b1 100644 --- a/src/daemon.zig +++ b/src/daemon.zig @@ -16,14 +16,22 @@ //! //! Messages are SOCK_SEQPACKET datagrams: a line of words, and the fds it //! carries (SCM_RIGHTS). +//! +//! A replica (docs/next-daemon.md, phase 5) comes in on a stream socket of +//! its own, `pardes-replica.sock`, which `ssh -L` can forward: its hello +//! (detached/wire.zig) names a session, and once its build is the session's +//! the connection is handed to that session, which it talks to from then on. const std = @import("std"); const builtin = @import("builtin"); const libc = std.c; const posix = std.posix; const ninep_io = @import("9p_io.zig"); +const wire = @import("detached/wire.zig"); +const log = std.log.scoped(.replica); pub const supported = builtin.os.tag == .linux or builtin.os.tag == .freebsd; -const version = 1; +/// 2: a session's hello carries its semantics hash (wire.semantics). +const version = 2; pub const max_fds = 64; const msg_max = 4096; /// Idle this long, it exits: long enough for the session that started it to @@ -31,6 +39,9 @@ const msg_max = 4096; const linger_ms = 1000; const max_conns = 64; const max_held = 256; +/// Replicas whose hello is still on its way. ponytail: one that never sends +/// it holds its slot until it hangs up; past 16 a new one is closed at once. +const max_replicas = 16; const sun_path_len = ninep_io.sun_path_len; const nosignal: u32 = if (builtin.os.tag == .linux) libc.MSG.NOSIGNAL else 0; @@ -258,7 +269,7 @@ fn spawn(listener: c_int, lock: c_int) bool { /// (`watch`) takes the `ok`, and only then is the session kept (`kept`). fn hello(fd: c_int, k: Kind, pid: libc.pid_t, named: []const u8, detached: bool) bool { var buf: [256]u8 = undefined; - const words = std.fmt.bufPrint(&buf, "hello {d} {t} {d} {s} {s}", .{ version, k, pid, if (detached) "detached" else "attached", named }) catch return false; + const words = std.fmt.bufPrint(&buf, "hello {d} {t} {d} {s} {x} {s}", .{ version, k, pid, if (detached) "detached" else "attached", wire.semantics, named }) catch return false; return send(fd, words, &.{}); } @@ -376,6 +387,11 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no .stub = if (got.nfds >= 2) got.fds[1] else -1, } }); for (got.fds[@min(got.nfds, 2)..got.nfds]) |f| _ = libc.close(f); + } else if (std.mem.eql(u8, verb, "replica")) { + if (got.nfds >= 1) { + if (std.Thread.spawn(.{}, serveReplica, .{got.fds[0]})) |t| t.detach() else |_| _ = libc.close(got.fds[0]); + } + for (got.fds[@min(got.nfds, 1)..got.nfds]) |f| _ = libc.close(f); } else if (std.mem.eql(u8, verb, "adopted")) { var note: Note = .{ .adopted = .{ .pids = undefined, .fds = undefined, .n = 0 } }; const a = ¬e.adopted; @@ -395,6 +411,49 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no } } +fn writeAll(fd: c_int, bytes: []const u8) bool { + var at: usize = 0; + while (at < bytes.len) { + const n = libc.send(fd, bytes[at..].ptr, bytes.len - at, nosignal); + if (n < 0 and libc.errno(n) == .INTR) continue; + if (n <= 0) return false; + at += @intCast(n); + } + return true; +} + +/// A replica the daemon handed over, its hello accepted: welcomed, its pings +/// answered, until it says bye or hangs up. ponytail: phase 5 proper makes it +/// a replica (the log, the dump, terminal state); this stub is what times a +/// round trip through the daemon's handoff and `ssh -L`. A message larger +/// than its buffer ends it. +fn serveReplica(fd: c_int) void { + defer _ = libc.close(fd); + log.info("a replica connected to '{s}'", .{name()}); + defer log.info("a replica of '{s}' left", .{name()}); + var out: [wire.hello_max]u8 = undefined; + const pid: u32 = @intCast(libc.getpid()); + if (!writeAll(fd, wire.encodeServer(&out, .{ .welcome = .{ .pid = pid, .session = name() } }) catch return)) return; + var buf: [msg_max]u8 = undefined; + var len: usize = 0; + while (true) { + while (wire.framed(buf[0..len]) catch return) |f| { + switch (wire.decodeClient(f.tag, f.payload) catch return) { + .ping => |v| if (!writeAll(fd, wire.encodeServer(&out, .{ .pong = v }) catch return)) return, + .bye, .hello => return, + .event => {}, + } + std.mem.copyForwards(u8, &buf, buf[f.total..len]); + len -= f.total; + } + if (len == buf.len) return; + const n = libc.read(fd, buf[len..].ptr, buf.len - len); + if (n < 0 and libc.errno(n) == .INTR) continue; + if (n <= 0) return; + len += @intCast(n); + } +} + /// A session ended by a signal (TERM, HUP, INT): its shells go with it, as /// at a quit. Async-signal-safe: one send. One killed outright (KILL) or /// crashed says nothing, and its shells live on for an Adopt. @@ -610,6 +669,8 @@ const Conn = struct { kind: ?Kind = null, pid: libc.pid_t = 0, detached: bool = false, + /// Its build's wire.semantics: a replica's must be the same. + semantics: u64 = 0, name: [128]u8 = undefined, name_len: usize = 0, @@ -625,9 +686,18 @@ const Held = struct { owner: ?u8 = null, }; +/// A replica's connection until its hello is whole: read no further than +/// the hello, so what follows it is the session's to read. +const Replica = struct { + fd: c_int = -1, + buf: [wire.hello_max]u8 = undefined, + len: usize = 0, +}; + const Daemon = struct { conns: [max_conns]Conn = @splat(.{}), held: [max_held]Held = @splat(.{}), + replicas: [max_replicas]Replica = @splat(.{}), fn idle(d: *const Daemon) bool { for (d.conns) |c| if (c.fd >= 0) return false; @@ -668,6 +738,7 @@ const Daemon = struct { const k = std.meta.stringToEnum(Kind, words.next() orelse ""); const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch 0; const state = words.next() orelse ""; + const semantics = std.fmt.parseInt(u64, words.next() orelse "", 16) catch 0; const rest = std.mem.trim(u8, words.rest(), " "); if (v != version or k == null or pid <= 0) { // Another build's: it runs without a daemon. @@ -677,6 +748,7 @@ const Daemon = struct { c.kind = k; c.pid = pid; c.detached = std.mem.eql(u8, state, "detached"); + c.semantics = semantics; c.name_len = @min(rest.len, c.name.len); @memcpy(c.name[0..c.name_len], rest[0..c.name_len]); return d.reply(i, "ok", &.{}); @@ -796,6 +868,58 @@ const Daemon = struct { return error.Said; } + /// More of a replica's hello; once it is whole, the connection refused + /// in words or handed to its session. + fn hear(d: *Daemon, r: *Replica) void { + const want = if (r.len < wire.header_len) wire.header_len else wire.header_len + @as(usize, std.mem.readInt(u32, r.buf[1..5], .little)); + if (want > r.buf.len) return refuse(r, "the first message is not a hello"); + const n = libc.read(r.fd, r.buf[r.len..want].ptr, want - r.len); + if (n < 0 and libc.errno(n) == .INTR) return; + if (n <= 0) { + _ = libc.close(r.fd); + r.* = .{}; + return; + } + r.len += @intCast(n); + if (r.len < wire.header_len or r.len < wire.header_len + std.mem.readInt(u32, r.buf[1..5], .little)) return; + const f = (wire.framed(r.buf[0..r.len]) catch null) orelse return refuse(r, "the first message is not a hello"); + if (f.tag != @backingInt(wire.ClientTag.hello)) return refuse(r, "the first message is not a hello"); + var why: [512]u8 = undefined; + const v = wire.helloVersion(f.payload) catch 0; + if (v != wire.version) return refuse(r, std.fmt.bufPrint(&why, "this client speaks replica protocol {d}, and this daemon {d}: run the same pardes at both ends", .{ v, wire.version }) catch "another protocol"); + const h = (wire.decodeClient(f.tag, f.payload) catch return refuse(r, "a malformed hello")).hello; + const target = for (&d.conns, 0..) |*c, i| { + if (c.fd >= 0 and c.kind != null and std.mem.eql(u8, c.named(), h.session)) break i; + } else return refuse(r, std.fmt.bufPrint(&why, "no session called '{s}'", .{h.session}) catch "no such session"); + const t = &d.conns[target]; + if (t.semantics != h.semantics) return refuse(r, std.fmt.bufPrint(&why, "session '{s}' runs another build of pardes (semantics {x:0>16}, this client's {x:0>16}): a replica needs the same build at both ends, as `pardes --version` shows", .{ h.session, t.semantics, h.semantics }) catch "another build"); + if (!send(t.fd, "replica", &.{r.fd})) { + d.hangUp(@intCast(target)); + return refuse(r, "that session does not answer"); + } + log.info("a replica handed to '{s}'", .{h.session}); + _ = libc.close(r.fd); + r.* = .{}; + } + + fn refuse(r: *Replica, why: []const u8) void { + var out: [600]u8 = undefined; + // A fresh connection's buffer is empty: this never blocks. + if (wire.encodeServer(&out, .{ .refused = why[0..@min(why.len, 512)] })) |bytes| _ = writeAll(r.fd, bytes) else |_| {} + _ = libc.close(r.fd); + r.* = .{}; + } + + fn acceptReplica(d: *Daemon, listener: c_int) void { + const fd = libc.accept4(listener, null, null, libc.SOCK.CLOEXEC); + if (fd < 0) return; + for (&d.replicas) |*r| if (r.fd < 0) { + r.* = .{ .fd = fd }; + return; + }; + _ = libc.close(fd); + } + fn accept(d: *Daemon, listener: c_int) void { const fd = libc.accept4(listener, null, null, libc.SOCK.CLOEXEC); if (fd < 0) return; @@ -807,6 +931,21 @@ const Daemon = struct { } }; +/// The replicas' stream socket, bound and listening; -1 when it cannot be +/// (a runtime directory too long for a socket's path: 104 bytes on FreeBSD). +/// Ours to replace: the daemon's lock is held. +fn listenReplicas() c_int { + var sock_buf: [sun_path_len:0]u8 = undefined; + const sock = place(&sock_buf, "pardes-replica.sock") orelse return -1; + _ = libc.unlink(sock); + const fd = libc.socket(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0); + if (fd < 0) return -1; + const addr = address(sock); + if (libc.bind(fd, @ptrCast(&addr), @sizeOf(libc.sockaddr.un)) == 0 and libc.chmod(sock, 0o600) == 0 and libc.listen(fd, max_replicas) == 0) return fd; + _ = libc.close(fd); + return -1; +} + /// `pardes --daemon`: what `spawn` started, on the listener (fd 3) and the /// lock (fd 4). Returns only to exit, idle. pub fn serve() noreturn { @@ -815,22 +954,33 @@ pub fn serve() noreturn { ninep_io.setCloexec(4); const ignore: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.IGN }, .mask = posix.sigemptyset(), .flags = 0 }; for ([_]posix.SIG{ .PIPE, .HUP, .INT }) |sig| posix.sigaction(sig, &ignore, null); + const replicas = listenReplicas(); var d: Daemon = .{}; - const slots = 1 + max_conns + max_held; + const slots = 2 + max_conns + max_replicas + max_held; var fds: [slots]libc.pollfd = undefined; var conn_of: [slots]u8 = undefined; var held_of: [slots]u16 = undefined; + var replica_of: [slots]u8 = undefined; var buf: [msg_max]u8 = undefined; while (true) { var n: usize = 0; fds[n] = .{ .fd = listener, .events = libc.POLL.IN, .revents = 0 }; n += 1; + // -1 when there is none: poll skips a negative fd. + fds[n] = .{ .fd = replicas, .events = libc.POLL.IN, .revents = 0 }; + n += 1; const conns_at = n; for (&d.conns, 0..) |*c, i| if (c.fd >= 0) { fds[n] = .{ .fd = c.fd, .events = libc.POLL.IN, .revents = 0 }; conn_of[n] = @intCast(i); n += 1; }; + const replicas_at = n; + for (&d.replicas, 0..) |*r, i| if (r.fd >= 0) { + fds[n] = .{ .fd = r.fd, .events = libc.POLL.IN, .revents = 0 }; + replica_of[n] = @intCast(i); + n += 1; + }; const held_at = n; // No events asked of a master: its hangup (every slave closed, the // shell and all it ran gone) is reported anyway, and its output is @@ -858,7 +1008,12 @@ pub fn serve() noreturn { break; } if (fds[0].revents & libc.POLL.IN != 0) d.accept(listener); - for (fds[conns_at..held_at], conn_of[conns_at..held_at]) |pfd, i| { + if (fds[1].revents & libc.POLL.IN != 0) d.acceptReplica(replicas); + for (fds[replicas_at..held_at], replica_of[replicas_at..held_at]) |pfd, i| { + if (pfd.revents == 0 or d.replicas[i].fd != pfd.fd) continue; + d.hear(&d.replicas[i]); + } + for (fds[conns_at..replicas_at], conn_of[conns_at..replicas_at]) |pfd, i| { if (pfd.revents == 0 or d.conns[i].fd != pfd.fd) continue; const got = recv(pfd.fd, &buf) orelse { d.hangUp(i); @@ -874,6 +1029,9 @@ pub fn serve() noreturn { var sock_buf: [sun_path_len:0]u8 = undefined; _ = libc.close(listener); if (place(&sock_buf, "pardes-daemon.sock")) |sock| _ = libc.unlink(sock); + if (replicas >= 0) { + if (place(&sock_buf, "pardes-replica.sock")) |sock| _ = libc.unlink(sock); + } libc._exit(0); } diff --git a/src/detached/wire.zig b/src/detached/wire.zig index 20d75274..097cbee7 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -1,13 +1,41 @@ -//! The framed stream a remote client will speak (docs/next-daemon.md, -//! phase 5): fixed-width little-endian fields and explicit tags, the hello -//! and its version, and the input Events. Native struct layout never reaches -//! the wire. The cell frames that went the other way, and the frontends that -//! drew them, went with phase 3. +//! The framed stream a replica speaks (docs/next-daemon.md, phase 5), on +//! the daemon's `pardes-replica.sock` and then its session's: fixed-width +//! little-endian fields and explicit tags, the hello and its version, a +//! ping, and the input Events. Native struct layout never reaches the wire. +//! The cell frames that went the other way, and the frontends that drew +//! them, went with phase 3. const std = @import("std"); +const builtin = @import("builtin"); const pardes = @import("../pardes.zig"); - -/// 13: the frames, and every message a session sent, are gone (phase 3). -pub const version: u16 = 13; +const config = @import("pardes_config"); + +/// 14: the hello names a session and carries the semantics hash, and a +/// ping is answered (phase 5's groundwork); 13: the frames went (phase 3). +pub const version: u16 = 14; + +/// What makes two cores step differently, hashed: a replica's hello carries +/// its own, and one of another build is refused. The protocol, the release +/// and commit, the platform and build options, every dependency's content +/// hash (grammars, ghostty, Unicode) and the walker codec's assumptions +/// (pointer width, byte order). Not the OS: a Linux client of a FreeBSD +/// session is the main case, and what differs there is the host's, taped. +/// ponytail: an unstamped build (Debug with -Dplatform, every test build) +/// has no commit, so two dev trees of one release are told apart only by +/// their options and dependencies; -Dstamp-commit stamps one. +pub const semantics: u64 = blk: { + @setEvalBranchQuota(1_000_000); + break :blk std.hash.Wyhash.hash(0, std.fmt.comptimePrint( + "wire {d}\npardes {s} {s}\n{t} grammars {} {} {} {} mupdf {} themes {} workspace_tag {} sources {} board {d}x{d}\nusize {d} {t}\n{s}", + .{ + version, config.version, config.commit orelse "unstamped", + config.platform, config.syntax_highlighting, config.syntax_zig_grammar, + config.syntax_minimal_grammars, config.syntax_full_grammars, config.mupdf, + config.theme_animation, config.workspace_tag, config.embed_sources, + config.esp32p4_cols, config.esp32p4_rows, @sizeOf(usize), + builtin.cpu.arch.endian(), config.deps, + }, + )); +}; /// EndOfStream: the message ends early; WriteFailed: no room for it. /// ReadFailed is in only because std.Io.Reader says so: a fixed one never @@ -23,6 +51,7 @@ pub const header_len = 5; // tag:u8, payload length:u32le pub const ClientTag = enum(u8) { hello = 0x01, bye = 0x02, + ping = 0x03, key = 0x10, mouse = 0x11, @@ -59,12 +88,50 @@ const KindTag = enum(u8) { press = 0x00, release = 0x01, motion = 0x02, drag = 0 /// when the rest of the layout is the part that changed. pub const Hello = struct { version: u16 = version, - /// This client's grid. Never zero: a client not sized yet must not - /// collapse a shared session (getCols). - cols: u16, - rows: u16, + /// The client's `semantics`: the daemon refuses it unless the session's + /// is the same. + semantics: u64 = semantics, + /// Which session (its 9P name, as `--attach=` names it). + session: []const u8, +}; + +/// A session's name on the wire, as the daemon keeps it. +pub const max_name = 128; +/// The longest hello there is, header and all. +pub const hello_max = header_len + 2 + 8 + 2 + max_name; + +/// Daemon or session -> client. +pub const ServerTag = enum(u8) { + /// The hello is accepted and the connection is the session's now: its pid + /// and name. + welcome = 0x01, + /// Refused, said in words; the connection ends. + refused = 0x02, + /// A ping's value back. + pong = 0x03, }; +pub const ServerMsg = union(ServerTag) { + welcome: struct { pid: u32, session: []const u8 }, + refused: []const u8, + pong: u64, +}; + +pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { + var w: std.Io.Writer = .fixed(out); + const at = try beginMessage(&w, @backingInt(std.meta.activeTag(msg))); + switch (msg) { + .welcome => |h| { + try w.writeInt(u32, h.pid, .little); + try putSlice16(&w, h.session); + }, + .refused => |words| try putSlice16(&w, words), + .pong => |v| try w.writeInt(u64, v, .little), + } + try finishMessage(&w, at); + return w.buffered(); +} + /// `Hello.version` alone, read out of the still-undecoded payload. /// /// Separate from `decodeClient` because of the guarantee the fixed offset above @@ -88,6 +155,8 @@ pub fn helloVersion(payload: []const u8) Error!u16 { pub const ClientMsg = union(enum) { hello: Hello, bye, + /// A round trip's probe, answered `pong` with the same value. + ping: u64, event: pardes.Event, }; @@ -291,10 +360,12 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { switch (msg) { .hello => |h| { try w.writeInt(u16, h.version, .little); - try w.writeInt(u16, h.cols, .little); - try w.writeInt(u16, h.rows, .little); + try w.writeInt(u64, h.semantics, .little); + if (h.session.len > max_name) return error.Overlong; + try putSlice16(&w, h.session); }, .bye => {}, + .ping => |v| try w.writeInt(u64, v, .little), .event => |ev| switch (ev) { .key => |k| { try w.writeInt(u32, k.cp, .little); @@ -352,10 +423,15 @@ pub fn decodeClient(tag: u8, payload: []const u8) Error!ClientMsg { const msg: ClientMsg = switch (std.enums.fromInt(ClientTag, tag) orelse return error.BadTag) { .hello => .{ .hello = .{ .version = try r.takeInt(u16, .little), - .cols = try getCols(&r), - .rows = try getRows(&r), + .semantics = try r.takeInt(u64, .little), + .session = blk: { + const n = try r.takeInt(u16, .little); + if (n > max_name) return error.BadValue; + break :blk try r.take(n); + }, } }, .bye => .bye, + .ping => .{ .ping = try r.takeInt(u64, .little) }, .key => blk: { const cp = try r.takeInt(u32, .little); // `Key.cp` is a u21, and the specials live in the private-use @@ -415,7 +491,8 @@ const msg_slack = header_len + 64; /// once instead of guessing and retrying. pub fn clientBound(msg: ClientMsg) usize { return msg_slack + switch (msg) { - .hello, .bye => 0, + .hello => |h| h.session.len, + .bye, .ping => 0, .event => |ev| switch (ev) { .mouse, .resize, .pdf_scroll, .pinch, .touch_scroll, .pointer_leave, .focus => 0, .key => |k| k.text.len, @@ -458,12 +535,21 @@ test "detached wire: every Event variant round-trips" { try testing.expectEqual(@as(u8, 0x1d), @backingInt(ClientTag.pointer_leave)); { - const got = try roundClient(&buf, .{ .hello = .{ .cols = 80, .rows = 24 } }); + const got = try roundClient(&buf, .{ .hello = .{ .session = "work" } }); try testing.expectEqual(version, got.hello.version); - try testing.expectEqual(@as(u16, 80), got.hello.cols); - try testing.expectEqual(@as(u16, 24), got.hello.rows); + try testing.expectEqual(semantics, got.hello.semantics); + try testing.expectEqualStrings("work", got.hello.session); } try testing.expectEqual(ClientMsg.bye, try roundClient(&buf, .bye)); + try testing.expectEqual(@as(u64, 0xfeed_beef_0000_0001), (try roundClient(&buf, .{ .ping = 0xfeed_beef_0000_0001 })).ping); + { + // The other way: framed the same, its tag the ServerTag's number. + const bytes = try encodeServer(&buf, .{ .welcome = .{ .pid = 42, .session = "work" } }); + const f = (try framed(bytes)).?; + try testing.expectEqual(@as(u8, 0x01), f.tag); + try testing.expectEqualSlices(u8, &.{ 42, 0, 0, 0, 4, 0, 'w', 'o', 'r', 'k' }, f.payload); + try testing.expectEqual(@as(u8, 0x03), (try framed(try encodeServer(&buf, .{ .pong = 7 }))).?.tag); + } { const key: pardes.Key = .{ .cp = pardes.Key.page_down, .text = "ü", .ctrl = true, .alt = false, .shift = true }; @@ -530,20 +616,19 @@ test "detached wire: a session is never told to do a frontend's remembering" { // Adding a name here is meant to be an ARGUMENT, not a formality, and the // bar is one sentence: A HUMAN DID IT. A keystroke, a click, a pinch, a // window resized, a paste, a command line executed, a pointer leaving the - // window, the window's focus — plus the two session words that say who is speaking. A pty's + // window, the window's focus — plus the session words that say who is speaking, time the link and end it. A pty's // output, a worker's answer, a watched file's new bytes and an animation // tick all fail that bar the same way: nobody did them, a machine reported // them, and the machine that reports them is the one already holding the // core. const allowed = [_][]const u8{ - // Who this connection is, and that it is finished. - "hello", "bye", + // Who this connection is, its round trip, and that it is finished. + "hello", "bye", "ping", // ...and everything a person can do to a window. - "key", "mouse", - "resize", "paste", - "command", "pdf_scroll", - "pinch", "touch_scroll", - "pointer_leave", "focus", + "key", "mouse", "resize", + "paste", "command", "pdf_scroll", + "pinch", "touch_scroll", "pointer_leave", + "focus", }; // One: the tag set is exactly that, named rather than counted, so @@ -663,18 +748,16 @@ test "detached wire: values a field cannot mean are refused" { @backingInt(ClientTag.pdf_scroll), &.{pardes.MAX_PANES}, )); - // A zero-column grid would collapse a shared session; an over-wide one is - // past what this protocol carries. - try testing.expectError(error.BadValue, decodeClient( - @backingInt(ClientTag.hello), - &.{ 1, 0, 0, 0, 24, 0 }, - )); + // A session name longer than the daemon keeps one: refused, never cut + // to another session's name. { - var hello: [6]u8 = undefined; + var hello: [12 + max_name + 1]u8 = @splat('x'); std.mem.writeInt(u16, hello[0..2], version, .little); - std.mem.writeInt(u16, hello[2..4], max_cols + 1, .little); - std.mem.writeInt(u16, hello[4..6], 24, .little); + std.mem.writeInt(u16, hello[10..12], max_name + 1, .little); try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.hello), &hello)); + std.mem.writeInt(u16, hello[10..12], max_name, .little); + try testing.expectEqual(@as(usize, max_name), (try decodeClient(@backingInt(ClientTag.hello), hello[0 .. hello.len - 1])).hello.session.len); + try testing.expect(header_len + hello.len - 1 == hello_max); } // A NaN scroll distance. `pinch` multiplies into a zoom the pane keeps. { diff --git a/src/main.zig b/src/main.zig index 378dbea8..f310bf3c 100644 --- a/src/main.zig +++ b/src/main.zig @@ -288,10 +288,12 @@ fn badArgs(io: std.Io, comptime fmt: []const u8, args: anytype) noreturn { std.process.exit(1); } -const version_text = if (pardes.commit) |c| +/// The second line is what a replica's build must share with its session's +/// (detached/wire.zig `semantics`). +const version_text = (if (pardes.commit) |c| "pardes " ++ pardes.version ++ " (" ++ c ++ ")\n" else - "pardes " ++ pardes.version ++ "\n"; + "pardes " ++ pardes.version ++ "\n") ++ std.fmt.comptimePrint("semantics {x:0>16}\n", .{@import("detached/wire.zig").semantics}); const nested_text = \\pardes: this shell is already inside pardes, and a pardes inside a pardes diff --git a/test/daemon.py b/test/daemon.py index 41cfbaf7..2be3f355 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -6,16 +6,24 @@ private HOME and runtime directory: 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; +- a replica's hello on the daemon's stream socket (phase 5): one of this + build handed to its session, which answers it and its pings; another + build's refused, and a session nobody has; - nothing left behind: no session, shell, daemon or socket. python3 -B test/daemon.py [cycles] python3 -B test/daemon.py --gui [cycles] (a hidden window; needs a Wayland display, and a pardes beside it for the refusal) + python3 -B test/daemon.py --ping [n] + a hello of 's build and n pings on a replica socket (one + `ssh -L` forwards, say), timed """ import fcntl import os import shutil import signal +import socket +import statistics import struct import subprocess import sys @@ -153,6 +161,103 @@ def fds(pid): return -1 +def semantics(binary): + """What a replica's build must share with its session's (--version).""" + out = subprocess.run([binary, '--version'], capture_output=True, check=True).stdout.decode() + return int(next(line.split()[1] for line in out.splitlines() if line.startswith('semantics ')), 16) + + +class Replica: + """A replica's connection (src/detached/wire.zig): length-prefixed + messages, a tag byte and a little-endian u32 length.""" + WIRE = 14 + + def __init__(self, path, timeout=10): + self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.s.settimeout(timeout) + self.s.connect(os.fspath(path)) + + def send(self, tag, payload): + self.s.sendall(struct.pack(' 5 else 50) + elif '--gui' in sys.argv: args = [a for a in sys.argv[1:] if a != '--gui'] gui(args[0], int(args[1]) if len(args) > 1 else 50) else: -- cgit v1.3 From fdf59131f68db19fc4818b6e5db7c9fe4cc609fd Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 29 Oct 2026 20:51:15 -0300 Subject: pdf: Esc in a PDF pane drops the selection or the search highlights the page shows, and with none goes back a pane as Esc does everywhere else; Shift-Esc still goes at once Co-Authored-By: Claude Opus 5.5 --- docs/helix-keys.md | 2 +- docs/typ/cheatsheet.typ | 2 +- docs/typ/guide.typ | 2 +- src/normal.zig | 2 ++ src/pdf_view.zig | 14 +++++++++++--- test/pdf.zig | 29 +++++++++++++++++++++++------ 6 files changed, 39 insertions(+), 12 deletions(-) (limited to 'docs/typ') diff --git a/docs/helix-keys.md b/docs/helix-keys.md index d47f3051..04aa60dd 100644 --- a/docs/helix-keys.md +++ b/docs/helix-keys.md @@ -122,7 +122,7 @@ language-backend queries, and the shell pipe. | `y` | yank each range's text into the register (`"` names one, else `"`), one value per range | line-yank vim-ism removed (phase 5); yank keeps selection AND cursor (helix). The system clipboard is `"+y` / `SPC y`, helix's own split: a `d` of one character never clobbers what the desktop holds | helix-verified | | `u` / `U` | undo / redo | restores the pre-edit selection (helix); snapshot granularity, `Alt-u`/`Alt-U` are the same two: helix walks a history tree by time with them, and pardes's history is linear, so earlier and later ARE undo and redo | helix-verified | | `p` (normal) | paste the register after each range: value i at range i, the last value repeated when there are fewer | helix `paste_impl`. `"+p` asks the system clipboard (`SPC p`); on a tty that read is OSC 52, which most terminals refuse: an honest no-op rather than a paste of the wrong text | helix-verified | -| `Esc` (body normal) | clear a pending modal prefix / exit select mode, keeping the selection, then run `Last`: hop to the pane you were in before this one, whichever kind it was, exactly like `SPC j j` — so held down it alternates between two panes, two files as readily as a file and its shell. A PDF pane is the ONE exception: there Esc is the document's own cancel (drop the mouse selection and the search overlay, stay where you are reading) and `Shift-Esc` is the hop out, while raw tty takes unmodified Esc as `Last` and sends Shift-Esc to the program (with `ProgramEsc on`, Esc goes to the program except at a detected shell prompt) | Pardes-specific focus binding layered on helix's cleanup. A leader path, tag, topbar or search owns Esc while it is active; raw tty forwards it | pardes-specific (cleanup helix-verified) | +| `Esc` (body normal) | clear a pending modal prefix / exit select mode, keeping the selection, then run `Last`: hop to the pane you were in before this one, whichever kind it was, exactly like `SPC j j` — so held down it alternates between two panes, two files as readily as a file and its shell. In a PDF pane Esc first drops the mouse selection and the search highlights when the page shows any, staying where you are reading, and the next Esc hops; `Shift-Esc` hops at once. Raw tty takes unmodified Esc as `Last` and sends Shift-Esc to the program (with `ProgramEsc on`, Esc goes to the program except at a detected shell prompt) | Pardes-specific focus binding layered on helix's cleanup. A leader path, tag, topbar or search owns Esc while it is active; raw tty forwards it | pardes-specific (cleanup helix-verified) | | `Esc` (insert) | back to normal mode, cursor right after the insertion (no vim left-step) | | helix-verified | | `Enter` (normal) | acme **look** chord: EXPLICIT selection, else file-ish word under cursor | pardes-specific, keep (helix normal-mode Enter unbound). Covers helix `gf`. Implicit motion residue falls back to the cursor word | pardes-specific | | `Tab` (normal) | acme **execute** chord | pardes-specific, keep; explicit-selection rule as Enter | pardes-specific | diff --git a/docs/typ/cheatsheet.typ b/docs/typ/cheatsheet.typ index 11f7c6fc..9dc9c473 100644 --- a/docs/typ/cheatsheet.typ +++ b/docs/typ/cheatsheet.typ @@ -72,7 +72,7 @@ Helix-style: motions *select*, then an edit acts on the selection. Mode box: bla == Keys: panes #pairs( [#key("Ctrl-w")], [window mode: #keys("h", "j", "k", "l") move the outline, #key("d") deletes it (then #key("k")/#key("j") between two), #key("c") collapses it, #key("Enter")/#key("Esc") or a pane's letter focuses (not in insert or raw `$`)], - [#key("Esc")], [back to the previous pane (insert: to normal)], + [#key("Esc")], [back to the previous pane (insert: to normal; a PDF: its selection and search highlights go first)], [#key("Shift-Esc")], [back to the previous pane from any mode but raw, where it is the program's Esc; needs the kitty keyboard protocol or the GUI, elsewhere a plain Esc], [#keys("Ctrl-o", "Ctrl-i")], [jump history back, forward; this file first. #key("Ctrl-i") is #key("Tab") without the kitty protocol: #key("SPC j i")], [#key("Alt-n")], [new terminal below], diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index 40802ed9..0b721658 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -43,7 +43,7 @@ steps raw, normal, insert. [#mode-box(" ") normal], [#key("Esc"): back to the previous pane (#word("Last")), unlike helix. #key("Shift-Esc"): the same.], [#mode-box("^") insert], [#key("Esc"): back to normal. #key("Shift-Esc"): out of insert and back to the previous pane.], [#mode-box("$") raw], [#key("Esc"): back to the previous pane. #key("Shift-Esc"): an Esc to the program. Either way the terminal stays raw. #word("ProgramEsc") `on` swaps them back: #key("Esc") goes to the program, except at a shell prompt with nothing typed on it, and #key("Shift-Esc") always goes back.], - [a PDF], [#key("Esc"): clears the selection and the search highlights. #key("Shift-Esc"): back to the previous pane.], + [a PDF], [#key("Esc"): clears the selection and the search highlights, and with none shown goes back to the previous pane. #key("Shift-Esc"): back at once.], ) In acme, Esc selects the text typed since the last click; here it leaves diff --git a/src/normal.zig b/src/normal.zig index f214121a..25e2deec 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -1016,6 +1016,8 @@ pub fn handlePdfNormal(p: *Pardes, pane: *Pane, key: Key) void { if (result.page_changed) panes.Pdf.resetPageChrome(pane); switch (result.host) { .none => {}, + // typed again by a macro, Esc is only the page's + .last => if (p.macro.replaying == 0) exec.runBuiltin(p, .Last, p.active, "", null), .leader => { p.leader_on = true; p.leader_n = 0; diff --git a/src/pdf_view.zig b/src/pdf_view.zig index 4ddbf299..b2b9c5a3 100644 --- a/src/pdf_view.zig +++ b/src/pdf_view.zig @@ -906,12 +906,15 @@ pub const State = if (enabled) struct { if (page) |selected_page| state.invalidateRaster(selected_page); } - pub fn cancelChrome(state: *@This(), gpa: std.mem.Allocator) void { + /// Drops the selection and the search; true when there was one. + pub fn cancelChrome(state: *@This(), gpa: std.mem.Allocator) bool { + const had = state.selection != null or state.search_query.len > 0; state.clearDrag(); state.clearSelection(gpa); - if (state.search_query.len == 0) return; + if (state.search_query.len == 0) return had; state.dropSearchQuery(gpa); state.invalidateRaster(state.page); + return had; } fn invalidatePage(state: *@This(), gpa: std.mem.Allocator) void { @@ -1230,6 +1233,7 @@ pub const ScrollResult = struct { active_page: usize }; pub const CellPixels = struct { w: u16, h: u16 }; pub const NormalHost = enum { none, + last, leader, command_line, search, @@ -2476,7 +2480,11 @@ pub fn applyNormal( if (comptime !enabled) return .{}; var result: NormalResult = .{}; switch (semantic) { - .escape => state.cancelChrome(gpa), + // Esc drops a selection or a search the page shows, else goes back + // a pane (text-only, the page shows neither). + .escape => if (!state.cancelChrome(gpa) or !native_images) { + result.host = .last; + }, .move => |move| switch (move.motion) { .down => result.page_changed = moveRows( state, diff --git a/test/pdf.zig b/test/pdf.zig index 3f84195c..a50f3bf6 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -1454,7 +1454,7 @@ test "PDF normal adapter consumes unsupported actions and navigates page fallbac try std.testing.expect(pane.prompt == .none); } -test "Escape cancels PDF chrome in place and Shift-Escape leaves the pane" { +test "Escape cancels PDF chrome in place, then leaves the pane; Shift-Escape leaves at once" { if (!pdf_enabled or platform == .web) return; const gpa = std.testing.allocator; @@ -1507,15 +1507,32 @@ test "Escape cancels PDF chrome in place and Shift-Escape leaves the pane" { try std.testing.expectEqual(scroll_before, pv.document_scroll_y); try std.testing.expectEqual(@as(u32, 0), pane.body.normal.count); try std.testing.expectEqual(.none, pane.body.normal.prefix); - // A second Escape on a bare document is inert rather than an exit. + // With nothing left to drop, Escape goes back a pane as anywhere else, + // and leaves the document as it found it. p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expectEqual(@as(usize, 0), p.active); - - // Shift-Escape is the way out, and it leaves the document as it found it. - p.update(.{ .key = .{ .cp = Key.escape, .shift = true } }); try std.testing.expectEqual(@as(usize, 1), p.active); try std.testing.expectEqual(page_before, pv.page); try std.testing.expectEqual(scroll_before, pv.document_scroll_y); + + // Shift-Escape goes at once, over a selection too. + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual( + panes.Pdf.SelectionUpdate.changed, + pv.setSelection(p.pdf_gpa, quad.ul, quad.lr, false), + ); + p.update(.{ .key = .{ .cp = Key.escape, .shift = true } }); + try std.testing.expectEqual(@as(usize, 1), p.active); + try std.testing.expect(pv.selection != null); + + // A text-only page shows neither: one Escape drops them and goes. + p.native_images = false; + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try pv.setSearchQuery(p.pdf_gpa, "Pardes"); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqual(@as(usize, 1), p.active); + try std.testing.expect(pv.selection == null and pv.search_query.len == 0); } test "PDF continuous strip renders every intersecting short page" { -- cgit v1.3 From 70de5ec5ff3dad01afcc45244ad5e5a481486da6 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 29 Oct 2026 17:01:35 -0300 Subject: dump: one walker dump of the whole session, by name across builds, for Restore, -l, Handover and the store; dump.zig's hand-written schema gone A dump is walk.zig's walk of the core with a table of every type it reaches (fields, enum and union names, number widths), read back by name; terminals are ghostty's snapshot (screens, history, kitty images); a failed load frees what it made. Co-Authored-By: Claude Opus 5.5 --- build.zig | 3 + build/snap.zig | 10 +- docs/typ/building.typ | 4 +- docs/typ/reference.typ | 35 +- src/File.zig | 387 --------------- src/Handover.zig | 112 +++-- src/Output.zig | 34 +- src/Pipe.zig | 4 + src/Query.zig | 9 +- src/Store.zig | 57 +-- src/builtins.zig | 2 +- src/dump.zig | 1176 +++++++++++----------------------------------- src/file_watch.zig | 57 +-- src/image.zig | 63 --- src/ninep/ctl.zig | 64 +-- src/ninep/events.zig | 24 +- src/panes.zig | 4 +- src/pardes.zig | 55 +-- src/pdf.zig | 4 +- src/pdf_view.zig | 14 + src/tagline.zig | 8 - src/tape.zig | 40 +- src/terminal.zig | 316 ++++++------- src/walk.zig | 1120 ++++++++++++++++++++++++++++++++++++++++++- test/fs.py | 5 +- test/fs_namespace.zig | 44 +- test/kitty.zig | 6 +- test/monkey.zig | 9 +- test/output.zig | 17 - test/panes.zig | 61 +-- test/pdf.zig | 39 -- test/snapshot.zig | 9 +- test/snapshots/dump.snap | 9 +- 33 files changed, 1851 insertions(+), 1950 deletions(-) (limited to 'docs/typ') diff --git a/build.zig b/build.zig index 1a5dd200..962b6322 100644 --- a/build.zig +++ b/build.zig @@ -1950,6 +1950,9 @@ pub fn build(b: *std.Build) void { run_shell_test.has_side_effects = true; unit_step.dependOn(&run_shell_test.step); if (unit_match) |check| check.addArtifactArg(shell_test); + // The native shell's tests alone, without the perf gate's + // ReleaseFast build: what a -Dtest-filter iteration wants. + b.step("shell-test", "run the native shell's unit tests (src/main.zig's)").dependOn(&run_shell_test.step); const run_profile = b.addRunArtifact(unit_profile); run_profile.addArtifactArg(shell_test); run_profile.addPassthruArgs(); diff --git a/build/snap.zig b/build/snap.zig index d74767d3..c1a26e64 100644 --- a/build/snap.zig +++ b/build/snap.zig @@ -69,19 +69,21 @@ pub fn addTty(b: *std.Build, opts: struct { // The replay-divergence gate (src/tape.zig, docs/next-daemon.md): every // snapshot script and `replay-seeds` monkey seeds with each session's // tape recorded, each replayed into two replicas at different - // addresses and one that never draws, every digest checked. + // addresses and one that never draws, every digest checked; and at each + // session's end its dump loaded, which must be that session, digest for + // digest, and dump again to the same bytes (phase 2). const tapes = ".zig-cache/tapes"; const run_replay = b.addRunArtifact(snap); run_replay.addArtifactArg(opts.exe); run_replay.addPrefixedFileArg("--lspmock=", lspmock.getEmittedBin()); - run_replay.addArg("--tape=" ++ tapes); + run_replay.addArgs(&.{ "--tape=" ++ tapes, "--dump" }); run_replay.setCwd(b.path(".")); run_replay.has_side_effects = true; const seeds = b.option(u32, "replay-seeds", "monkey seeds `zig build replay` records and replays (default 20)") orelse 20; const run_monkey_replay = b.addRunArtifact(monkey); run_monkey_replay.addArtifactArg(snap); run_monkey_replay.addArtifactArg(opts.exe); - run_monkey_replay.addArgs(&.{ b.fmt("{d}", .{seeds}), "70", "--tape=" ++ tapes ++ "/monkey", "--out=" ++ tapes ++ "/monkey" }); + run_monkey_replay.addArgs(&.{ b.fmt("{d}", .{seeds}), "70", "--tape=" ++ tapes ++ "/monkey", "--dump", "--out=" ++ tapes ++ "/monkey" }); run_monkey_replay.setCwd(b.path(".")); run_monkey_replay.has_side_effects = true; // One pardes-snap run at a time (its lock): the scripts, then the seeds. @@ -95,7 +97,7 @@ pub fn addTty(b: *std.Build, opts: struct { run_views_replay.setCwd(b.path(".")); run_views_replay.has_side_effects = true; run_views_replay.step.dependOn(&run_monkey_replay.step); - b.step("replay", "record every snapshot script's and -Dreplay-seeds monkey seeds' tapes (one terminal and three) and require each to replay without diverging").dependOn(&run_views_replay.step); + b.step("replay", "record every snapshot script's and -Dreplay-seeds monkey seeds' tapes (one terminal and three) and require each to replay without diverging, and each session's dump to load to its digest").dependOn(&run_views_replay.step); const monkey_tests = b.addTest(.{ .root_module = monkey.root_module }); b.step("monkey-test", "test the monkey's generator and panic detector").dependOn(&b.addRunArtifact(monkey_tests).step); const run_driver_test = b.addRunArtifact(snap); diff --git a/docs/typ/building.typ b/docs/typ/building.typ index 00088d7b..e42702c6 100644 --- a/docs/typ/building.typ +++ b/docs/typ/building.typ @@ -19,7 +19,7 @@ builds MuPDF and is on by default (`-Dmupdf=false` drops it). 9P over QUIC [`zig build`], [the terminal shell and the SDL window together, *installed into `~/.local/bin`* (`pardes`, `pardes-gui`, and `pardes-v9fs`, the #word("Tty9p") helper)], [`zig build -Dplatform=tty`], [the terminal shell alone], [`zig build -Dplatform=gui`], [the SDL3 window alone], - [`zig build web -Dplatform=web -Dtarget=wasm32-freestanding -Ddump=`], [a freestanding wasm core plus vanilla JavaScript (`docs/web.md`)], + [`zig build web -Dplatform=web -Dtarget=wasm32-freestanding -Ddump=`], [a freestanding wasm core plus vanilla JavaScript (`docs/web.md`)], [`zig build -Dplatform=macos`], [an AppKit and CoreText app over a static `libpardes.a` (`docs/macos.md`)], [`zig build -Dplatform=esp32p4`], [a freestanding riscv32 editor object for the ESP32-P4, with a 384 KiB heap], ) @@ -59,7 +59,7 @@ there; its namespace is in `src/esp32p4_gpio.zig`. [`-Dprebuilt-shaders`], [bool: embed the committed SPIR-V; on for a bare `zig build`, off with `-Dplatform`; `zig build shaders` refreshes it with glslc], [`-Dtracy`], [path to a Tracy checkout; off], [`-Dmacos-identity`], [codesigning identity for `pardes.app`; `-` (ad hoc)], - [`-Ddump`], [a `dump.zon` to embed in the web shell], + [`-Ddump`], [a Dump to embed in the web shell], [`-Dtest-filter`], [run only tests whose name contains it; a filter that matches nothing fails], [`-Dtest-rebuild`], [bool: fresh Zig test compilation], [`-Dhelix-harness`], [reference executable for live differential tests; `HX_HARNESS`, else `hx-harness` on `PATH`], diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index ce2a45f1..2e395cc6 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -368,22 +368,20 @@ Writes take settings and session builtins (`scope = .session` in #word("Delcol") and a pane's `get` refuse the same way with their own word, except that #word("Delcol") opens no `+Unsaved` pane: it names the panes only in its `unsaved` records and its notice. -- #word("Dump") writes `pardes--