This is an automated email from the git hooks/post-receive script.
git pushed a commit to branch tymux-12-session-parity
in repository terminology.
View the commit online.
commit 3ff9024c04fffbd964af1b00064847796654bc31
Author: Cedric BAIL <[email protected]>
AuthorDate: Mon Nov 23 19:36:25 2026 -0600
docs: describe the tymux architecture
The design of tymux is spread across the daemon, the native client,
the inline proxy and the wire protocol. Give readers one place that
shows how they fit together, with component and flow diagrams, and
what each path does and does not guarantee.
---
docs/tymux-architecture.md | 910 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 910 insertions(+)
diff --git a/docs/tymux-architecture.md b/docs/tymux-architecture.md
new file mode 100644
index 00000000..f9225e97
--- /dev/null
+++ b/docs/tymux-architecture.md
@@ -0,0 +1,910 @@
+# tymux architecture and design
+
+This document describes tymux as implemented at the tip of the
+`tymux-12-session-parity` branch. `tymux-11-parser-speedup` only speeds up the
+escape parser, and changes nothing described here.
+
+For command line usage, see `man/tymux.1`.
+
+## 1. What tymux is
+
+tymux keeps a shell running after its terminal goes away. Each named session
+is one `tymuxd` process that owns a real pty and runs Terminology's terminal
+emulation headless. Any number of terminals can attach to it, detach, and
+come back later.
+
+Three design choices set it apart from a classic multiplexer:
+
+* **One daemon per session.** A crash or a hang stays inside one session, and
+ there is no server state shared between sessions.
+* **The screen and the scrollback travel through shared memory.** The socket
+ only carries small control messages. A client maps the cells rather than
+ receiving them as a re-encoded escape stream.
+* **A native client inside Terminology.** A Terminology terminal attached to a
+ session renders it through the normal `termio` path, so scrolling,
+ selection, search and the miniview work as they do on a local shell.
+
+### Goals and non-goals
+
+| Goals | Non-goals |
+|---|---|
+| Sessions survive the terminal, the window and Terminology itself | Surviving a reboot or a `tymuxd` crash, as nothing is persisted |
+| Hijack, shared and read-only attachment | Panes, windows or layouts inside a session |
+| Scrollback that costs little memory, even with many idle terminals | Attaching over the network |
+| A slow client can never stall the shell or other clients | Platforms other than Linux, because the design needs memfd and sealing |
+
+## 2. Component overview
+
+```mermaid
+flowchart TB
+ subgraph user["User-facing clients"]
+ direction LR
+ cli["<b>tymux</b><br/>CLI and inline proxy<br/><i>tymux.c</i>"]
+ subgraph term["<b>terminology</b> process"]
+ direction TB
+ win["win.c<br/>tabs, titles, pause and<br/>session indicators"]
+ termio["termio.c<br/>widget, input, hand-off,<br/>session lifecycle"]
+ client["termtymux.c<br/>native client"]
+ shadow["shadow Termpty<br/>no fd, no child"]
+ cview["BacklogView<br/>remote source"]
+ win --- termio
+ termio --> client
+ client --> shadow
+ client --> cview
+ cview --> shadow
+ end
+ end
+
+ proto["<b>termsrv.c / termsrv.h</b><br/>wire protocol, seqlock, socket paths,<br/>daemon spawning, detach chord, command routes"]
+ tbl["<b>termsrv_table.c</b><br/>session table: links and blocks<br/>single writer, seqlock per slot"]
+
+ subgraph daemon["<b>tymuxd</b> process, one per session"]
+ direction TB
+ main["tymuxd.c<br/>listen socket, signals, fd budget"]
+ td["termd_tymux.c<br/>clients, roles, frames, page requests"]
+ pty["Termpty<br/>parser and screen state"]
+ blocks["termptyblock.c<br/>parses the media block commands"]
+ store["BacklogStore (MEMFD)<br/>pages, compression"]
+ dview["BacklogView<br/>head only"]
+ stubs["tymuxd_stubs.c<br/>stands in for termio and palette"]
+ main --> td
+ td --> pty
+ pty --> blocks
+ pty --> store
+ pty --> dview
+ dview --> store
+ pty -.-> stubs
+ end
+
+ shell["shell and its programs"]
+ screen[("screen memfd, with the session table<br/>read-only for clients")]
+ pages[("backlog page memfds<br/>read-only for clients")]
+
+ cli -. uses .-> proto
+ client -. uses .-> proto
+ td -. uses .-> proto
+ cli <-->|unix socket| td
+ client <-->|unix socket| td
+ td -->|writes frames and the table| screen
+ td -. uses .-> tbl
+ client -. reads .-> tbl
+ screen -->|mmap| cli
+ screen -->|mmap| client
+ store --- pages
+ pages -->|mmap| cview
+ pty <-->|pty master| shell
+```
+
+### Source map
+
+| File | Responsibility | Built into |
+|---|---|---|
+| `tymux.c` | `new`, `attach`, `list`, `kill`, and the inline proxy | `tymux` |
+| `tymuxd.c` | Daemon entry point, socket, signals | `tymuxd` |
+| `termd_tymux.c` | Session: client roles, frame publication, page serving, command routing, tysend transfers | `tymuxd` |
+| `tymuxd_stubs.c` | Replaces the widget functions the parser calls | `tymuxd` |
+| `termsrv.[ch]` | Protocol, shared memory layout, daemon spawn, command routes | all three |
+| `termsrv_table.[ch]` | Session table in shared memory: writer, validating reader | `tymuxd`, `terminology`, `tytest` |
+| `termptyblock.c` | Parses the media block commands (`is ic if it ij ib ie`) for a `Termpty` | `terminology`, `tymuxd`, `tytest` |
+| `termtymux.[ch]` | Native client and shadow pty | `terminology`, `tytest` |
+| `backlog_store.[ch]` | Paged scrollback, compression, rebuild, restore | `terminology`, `tymuxd`, `tytest` |
+| `backlog_view.[ch]` | Ring entries over pages, retention policy | `terminology`, `tymuxd`, `tytest` |
+| `backlog_window.h` | Which pages stay mapped around the viewport | same as view |
+| `backlog_compress.[ch]` | zlib through Emile, thread safe | same as store |
+| `tybenchd.c`, `tytest_tymux.c` | Throughput benchmark, live daemon tests | tools |
+
+`tymux` links only Eina and Ecore, so it stays small and runs without a
+display. `tymuxd` reuses the real `termpty*` parser, which guarantees that a
+session emulates exactly what a local terminal does.
+
+### How the series built it
+
+The branches form one linear stack. Each one adds a layer:
+
+| Branch | Adds |
+|---|---|
+| `tymux-02-daemon-cli` | `tymuxd`, the protocol, the `tymux` CLI and inline proxy |
+| `tymux-03-native-client` | `termtymux`: shadow pty and the `ESC } at` hand-off |
+| `tymux-04-scrollback` | Session scrollback available to native clients |
+| `tymux-05-newtab-pause` | `--new-tab` and the paused overlay |
+| `tymux-06-lifecycle` | The terminal survives leaving a session |
+| `tymux-07-indicator` | Session name in titles and a visual indicator |
+| `tymux-08-backlog-compression` | Pages in memfds, compressed when idle |
+| `tymux-09-unified-scrollback` | Local terminals and `tymuxd` share `BacklogStore` and `BacklogView` |
+| `tymux-10-quiet-head` | Quiet, unfocused terminals compress their head page too |
+| `tymux-11-parser-speedup` | A faster escape parser, with no change in behavior |
+| `tymux-12-session-parity` | A session behaves like a local terminal: links, blocks and commands, `tysend`, a safe hand-off, inline proxy modes |
+
+## 3. Process and memory model
+
+```mermaid
+flowchart LR
+ subgraph D["tymuxd address space"]
+ DS["screen mapping<br/>read-write"]
+ DH["head page mapping<br/>read-write"]
+ DB["compressed blobs<br/>heap"]
+ DL["termd_tymux<br/>main loop"]
+ end
+ subgraph K["kernel objects"]
+ SFD[("screen memfd<br/>sealed")]
+ PFD[("page memfds<br/>sealed")]
+ SOCK{{"unix socket<br/>$XDG_RUNTIME_DIR/terminology/tymux/NAME.sock"}}
+ end
+ subgraph C["client address space"]
+ CS["screen mapping<br/>read-only"]
+ CP["mapped pages near viewport<br/>read-only"]
+ CF["shadow screen<br/>private copy"]
+ CL["termtymux<br/>main loop"]
+ end
+ DS --- SFD
+ DH --- PFD
+ SFD -. "read-only fd via SCM_RIGHTS" .-> CS
+ PFD -. "read-only fd via SCM_RIGHTS" .-> CP
+ CS -->|seqlock copy| CF
+ DL <-->|control messages| SOCK
+ SOCK <-->|control messages| CL
+```
+
+### Screen memory
+
+The screen memfd holds a 4 KiB `TermSrvShmHeader` and a grid of
+`TermSrvCell`, row 0 first. It is sized once for the maximum of 1920 by 1280
+cells, about 37.5 MiB of address space. Only the cells of the current size
+are ever touched, so the rest never becomes resident, and a resize needs no
+new mapping.
+
+`TermSrvCell` is a bit-exact mirror of `Termcell`, so the daemon can `memcpy`
+rows. A `_Static_assert` checks the size at build time, and
+`tytest_termsrv_cell_layout` checks the bit layout.
+
+**Consistency uses a seqlock.** `write_seq` is odd while the daemon writes a
+frame and even once it is complete. A reader copies the frame, then rereads
+`write_seq`, and retries up to 100 times if it changed. The daemon never
+waits for a reader, so a stopped client cannot block it.
+
+### Backlog pages
+
+A page is a sparse memfd: a header with the entry offsets and widths, then
+the cells of its logical lines packed with no gap.
+
+* A store with a scrollback of *N* lines uses pages of *N*/16 entries, rounded
+ up to a power of two between 64 and 4096.
+* A page is sealed once it holds that many entries or 1 Mi cells. The last
+ page is the **head**, and it is the only one still written to.
+* Page ids are consecutive and never reused, even across a terminal reset, so
+ an id cannot mean two different pages to a client.
+* Clients follow the head without a lock. Cells are written before the width
+ that covers them, and an entry's offset and width before `num_entries`
+ counts it, with release/acquire ordering.
+
+### Session table
+
+Hyperlink targets and media block definitions are state, not events, so they
+too are published in shared memory, in the screen memfd after the cells (the
+version of the layout, `TERMSRV_SHM_VERSION`, is 2, so a client of another
+version gets the clear version error). The memfd stays sparse.
+
+```
+[ header 4 KiB ][ cells ][ link slots ][ block slots ][ arena ]
+```
+
+* One slot per id: 65536 link slots and 8192 block slots. A slot holds a
+ per-slot seqlock, a generation that changes whenever the id gets a new
+ meaning, the offset and length of its record in the arena, and `valid_from`,
+ the `write_seq` of the first frame that can use this meaning of the id.
+* The arena is 64 MiB of address space, and a record is at most 1 MiB. The
+ daemon, the only writer, allocates from it with a buddy allocator, and
+ reuses freed blocks, as a sealed memfd cannot give them back.
+* A link record is its OSC 8 `id` key and its URL. A block record is its size,
+ scale flags, path, link, channel and initial commands.
+* The table is written before the frame that uses it.
+
+A shadow pty reads lazily: it resolves an id when a cell first uses it, and
+again when the generation changed. The reader treats the table as untrusted:
+it copies a record under the slot's seqlock and checks the offset and length
+against the arena. A client takes an id for no link and no block while the
+slot's `valid_from` is newer than the frame it shows, as the daemon reuses an
+id at once and an older frame would otherwise show a new URL. Entries of pages
+below the daemon's first page resolve to nothing too. A record the arena cannot
+take is logged once, and its link or media stays inert on clients. A reattach
+needs no snapshot: a late client reads what it needs.
+
+## 4. Wire protocol
+
+Each message is a `TermSrvMsgHdr` (`type`, `size`) followed by at most 64 KiB
+of payload. File descriptors travel as `SCM_RIGHTS` on the first byte of
+their message.
+
+| Message | Direction | Payload | Purpose |
+|---|---|---|---|
+| `ATTACH` (1) | C → D | mode byte | Join as hijack, shared or read-only |
+| `ATTACHED` (2) | D → C | size, shell pid, page range, **screen fd** | Handshake reply |
+| `DETACH` (3) | C → D | none | Leave the session |
+| `INPUT` (4) | C → D | bytes | Write to the pty |
+| `RESIZE` (5) | C → D | cols, rows | Honored from the primary only |
+| `NOTIFY` (6) | D → C | `write_seq`, input modes, page range | A new frame is ready |
+| `TITLE` (7) | D → C | string | Title changed |
+| `BELL` (8) | D → C | none | Bell |
+| `EXIT` (9) | D → C | exit code | The session ended |
+| `PAUSE` (10) | D → C | none | Another client took over |
+| `RESUME` (11) | D → C | none | Control came back |
+| `BACKLOG_PAGE_REQ` (14) | C → D | page id | Ask for a page |
+| `BACKLOG_PAGE` (15) | D → C | page id, **page fd** or none | Reply. No fd means it cannot be served |
+| `BACKLOG_PAGE_RELEASE` (16) | C → D | page id | Done with a page |
+| `BACKLOG_MAP_REQ` (17) | C → D | first id, count | Ask for entry widths |
+| `BACKLOG_MAP` (18) | D → C | widths per page | Lets a client lay out pages it has not mapped |
+| `COMMAND` (19) | D → C | `more` flag, command bytes | A Terminology escape to apply, in fragments of 64 KiB or less, all but the last with `more` |
+| `CLIENT_INFO` (20) | C → D | cell size in pixels | The client applies commands: it is native, and its cell size is the one `qs` reports |
+| `ACTION` (21) | D → C | one byte | Whether the client now is the action client, sent when that changes |
+| `TRANSFER_REPLY` (22) | C → D | `k\n` or `n\n` | The answer to a packet of a `tysend` transfer. Written to the pty only for the client that receives the transfer |
+| `TRANSFER_LOST` (23) | D → C | none | The transfer the client receives is lost: drop what it has |
+| `TRANSFER_LOST_ACK` (24) | C → D | none | The loss was handled, in any role. A reply sent before it answers nothing |
+| `BLOCK_EVENT` (25) | C → D | bytes | What a block reports to the application. Written to the pty only under the rules of section 5.8 |
+
+Types 12 and 13 are retired. They streamed the backlog before pages existed.
+Message types 1 to 18 are unchanged: the screen memfd layout is version 2, as
+the table follows the cells, and `ATTACH` itself did not change.
+
+`NOTIFY` carries the input modes (application cursor, mouse, bracketed paste,
+focus reporting) because the native client encodes keys and mouse events
+locally and must match what the application asked for.
+
+## 5. Key flows
+
+### 5.1 Starting and attaching
+
+`tymux` picks between handing the session to Terminology and proxying it:
+
+```mermaid
+flowchart TD
+ A["tymux new NAME<br/>or tymux attach NAME"] --> B{"new: already running?"}
+ B -- yes --> B1["error: use attach"]
+ B -- "no" --> B2["termsrv_daemon_spawn<br/>double fork, setsid, exec tymuxd"]
+ B2 --> C
+ A -- attach --> C{"socket connects?"}
+ C -- no --> C1["error: no such session"]
+ C -- yes --> D{"TERMINOLOGY_HANDOFF set, stdin and stdout<br/>are ttys, TMUX, STY, TYMUX_NO_NATIVE unset?"}
+ D -- yes --> E["raw mode, then write<br/>ESC } at[n][s|r];TOKEN;NONCE;NAME NUL<br/>and wait up to 1 s for the reply"]
+ E --> R{"reply?"}
+ R -- "ok" --> F{"--new-tab?"}
+ R -- "err" --> RE["report the error, exit 1"]
+ R -- "none in time" --> RN{"--new-tab?"}
+ RN -- yes --> RNE["report the error, exit 1"]
+ RN -- no --> J
+ F -- no --> G["tymux sends the commit,<br/>Terminology swaps this terminal's pty<br/>for a shadow pty, the old shell gets SIGHUP"]
+ F -- yes --> H["Terminology opens a new tab<br/>on the session, no commit"]
+ D -- no --> I{"--new-tab?"}
+ I -- yes --> I1["error: only works inside Terminology"]
+ I -- no --> J["inline proxy<br/>raw mode, redraw by diffing the screen"]
+```
+
+The escape carries `TOKEN`, the 128-bit secret (32 hex digits) that
+Terminology gives each local terminal and exports to its shell as
+`TERMINOLOGY_HANDOFF`, and `NONCE`, 8 hex digits chosen by `tymux`. Terminology
+compares the token in constant time, and ignores any other form: bytes that are
+merely displayed, such as a `cat` of a file or an ssh message of the day, hold
+no token and cannot hand the terminal off. `tymuxd` removes the variable before
+it starts the shell, so a session never inherits a token and `tymux` run in
+a session uses the inline proxy. A nonce is honored once.
+
+The hand-off runs from an `ecore_job`, because the escape is parsed deep inside
+the pty read path, and replacing the pty there would free it under its caller.
+Closing a pty master discards what its reader has not read yet, so Terminology
+keeps the old pty after it answers, and swaps on the commit of `tymux`, or
+after 250 ms without one.
+
+```mermaid
+sequenceDiagram
+ autonumber
+ participant S as tymux in the local shell
+ participant T as termio
+ participant C as termtymux
+ participant D as tymuxd
+ S->>S: raw mode
+ S->>T: ESC } at, TOKEN, NONCE, NAME
+ T->>T: check token and nonce, schedule ecore_job
+ T->>C: termtymux_new(NAME, mode)
+ C->>D: connect, ATTACH(mode)
+ D-->>C: ATTACHED + screen fd
+ D->>D: if hijack, pause the previous primary
+ C->>C: mmap, check magic and version
+ C->>C: build shadow pty, BacklogView, write hook
+ C-->>T: TermTymux + shadow pty
+ T-->>S: ESC } ta, NONCE, ok
+ S->>T: ESC } atc, TOKEN, NONCE
+ T->>T: swap the pty, SIGHUP to the old shell
+ T->>C: commands start, CLIENT_INFO
+ C->>D: CLIENT_INFO
+ T->>C: termtymux_resize(grid)
+ C->>D: RESIZE
+ D-->>C: NOTIFY
+ C->>C: copy frame, render
+```
+
+If `termtymux_new()` fails, the reply is `err` and the terminal is left as it
+was. A new tab hand-off gets the same reply and no commit, as nothing is
+replaced.
+
+The same `ESC } at` family is also what the old `at[on/true/yes...]` alpha
+command looks like: only an argument with a `;` is taken for a hand-off, and
+anything malformed falls through to the alpha handling.
+
+### 5.2 Output: from the shell to the screen
+
+```mermaid
+sequenceDiagram
+ autonumber
+ participant P as Shell
+ participant Y as Termpty (daemon)
+ participant TD as termd_tymux
+ participant M as Screen memfd
+ participant C as termtymux
+ participant R as termio render
+ P->>Y: bytes on the pty
+ Y->>Y: parse, update screen and backlog
+ Y->>TD: cb.change
+ alt mode 2026 synchronized update active
+ TD->>TD: wait for its end
+ else
+ TD->>TD: arm one animator tick
+ end
+ Note over TD: Several reads collapse into one frame
+ TD->>M: write_seq odd, copy cells, write_seq even
+ TD-->>C: NOTIFY(seq, modes, page range)
+ C->>C: update backlog range and sync
+ C->>M: seqlock read
+ C->>C: apply to shadow screen and modes
+ C->>R: cb.change
+```
+
+A client that is slow only ever skips frames, since each `NOTIFY` says "read
+the latest". If its output queue passes 1 MiB, the daemon drops it rather than
+buffering without limit.
+
+### 5.3 Input: from the keyboard to the shell
+
+The native client reuses `termio`'s key encoding, and intercepts the result
+with the pty's **write hook**:
+
+```mermaid
+flowchart TD
+ K["key, mouse or paste in termio"] --> W["termpty_write on the shadow pty"]
+ W --> H["_write_hook"]
+ H --> P{"paste?"}
+ P -- yes --> P1["flush a held Ctrl+b,<br/>never scan the pasted bytes"]
+ P -- no --> F{"Ctrl+b d complete?"}
+ F -- yes --> DET["drop pending input, send DETACH"]
+ F -- no --> Q
+ P1 --> Q{"paused by a hijack?"}
+ Q -- yes --> DROP["drop the input"]
+ Q -- no --> SPLIT["split in chunks of 64 KiB or less"]
+ SPLIT --> SEND["send INPUT"]
+ SEND --> ROLE{"daemon: role?"}
+ ROLE -- "primary or shared" --> PTY["termpty_write on the real pty"]
+ ROLE -- "read-only or paused" --> IGN["ignored"]
+```
+
+A paste can never detach, because only a real key press can complete the
+chord. The daemon checks the role again, so a client cannot bypass read-only
+mode by sending `INPUT` anyway.
+
+### 5.4 Client roles
+
+```mermaid
+stateDiagram-v2
+ [*] --> Pending: accept
+ Pending --> Primary: ATTACH hijack
+ Pending --> Shared: ATTACH shared
+ Pending --> ReadOnly: ATTACH read-only
+ Pending --> [*]: invalid ATTACH
+ Primary --> Paused: another client hijacks / PAUSE
+ Paused --> Primary: primary left, most recent paused first / RESUME
+ Primary --> [*]: detach or dropped
+ Paused --> [*]: detach or dropped
+ Shared --> [*]: detach or dropped
+ ReadOnly --> [*]: detach or dropped
+```
+
+| Role | Sees frames | Sends input | Resizes |
+|---|---|---|---|
+| Primary | yes | yes | yes |
+| Shared | yes | yes | no |
+| Read-only | yes | no | no |
+| Paused | yes | no | no |
+
+Paused clients form a stack, so nested hijacks unwind in order.
+
+**The action client.** The commands of section 5.7 that act on the user's
+screen, such as a popup or the background, and the files of `tysend`, need one
+terminal to answer. It is the native primary, or else the oldest native shared
+client: a read-only or paused client never acts, and neither does a client of
+the inline proxy, which is not native. The daemon sends `ACTION` to a client
+when that changes, which happens at a `CLIENT_INFO`, a role change or a
+departure. A native client sends `CLIENT_INFO` once it is ready to apply
+commands, which for a hand-off is at the swap: what it missed, the edje
+channels, it is then told once.
+
+A terminal resumed after a hijack sends its grid size again, as the inline
+proxy does, so the session does not keep the size of a hijacker that left.
+
+### 5.5 Leaving a session
+
+```mermaid
+flowchart TD
+ A{"Why did the mirror end?"}
+ A -- "Ctrl+b d, daemon gone,<br/>or socket failure" --> D["END_DETACHED"]
+ A -- "EXIT message:<br/>shell exited or tymux kill" --> E["END_EXITED"]
+ D --> L["_termio_tymux_leave:<br/>new local shell in the same terminal"]
+ E --> S{"switched in from a local shell?"}
+ S -- yes --> L2["new local shell<br/>in the original directory"]
+ S -- "no: --tymux or new tab" --> X["close the terminal"]
+```
+
+On `SIGTERM`, `tymuxd` broadcasts `EXIT` before quitting. Without it, clients
+would see a plain end of file and mistake the kill for a detach.
+
+### 5.6 Scrolling back through a session
+
+```mermaid
+sequenceDiagram
+ autonumber
+ participant U as User
+ participant V as BacklogView (client)
+ participant C as termtymux
+ participant TD as termd_tymux
+ participant B as BacklogStore
+ U->>V: scroll, viewport_set
+ V->>C: map_request(range)
+ C->>TD: BACKLOG_MAP_REQ
+ TD-->>C: BACKLOG_MAP (widths)
+ C->>V: map_set, sync ring entries
+ V->>C: page_request(id)
+ C->>TD: BACKLOG_PAGE_REQ
+ TD->>TD: take a hold on the page
+ TD->>B: page_fd_async(id)
+ alt page is raw
+ B-->>TD: memfd now
+ else page is compressed
+ B->>B: rebuild on a thread
+ B-->>TD: memfd when done
+ end
+ TD-->>C: BACKLOG_PAGE + read-only fd
+ C->>C: validate header and seals, mmap
+ C->>V: page_set, entries point at real cells
+ V->>V: idler releases pages out of the window
+ V->>C: page_release(old id)
+ C->>TD: BACKLOG_PAGE_RELEASE
+```
+
+Replies keep their request order: only a client's oldest request waits on the
+store. Until its page arrives, an entry points at a shared blank, so scrolling
+never blocks on the daemon.
+
+### 5.7 Terminology's escapes in a session
+
+A shell run by `tymuxd` has no widget, so the daemon applies what it can and
+routes the rest. `termsrv_command_route()` decides, from the first two bytes of
+a command:
+
+| Commands | Handled by |
+|---|---|
+| `is ic if it ij ib ie` (media blocks) | the daemon, which also writes the cells the parser needs |
+| `qs` (grid size query) | the daemon, whatever `ty_escapes` says |
+| `iC ix qj` (edje channels) | every native client |
+| `pn pq` popups, `bt bp` background, `at ap` alpha | the action client |
+| `fr fs fd fx` (`tysend`) | the action client, see 5.9 |
+| a hand-off (`at` with a `;`, `atc`) | nobody: dropped |
+| anything else | dropped |
+
+A command reaches a client as `COMMAND`. A client applies it only if its own
+`ty_escapes` is on, and with it off it shows no media. A command that does not
+fit the queue of a client whole is skipped for that client rather than cut: the
+queue keeps room for the messages that must not be lost, such as `NOTIFY`.
+
+`qs` is answered by the daemon, because `tycat` and `tyls` wait for it with no
+timeout and a session can have no native client. It reports the session's grid
+and the cell size last announced by a native client, or 8 by 16 if none did.
+
+The channels the application listens on are kept by the daemon's real pty, as
+by any local pty (`qj+` adds one, `qj-NAME` removes one, `qj` forgets them
+all), at most 256 of at most 255 bytes. The subscription `qj+` carries a token
+and a nonce, which the daemon checks and never passes on (see 5.8): the clients
+are sent `qj+NAME` alone. A native client that attaches later is told the
+channels once, in that form, as it did not see the commands. Media blocks come
+from the session table, with the commands that define them, so a reattach shows
+them again. A block replayed from its stored commands starts as it was defined,
+not as it was left by the commands sent afterwards.
+
+### 5.8 Events of the blocks
+
+An edje block reports its signals and messages to the application by writing a
+line to the terminal input. That line must not be an `INPUT` of the session:
+the output of any program can define a block with a channel and an `emit`
+command, and the client that displays it would answer by typing into the
+shell, and the shell would run what it read. The same holds for a plain local
+terminal, so both use the same code: `termpty_channels_command()` for the
+subscriptions, and `termpty_event_write()` as the only way an event gets to the
+application.
+
+A program subscribes with `ESC } qj+TOKEN;NONCE;CHID NUL`:
+
+* `TOKEN` is the 32 hex digits of `event_token`, which `termpty_new()` draws
+ at random for each pty and exports to its child as
+ `TERMINOLOGY_EVENT_TOKEN`, replacing what was inherited. It is not the
+ `handoff_token`, which `tymuxd` turns off: one leaking grants nothing of the
+ other. It is compared in constant time. If no randomness was available the
+ token is empty and no subscription succeeds.
+* `NONCE` is 8 lowercase hex digits, used once, in a per-pty ring of 32 (the
+ hand-off has a ring of its own, of the same type).
+* `CHID` is the rest. The old `qj+CHID`, and a subscription with a wrong or
+ missing token or a malformed or used nonce, are ignored without an answer.
+ `qj-CHID` and `qj` only remove subscriptions and need nothing.
+* The subscription records the foreground process group of the pty. It is
+ refused if that group is unknown or is the group of the pty's own shell, so
+ no new event is written for a subscriber once its group has left the
+ foreground, though bytes it left unread can still reach the shell's input.
+ The group is read when the pty's output is parsed, not when the
+ program wrote it: a program that exits right after printing the escape may
+ be taken for the shell and refused, so it stays a moment.
+
+```mermaid
+sequenceDiagram
+ autonumber
+ participant P as Program with a block
+ participant D as tymuxd
+ participant A as action client
+ participant O as other clients
+ P->>D: qj+TOKEN;NONCE;CHAN, then the block
+ D->>D: token, nonce, foreground group not the shell's: keep CHAN with the group
+ D-->>A: COMMAND qj+CHAN and the block
+ D-->>O: COMMAND qj+CHAN and the block
+ A->>A: shadow pty keeps CHAN, apply the block, then listen
+ Note over A: the signals the stored commands queued are drained before the listener exists
+ A->>D: BLOCK_EVENT
+ D->>D: acts, and the foreground group holds a subscription?
+ alt both
+ D->>P: bytes written to the pty
+ else not
+ D->>D: dropped
+ end
+ Note over O: other clients do not listen, so they send nothing
+```
+
+* The events travel in `BLOCK_EVENT`, as one message of `CHID`, a NUL and the
+ event, whole (at most 8192 bytes for the event, bigger ones are dropped on
+ both sides, and an event is never split). The daemon checks the framing and
+ the channel, then calls `termpty_event_write()` on its own pty for the action
+ client: one gate for a local pty and a session. The gate is the pair of the
+ channel and the foreground group: it writes only if that group subscribed to
+ that channel. On a shadow pty the same function hands the message to the
+ write hook of the client.
+* What reaches the pty is not the event but one line, ` A #tyevent:HEX.` (a
+ space, `A` and a space first), where `HEX` is the lowercase hexadecimal of
+ the event (`ESC } ...`, without its NUL), written in that one place and
+ nowhere else. It holds no control character and no line terminator. A
+ program that subscribed and exits before it reads leaves the line in the tty
+ queue, where it can reach the input of the shell. In vi command mode with no
+ command pending, the leading ` A ` appends them at the end of the line, which
+ stays whole. In vi insert or replace mode, as in emacs mode, they land at the
+ cursor; there, or when they complete a pending vi command, they can change or
+ overwrite text, split a word or comment out the rest of the line. Check any
+ line that received one before pressing Enter. A line editor or a canonical
+ read runs nothing until Enter, but a program that reads single keys or up to
+ a delimiter of its own (`read -n 1`, `read -d .`) can be satisfied by an
+ event. Events follow one another with nothing between them, so a reader
+ splits on `.`. A reader in canonical mode gets lines cut at 4096 bytes.
+* The daemon authenticates against its real pty. Only the normalized
+ `qj+CHID` goes to the clients, and `_chids_replay()` sends that same form:
+ the token never reaches a client, a shared viewer, the session table or a
+ log. A client keeps it in its shadow pty, which has no token and no
+ process group, with the same API.
+* A terminal that attaches, or a block that is shown again after a reattach,
+ reports nothing for the commands it replays: the listener is set up after
+ the stored commands were applied and Edje's signal queue was drained.
+* The guarantee is this: displayed output cannot make an event run as a
+ command, as no event is one and none carries a line terminator of its own;
+ at a shell prompt it runs nothing until the user presses Enter, but it can
+ alter the line that Enter then runs. A program reading single keys or up to
+ its own delimiter can be satisfied by it. A shell function cannot receive
+ the events either. A program that did subscribe receives the events of what
+ it displays, including what hostile output made it display, and is
+ responsible for them. A program on the other side of ssh does not get the
+ token, unless the user forwards it with `SendEnv` and `AcceptEnv`, so it
+ cannot subscribe. A program of the user that holds the token can subscribe
+ the program that is then in the foreground, which then receives only the
+ encoded lines.
+* The channels of a group that is gone (`kill(-pgrp, 0)` fails with `ESRCH`)
+ are forgotten at the next subscription, so dead subscribers cannot exhaust
+ the 256 channels, and the daemon tells the clients (`qj-NAME`) of the names
+ that no group holds any more, so their lists stay the same as its own. The
+ shadow list holds a name once. `qj-NAME` takes away the channel of the
+ foreground group, or all of that name if that group cannot be read, and the
+ clients are told only when no group holds it any more. A reused group id can
+ still receive encoded lines.
+* The hand-off and the subscriptions keep their nonces apart, 32 of each, so
+ that one cannot make the other forget.
+
+### 5.9 `tysend` in a session
+
+`tysend` sends a file to the terminal it runs in, and waits with no timeout
+for the answer to its `fs` and to each `fd`. In a session the daemon routes the
+transfer to the action client, which saves the file on its own disk after the
+usual approval, and relays the answers.
+
+```mermaid
+sequenceDiagram
+ autonumber
+ participant T as tysend
+ participant D as tymuxd
+ participant A as action client
+ T->>D: fr, then fs with the size
+ D->>D: remember the foreground group of tysend
+ D->>A: COMMAND fr, fs
+ A->>A: approval popup
+ A->>D: TRANSFER_REPLY k
+ D->>T: k written to the pty, if the sender is still in front
+ loop each packet of 74 KiB at most
+ T->>D: fd, data
+ D->>A: COMMAND fd, in fragments
+ A->>D: TRANSFER_REPLY k
+ D->>T: k
+ end
+ T->>D: fx
+ D->>A: COMMAND fx
+```
+
+* **Packets** reach 74 KiB, above the message limit: a command travels in
+ fragments of 64 KiB or less, and the client joins them.
+* **Backpressure.** While more than 512 KiB wait in the queue of the receiving
+ client, the daemon stops reading the pty, so that a big file does not get it
+ dropped. This is the one time a slow client stalls the shell, and it ends
+ once the client took nothing for 5 s. The daemon also gives a client 5 s to
+ answer a packet it was sent.
+* **Loss.** The transfer is lost when the receiving client detaches, is
+ dropped, is hijacked, stops acting, or stalls. The daemon refuses what the
+ sender still waits for, once, and drops the rest of the transfer until the
+ next `fr`. A client still there gets `TRANSFER_LOST` and drops what it has,
+ deleting the file it was writing. It answers `TRANSFER_LOST_ACK`, and what it
+ sent before that, which answered a transfer already gone, is ignored.
+* **Where an answer goes.** What the daemon writes for a transfer is for the
+ sender to read, and only for it: it checks that the sender's process group
+ still is in front, as an answer written to a shell would run as a command,
+ and an `f` command that displayed text and no `fr` announced is refused with
+ nothing written. A session whose foreground group cannot be read refuses the
+ sender once.
+* **No native client.** The daemon refuses at once.
+
+### 5.10 The inline proxy
+
+The proxy has no widget, so it mirrors the input modes the application asked
+for into the outer terminal. On each `NOTIFY` it compares them with what it
+last set and writes only the differences:
+
+| Mode | Sequence |
+|---|---|
+| Application cursor | `DECSET 1` |
+| Application keypad | `ESC =` and `ESC >` |
+| Mouse | `DECSET 9, 1000, 1002, 1003` |
+| Mouse encoding | `DECSET 1005, 1006, 1015` |
+| Bracketed paste | `DECSET 2004` |
+| Focus reporting | `DECSET 1004` |
+
+The outer terminal encodes the events, and the proxy forwards their bytes.
+Every mode is reset when the proxy exits, on every exit path. While the proxy
+is paused every mode but bracketed paste is reset, and they are set again on
+resume. A read-only proxy does not enable mouse, paste or focus reporting.
+Cells with a block code point are drawn as a space, and a link as its text.
+
+**The paste filter.** The proxy keeps bracketed paste on in the outer terminal
+even when the application did not ask for it, and strips the markers in that
+case. The filter that finds `ESC [ 200 ~` and `ESC [ 201 ~` tracks them across
+reads, with a timeout for a stray prefix, so a pasted `Ctrl+b d` cannot detach:
+only a real key press completes the chord. The native client applies the same
+rule in its write hook.
+
+## 6. Scrollback memory design
+
+Since `tymux-09`, **every** terminal uses the same two classes. A local
+terminal uses an anonymous-memory store, and `tymuxd` uses a memfd store.
+
+```mermaid
+flowchart LR
+ subgraph local["Local terminal"]
+ LP["Termpty"] --> LV["BacklogView<br/>is its own source"]
+ LV --> LS["BacklogStore<br/>ANON"]
+ end
+ subgraph remote["Attached terminal"]
+ RP["shadow Termpty<br/>ring only, no store"] --> RV["BacklogView<br/>BacklogViewSource"]
+ end
+ subgraph d["tymuxd"]
+ DP["Termpty"] --> DV["BacklogView<br/>head only"]
+ DV --> DS["BacklogStore<br/>MEMFD"]
+ end
+ RV <-->|"page and map messages"| DS
+```
+
+* **`BacklogStore` owns the data**: pages, compression, rebuilds, eviction.
+* **`BacklogView` owns the policy**: it fills the pty's ring of `Termsave`
+ entries and decides which pages stay mapped.
+
+### 6.1 Page lifecycle
+
+```mermaid
+stateDiagram-v2
+ [*] --> RAW: page created
+ RAW --> COMPRESSING: maintain, page unheld and idle
+ COMPRESSING --> COMPRESSED: job done, worth keeping
+ COMPRESSING --> RAW: appended to, poor ratio, or failed
+ COMPRESSED --> RESTORING: head needed again
+ RESTORING --> RAW: thread done
+ COMPRESSED --> RAW: synchronous fallback
+ RAW --> [*]: evicted
+ COMPRESSED --> [*]: evicted
+
+ note right of COMPRESSED
+ A sealed page stays COMPRESSED when read.
+ A rebuilt copy serves readers and is
+ dropped after 60 s without a hold.
+ end note
+```
+
+`backlog_store_maintain()` runs about once a second. A page is compressed
+when all of these hold:
+
+* no client holds it, and it has been idle for 5 s
+* fewer than two compression jobs are running in its store
+* a head has also seen no append for 10 s, and has more than one entry
+* the blob saves at least 15% and frees at least 16 KiB, otherwise the page
+ stays raw and is marked as poor
+
+Holds do **not** prevent eviction. An evicted page leaves the store, but its
+mapping lasts until the last hold is released, so a reader is never left with
+a dangling pointer.
+
+### 6.2 Which pages stay mapped
+
+```mermaid
+flowchart TD
+ A{"viewport scrolled back,<br/>and not tymuxd's view?"}
+ A -- yes --> W["keep the head, plus 2 pages behind<br/>and 1 ahead of the viewport"]
+ A -- no --> B{"view active?<br/>focused, or output in the last 10-20 s"}
+ B -- no --> N["keep nothing:<br/>the head can be compressed"]
+ B -- yes --> C{"head has fewer entries<br/>than the screen has rows?"}
+ C -- "yes, and not tymuxd" --> H2["keep the head and the page before"]
+ C -- no --> H1["keep the head only"]
+```
+
+Releases run from an idler, one page further out than fetches, and only after
+the viewport moved by two pages, so a slow scroll does not bounce a page
+between mapped and released.
+
+### 6.3 Compressing the head without stalling
+
+The head is the page still being written to, so it needs special handling.
+A synchronous restore of a full page was measured at about 18 ms, too long
+for the main loop, which in `tymuxd` also serves every client.
+
+```mermaid
+sequenceDiagram
+ autonumber
+ participant M as Main loop
+ participant S as BacklogStore
+ participant W as Worker thread
+ Note over S: Quiet head, compressed, newest entry kept raw aside
+ M->>S: append(new row)
+ S->>S: map the whole page at a stable address
+ S->>S: write the newest entry back in place
+ S->>W: expand the blob into the cells before it
+ S-->>M: append lands after the restored region
+ Note over M,W: The two regions never overlap
+ M->>S: more appends, without waiting
+ W-->>S: restore finished
+ S->>S: state RAW, free blob, trim the reservation
+ S-->>M: prefetch callback, view repoints entries
+```
+
+The newest entry stays raw because three paths read it without waiting: the
+autowrap check on append, the reflow on resize, and the restore itself.
+
+Sealing the head early was rejected. A terminal printing one line every few
+minutes would create thousands of tiny pages, and wrapped lines would be split
+across a page boundary, breaking reflow.
+
+## 7. Robustness and security
+
+**Trust boundary.** The socket directory is `0700` and checked for ownership,
+so only the same user can connect. `tymux kill` also checks the peer's uid
+with `SO_PEERCRED` before signaling it.
+
+**What displayed output must not do.** A program, a `cat` of a file or an ssh
+message of the day controls what is displayed, and Terminology's escapes are
+on by default. Three rules keep that from reaching the shell:
+
+* A hand-off needs the token of the terminal, which only its own shells have.
+ `tymuxd` does not pass it on, and `tymux` does not write it to a file or a
+ pipe. A subscription to the events needs another token of its own, and a
+ nonce used once (section 5.8).
+* What a client types because of a block or a transfer is no `INPUT`: it is a
+ `BLOCK_EVENT` or a `TRANSFER_REPLY`, which the daemon writes to the pty only
+ for the program that can read it (sections 5.8 and 5.9).
+* A client reads the session table as untrusted input, and a stale id never
+ shows another link's URL.
+
+**Shared memory hardening:**
+
+* Memfds are sealed against resizing, so a peer cannot truncate one and make
+ the other side raise `SIGBUS`. The client refuses a page without that seal.
+* Clients receive read-only reopened descriptors, with `F_SEAL_FUTURE_WRITE`
+ on Linux 5.1 and later.
+* The store never trusts what it reads back from a shared header, and keeps
+ its own copy of page metadata.
+
+**Backpressure and limits:**
+
+| Limit | Value | When exceeded |
+|---|---|---|
+| Daemon output queue per client | 1 MiB | Client dropped |
+| Passed fds queued | 64 | Reader pauses, or client dropped |
+| Client control queue | 1 MiB | Client detaches |
+| Daemon not reading for | 20 s | Client detaches |
+| Page memfds per process | 1/4 of `RLIMIT_NOFILE` | Pages compressed or copied early |
+| Accept with no fds left | Backoff from 0.1 to 1 s | Listening resumes later |
+| A command | 768 KiB | Dropped |
+| Channels kept for events | 256, of 255 bytes | The new one is ignored |
+| Media blocks | 8192 ids, 64 per `is` still unfilled | An id wraps and replaces the old block, the oldest unfilled `is` is forgotten |
+| Hyperlinks | 65536 ids | As in a local terminal |
+| Session table arena | 64 MiB, 1 MiB per record | The link or media is inert on clients |
+| `tysend` queue at the receiver | 512 KiB | The daemon stops reading the pty |
+| `tysend` with no progress | 5 s | The transfer is lost |
+
+**Threads.** Parsing, protocol and all store state stay on the main loop.
+Worker threads only compress, rebuild or restore, on data the main loop does
+not touch at the same time.
+
+## 8. Known limitations
+
+Documented in `man/tymux.1`:
+
+* Color scheme changes and desktop notifications are dropped by the daemon.
+* The inline proxy has no scrollback, and draws links as plain text and media
+ as blanks.
+* The events of the blocks reach only a program that subscribed to them, with
+ the token of the terminal, and is in the foreground. A program on the other
+ side of ssh has no token and cannot subscribe. A program that subscribed
+ answers for what it reads: the text of an event comes from what is displayed.
+ The subscription is bound to the foreground group when the escape is parsed,
+ and a group id could in principle be reused after the pids wrap: what it
+ would receive is an encoded line.
+* Session size is capped at 1920 by 1280.
+* A hand-off whose reply does not come in 1 s is taken for ignored: `tymux
+ attach` then uses the inline proxy, and `--new-tab` fails. A reply that comes
+ later is a rare accepted race.
+
+Other limits of the design:
+
+* A block that was shown when a terminal attached starts from its stored
+ commands: the channel commands sent after it was defined are not replayed.
+* Media paths are resolved by the client, which must be on the same machine as
+ the daemon.
+* With several clients, one at a time acts: another terminal is not told of a
+ popup or an approval it does not own.
--
To stop receiving notification emails like this one, please contact
the administrator of this repository.