@awebai/oats 0.57.1 → 0.59.0

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.
Files changed (61) hide show
  1. package/bin/oats.mjs +24 -11
  2. package/docs/configuration.md +2 -1
  3. package/docs/desktop-cli-api.md +105 -17
  4. package/docs/desktop.md +30 -3
  5. package/docs/execution-targets.md +15 -0
  6. package/docs/implementation.md +2 -0
  7. package/docs/integrations.md +2 -2
  8. package/docs/knowledge.md +4 -4
  9. package/docs/official-catalog.md +4 -4
  10. package/docs/packages.md +14 -14
  11. package/docs/release-notes/v0.58.0.md +107 -0
  12. package/docs/release-notes/v0.59.0.md +288 -0
  13. package/docs/servers.md +4 -1
  14. package/docs/souls-and-instances.md +30 -0
  15. package/docs/tui.md +653 -117
  16. package/docs/workspaces.md +2 -2
  17. package/lib/core.mjs +227 -46
  18. package/lib/read-ahead-worker.mjs +119 -0
  19. package/lib/read-ahead.mjs +115 -0
  20. package/lib/retire-state.mjs +33 -0
  21. package/lib/servers.mjs +9 -1
  22. package/lib/session-input.mjs +14 -4
  23. package/package-catalog.json +3 -3
  24. package/package.json +1 -1
  25. package/packages/client/cli-locator.mjs +2 -2
  26. package/packages/client/deployment-data.mjs +4 -0
  27. package/packages/client/deployment-panel.mjs +3 -0
  28. package/packages/client/instance-acts.mjs +23 -8
  29. package/packages/client/instance-presentation.mjs +3 -2
  30. package/packages/client/instance-tree.mjs +84 -39
  31. package/packages/client/lifecycle-confirmation.mjs +9 -3
  32. package/packages/client/panel-views.mjs +1 -1
  33. package/packages/client/remote-roster.mjs +4 -1
  34. package/packages/client/retire-in-flight.mjs +65 -0
  35. package/packages/client/retire-state.mjs +30 -0
  36. package/packages/client/spawn-apply-cli.mjs +8 -2
  37. package/packages/client/spawn-apply.mjs +20 -7
  38. package/packages/client/spawn-preview-cli.mjs +2 -1
  39. package/packages/client/spawn-preview.mjs +30 -18
  40. package/packages/record/lib/directory-identity.mjs +14 -0
  41. package/packages/record/lib/native-history.mjs +6 -5
  42. package/packages/tui/README.md +23 -10
  43. package/packages/tui/lib/actions.mjs +63 -5
  44. package/packages/tui/lib/client.mjs +12 -1
  45. package/packages/tui/lib/config.mjs +7 -2
  46. package/packages/tui/lib/main.mjs +315 -82
  47. package/packages/tui/lib/model.mjs +523 -56
  48. package/packages/tui/lib/panel.mjs +519 -144
  49. package/packages/tui/lib/read.mjs +52 -26
  50. package/packages/tui/lib/store.mjs +908 -65
  51. package/packages/tui/lib/term/keys.mjs +9 -2
  52. package/packages/tui/lib/term/text.mjs +4 -0
  53. package/packages/tui/lib/term/through.mjs +12 -1
  54. package/packages/tui/lib/views/frame.mjs +394 -95
  55. package/packages/tui/lib/views/help.mjs +54 -13
  56. package/packages/tui/lib/views/instances.mjs +43 -25
  57. package/packages/tui/lib/views/palette.mjs +61 -0
  58. package/packages/tui/lib/views/souls.mjs +268 -0
  59. package/packages/tui/lib/views/spawn.mjs +299 -0
  60. package/packages/tui/lib/views/split.mjs +29 -0
  61. package/skills/oats-getting-started/SKILL.md +2 -2
@@ -1,10 +1,12 @@
1
- // An agent's terminal in a panel beside the list. The kernel's viewer (`oats session attach`, a
2
- // node process that runs a tmux client attached to the agent's own tmux server) runs in a pane of
3
- // a PRIVATE tmux server that this TUI run owns; the TUI keeps ONE control-mode client of that
4
- // server for the run, captures the pane when tmux says it changed, and sends the keys to it.
5
- // This is the only module of the TUI that runs tmux. It knows nothing of rows, keys or views: the
6
- // caller hands it the viewer's argv, a size and the bytes to type, and it hands back screens (built
7
- // by the caller's own cell builder) and the end of each viewer.
1
+ // Agents' terminals in a panel beside the list, as tabs. The kernel's viewer (`oats session
2
+ // attach`, a node process that runs a tmux client attached to the agent's own tmux server) runs in
3
+ // a pane of a PRIVATE tmux server that this TUI run owns, one window per tab; the TUI keeps ONE
4
+ // control-mode client of that server for the run, captures each displayed tab's pane when tmux
5
+ // says it changed, and sends the keys to the shown one.
6
+ // This is the only module of the TUI that runs tmux. It knows nothing of rows, keys, views or
7
+ // groups: the caller hands it the viewer's argv, each window's size, which tabs to display, which
8
+ // of them takes the keys and the bytes to type, and it hands back screens (built by the caller's
9
+ // own cell builder), which tab not displayed had output, and the end of each viewer.
8
10
  //
9
11
  // THE SERVER. Its socket is `<run dir>/tmux`, in the run's private directory (0700, made by the
10
12
  // caller's `dir()`, shared with the reader). Every call is `tmux -u -f /dev/null -S <socket> …`
@@ -25,6 +27,40 @@
25
27
  // crash in the next `new-window` (resize.c clients_calculate_size reads the window's manual size
26
28
  // before the window exists), as CI's tmux 3.4 did.
27
29
  //
30
+ // THE TABS. The panel holds up to MAX_TERMINALS viewers, each a window of the one session, in the
31
+ // order they were opened. Up to MAX_SHOWN of them are DISPLAYED (captured and handed back as
32
+ // screens, each with its own id: the caller draws each where it wants, one per group of a split),
33
+ // and ONE of the displayed is SHOWN, or none: the one typed to. Each tab's window has its own
34
+ // size: an open makes its window at the size it gives, and a resize is one `resize-window` per
35
+ // window it names, or every window (never the global `window-size`, above); the panel never sizes
36
+ // a window the caller did not name. A `%layout-change` is no output (every resize makes one for
37
+ // each window).
38
+ //
39
+ // THE OUTPUT OF A TAB NOT DRAWN. A tab not displayed is heard until it prints: its first
40
+ // `%output` in a spell not displayed marks it (`onActivity`, once in each spell: displayed and then
41
+ // not again, it may be marked again) and PAUSES its pane for this client (`refresh-client -A
42
+ // '%<pane>:pause'`, tmux 3.2: control.c control_pause_pane), so tmux sends none of its output, nor
43
+ // keeps it for this client, until the tab is displayed again. Every displayed tab is paused too
44
+ // while the panel is hidden, and is never marked. A tab displayed again is CONTINUED
45
+ // (`:continue`, control_continue_pane) BEFORE its capture: tmux starts its output afresh from where
46
+ // the pane is then, so nothing written meanwhile is replayed, and the capture is the pane's screen
47
+ // as it is. A paused pane is still read (server-client.c server_client_check_pane_buffer: a paused
48
+ // pane never stops the reading): its screen stays current and its viewer never waits. `pause`
49
+ // rather than `off`: from tmux 3.4 on, a pane every control client has turned off is no longer
50
+ // read (that same function disables its read event), so its viewer stalls and its screen goes
51
+ // stale. tmux prints `%pause` and `%continue` lines for them, which say nothing the panel needs. A
52
+ // hidden tab costs its first chunk of output in each spell; a quiet one costs nothing.
53
+ // Each display takes a PLACE (at most MAX_SHOWN), and a tab displayed `instead` of another takes
54
+ // that one's place; an open holds its place from the call on (the tab that was in it is no longer
55
+ // displayed then), and when its window exists its tab takes that place and is shown, whatever was
56
+ // displayed or shown there meanwhile. The panel never picks a neighbour: after the shown tab is
57
+ // closed or ends by itself NOTHING is shown, the other displayed tab included, until the caller
58
+ // says which (`focus`, `show`); the order of the tabs, the groups and the rule for the neighbour
59
+ // are the caller's. One open is under way at a time, and it counts towards MAX_TERMINALS; a tab
60
+ // closed frees its place at once. Captures are one at a time (one paste buffer, one file: THE
61
+ // CAPTURE), so two displayed tabs that changed are captured one after the other, the one stale
62
+ // longest first.
63
+ //
28
64
  // THE START, ONE PROCESS. The control client starts the server itself: `tmux -C new-session …`,
