@gjermundgaraba/clankermux 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,13 +1,13 @@
1
1
  # @gjermundgaraba/clankermux
2
2
 
3
- The browser client of [clankermux](https://github.com/gjermundgaraba/clankermux): a terminal on a canvas, its engine and connection in a module worker, speaking the clankermux protocol over the server's TLS WebSocket carrier.
3
+ The browser client of [clankermux](https://github.com/gjermundgaraba/clankermux): one connection to a server, speaking the clankermux protocol over its TLS WebSocket carrier from a module worker, and terminals on canvases mounted from it, the engine in the same worker.
4
4
 
5
5
  | Subpath | Exports |
6
6
  | --- | --- |
7
- | `.` | `mountTerminal` and its types, `ClientError` |
7
+ | `.` | `connect`, `Client`, the `Terminal` it mounts, their types, `ClientError` |
8
8
  | `./worker` | `runWorker`, for the worker module; no DOM types |
9
9
  | `./ghostty-vt.wasm` | the engine build the server's engine id names |
10
- | `./proto`, `./engine`, `./renderer` | the protocol messages, the engine and the canvas renderer |
10
+ | `./proto`, `./engine`, `./renderer` | the protocol messages, the engine and the canvas renderer; `Methods` maps each method to its params and result types, and `Catalog` is what `describe()` answers: the server's methods, events, frames and error codes with their JSON Schemas |
11
11
 
12
12
  ```ts
13
13
  // worker.ts, started as a module worker
@@ -15,41 +15,98 @@ import { runWorker } from "@gjermundgaraba/clankermux/worker";
15
15
  runWorker(self);
16
16
 
17
17
  // page
18
- import { mountTerminal } from "@gjermundgaraba/clankermux";
18
+ import { connect } from "@gjermundgaraba/clankermux";
19
19
  import wasm from "@gjermundgaraba/clankermux/ghostty-vt.wasm?url";
20
- const terminal = mountTerminal({
20
+ const client = await connect({
21
21
  worker: new Worker(new URL("./worker.ts", import.meta.url), { type: "module" }),
22
- canvas, container, wasm, url: "wss://127.0.0.1:7438/", session,
22
+ wasm, url: "wss://127.0.0.1:7438/",
23
+ });
24
+ const terminal = client.mount({
25
+ canvas, container, session,
23
26
  font: "14px monospace", colors: () => ({ fg: "#d8dee9", bg: "#282c34", cursor: "#ffffff" }),
24
- onLink: (link) => console.log(link),
27
+ });
28
+ terminal.onLink((link) => console.log(link));
29
+ // Requests need the connection: once the client's link is connected.
30
+ let created = false;
31
+ client.onLink(async (link) => {
32
+ if (link.state !== "connected" || created) return;
33
+ created = true;
34
+ const { id } = await client.create({ ...terminal.size(), on_exit: "keep" });
35
+ terminal.attach(id);
25
36
  });
26
37
  ```
27
38
 
28
- ## `MountedTerminal`
39
+ A page holds one client: one worker, one WebSocket, the session list and the event stream. Every terminal it mounts is one attachment on that connection, so a page with many panes holds one connection, and the client's methods serve them all.
40
+
41
+ ## `connect`
42
+
43
+ `connect({url, worker, wasm, client?})` starts the worker and resolves with the `Client` once the engine is loaded, before the connection is up: the worker connects, and after a loss reconnects, by itself, and the client's `onLink`, and each terminal's, says how that goes (below). Requests need a `connected` link. It rejects when the worker script or the engine cannot be loaded. An exception in the worker after that is the browser's to report, as before: it costs the message being handled, and the client goes on. `client` is the `{name, version}` the connection gives in `HELLO`, which the server lists in each session's `attachments`; `clankermux-web` and this package's version by default.
44
+
45
+ ## `Client`
46
+
47
+ Each method is the protocol method of the same name (PROTOCOL.md has their params, results and errors):
48
+
49
+ | Method | Protocol |
50
+ | --- | --- |
51
+ | `describe()`, `describe(method)` | `describe`: the catalog, or one method of it |
52
+ | `create(params?)` | `create`, all its params (`label`, `argv`, `cwd`, `env`, `cols`, `rows`, `on_exit`); resolves with the session. It attaches nothing: `terminal.attach(id)` does. `terminal.size()` is the grid a terminal's container holds, to create at that size |
53
+ | `sessions()` | `list`, paged to its end |
54
+ | `list(after?)` | `list`, one page |
55
+ | `inspect(id)` | `inspect` |
56
+ | `end(id)`, `signal(id, name)`, `remove(id)` | `end` (SIGHUP), `signal`, `remove`; resolve with nothing |
57
+ | `label(id, text)` | `label`; resolves with the session |
58
+ | `resize(id, {cols?, rows?, policy?})` | `resize` |
59
+ | `send(id, {text \| keys \| data, paste?, wait?}, {signal?})` | `send`; resolves with `{at, wait?}`. Aborting `signal` cancels its `wait` |
60
+ | `wait(id, until, {after?, timeout_ms?, signal?})` | `wait`; resolves with `{reason, at, exit?, match?, record?}`, a timeout being a result. Aborting `signal` sends `cancel`, and the wait rejects with `cancelled` |
61
+ | `read(id, {scrollback?, format?, scope?})` | `read` |
62
+ | `tail(id, after, {max_bytes?})` | `tail` |
63
+ | `ack(id, recordIds?)` | `ack` |
64
+ | `detach(id, channel, reason?)` | `detach`: another attachment, by its `channel` in `attachments` |
65
+ | `onLink(listener)` | the connection's link: `connecting {attempt}`, `connected` (with no session) or `ended`, the connection-level rows of the tables below; the latest at once to a listener added later |
66
+ | `onSessions(listener)` | every session at each change (below) |
67
+ | `onEvent(listener)` | each event, without loss across reconnects (below) |
68
+ | `mount(options)` | a `Terminal` on this connection |
69
+ | `close()` | disposes the terminals and terminates the worker, which ends the connection |
70
+
71
+ A method rejects with a `ClientError`:
72
+
73
+ - `kind: "server"` when the server refuses, with `code` (and `server`, its `ERROR`): `no_such_session`, `not_running`, `running`, `cancelled` for a cancelled wait, and the rest of PROTOCOL.md's codes;
74
+ - `kind: "closed"` when there is no connection (before the first, between a loss and the reconnect, after the server ended it), when the connection is lost meanwhile, and after `close()`;
75
+ - `kind: "protocol"` when the server sent a malformed frame meanwhile.
76
+
77
+ A request is not retried across a reconnect. `end` rejects with `not_running` when the session is not running (`exited`, `restored`): there is nothing to end. Closing a pane for good is `end` for a running session, then `remove` once it has exited (`wait(id, {exited: true})` says when), and `remove` alone for one that has exited, or that a previous server left `restored`. With `on_exit: "remove"` an ended session removes itself.
78
+
79
+ While connected, a cancelled wait is cancelled by the server, so it rejects with the server's `cancelled` also when its signal was aborted before the request was sent; without a connection it rejects with `closed`, as any request does.
80
+
81
+ ## `Terminal`
82
+
83
+ `client.mount({session?, canvas, container, font, colors, scheme?, readOnly?, ackOnFocus?})` draws on `canvas` the session `session`, if given, at the grid `container` holds. `readOnly` attaches read-only: the screen, and no input to the session. `ackOnFocus` marks the session's `done` and `error` records seen (`ack`) while the terminal has the keyboard and its window the focus: when it gets the focus, and when such a record wants the user meanwhile.
29
84
 
30
85
  | Method | Does |
31
86
  | --- | --- |
32
87
  | `attach(session)` | Detaches the current session and attaches `session`; after a connection-level end (below), connects again first. |
33
- | `create(options?)` | Creates a session at the current size, attaches it, and resolves with it. `options.onExit`: `"keep"` keeps it listed as `exited` when its program exits; `"remove"` removes it `limits.remove_grace` after. Without it the server's default (`remove`) applies. |
34
- | `end()` | Hangs up the attached session's processes (SIGHUP). Also resolves when the session is not running (`exited`, `restored`): there is nothing to end. |
35
- | `remove()` | Removes the attached session, which must be `exited` or `restored`; a running one rejects with `running`. |
36
- | `report()` | Reports the container's size, the colours and the scheme again. |
88
+ | `detach()` | Detaches the session; the terminal stays, attached to none (`connected` with no session). |
89
+ | `focus()` | Focuses the terminal's input element, as focusing the canvas does. |
90
+ | `selection()` | The selected text, as the last selection made copied it. |
37
91
  | `paste(text)` | Pastes, bracketed when the program asked for it. |
38
- | `dispose()` | Removes the listeners and terminates the worker, which drops its connection; requests in flight reject. |
39
-
40
- `create`, `end` and `remove` need a connection: call them after a `connected` link. They reject with a `ClientError`:
41
-
42
- - with `kind: "server"` and `server.code` when the server refuses;
43
- - with `kind: "closed"` when there is no connection, or after `dispose()`;
44
- - with `kind: "protocol"` when the server sent a malformed frame meanwhile (the connection then ends with `ended closed`, `retry: true`).
92
+ | `scroll(rows)` | Scrolls the view through the history by `rows`, up when negative. |
93
+ | `scrollToLive()` | Back to the live screen. |
94
+ | `report()` | Reports the container's size, the colours and the scheme again. |
95
+ | `size()` | `{cols, rows}`: the grid the container holds now. |
96
+ | `dispose()` | Detaches, and removes the listeners and the input element; the client and its other terminals stay. |
97
+ | `onLink(listener)` | Each change of the link to the session (below). |
98
+ | `onScroll(listener)` | The rows between the bottom of the view and the live screen's (below), from the first frame on. |
99
+ | `onStatus(listener)` | The same moments as `onLink`, and more, as text for display. |
100
+ | `onCopy(listener)` | Each copy to the clipboard as it ends: copied, or failed and why (below). |
45
101
 
46
- `end` and `remove` reject with a plain `Error` when no session is attached. Since 0.1.1 `create` returns this promise, where it returned nothing and dropped a request it could not make; a caller that ignores it should `.catch` it. Closing a pane for good is `end()` for a running session and `remove()` for one that has exited, or that a previous server left `restored`. With `onExit: "remove"` an ended session also removes itself.
102
+ The `on*` methods return a function that removes the listener; a listener added after a change gets the latest at once, except `onCopy`'s, which is told only of copies after it.
47
103
 
48
104
  ## Keys and composed text
49
105
 
50
106
  The terminal's input element is a textarea the mount places after the canvas: an input method composes only into an editable element. It is invisible, out of the tab order (`tabIndex = -1`) and ignores the pointer. Focusing the canvas (a click, `canvas.focus()`, a tab stop the page gives it) or calling `focus()` focuses the textarea, so `document.activeElement` is the textarea while the terminal has the keyboard: test for focus with `container.contains(document.activeElement)`, not `=== canvas`. Key events bubble from it through the container as they did from the canvas.
51
107
 
52
108
  - Keys go to the engine's key encoder, which follows the program's modes (cursor keys, the kitty keyboard protocol). The browser keeps Cmd (Meta) chords and Ctrl+Shift+V, its paste.
109
+ - Shift that made a key's text (`:`, `"`, `A`) is consumed, as a keyboard reports it: under the kitty protocol's disambiguation, which neovim asks for, the text goes as typed, on any layout; reporting all keys, the key is the layout's own character with Shift, and the shifted one is among the alternates when the program asks for them. Shift made the text when it is not the key's own character, as the browser's layout map has it (Chromium); for a key the map does not cover (the numpad, Space) or without a map (Safari, Firefox), when it is any text but a space.
53
110
  - A key that belongs to an input method is left to it: one that is composing (`isComposing`), that it processes (`Process`, key code 229), or a dead key (`Dead`). The composition is shown at the cursor, in the terminal's colours, while it lasts, and its text is sent when it ends (`compositionend`). A key that ended a composition sends no release.
54
111
  - Text inserted with no key that sent it (a dead key's character, the emoji picker, dictation) is sent as it is inserted (`beforeinput` `insertText`); a line break or a backward delete from such a source is sent as Enter or Backspace.
55
112
  - Composed text goes to the program as UTF-8, as typed text does, not as a paste.
@@ -60,28 +117,33 @@ Verified in headless Chrome on macOS through CDP (`Input.imeSetComposition`, `In
60
117
 
61
118
  ## `onSessions`
62
119
 
63
- `onSessions(sessions, current)` reports every session on the server, and which one the page shows, at each change: a session created, exited or removed, and a `session_changed`, which the server sends when a session's label, size, attachments, title or working directory changes. The title is the program's (OSC 0 or 2), the working directory the one it reports (OSC 7, as a path), each empty until set, and both cleared by a full reset. A status line takes them from the session whose `id` is `current`; the `session` of a `connected` link is the one `ATTACHED` described, and does not follow these changes.
120
+ `client.onSessions(listener)` reports every session on the server at each change: a session created, exited or removed, and a `session_changed`, which the server sends when a session's label, size, size policy, attachments, title, working directory or attention changes. A listener added once the list is known gets it at once. `attachments` is the list of open attachments in the order they opened, each `{channel, client: {name, version}, read_only, viewport?: {cols, rows}, since, last_input?}`: `channel` is unique on the server, `client` the connecting page or program's own name, `viewport` its latest size report, `last_input` when it last typed (input alone sends no `session_changed`). `size` is `{policy, owner?}`, `owner` being the channel whose report sets the size under `latest`. The title is the program's (OSC 0 or 2), the working directory the one it reports (OSC 7, as a path), each empty until set, and both cleared by a full reset. A status line takes them from the session its terminal shows; the `session` of a `connected` link is the one `ATTACHED` described, and does not follow these changes.
121
+
122
+ A session's `attention`, when present, is the program status record that most wants the user (`{state, kind?, app?, msg?, record}`: `blocked`, then an unseen `error`, then an unseen `done`, then `working`), so a badge needs no request per session; a `session_changed` follows each change of it.
123
+
124
+ ## `onEvent`
125
+
126
+ `client.onEvent(listener)` reports each server event, of every session, in `seq` order, as PROTOCOL.md describes them: `session_created`, `session_changed`, `session_exited`, `session_removed`, `program_status_changed`, `program_status_removed`, `bell`, `notification`, `progress`, `command_started`, `command_ended`, `attachment_opened` and `attachment_closed`. After a reconnect the client subscribes from the last event it saw (`subscribe {after, incarnation}`), so the events missed while the connection was down are reported then, in order, before any later one. When the server cannot replay them (it restarted, so `seq` counts from 1 again, or more happened meanwhile than it retains), the listener gets `{event: "gap", incarnation}` instead, and the session list is paged again: `onSessions` has the current state.
64
127
 
65
128
  ## `onLink`
66
129
 
67
- `onLink(link)` reports each change of the page's link to its session, through the connection and the attachment. `onStatus(text)` reports the same moments, and more, as text for display.
130
+ `terminal.onLink(listener)` reports each change of the terminal's link to its session, through the client's connection and the terminal's attachment. A terminal mounted later first gets the connection as it is then: `connecting` with the current attempt, or `connected` (and its own screen, if it names a session); after a connection-level end it connects again, as `attach` does.
68
131
 
69
132
  ```ts
70
133
  type Link =
71
134
  | { state: "connecting"; attempt: number }
72
135
  | { state: "connected"; session: Session | undefined }
73
136
  | { state: "ended"; reason: LinkEnd; code?: ErrorCode; message?: string; exit?: Exit; retry: boolean };
74
- type LinkEnd = "closed" | "removed" | "stopping" | "exited" | "no_such_session" | "engine_mismatch" | "error";
137
+ type LinkEnd = "closed" | "removed" | "stopping" | "detached" | "exited" | "no_such_session" | "engine_mismatch" | "error";
75
138
  ```
76
139
 
77
- `retry` means the worker reconnects or attaches again by itself, so a `connecting` or `connected` follows. Otherwise nothing follows until the page calls `attach` or `create`. After a connection-level end (the last three rows of the first table) there is no connection: `create` rejects, and `attach` connects again (`connecting` from attempt 1), so "Retry" can be `attach`. An engine that failed to load needs a new mount.
140
+ `retry` means the worker reconnects or attaches again by itself, so a `connecting` or `connected` follows. Otherwise nothing follows until the page calls `attach`. The connection is the client's, so a connection-level change (the first table) reaches every terminal. After a connection-level end (the last three rows of the first table) there is no connection: the client's methods reject with `closed`, and a terminal's `attach`, or a terminal mounted then, connects again (`connecting` from attempt 1), so "Retry" can be `attach` or a new mount. An engine that failed to load rejects `connect`.
78
141
 
79
142
  | When | Link |
80
143
  | --- | --- |
81
- | A connection is opened: at mount, and at each reconnect | `connecting`, `attempt` from 1; it starts again at 1 once a server answers |
144
+ | A connection is opened: at `connect`, and at each reconnect | `connecting`, `attempt` from 1; it starts again at 1 once a server answers |
82
145
  | A connection cannot be opened, or closes before `WELCOME` | nothing at once; the next `connecting` after a backoff |
83
146
  | The connection closes | `ended closed`, `retry: true`, then `connecting` |
84
- | The engine cannot be loaded | `ended error`, `retry: false` |
85
147
  | The server refuses the handshake (`ERROR` before `WELCOME`, e.g. `version_mismatch`), or sends something else first | `ended error` with the code when there is one, `retry: false` |
86
148
  | The server ends the connection (`ERROR` without an id, e.g. `protocol_error`) | `ended error` with the code, `retry: false` |
87
149
  | `subscribe` fails on a live connection | `ended error`, `retry: false`; the worker closes the connection |
@@ -91,11 +153,12 @@ Once connected:
91
153
  | When | Link |
92
154
  | --- | --- |
93
155
  | Connected with no session to attach | `connected`, `session: undefined` |
94
- | A session's screen is shown: a snapshot's first screen, a resume, again after a gap, a re-attach or a reconnect | `connected` with the session as `ATTACHED` described it; `status` tells `running`, `restored` or `exited` |
156
+ | A session's screen is shown: a snapshot's first screen, a resume, again after a gap, a re-attach or a reconnect | `connected` with the session as `ATTACHED` described it; `status` tells `running`, `restored` or `exited`. A reconnect to the same server resumes from the terminal's place in the stream (`onStatus` says `resumed`); one to a restarted server shows the session `restored` |
95
157
  | A snapshot shows a session that has exited already | `connected`, then at once `ended exited` with its `exit`, `retry: false` (a resume onto such a session gets its `EXITED`, the next row, instead) |
96
158
  | The session's program exits (`EXITED`) | `ended exited` with `exit`, `retry: false` |
97
159
  | `CLOSED removed` | `ended removed`, `retry: false`; the worker forgets the session |
98
160
  | `CLOSED stopping` | `ended stopping`, `retry: true`; the connection's close follows, and the reconnect attaches the session again (as `restored`) |
161
+ | `CLOSED detached` (another client's `detach`) | `ended detached`, `retry: false`, `message` the reason it gave, if any; the worker forgets the session, so a reconnect does not take it back |
99
162
  | `OPEN` refused, or the attachment ended, with `no_such_session` or `engine_mismatch` | `ended` with that reason and code, `retry: false` |
100
163
  | The attachment ended with `invalid_request` | `ended error`, `retry: false` |
101
164
  | The attachment ended with another error (`too_slow`, a snapshot that failed, `internal`) | `ended error` with the code, `retry: true`; the worker attaches again after a backoff |
@@ -106,7 +169,7 @@ Nothing fires for:
106
169
 
107
170
  - the errors that keep an attachment (`read_only`, `not_running`, `input_overflow`);
108
171
  - a gap, until its new screen fires `connected`;
109
- - `attach` or `create` before their screen;
172
+ - `attach` before its screen;
110
173
  - `dispose`.
111
174
 
112
175
  `reason: "closed"` is the connection's close. The worker detaches without waiting for the server's `CLOSED closed`, so that frame never shows up as a link change.
@@ -132,7 +195,26 @@ The selection is the engine's, drawn inverted, and the engine keeps it on its ce
132
195
 
133
196
  It is cleared by a click (a press that selects nothing), by input sent to the session (a key that sends something, a paste, composed text; not a modifier alone), by a switch to the alternate screen (it is not back when the program leaves it), by a full reset (RIS), and by a new screen (attaching, a gap).
134
197
 
135
- The copy on release starts within `mouseup`, as Safari requires: `navigator.clipboard.write` with a `ClipboardItem` whose text arrives when the worker has it, a few milliseconds later; when nothing was selected it fails and the clipboard is left alone. Where `ClipboardItem` is missing it is `writeText` once the text arrives, which a browser that wants the gesture still running may refuse; Cmd+C then copies. Verified in headless Chrome only. A `beforecopy` listener lets WebKit offer Copy on the empty input element while there is a selection. Where the browser keeps Ctrl+Shift+C for itself (a developer tools shortcut), Cmd+C or the Copy menu copies. Programs that ask for mouse reports get none from this client, so the mouse always selects.
198
+ The copy on release starts within `mouseup`, as Safari requires: `navigator.clipboard.write` with a `ClipboardItem` whose text arrives when the worker has it, a few milliseconds later; when nothing was selected it fails and the clipboard is left alone. Where `ClipboardItem` is missing, or takes no text to come, it is `writeText` once the text arrives, which a browser that wants the gesture still running may refuse; Cmd+C then copies. Verified in headless Chrome only. A `beforecopy` listener lets WebKit offer Copy on the empty input element while there is a selection. Where the browser keeps Ctrl+Shift+C for itself (a developer tools shortcut), Cmd+C or the Copy menu copies. Programs that ask for mouse reports get none from this client, so the mouse always selects.
199
+
200
+ ### Copy outcome
201
+
202
+ `terminal.onCopy(listener)` tells the page what each copy to the clipboard came to, once it is known:
203
+
204
+ ```ts
205
+ type Copy =
206
+ | { ok: true; source: CopySource; chars: number }
207
+ | { ok: false; source: CopySource; reason: "refused" | "timeout" | "unavailable"; chars?: number; message?: string };
208
+ type CopySource = "release" | "keys" | "browser" | "program";
209
+ ```
210
+
211
+ - `source`: `release`, the selection copied as the button came up; `keys`, Ctrl+Shift+C; `browser`, the browser's own copy (Cmd+C, the Copy menu); `program`, the program's OSC 52 write.
212
+ - `chars` is the text's length in characters (code points). The text itself is in the clipboard, and `selection()` has it.
213
+ - `ok: true` once the browser's write resolved (for `browser`, once the `copy` event's data was set).
214
+ - `refused`: the browser rejected the write, `message` its error (`NotAllowedError: …`): a permission denied, a document without the focus, an Electron shell that does not allow it. `timeout`: the copy did not finish within two seconds (the worker's text or the write); without the worker's text it has no `chars`. `unavailable`: the page has no `navigator.clipboard` (it is not a secure context).
215
+ - A release that selected nothing (a click) is no copy and tells nothing; nor does a release whose copy a newer one replaced before its text arrived. Each copy is told once.
216
+
217
+ A page shows a brief notification on `ok: true` ("Copied 42 characters"), and on a failure says the clipboard did not take it (with Cmd+C as the way to try again, since the browser's own copy is the one a browser that refuses `navigator.clipboard` still allows). A mouseup with `selection()` is no substitute: it says nothing about whether the write succeeded. `program` copies arrive without the user's gesture, which a browser may refuse; a page that announces only the user's copies leaves them out. Verified in headless Chrome: a double click's copy is told `ok` with the clipboard holding the word, and `refused` with the clipboard permission denied; the rest (timeouts, no `ClipboardItem`, no clipboard) by the package's tests against a stand-in clipboard. Not verified in Safari, Firefox or Electron.
136
218
 
137
219
  ## Scrollback
138
220
 
@@ -143,11 +225,11 @@ The terminal holds the session's history (the server sends what it keeps with th
143
225
 
144
226
  Output while the view is scrolled back leaves it where it is. Any input that sends something (a key, a paste, composed text) brings it back to the live screen first; a modifier alone does not. The alternate screen of full-screen programs (`vim`, `less`) has no history: there Shift+PageUp and the rest go to the program as keys, and the wheel sends the up and down arrow keys while the program leaves alternate scroll (mode 1007) on, as it is by default, or nothing.
145
227
 
146
- While the view is scrolled back the canvas draws a mark at its right edge, the view's share of the history and its place in it. `onScroll(rows)` reports the rows between the bottom of the view and the live screen's at each change: above 0 when scrolled back (it grows as output arrives meanwhile), 0 at the live screen.
228
+ While the view is scrolled back the canvas draws a mark at its right edge, the view's share of the history and its place in it. `onScroll(rows)` reports, on the first frame and then at each change, the rows between the bottom of the view and the live screen's: above 0 when scrolled back (it grows as output arrives meanwhile), 0 at the live screen.
147
229
 
148
230
  ## Size between clients
149
231
 
150
- A session has one size, and the server applies the latest report (PROTOCOL.md, "Size"). The terminal reports its container's size, its colours and its scheme only while its page is visible and its window has the focus (`document.visibilityState === "visible"` and `document.hasFocus()`). It reports again when the page is shown or its window focused, even at an unchanged size, and when the session was resized to another client's size while the page kept its focus (the user went to another machine and came back), at the page's next input: a key or text that sends something, a paste, a click on the canvas, the wheel. So with the same session open in several tabs or on several machines, the session takes the size of the one you look at, and a hidden or unfocused one never resizes it: its `OPEN` carries no viewport, it sends no `VIEWPORT`, and its canvas shows the session's size, clipped or with a margin. `report()` follows the same rule. `create()` makes the session at the container's current size, focused or not. A headless browser counts only its newest page as visible and focused, and a terminal in an iframe has the focus only once the frame does; such a page does not size the session until then.
232
+ A session has one size, and under the default size policy, `latest`, the server applies the latest report (PROTOCOL.md, "Size"); under `smallest` it takes the smallest columns and rows among the attachments' reports, and under `fixed` only a `resize` request changes it, the reports being recorded but not applied. The terminal reports its container's size, its colours and its scheme only while its page is visible and its window has the focus (`document.visibilityState === "visible"` and `document.hasFocus()`). It reports again when the page is shown or its window focused, even at an unchanged size, and when the session was resized to another client's size while the page kept its focus (the user went to another machine and came back), at the page's next input: a key or text that sends something, a paste, a click on the canvas, the wheel. So under `latest`, with the same session open in several tabs or on several machines, the session takes the size of the one you look at, and a hidden or unfocused one never resizes it: its `OPEN` carries no viewport, it sends no `VIEWPORT`, and its canvas shows the session's size, clipped or with a margin. `report()` follows the same rule. `size()` is the container's grid, focused or not, for a `create` at that size. A headless browser counts only its newest page as visible and focused, and a terminal in an iframe has the focus only once the frame does; such a page does not size the session until then.
151
233
 
152
234
  ## Colour scheme
153
235
 
@@ -24,6 +24,7 @@ export type Action =
24
24
  } | {
25
25
  type: "closed";
26
26
  reason: Closed["reason"];
27
+ message?: string;
27
28
  }
28
29
  /** `read_only`, `not_running` and `input_overflow` keep the attachment;
29
30
  * any other code ended it. */
@@ -156,7 +156,7 @@ export class Attachment {
156
156
  case FrameType.Closed: {
157
157
  const closed = this.json(frame);
158
158
  this.end(true);
159
- actions.push({ type: "closed", reason: closed.reason });
159
+ actions.push({ type: "closed", reason: closed.reason, ...(closed.message !== undefined && { message: closed.message }) });
160
160
  break;
161
161
  }
162
162
  case FrameType.Error: {
@@ -0,0 +1,123 @@
1
+ /** The page side of a client: one worker, one connection, the control
2
+ * surface, and the terminals mounted from it. */
3
+ import type { Acked, Catalog, CreateParams, Description, Event, Page, Peer, Read, ReadParams, ResizeParams, SendParams, Sent, Session, StreamCursor, Tail, Until, Waited } from "../proto/index.ts";
4
+ import { type MountOptions, type Terminal } from "./mount.ts";
5
+ import type { Link, ToWorker } from "./worker.ts";
6
+ export interface ConnectOptions {
7
+ /** The server's WebSocket carrier, `wss://<node>:<port>/`. */
8
+ url: string;
9
+ /** A module worker whose script calls `runWorker(self)`; the client
10
+ * owns it from here. */
11
+ worker: Worker;
12
+ /** ghostty-vt.wasm, resolved against the page. */
13
+ wasm: string;
14
+ /** The name and version the client gives in `HELLO`, which the
15
+ * session's `attachments` list; `clankermux-web` and this package's
16
+ * version by default. */
17
+ client?: Peer;
18
+ }
19
+ /** Events were lost: the server restarted (a new `incarnation`), or more
20
+ * happened while the connection was down than it retains. The session
21
+ * list was paged again, and `onSessions` has it. */
22
+ export interface EventGap {
23
+ event: "gap";
24
+ incarnation: string;
25
+ }
26
+ /** `send`'s input: exactly one of `text`, `keys` and `data`. */
27
+ export type SendInput = Omit<SendParams, "session">;
28
+ export interface WaitOptions {
29
+ /** The cursor to wait from; now by default. */
30
+ after?: StreamCursor;
31
+ timeout_ms?: number;
32
+ /** Aborting it cancels the wait, which rejects with `cancelled`. */
33
+ signal?: AbortSignal;
34
+ }
35
+ /**
36
+ * Starts the worker and its connection to the server at `url`. Resolves
37
+ * once the engine is loaded, before the connection is up: the worker
38
+ * connects, and reconnects after a loss, by itself, and the client's
39
+ * `onLink` (and each mounted terminal's) says how it goes. Rejects when
40
+ * the worker or the engine cannot be loaded.
41
+ */
42
+ export declare function connect(options: ConnectOptions): Promise<Client>;
43
+ /**
44
+ * One connection to a server: each method is the protocol method of the
45
+ * same name, and rejects with a `ClientError` (the server's `code`, or
46
+ * `closed` when there is no connection). Terminals mount from it and share
47
+ * its connection.
48
+ */
49
+ export declare class Client {
50
+ private readonly worker;
51
+ private nextId;
52
+ private readonly pending;
53
+ private readonly mounts;
54
+ private readonly terminals;
55
+ private readonly sessionListeners;
56
+ private readonly eventListeners;
57
+ private readonly linkListeners;
58
+ private latest;
59
+ private link;
60
+ private started;
61
+ private closed;
62
+ /** @internal Use `connect`. */
63
+ constructor(worker: Worker, started: (error?: Error) => void);
64
+ private setLink;
65
+ /** @internal */
66
+ post(message: ToWorker): void;
67
+ private call;
68
+ /** The server's catalog, or one method of it. */
69
+ describe(): Promise<Catalog>;
70
+ describe(method: string): Promise<Description>;
71
+ create(params?: CreateParams): Promise<Session>;
72
+ /** Every session, `list` paged to its end. */
73
+ sessions(): Promise<Session[]>;
74
+ /** One page of sessions, after the session id `after`. */
75
+ list(after?: string): Promise<Page>;
76
+ inspect(session: string): Promise<Session>;
77
+ /** Hangs up the session's processes (SIGHUP). */
78
+ end(session: string): Promise<void>;
79
+ /** Sends `signal` (`HUP`, `INT`, `TERM`, `KILL`, ...) to the session's processes. */
80
+ signal(session: string, signal: string): Promise<void>;
81
+ /** Removes a session that is `exited` or `restored`. */
82
+ remove(session: string): Promise<void>;
83
+ label(session: string, label: string): Promise<Session>;
84
+ /** Sets the size, the size policy, or both. */
85
+ resize(session: string, size: Omit<ResizeParams, "session">): Promise<void>;
86
+ /** Text, keys or bytes to the session's program, with a wait armed
87
+ * before they are written when `input.wait` is given; aborting
88
+ * `options.signal` cancels that wait. */
89
+ send(session: string, input: SendInput, options?: {
90
+ signal?: AbortSignal;
91
+ }): Promise<Sent>;
92
+ /** Waits on the server until one of `until` holds, or the timeout,
93
+ * which is a result. */
94
+ wait(session: string, until: Until, options?: WaitOptions): Promise<Waited>;
95
+ /** The screen, or the scope and format asked for. */
96
+ read(session: string, options?: Omit<ReadParams, "session">): Promise<Read>;
97
+ /** The stream as text, from the offset `after`. */
98
+ tail(session: string, after: number, options?: {
99
+ max_bytes?: number;
100
+ }): Promise<Tail>;
101
+ /** Marks the session's `done` and `error` records seen: all, or those named. */
102
+ ack(session: string, recordIds?: string[]): Promise<Acked>;
103
+ /** Ends another attachment, by its `channel` in the session's `attachments`. */
104
+ detach(session: string, channel: number, reason?: string): Promise<void>;
105
+ /** The connection's link, at each change: `connecting` with its
106
+ * attempt, `connected` (with no session), or `ended`, as a terminal's
107
+ * `onLink` reports the connection-level changes. Requests need
108
+ * `connected`. A listener added later gets the latest at once. */
109
+ onLink(listener: (link: Link) => void): () => void;
110
+ /** Every session on the server, at each change; a listener added once
111
+ * the list is known gets it at once. */
112
+ onSessions(listener: (sessions: Session[]) => void): () => void;
113
+ /** Each server event, in `seq` order, without loss across reconnects:
114
+ * the ones missed while the connection was down are replayed, or an
115
+ * `EventGap` says they cannot be. */
116
+ onEvent(listener: (event: Event | EventGap) => void): () => void;
117
+ /** Mounts a terminal on `options.canvas`, attached to `options.session`
118
+ * if given, on this client's connection. */
119
+ mount(options: MountOptions): Terminal;
120
+ /** Disposes the terminals and terminates the worker, which ends the
121
+ * connection; requests in flight reject with `closed`. */
122
+ close(): void;
123
+ }