29
65
  // with `set-option -s exit-unattached on` and the other options in the SAME command list. The
30
66
  // order matters. `exit-unattached` set before any client is attached ends the server at once (the
@@ -89,9 +125,29 @@
89
125
  // hang-up reaches it at once as SIGHUP, and it cleans up after itself. A pane is never closed by
90
126
  // its process's end: `remain-on-exit` is on, so tmux keeps a dead pane with its exit status, and
91
127
  // the control client is subscribed (`refresh-client -B`, DEAD_SUBSCRIPTION) to every pane's
92
- // `#{pane_dead} #{pane_dead_status}`. tmux checks a subscription once a second, so a viewer's end
93
- // is heard within a second: `1 <status>` (no status when a signal ended it). The panel then kills
94
- // the dead pane, which closes its window. A pane-died hook cannot do it: tmux sends no
128
+ // `#{pane_dead} #{pane_dead_status} #{pane_dead_signal}`. tmux checks a subscription once a second,
129
+ // so a viewer's end is heard within a second: `1 <status> ` when it exited, `1 <signal>` when a
130
+ // signal ended it. The panel then kills the dead pane, which closes its window. A pane can be
131
+ // heard dead BEFORE tmux has its status: tmux marks it dead when its terminal hangs up (the
132
+ // process's files closed as it exits) and takes the status only when it reaps the process, a
133
+ // moment later (server_destroy_pane, then server_child_exited; 3.2 to 3.4 at least, and CI on 3.4
134
+ // heard the dead pane between the two). That line, `1 `, is not the end: the line with the status
135
+ // follows at the next check, and the panel waits for it, a bounded time: a viewer heard so is over
136
+ // without a status once STATUS_WAIT_MS have passed with no other line, its pane killed, so a
137
+ // status that never comes never leaves a terminal open that nothing will close (CI, tmux 3.4).
138
+ // THE STATUS TMUX LOSES. A tmux built with libutempter (Ubuntu's, Debian's) can lose a viewer's
139
+ // status for good: at the hang-up server_destroy_pane calls utempter_remove_record (3.4,
140
+ // server-fn.c), and libutempter sets SIGCHLD to its default while it forks and waits for its
141
+ // helper, so a viewer that exits in that moment has its SIGCHLD discarded. tmux reaps only on a
142
+ // SIGCHLD (waitpid for any child), so the viewer stays a zombie, and its status unknown, until
143
+ // another child of the server exits (awebai/oats#1277; spawn.c guards the same call on a pane's
144
+ // creation by signalling itself). So a viewer heard dead with no status makes the server run a
145
+ // child that exits at once, `run-shell true` through the control client, at once and every
146
+ // REAP_ASK_MS while it waits: that child's SIGCHLD makes tmux reap every child that has exited,
147
+ // the viewer included, and the line with its status follows at the next check. No process is
148
+ // signalled by pid. Without the lost SIGCHLD the child changes nothing.
149
+ // tmux 3.2 has no `pane_dead_signal` (3.3 added it), so there a signal's end reads `1 ` for good,
150
+ // and the wait is the shorter DEAD_WAIT_MS. A pane-died hook cannot do it: tmux sends no
95
151
  // notification for a command a hook runs. A pane the panel kills (close(), an open given up) is
96
152
  // gone at once, with no status. Verified with tmux 3.4 and 3.7c; read in 3.2's source (control.c,
97
153
  // format.c, server-fn.c), the same.
@@ -108,15 +164,17 @@ import { closeSync, constants as FS, fstatSync, lstatSync, openSync, readSync, r
108
164
  import { tmpdir as osTmpdir } from "node:os";
109
165
  import { join } from "node:path";
110
166
 
111
- /** How many terminals a run may hold open at once in the next version. This version opens one at
112
- * a time: `open` refuses while one is open (E_PANEL_BUSY). */
167
+ /** How many terminals a run may hold open at once, as tabs (THE TABS): an open past it, counting
168
+ * one under way, is refused (E_PANEL_FULL). */
113
169
  export const MAX_TERMINALS = 4;
170
+ /** How many tabs are displayed at once, at most (THE TABS): one per group of a split. */
171
+ export const MAX_SHOWN = 2;
114
172
  /** The most of a viewer's stderr that is kept, in bytes: the last ones. */
115
173
  export const STDERR_KEPT = 4096;
116
174
  /** The frame tick, in milliseconds: a capture follows the output that asked for it by one tick, so
117
175
  * a burst of output is drawn once. The tick is not what bounds the rate: a fresh capture (open,
118
- * resize, refresh, showing again) skips it, and what bounds them all is that at most one capture
119
- * is in flight. */
176
+ * show, resize, refresh, showing again) skips it, and what bounds them all is that at most one
177
+ * capture is in flight. */
120
178
  export const FRAME_MS = 16;
121
179
  /** The pane's command around the viewer, a CONSTANT: its stderr to the file named by E, then the
122
180
  * viewer itself in the shell's place (`exec "$0" "$@"`: its argv, which follows this script as
@@ -131,10 +189,28 @@ export const FRAME_MS = 16;
131
189
  * VIEWER). */
132
190
  export const VIEW_SCRIPT = 'exec "$0" "$@" 2>"$E"';
133
191
  /** The control client's subscription to every pane's end (THE END OF A VIEWER): its name, and
134
- * the line tmux prints when a pane's value changes, `1 <status>` for a dead pane (no status when
135
- * a signal ended it), `0 ` for a live one. */
192
+ * the line tmux prints when a pane's value changes, `1 <status> ` for a dead pane whose process
193
+ * exited, `1 <signal>` for one a signal ended (a name, or its number), `1 ` for one whose status
194
+ * tmux does not have yet (or, on tmux 3.2, a signal's), `0 ` for a live one. */
136
195
  const DEAD_SUBSCRIPTION = "oats-tui-dead";
137
- const DEAD_LINE = /^%subscription-changed oats-tui-dead \$\d+ (@\d+) \d+ %\d+ : ([01]) (\d{0,3})$/;
196
+ const DEAD_LINE = /^%subscription-changed oats-tui-dead \$\d+ (@\d+) \d+ %\d+ : ([01]) (\d{0,3}) ([A-Z0-9]{0,12})$/;
197
+ /** On tmux 3.2 (no `pane_dead_signal`), how long a viewer heard dead with no status and no signal
198
+ * (`1 `) waits for the line that has one, in milliseconds: two checks of the subscription past
199
+ * the one that heard it. */
200
+ export const DEAD_WAIT_MS = 2500;
201
+ /** On tmux 3.3 and later, the same wait: ten checks of the subscription. tmux has the status a
202
+ * moment after the hang-up; a viewer that closed its terminal and lives on keeps it longer, and
203
+ * one whose status never comes is over without one when this has passed. */
204
+ export const STATUS_WAIT_MS = 10000;
205
+ /** While a viewer waits for its status, how often the server is made to reap its children (THE
206
+ * STATUS TMUX LOSES), in milliseconds: once a check of the subscription. */
207
+ export const REAP_ASK_MS = 1000;
208
+ /** The child the server runs for that, which exits at once and prints nothing. */
209
+ const REAP_COMMAND = "run-shell true";
210
+ /** The first tmux whose `pane_dead_signal` says which signal ended a pane. */
211
+ const DEAD_SIGNAL_TMUX = Object.freeze([3, 3]);
212
+ /** What a dead line with no status and no signal says of a viewer: its status is still to come. */
213
+ const PENDING = Symbol("pending");
138
214
  /** The one session of the private server, and its keeper window's command. */
139
215
  export const SESSION = "oats-tui";
140
216
  /** The keeper's command (see THE KEEPER), a constant run as `sh -c KEEPER_SCRIPT oats-tui-keeper
@@ -169,7 +245,7 @@ export const startCommands = ({ alive }) => [
169
245
  ["set-option", "-gw", "remain-on-exit", "on"],
170
246
  // Nothing drawn over a dead pane (tmux 3.3 and later; -q: 3.2 has no such option).
171
247
  ["set-option", "-gwq", "remain-on-exit-format", ""],
172
- ["refresh-client", "-B", `${DEAD_SUBSCRIPTION}:%*:#{pane_dead} #{pane_dead_status}`],
248
+ ["refresh-client", "-B", `${DEAD_SUBSCRIPTION}:%*:#{pane_dead} #{pane_dead_status} #{pane_dead_signal}`],
173
249
  ["unbind-key", "-a"],
174
250
  ["unbind-key", "-a", "-T", "root"],
175
251
  ["unbind-key", "-a", "-T", "copy-mode"],
@@ -231,13 +307,13 @@ function tmuxEnvironment(env) {
231
307
  const cells = (n, fallback) => (Number.isInteger(n) && n > 0 ? Math.min(n, 10_000) : fallback);
232
308
  /** Bytes as tmux's `send-keys -H` takes them: two hex digits each, separated by spaces. */
233
309
  const hex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(" ");
234
- /** Whether a `tmux -V` answer names a version older than MIN_TMUX. A name without a version
235
- * (a build from the repository says `master` or `next-…`) is taken as new enough. */
236
- function tooOld(answer) {
310
+ /** Whether a `tmux -V` answer names a version older than `[major, minor]`. A name without a
311
+ * version (a build from the repository says `master` or `next-…`) is taken as new enough. */
312
+ function older(answer, [least, leastMinor]) {
237
313
  const found = /(\d+)\.(\d+)/.exec(String(answer));
238
314
  if (!found) return false;
239
315
  const [major, minor] = [Number(found[1]), Number(found[2])];
240
- return major < MIN_TMUX[0] || (major === MIN_TMUX[0] && minor < MIN_TMUX[1]);
316
+ return major < least || (major === least && minor < leastMinor);
241
317
  }
242
318
 
243
319
  /** What this module does to the file system, each replaceable by a test.
@@ -295,8 +371,9 @@ function readPart(file, max, fromEnd) {
295
371
  } finally { quietly(() => closeSync(fd)); }
296
372
  }
297
373
 
298
- /** The panel of a run: the private server, its control client and the viewer open in it.
299
- * -> { open, close, resize, input, paste, setVisible, refresh, pause, resume, end, get current }
374
+ /** The panel of a run: the private server, its control client and the viewers open in it, its
375
+ * tabs (THE TABS).
376
+ * -> { open, show, focus, hide, close, resize, input, paste, setVisible, refresh, pause, resume, end, get tabs, get current }
300
377
  *
301
378
  * Options:
302
379
  * dir() the run's private directory: called at the first open, and expected to answer
@@ -305,8 +382,13 @@ function readPart(file, max, fromEnd) {
305
382
  * capture(text, { cols, rows }) REQUIRED: the caller's cell builder, handed what
306
383
  * `capture-pane -e -N` captured (its lines joined by "\n") and the pane's size;
307
384
  * what it answers is handed on as `screen`.
308
- * onScreen({ id, screen, cursor: { x, y, visible } }) a capture of the open viewer.
309
- * onClosed({ id, status, stderr, asked }) a viewer ended: `status` its exit status as tmux
385
+ * onScreen({ id, screen, cursor: { x, y, visible } }) a capture of a displayed tab, `id`
386
+ * its own: never of a tab not displayed.
387
+ * onActivity({ id }) a tab not displayed had output: told once in each spell it is not
388
+ * displayed (told again only after it was displayed and then not again). Nothing
389
+ * is captured for it. A displayed tab's output is never activity, the panel
390
+ * hidden (setVisible) or not.
391
+ * onClosed({ id, status, stderr, asked }) a viewer ended, displayed or not: `status` its exit status as tmux
310
392
  * kept it for its dead pane (null when there is none: a signal ended the viewer,
311
393
  * its pane was killed, or its server went away), `stderr` the last STDERR_KEPT
312
394
  * bytes it wrote to its file, as text, `asked`
@@ -315,40 +397,80 @@ function readPart(file, max, fromEnd) {
315
397
  * env the environment tmux is given (TMUX and TMUX_PANE removed); default process.env.
316
398
  * tmux the program; default "tmux" on PATH.
317
399
  * spawn, execFile, execFileSync, fs (see PANEL_FS), timers ({ setTimeout, clearTimeout }: the
318
- * frame tick, the only timer of this module), clock (an ISO time, for
400
+ * frame tick and a dead viewer's wait for its status, STATUS_WAIT_MS or
401
+ * DEAD_WAIT_MS, the only timers of this module), clock (an ISO time, for
319
402
  * owner.json), pid (the TUI's, for owner.json): for tests.
403
+ * trace(text) told, when given, each notification of a viewer's end the control client printed
404
+ * (the dead-pane subscription's lines, a window's end, the client's own end) and
405
+ * what the panel made of it: tmux's ids and numbers and this module's words only,
406
+ * never a pane's text. For diagnosing an end in a test; default none.
320
407
  * A callback that throws does not break the panel: what it threw is thrown again in a microtask,
321
408
  * where the run hears it as any uncaught error.
322
409
  *
323
- * open({ argv, cols, rows }) -> Promise<{ id }>: start the viewer `argv` ([node, bin, ...args],
324
- * the kernel's `oats session attach …`) in a new window of cols x rows. `id` is tmux's window id.
325
- * The first open starts the server; so does the first after the server went away. Rejected with
326
- * a coded Error: E_PANEL_BUSY (a viewer is open, or an open is under way: the caller closes it
327
- * first, and may open the next as soon as close() has returned),
328
- * E_PANEL_TMUX (no tmux, or one older than 3.2), E_PANEL_START (the server or its control
410
+ * WHICH PLACE (`instead`, of open and show): omitted, the shown tab's place; an id, that
411
+ * displayed tab's place (an id of a tab not displayed is as omitted); null, a place of its own
412
+ * beside the displayed ones while fewer than MAX_SHOWN are taken, and with MAX_SHOWN taken, as
413
+ * omitted. With no tab shown, an omitted `instead` takes the place an open under way holds (so
414
+ * that open overrides it, as it does a show), else a place of its own while there is room, else
415
+ * the first place taken.
416
+ *
417
+ * open({ argv, cols, rows, instead }) -> Promise<{ id }>: start the viewer `argv` ([node, bin,
418
+ * ...args], the kernel's `oats session attach …`) in a NEW tab, a new window of cols x rows (its
419
+ * own size: no other window is resized; a size that is no number is the last one given), and
420
+ * display it in the place `instead` names (WHICH PLACE): the tab displayed there is no longer
421
+ * displayed from the call on, nothing is shown (keys are dropped) until the new window exists,
422
+ * and then the new tab takes that place and is shown, whatever a show() or focus() made
423
+ * meanwhile. `id` is tmux's window id. The first open starts the server; so does the first after
424
+ * the server went away. Rejected with a coded Error:
425
+ * E_PANEL_FULL (MAX_TERMINALS tabs are open, an open under way counted: the caller closes one
426
+ * first, and may open as soon as close() has returned), E_PANEL_BUSY (another open is under
427
+ * way), E_PANEL_TMUX (no tmux, or one older than 3.2), E_PANEL_START (the server or its control
329
428
  * client did not start; `detail` holds what tmux said, untrusted text), E_PANEL_OPEN (the
330
- * window was not made; `detail` likewise, or a bad argv), E_PANEL_ENDED (after end()).
331
- * close(): end the open viewer (`kill-pane`: its terminal hangs up, the viewer gets SIGHUP and
332
- * cleans up after itself). THE SLOT IS FREE WHEN IT RETURNS: the next open may follow at once,
333
- * and the closed viewer is reported by onClosed with `asked: true` when its window has ended.
334
- * Asked while an open is under way, that open still answers its `{ id }`, and its window is
335
- * killed as soon as it exists (reported likewise). With no viewer and no open, nothing.
336
- * resize(cols, rows): the window's new size, then a fresh capture.
337
- * input(bytes): bytes (a Buffer, or a string as UTF-8) typed into the viewer, in order. With no
338
- * viewer window yet (an open under way) or none at all, they are dropped.
339
- * paste(text): `text` as a bracketed paste (any end mark inside it removed); the agent's own
340
- * server decides whether its program sees the marks (the viewer is a tmux client).
341
- * setVisible(on): hidden, no capture runs and output only marks the screen stale; shown again,
342
- * one fresh capture. refresh(): one fresh capture now (after `fg`, Ctrl+L).
343
- * pause() / resume(): around a suspend of the TUI: tmux stops sending the pane's output (a
344
- * stopped TUI does not read its pipe), then sends it again, and a fresh capture follows.
345
- * end(): leave, synchronously: kill the server, end the control client, remove the socket,
346
- * owner.json and the view files. Idempotent.
347
- * current: the id of the open viewer, or null.
429
+ * window was not made; `detail` likewise, or a bad argv), E_PANEL_ENDED (after end()). An open
430
+ * that is refused once under way displays nothing in its place and leaves nothing shown (the
431
+ * other displayed tab stays displayed): which tab to show is the caller's.
432
+ * show(id, { instead }): display tab `id` in the place `instead` names (WHICH PLACE; the tab
433
+ * there is no longer displayed) and make it the shown one; one fresh capture of it follows, when
434
+ * the panel is visible. A tab already displayed only becomes the shown one (`instead` ignored,
435
+ * nothing captured). An unknown id does nothing.
436
+ * focus(id): a displayed tab becomes the shown one: the keys go to it. Nothing else changes, and
437
+ * nothing is captured. A tab not displayed, or an unknown id, does nothing.
438
+ * hide(id): tab `id` is no longer displayed (its output marks it, from then on); when it was the
439
+ * shown one, the other displayed tab is shown, or none. A tab not displayed does nothing.
440
+ * close(id): end tab `id`'s viewer (`kill-pane`: its terminal hangs up, the viewer gets SIGHUP
441
+ * and cleans up after itself). ITS PLACE IS FREE WHEN IT RETURNS: the next open may follow at
442
+ * once, and the closed viewer is reported by onClosed with `asked: true` when its window has
443
+ * ended. With no id: the open under way if there is one (it still answers its `{ id }`, its
444
+ * window is killed as soon as it exists, and it is reported likewise), else the shown tab.
445
+ * A displayed tab closed is no longer displayed. After the shown tab is closed, or ends by
446
+ * itself, nothing is shown (the other displayed tab stays displayed, not shown) until focus() or
447
+ * show(). An unknown id, or nothing to close, does nothing.
448
+ * resize(cols, rows, ids): the windows of the tabs `ids` names (an array of ids), or with no
449
+ * `ids` every tab's (an open under way's too, when its window exists), resized to cols x rows;
450
+ * then one fresh capture of each displayed tab whose size changed. A size that is no number
451
+ * keeps that window's own.
452
+ * input(bytes): bytes (a Buffer, or a string as UTF-8) typed into the shown tab's viewer, in
453
+ * order. With none shown (an open under way, or no tab), they are dropped.
454
+ * paste(text): `text` as a bracketed paste (any end mark inside it removed), into the shown tab;
455
+ * the agent's own server decides whether its program sees the marks (the viewer is a tmux
456
+ * client).
457
+ * setVisible(on): the panel as a whole (behind another view). Hidden, no capture runs and a
458
+ * displayed tab's output only marks its screen stale (no activity); shown again, one fresh
459
+ * capture of each displayed tab. refresh(): one fresh capture of each displayed tab now (after
460
+ * `fg`, Ctrl+L).
461
+ * pause() / resume(): around a suspend of the TUI: tmux stops sending every pane's output (a
462
+ * stopped TUI does not read its pipe), then sends it again, and a fresh capture of each
463
+ * displayed tab follows.
464
+ * end(): leave, synchronously: kill the server (every tab with it), end the control client,
465
+ * remove the socket, owner.json and the view files. Idempotent.
466
+ * tabs: { ids, shown, displayed }: the open tabs' window ids in opening order (an open under way
467
+ * is listed once it has its id), the shown one's, or null, and the displayed ones' in opening
468
+ * order (the shown one among them). A new object each time.
469
+ * current: tabs.shown.
348
470
  * No method but open() throws or rejects: a server that went away makes each of them do nothing. */
349
- export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () => {}, env = process.env, tmux = "tmux",
471
+ export function createPanel({ dir, capture, onScreen = () => {}, onActivity = () => {}, onClosed = () => {}, env = process.env, tmux = "tmux",
350
472
  spawn = nodeSpawn, execFile = nodeExecFile, execFileSync = nodeExecFileSync, fs: givenFs = {}, timers = { setTimeout, clearTimeout },
351
- clock = () => new Date().toISOString(), pid = process.pid } = {}) {
473
+ clock = () => new Date().toISOString(), pid = process.pid, trace = null } = {}) {
352
474
  if (typeof dir !== "function") throw new TypeError("createPanel needs dir(): the run's private directory");
353
475
  if (typeof capture !== "function") throw new TypeError("createPanel needs capture(text, { cols, rows }): the cell builder");
354
476
  const fs = { ...PANEL_FS, ...givenFs };
@@ -356,6 +478,8 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
356
478
  /** The run directory and the socket in it, once known; whether owner.json was written, tmux's
357
479
  * version checked, and a server ever started in this run. */
358
480
  let runDir = null, socket = null, ownerWritten = false, checked = false, everStarted = false;
481
+ /** Whether this tmux says which signal ended a pane (DEAD_SIGNAL_TMUX), known once checked. */
482
+ let signals = true;
359
483
  /** The capture's file, and that path as a word of a control line (see THE CAPTURE). */
360
484
  let capturePath = null, captureWord = null;
361
485
  /** The write end of `<run dir>/alive`, held for the run once made (see THE KEEPER), or null. */
@@ -364,25 +488,36 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
364
488
  * block being read), startLeft (the blocks of the start list still to come), attached, gone,
365
489
  * onAttach, stderr }, or null. A start under way is `starting` (its promise). */
366
490
  let server = null, starting = null;
367
- /** THE SLOT: the viewer open now ({ id, pane, cols, rows, files, asked, over, status }), or the open
368
- * under way that will be it (`opening`: { closeAsked, files }), or neither. close() frees it at
369
- * once: the viewer it closed waits in `closing` (window id -> viewer) for its window's end, and
370
- * an open it gave up goes on to kill its window as soon as it exists. Every open under way, the
371
- * given-up ones included, is in `openings`.
491
+ /** THE TABS: the viewers open now, by window id in opening order (`tabs`: id -> { id, pane, cols,
492
+ * rows, files, asked, over, status, marked, place, dirty, due, dueAt }, `cols` and `rows` its
493
+ * window's own size, `marked` once its activity was told in this spell not displayed, `place`
494
+ * the place it is displayed in, or null), the one of them shown (`shown`, or null: always a
495
+ * displayed one), and the open under way that will be the next (`opening`: { closeAsked, files,
496
+ * place, size }, `size` the one its window will have), or none. `places`: the places taken, at
497
+ * most MAX_SHOWN, each { v (the tab displayed in it, or null), opening (the open under way that
498
+ * holds it, or null) }. close() frees a place at once: the viewer it
499
+ * closed waits in `closing` (window id -> viewer) for its window's end, and an open it gave up
500
+ * goes on to kill its window as soon as it exists. Every open under way, the given-up ones
501
+ * included, is in `openings`. `size` is the size of the last open, or of the last resize of
502
+ * every tab: an open that gives none takes it.
372
503
  * `closedSeen`: the window ids whose end was heard while an open was under way. A viewer that
373
504
  * exits at once can end before new-window has answered with its id; ids are never reused by a
374
505
  * server, and the set is emptied when no open is under way, and at every new server.
375
- * `diedSeen`: the same for a pane heard dead (window id -> its status, or null). */
376
- let viewer = null, opening = null;
377
- const closing = new Map(), openings = new Set(), closedSeen = new Set(), diedSeen = new Map();
378
- /** The frames: the screen is stale (`dirty`), a tick is armed (`tick`), a capture is in flight. */
379
- let dirty = false, tick = null, capturing = false, visible = true, paused = false;
506
+ * `diedSeen`: the same for a pane heard dead (window id -> its status, null, or PENDING). */
507
+ let shown = null, opening = null, size = { cols: 80, rows: 24 };
508
+ const tabs = new Map(), closing = new Map(), openings = new Set(), places = new Set(), closedSeen = new Set(), diedSeen = new Map();
509
+ /** The frames: a tick is armed (`tick`), a capture is in flight (`capturing`); each displayed
510
+ * tab's screen is stale (`dirty`, since `dueAt` counted) and its capture waits for the one in
511
+ * flight (`due`). */
512
+ let tick = null, capturing = false, visible = true, paused = false, dues = 0;
380
513
  let ended = false, files = 0;
381
514
 
382
515
  /** A callback of the caller's, called so that what it throws cannot break the panel. */
383
516
  function tell(act) {
384
517
  try { act(); } catch (error) { queueMicrotask(() => { throw error; }); }
385
518
  }
519
+ /** One line of the trace, when the caller asked for one. */
520
+ const traced = (text) => { if (trace) tell(() => trace(text)); };
386
521
  /** The flags every call starts with. */
387
522
  const base = () => ["-u", "-f", "/dev/null", "-S", socket];
388
523
 
@@ -420,7 +555,9 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
420
555
  * `%end` or `%error` line that repeats its `%begin`'s time, number and flags EXACTLY (tmux
421
556
  * prints the same time and number on both lines of a block). No pane's text is ever in a block
422
557
  * (THE CAPTURE); the exact end is kept all the same. Outside a block a line is a notification
423
- * (tmux never prints one inside a block; `%output` carries a pane's text escaped, one line). The FIRST blocks, one per command of
558
+ * (`%output` carries a pane's text escaped, one line). tmux prints notifications outside blocks,
559
+ * but for the `%pause` or `%continue` that a `refresh-client -A` writes while it runs, which is
560
+ * inside that command's block and is all its block may hold (`flow`). The FIRST blocks, one per command of
424
561
  * the start list, answer the start itself; every later one answers the oldest command waiting. */
425
562
  function heard(s, line) {
426
563
  if (s.block) {
@@ -452,11 +589,16 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
452
589
  return;
453
590
  }
454
591
  const [kind, first] = line.split(" ", 2);
455
- if (kind === "%output" || kind === "%extended-output") { if (viewer && first === viewer.pane) stale(); }
456
- else if (kind === "%layout-change") { if (viewer && first === viewer.id) stale(); }
457
- else if (kind === "%window-close" || kind === "%unlinked-window-close") windowClosed(first);
458
- else if (kind === "%exit") lost(s);
459
- else if (kind === "%subscription-changed") { const dead = DEAD_LINE.exec(line); if (dead && dead[2] === "1") paneDied(dead[1], dead[3] === "" ? null : Number(dead[3])); }
592
+ if (kind === "%output" || kind === "%extended-output") output(first);
593
+ // Not output: a resize makes one for every tab's window (THE TABS).
594
+ else if (kind === "%layout-change") { const v = tabs.get(first); if (v?.place && !v.over) stale(v); }
595
+ else if (kind === "%window-close" || kind === "%unlinked-window-close") { traced(line); windowClosed(first); }
596
+ else if (kind === "%exit") { traced(line); lost(s); }
597
+ else if (kind === "%subscription-changed") {
598
+ const dead = DEAD_LINE.exec(line);
599
+ if (first === DEAD_SUBSCRIPTION) traced(dead ? line : `${DEAD_SUBSCRIPTION}: a line not of its shape`);
600
+ if (dead && dead[2] === "1") paneDied(dead[1], dead[3] !== "" ? Number(dead[3]) : dead[4] !== "" ? null : PENDING);
601
+ }
460
602
  }
461
603
 
462
604
  /** The start's blocks are over, or one failed: the start waits for this (see `ensureServer`). */
@@ -468,8 +610,8 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
468
610
  }
469
611
 
470
612
  /** The control client is gone (`%exit`, its pipe closed, it did not start): the server with it,
471
- * as far as this run is concerned. Every command waiting is answered as failed, the open viewer
472
- * is closed with no status, and the next open starts a new server. */
613
+ * as far as this run is concerned. Every command waiting is answered as failed, every tab is
614
+ * closed with no status, and the next open starts a new server. */
473
615
  function lost(s) {
474
616
  if (s.gone) return;
475
617
  s.gone = true;
@@ -481,8 +623,7 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
481
623
  quietly(() => s.child.kill("SIGTERM"));
482
624
  quietly(() => s.child.unref());
483
625
  stopFrames();
484
- if (viewer) finish(viewer, { lost: true });
485
- for (const v of [...closing.values()]) finish(v, { lost: true });
626
+ for (const v of [...tabs.values(), ...closing.values()]) finish(v, { lost: true });
486
627
  }
487
628
 
488
629
  /** Start the server through the control client, with startCommands as its list, and wait for
@@ -549,7 +690,8 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
549
690
  try { answer = await call(["-V"]); } catch (error) {
550
691
  throw error?.code === "ENOENT" ? refusal("E_PANEL_TMUX", "tmux is not installed") : refusal("E_PANEL_TMUX", "tmux did not say its version", { detail: detail(error) });
551
692
  }
552
- if (tooOld(answer.stdout)) throw refusal("E_PANEL_TMUX", "the panel needs tmux 3.2 or later", { detail: answer.stdout.trim().slice(0, 80) });
693
+ if (older(answer.stdout, MIN_TMUX)) throw refusal("E_PANEL_TMUX", "the panel needs tmux 3.2 or later", { detail: answer.stdout.trim().slice(0, 80) });
694
+ signals = !older(answer.stdout, DEAD_SIGNAL_TMUX);
553
695
  checked = true;
554
696
  }
555
697
  if (ended) throw refusal("E_PANEL_ENDED", "the panel has ended");
@@ -603,37 +745,90 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
603
745
 
604
746
  // FRAMES ---------------------------------------------------------------------------------------
605
747
 
606
- /** Whether a capture may run now. */
607
- const showing = () => viewer !== null && !viewer.over && visible && !paused && !ended;
608
- /** Arm the tick, unless one is armed or a capture is in flight (it arms one when it is over). */
748
+ /** Whether a capture may run now (of a displayed tab: no other is ever captured). */
749
+ const capturable = () => visible && !paused && !ended;
750
+ /** The displayed tabs, in opening order. */
751
+ const displayedTabs = () => [...tabs.values()].filter((v) => v.place !== null && !v.over);
752
+ /** Arm the tick, when a displayed tab's screen is stale and it is not yet waiting for the capture
753
+ * in flight, unless one is armed or a capture is in flight (it arms one when it is over). The
754
+ * tick makes every stale displayed tab wait for its capture, and they are captured one after the
755
+ * other. */
609
756
  function arm() {
610
- if (!showing() || tick !== null || capturing) return;
611
- tick = timers.setTimeout(() => { tick = null; startCapture(); }, FRAME_MS);
757
+ if (!capturable() || tick !== null || capturing) return;
758
+ if (!displayedTabs().some((v) => v.dirty && !v.due)) return;
759
+ tick = timers.setTimeout(() => {
760
+ tick = null;
761
+ for (const v of displayedTabs()) if (v.dirty) due(v);
762
+ pump();
763
+ }, FRAME_MS);
612
764
  }
613
765
  function stopFrames() {
614
766
  if (tick !== null) { quietly(() => timers.clearTimeout(tick)); tick = null; }
615
767
  }
616
- /** A notification said the screen changed: stale, and a capture one tick later. NO TIMER RUNS
617
- * BUT THIS ONE: nothing is ever captured unless tmux said something changed, or the caller asked. */
618
- function stale() { dirty = true; arm(); }
619
- /** A capture now (or right after the one in flight), whatever the tick. */
620
- function fresh() {
621
- dirty = true;
622
- if (!showing() || capturing) return;
768
+ /** The tick, put away when no displayed tab's screen is stale any more. */
769
+ function idle() { if (tick !== null && !displayedTabs().some((v) => v.dirty)) stopFrames(); }
770
+ /** A tab's screen stale: counted (`dueAt`) when it was not, so the one stale longest is captured
771
+ * first. */
772
+ function soil(v) { if (!v.dirty) { v.dirty = true; v.dueAt = ++dues; } }
773
+ /** A tab's screen stale, and its capture waiting for the one in flight. */
774
+ function due(v) { soil(v); v.due = true; }
775
+ /** A notification said a displayed tab's screen changed: stale, and a capture one tick later. NO
776
+ * TIMER RUNS BUT THIS ONE: nothing is ever captured unless tmux said something changed, or the
777
+ * caller asked. */
778
+ function stale(v) { soil(v); arm(); }
779
+ /** A pane printed: a displayed tab's screen is stale; a tab not displayed is marked, once in this
780
+ * spell not displayed, and paused (THE OUTPUT OF A TAB NOT DRAWN), and nothing is captured for
781
+ * it. What it printed before tmux took the pause in is nothing more. Any other pane's output (the
782
+ * keeper's, an open under way, a viewer being closed) is nobody's. */
783
+ function output(pane) {
784
+ for (const v of tabs.values()) {
785
+ if (v.pane !== pane) continue;
786
+ if (v.place !== null) return stale(v);
787
+ if (!v.marked && !v.over && !ended) { v.marked = true; flow(v, false); tell(() => onActivity({ id: v.id })); }
788
+ return;
789
+ }
790
+ }
791
+ /** Tab `v`'s pane paused or continued for this client (THE OUTPUT OF A TAB NOT DRAWN), when it is
792
+ * not so already. A tab whose viewer is over is left alone: its pane is going. */
793
+ function flow(v, on) {
794
+ if (v.over || v.off === !on) return;
795
+ v.off = !on;
796
+ // tmux prints `%pause %<pane>` (or `%continue`) while it runs the command, so inside its block.
797
+ const said = `%${on ? "continue" : "pause"} ${v.pane}`;
798
+ ask(`refresh-client -A '${v.pane}:${on ? "continue" : "pause"}'`, (lines) => lines.length === 0 || (lines.length === 1 && lines[0] === said));
799
+ }
800
+ /** A capture of tab `v` now (or right after the one in flight), whatever the tick. A tick armed
801
+ * then is folded in: every stale displayed tab waits for its capture too. */
802
+ function fresh(v) {
803
+ due(v);
804
+ if (!capturable() || capturing) return;
623
805
  stopFrames();
624
- startCapture();
806
+ for (const other of displayedTabs()) if (other.dirty) due(other);
807
+ pump();
808
+ }
809
+ /** A fresh capture of every displayed tab. */
810
+ function freshAll() { for (const v of displayedTabs()) fresh(v); }
811
+ /** The next capture: of the waiting displayed tab stale longest, else the tick for the stale
812
+ * ones. At most one capture is in flight. */
813
+ function pump() {
814
+ if (capturing || !capturable()) return;
815
+ let next = null;
816
+ for (const v of displayedTabs()) if (v.due && (next === null || v.dueAt < next.dueAt)) next = v;
817
+ if (next === null) return arm();
818
+ startCapture(next);
625
819
  }
626
820
  /** A capture whose promise nobody awaits: it never rejects. */
627
- const startCapture = () => { captureNow().catch(() => { capturing = false; }); };
628
- /** One capture: the pane's cells into the capture's file, and its cursor, asked through the
629
- * control client in one go (see THE CAPTURE). At most one in flight; what was marked stale
630
- * meanwhile arms the next tick after it. A capture that fails (the pane gone, the file missing,
631
- * too large or not a file) draws nothing, and the next change tries again. */
632
- async function captureNow() {
633
- const v = viewer;
634
- if (!showing() || capturing) return;
821
+ const startCapture = (v) => { captureNow(v).catch(() => { capturing = false; }); };
822
+ /** One capture of tab `v`: the pane's cells into the capture's file, and its cursor, asked
823
+ * through the control client in one go (see THE CAPTURE). At most one in flight, so the one
824
+ * file is never written for two panes at once; what was marked stale meanwhile is captured
825
+ * after it. A capture that fails (the pane gone, the file missing, too large or not a file)
826
+ * draws nothing, and the next change tries again. */
827
+ async function captureNow(v) {
828
+ if (capturing || !capturable()) return;
635
829
  capturing = true;
636
- dirty = false;
830
+ v.dirty = false;
831
+ v.due = false;
637
832
  const [taken, saved, , cursor] = await Promise.all([
638
833
  ask(`capture-pane -e -N -b ${CAPTURE_BUFFER} -t ${v.pane}`),
639
834
  ask(`save-buffer -b ${CAPTURE_BUFFER} ${captureWord}`),
@@ -641,9 +836,12 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
641
836
  ask(`display -p -t ${v.pane} '#{cursor_x} #{cursor_y} #{cursor_flag}'`, SAYS_CURSOR),
642
837
  ]);
643
838
  capturing = false;
644
- if (ended || viewer !== v || v.over) return;
839
+ if (ended) return;
840
+ // No longer displayed (or over) while it was in flight: not drawn, and the capture that waited
841
+ // for this one (the show's) runs now.
842
+ if (v.place === null || v.over) return pump();
645
843
  // Hidden or paused while it was in flight: not drawn; the capture that showing again asks for is.
646
- if (!showing()) { dirty = true; return; }
844
+ if (!capturable()) { soil(v); return; }
647
845
  const held = taken.ok && saved.ok && cursor.ok ? quietly(() => fs.whole(capturePath, CAPTURE_MAX)) : null;
648
846
  if (typeof held === "string") {
649
847
  const at = CURSOR_LINE.exec(cursor.lines[0]);
@@ -652,23 +850,53 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
652
850
  const text = held.endsWith("\n") ? held.slice(0, -1) : held;
653
851
  tell(() => onScreen({ id: v.id, screen: capture(text, { cols: v.cols, rows: v.rows }), cursor: where }));
654
852
  }
655
- if (dirty) arm();
853
+ pump();
656
854
  }
657
855
 
658
856
  // VIEWERS --------------------------------------------------------------------------------------
659
857
 
660
858
  /** A viewer's pane is dead (THE END OF A VIEWER): the viewer is over with the status tmux kept,
661
- * and its pane is killed, which closes its window. A pane not yet known (an open under way) is
662
- * remembered with its status; any other is not a viewer's (the keeper's, one already over). */
859
+ * and its pane is killed, which closes its window. PENDING (dead, and tmux has no status yet) is
860
+ * not the end: the viewer waits for the line with its status (`waitStatus`). A pane not yet
861
+ * known (an open under way) is remembered with what was heard; any other is not a viewer's (the
862
+ * keeper's, one already over). */
663
863
  function paneDied(id, status) {
664
- const v = viewer?.id === id ? viewer : closing.get(id);
864
+ const v = tabs.get(id) ?? closing.get(id);
865
+ if (v && status === PENDING) return waitStatus(v);
665
866
  if (v) { v.status = status; ask(`kill-pane -t ${v.pane}`); return finish(v, {}); }
666
- if (openings.size > 0) diedSeen.set(id, status);
867
+ if (openings.size > 0 && !(status === PENDING && diedSeen.has(id))) diedSeen.set(id, status);
868
+ }
869
+ /** A viewer heard dead with no status: it stays open until the line with its status or its
870
+ * signal, a close, or its server's end, and at most STATUS_WAIT_MS (DEAD_WAIT_MS on tmux 3.2,
871
+ * which says a signal's end no other way): then it is over without a status, and its pane is
872
+ * killed. Armed once. Meanwhile the server reaps its children, at once and every REAP_ASK_MS
873
+ * (`reap`). */
874
+ function waitStatus(v) {
875
+ if (v.over || v.waiting !== null) return;
876
+ const ms = signals ? STATUS_WAIT_MS : DEAD_WAIT_MS;
877
+ traced(`${v.id} dead, waiting ${ms} ms for its status`);
878
+ reap(v);
879
+ v.waiting = timers.setTimeout(() => {
880
+ v.waiting = null;
881
+ if (ended || v.over) return;
882
+ traced(`${v.id} no status after ${ms} ms`);
883
+ v.status = null;
884
+ if (server && !server.gone) ask(`kill-pane -t ${v.pane}`);
885
+ finish(v, {});
886
+ }, ms);
887
+ }
888
+ /** The server runs a child that exits at once, so that it reaps a viewer whose SIGCHLD it lost
889
+ * (THE STATUS TMUX LOSES); again in REAP_ASK_MS, until the viewer is over. */
890
+ function reap(v) {
891
+ v.reaping = null;
892
+ if (v.over || ended || !server || server.gone) return;
893
+ ask(REAP_COMMAND);
894
+ v.reaping = timers.setTimeout(() => reap(v), REAP_ASK_MS);
667
895
  }
668
- /** A window ended: the open viewer's, one closing, or (an open under way) one to remember. */
896
+ /** A window ended: a tab's, shown or hidden, one closing, or (an open under way) one to remember. */
669
897
  function windowClosed(id) {
670
- if (viewer && viewer.id === id) return finish(viewer, {});
671
- if (closing.has(id)) return finish(closing.get(id), {});
898
+ const v = tabs.get(id) ?? closing.get(id);
899
+ if (v) return finish(v, {});
672
900
  if (openings.size > 0) closedSeen.add(id);
673
901
  }
674
902
  /** A viewer is over: read what it left, remove its file, and say so. Its status is what tmux kept
@@ -679,14 +907,87 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
679
907
  const status = v.status;
680
908
  if (v.over) return;
681
909
  v.over = true;
910
+ unwait(v);
682
911
  closing.delete(v.id);
683
- if (viewer === v) free();
912
+ leave(v);
684
913
  const stderr = quietly(() => fs.tail(v.files.err, STDERR_KEPT)) ?? "";
914
+ traced(`${v.id} over, status ${gone ? null : status}${gone ? ", its server gone" : ""}${v.asked ? ", closed" : ""}`);
685
915
  forget(v.files);
686
916
  if (!ended) tell(() => onClosed({ id: v.id, status: gone ? null : status, stderr, asked: v.asked }));
687
917
  }
688
- /** The slot is free: no viewer, no frame to come. */
689
- function free() { viewer = null; stopFrames(); dirty = false; }
918
+ /** A viewer's wait for its status (waitStatus), and its asks to reap, put away. */
919
+ function unwait(v) {
920
+ if (v.waiting !== null) { quietly(() => timers.clearTimeout(v.waiting)); v.waiting = null; }
921
+ if (v.reaping !== null) { quietly(() => timers.clearTimeout(v.reaping)); v.reaping = null; }
922
+ }
923
+ /** A tab is no longer one: its place among the tabs is free, it is no longer displayed, and when
924
+ * it was the shown tab, nothing is shown (the panel never picks a neighbour: THE TABS). */
925
+ function leave(v) {
926
+ if (tabs.get(v.id) === v) tabs.delete(v.id);
927
+ undisplay(v);
928
+ }
929
+
930
+ // PLACES (THE TABS) ----------------------------------------------------------------------------
931
+
932
+ /** A tab out of its place: no frame to come for it, not shown, and a new spell not displayed for
933
+ * it, in which its output may mark it again. The place itself is the caller's to keep or free. */
934
+ function detach(v) {
935
+ v.place = null;
936
+ // Heard again until it prints (a displayed tab is paused while the panel is hidden).
937
+ flow(v, true);
938
+ v.marked = false;
939
+ v.dirty = false;
940
+ v.due = false;
941
+ if (shown === v) shown = null;
942
+ }
943
+ /** A tab no longer displayed: its place is freed, or, when an open under way holds it, kept for
944
+ * that open's tab. */
945
+ function undisplay(v) {
946
+ const place = v.place;
947
+ if (!place) return;
948
+ detach(v);
949
+ place.v = null;
950
+ if (!place.opening) places.delete(place);
951
+ idle();
952
+ }
953
+ /** A new place, beside the ones taken (the caller has checked there is room). */
954
+ function newPlace() { const place = { v: null, opening: null }; places.add(place); return place; }
955
+ /** The place `instead` names (see WHICH PLACE in createPanel): taken now, or a new one. */
956
+ function placeFor(instead) {
957
+ const named = typeof instead === "string" ? tabs.get(instead) : undefined;
958
+ if (named && !named.over && named.place) return named.place;
959
+ const room = places.size < MAX_SHOWN;
960
+ if (instead === null && room) return newPlace();
961
+ if (shown?.place) return shown.place;
962
+ const held = [...places].find((place) => place.opening !== null);
963
+ if (held) return held;
964
+ if (room) return newPlace();
965
+ return places.values().next().value;
966
+ }
967
+ /** Tab `v` displayed in `place` (one taken, or a new one when that is gone): the tab displayed
968
+ * there before is no longer displayed. */
969
+ function display(v, place) {
970
+ if (!places.has(place)) place = placeFor(undefined);
971
+ const before = place.v;
972
+ if (before && before !== v) detach(before);
973
+ if (v.place && v.place !== place) undisplay(v);
974
+ place.v = v;
975
+ v.place = place;
976
+ v.marked = false;
977
+ // Continued before anything captures it (show and resize capture after this); paused while
978
+ // the panel is hidden.
979
+ flow(v, visible);
980
+ }
981
+ /** An open no longer holds its place: a place it held empty is freed (a tab a show() put there
982
+ * meanwhile keeps it). */
983
+ function release(mine) {
984
+ const place = mine.place;
985
+ mine.place = null;
986
+ if (!place || place.opening !== mine) return;
987
+ place.opening = null;
988
+ if (place.v === null) places.delete(place);
989
+ }
990
+
690
991
  const forget = (made) => { for (const path of [made?.err, made?.status]) if (path) quietly(() => fs.unlink(path)); };
691
992
  /** End a viewer the caller closed (or gave up while it opened): its pane killed through the
692
993
  * control client, and its end awaited in `closing`. With no server, it is over now. */
@@ -698,12 +999,21 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
698
999
  }
699
1000
 
700
1001
  /** See createPanel. */
701
- function open({ argv, cols, rows } = {}) {
1002
+ function open({ argv, cols, rows, instead } = {}) {
702
1003
  if (ended) return Promise.reject(refusal("E_PANEL_ENDED", "the panel has ended"));
703
- if (viewer || opening) return Promise.reject(refusal("E_PANEL_BUSY", "a terminal is open in the panel"));
1004
+ if (tabs.size + (opening ? 1 : 0) >= MAX_TERMINALS) return Promise.reject(refusal("E_PANEL_FULL", `${MAX_TERMINALS} terminals are open in the panel`));
1005
+ if (opening) return Promise.reject(refusal("E_PANEL_BUSY", "a terminal is opening in the panel"));
704
1006
  if (!Array.isArray(argv) || argv.length === 0 || !argv.every((arg) => typeof arg === "string" && !arg.includes("\0"))) return Promise.reject(refusal("E_PANEL_OPEN", "the viewer's argv is not a list of strings"));
705
- const size = { cols: cells(cols, 80), rows: cells(rows, 24) };
706
- const mine = opening = { closeAsked: false, files: null };
1007
+ // The new window is made at the size it gives, and no other window is resized: each window's
1008
+ // size is the caller's (THE TABS).
1009
+ size = { cols: cells(cols, size.cols), rows: cells(rows, size.rows) };
1010
+ const start = { ...size };
1011
+ // The new tab takes its place from now on: the tab displayed there is no longer displayed, and
1012
+ // nothing is shown, nor typed to, until the new one's window exists.
1013
+ const place = placeFor(instead), mine = opening = { closeAsked: false, files: null, place, size: { ...start } };
1014
+ place.opening = mine;
1015
+ if (place.v) undisplay(place.v);
1016
+ shown = null;
707
1017
  openings.add(mine);
708
1018
  /** This open is no longer under way. */
709
1019
  const settle = () => {
@@ -720,7 +1030,7 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
720
1030
  try { fs.make(made.err); mine.files = made; } catch (error) { throw refusal("E_PANEL_OPEN", "the panel could not make the viewer's file", { detail: detail(error) }); }
721
1031
  let answer;
722
1032
  try {
723
- answer = await call(["set-option", "-t", SESSION, "default-size", `${size.cols}x${size.rows}`,
1033
+ answer = await call(["set-option", "-t", SESSION, "default-size", `${start.cols}x${start.rows}`,
724
1034
  ";", "new-window", "-d", "-P", "-F", "#{window_id} #{pane_id}", "-t", `${SESSION}:`,
725
1035
  "-e", tmuxArgument(`E=${made.err}`),
726
1036
  "/bin/sh", "-c", VIEW_SCRIPT, ...argv.map(tmuxArgument)]);
@@ -734,18 +1044,24 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
734
1044
  throw refusal("E_PANEL_OPEN", "tmux did not name the window it opened");
735
1045
  }
736
1046
  if (ended) throw refusal("E_PANEL_ENDED", "the panel has ended");
737
- const v = { id: ids[1], pane: ids[2], ...size, files: made, asked: false, over: false, status: null };
1047
+ const v = { id: ids[1], pane: ids[2], ...start, files: made, asked: false, over: false, status: null, waiting: null, reaping: null, marked: false, place: null, dirty: false, due: false, dueAt: 0, off: false };
738
1048
  mine.files = null; // the viewer's now: finish() removes them
739
- const died = diedSeen.has(v.id), status = diedSeen.get(v.id) ?? null;
1049
+ // Heard dead with no status yet: opened as any other, and waiting for the line with it.
1050
+ const pending = diedSeen.get(v.id) === PENDING;
1051
+ const died = diedSeen.has(v.id) && !pending, status = died ? diedSeen.get(v.id) : null;
740
1052
  const already = closedSeen.has(v.id) || died, gone = server !== s;
1053
+ traced(`${v.id} ${v.pane} opened${closedSeen.has(v.id) ? ", its window already closed" : died ? `, already dead with status ${status}` : pending ? ", already dead with no status yet" : ""}${gone ? ", its server gone" : ""}`);
741
1054
  settle();
1055
+ // Its place, held until now, is the tab's (or, given up, freed).
1056
+ const at = mine.place;
1057
+ if (at) at.opening = null;
1058
+ if (mine.closeAsked) release(mine);
742
1059
  if (already || gone) {
743
1060
  // Over before its id was known (it exited at once, or the server went away meanwhile):
744
1061
  // said after open() has answered, so the caller knows the id onClosed names. A pane that
745
1062
  // died is killed, as paneDied does.
746
1063
  v.asked = mine.closeAsked;
747
- if (!mine.closeAsked) viewer = v;
748
- else closing.set(v.id, v);
1064
+ if (!mine.closeAsked) { tabs.set(v.id, v); display(v, at); shown = v; } else closing.set(v.id, v);
749
1065
  // The status is the viewer's from here: the window's end that answers this kill-pane can
750
1066
  // come before the finish below, and finishes it with this status (CI, under load).
751
1067
  v.status = status;
@@ -753,43 +1069,95 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
753
1069
  setImmediate(() => finish(v, { lost: gone && !already }));
754
1070
  } else if (mine.closeAsked) kill(v); // given up while it opened: killed at once
755
1071
  else {
756
- viewer = v;
757
- ask(`resize-window -t ${v.id} -x ${v.cols} -y ${v.rows}`);
758
- fresh();
1072
+ // A tab, displayed in its place and the shown one (even when show() or focus() named
1073
+ // another meanwhile), at its size now: a resize of every tab while its window was being
1074
+ // made is its too. Its own resize-window makes its window's size manual (THE SERVER).
1075
+ tabs.set(v.id, v);
1076
+ display(v, at);
1077
+ shown = v;
1078
+ sizeTo(v, mine.size.cols, mine.size.rows);
1079
+ fresh(v);
1080
+ if (pending) waitStatus(v);
759
1081
  }
760
1082
  return { id: v.id };
761
1083
  } catch (error) {
762
1084
  settle();
1085
+ release(mine);
763
1086
  forget(mine.files);
764
1087
  throw error;
765
1088
  }
766
1089
  })();
767
1090
  }
768
1091
 
769
- /** See createPanel. The slot is free when this returns. */
770
- function close() {
1092
+ /** See createPanel. */
1093
+ function show(id, { instead } = {}) {
1094
+ if (ended) return;
1095
+ const v = tabs.get(id);
1096
+ if (v === undefined || v.over) return;
1097
+ if (v.place) { shown = v; return; }
1098
+ display(v, placeFor(instead));
1099
+ shown = v;
1100
+ fresh(v);
1101
+ }
1102
+ /** See createPanel. */
1103
+ function focus(id) {
1104
+ if (ended) return;
1105
+ const v = tabs.get(id);
1106
+ if (v !== undefined && !v.over && v.place) shown = v;
1107
+ }
1108
+ /** See createPanel. */
1109
+ function hide(id) {
1110
+ if (ended) return;
1111
+ const v = tabs.get(id);
1112
+ if (v === undefined || v.over || !v.place) return;
1113
+ const was = shown === v;
1114
+ undisplay(v);
1115
+ if (was) shown = displayedTabs()[0] ?? null;
1116
+ }
1117
+
1118
+ /** See createPanel. The tab's place is free when this returns. */
1119
+ function close(id) {
771
1120
  if (ended) return;
772
- if (viewer) {
773
- const v = viewer;
774
- free();
775
- return kill(v);
1121
+ if (id === undefined || id === null) {
1122
+ if (opening) { opening.closeAsked = true; release(opening); opening = null; return; }
1123
+ if (shown === null) return;
1124
+ id = shown.id;
776
1125
  }
777
- if (opening) { opening.closeAsked = true; opening = null; }
1126
+ const v = tabs.get(id);
1127
+ if (v === undefined || v.over) return;
1128
+ leave(v);
1129
+ kill(v);
778
1130
  }
779
1131
 
780
- function resize(cols, rows) {
781
- const v = viewer;
782
- if (ended || !v || v.over) return;
783
- v.cols = cells(cols, v.cols);
784
- v.rows = cells(rows, v.rows);
1132
+ /** A tab's window at a size (THE TABS: its own `resize-window`). */
1133
+ function sizeTo(v, cols, rows) {
1134
+ v.cols = cols;
1135
+ v.rows = rows;
785
1136
  ask(`resize-window -t ${v.id} -x ${v.cols} -y ${v.rows}`);
786
- fresh();
1137
+ }
1138
+ function resize(cols, rows, ids) {
1139
+ if (ended) return;
1140
+ const named = Array.isArray(ids) ? new Set(ids) : null;
1141
+ if (named === null) {
1142
+ size = { cols: cells(cols, size.cols), rows: cells(rows, size.rows) };
1143
+ for (const under of openings) under.size = { cols: cells(cols, under.size.cols), rows: cells(rows, under.size.rows) };
1144
+ }
1145
+ const changed = [];
1146
+ for (const v of tabs.values()) {
1147
+ if (v.over || (named !== null && !named.has(v.id))) continue;
1148
+ const next = { cols: cells(cols, v.cols), rows: cells(rows, v.rows) };
1149
+ if (next.cols === v.cols && next.rows === v.rows) continue;
1150
+ sizeTo(v, next.cols, next.rows);
1151
+ changed.push(v);
1152
+ }
1153
+ // Every window resized first: each capture follows its own window's resize.
1154
+ for (const v of changed) if (v.place) fresh(v);
787
1155
  }
788
1156
 
789
- /** Bytes to the open pane, in commands of at most INPUT_CHUNK bytes, in order (one pipe, and
790
- * tmux runs a client's commands in the order they came); their answers are consumed. */
1157
+ /** Bytes to the shown tab's pane, in commands of at most INPUT_CHUNK bytes, in order (one pipe,
1158
+ * and tmux runs a client's commands in the order they came); their answers are consumed. */
791
1159
  function send(bytes) {
792
- const v = viewer;
1160
+ const v = shown;
793
1161
  if (ended || !v || v.over || !server || bytes.length === 0) return;
794
1162
  for (let at = 0; at < bytes.length; at += INPUT_CHUNK) ask(`send-keys -t ${v.pane} -H ${hex(bytes.subarray(at, at + INPUT_CHUNK))}`);
795
1163
  }
@@ -814,10 +1182,13 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
814
1182
  function setVisible(on) {
815
1183
  if (ended) return;
816
1184
  visible = on === true;
1185
+ // Hidden, no displayed tab is drawn: each is paused until the panel shows again, and continued
1186
+ // before its capture.
1187
+ for (const v of displayedTabs()) flow(v, visible);
817
1188
  if (!visible) stopFrames();
818
- else fresh();
1189
+ else freshAll();
819
1190
  }
820
- function refresh() { if (!ended) fresh(); }
1191
+ function refresh() { if (!ended) freshAll(); }
821
1192
 
822
1193
  /** `refresh-client -f no-output` (tmux 3.2): tmux keeps no pane output for this client while the
823
1194
  * TUI is stopped, so the pipe does not fill and tmux does not drop a client that falls behind.
@@ -832,7 +1203,7 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
832
1203
  if (ended || !paused) return;
833
1204
  paused = false;
834
1205
  ask("refresh-client -f '!no-output'");
835
- fresh();
1206
+ freshAll();
836
1207
  }
837
1208
 
838
1209
  /** Kill this run's server, synchronously and bounded: it runs in the exit path. An end() that
@@ -858,11 +1229,13 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
858
1229
  quietly(() => s.child.kill("SIGTERM"));
859
1230
  quietly(() => s.child.unref());
860
1231
  }
861
- // Nothing more is said: the run is leaving. Every viewer's files go, and so do those of an open
1232
+ // Nothing more is said: the run is leaving. Every tab's files go, and so do those of an open
862
1233
  // under way (which then rejects with E_PANEL_ENDED and makes nothing more).
863
- for (const v of [viewer, ...closing.values()]) if (v) { v.over = true; forget(v.files); }
864
- viewer = null;
1234
+ for (const v of [...tabs.values(), ...closing.values()]) { v.over = true; unwait(v); forget(v.files); }
1235
+ shown = null;
1236
+ tabs.clear();
865
1237
  closing.clear();
1238
+ places.clear();
866
1239
  for (const under of openings) forget(under.files);
867
1240
  if (runDir !== null) {
868
1241
  quietly(() => fs.unlink(socket));
@@ -873,7 +1246,9 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
873
1246
  }
874
1247
  }
875
1248
 
876
- return { open, close, resize, input, paste, setVisible, refresh, pause, resume, end, get current() { return viewer && !viewer.over ? viewer.id : null; } };
1249
+ /** See createPanel: the open tabs in opening order, the shown one, and the displayed ones. */
1250
+ const listed = () => ({ ids: [...tabs.values()].filter((v) => !v.over).map((v) => v.id), shown: shown && !shown.over ? shown.id : null, displayed: displayedTabs().map((v) => v.id) });
1251
+ return { open, show, focus, hide, close, resize, input, paste, setVisible, refresh, pause, resume, end, get tabs() { return listed(); }, get current() { return listed().shown; } };
877
1252
  }
878
1253
 
879
1254
  /** What the sweep reads and removes, each replaceable by a test (see PANEL_FS). */