@awebai/oats 0.58.0 → 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 (53) hide show
  1. package/bin/oats.mjs +1 -1
  2. package/docs/desktop-cli-api.md +68 -3
  3. package/docs/desktop.md +30 -3
  4. package/docs/execution-targets.md +11 -0
  5. package/docs/implementation.md +2 -0
  6. package/docs/integrations.md +2 -2
  7. package/docs/knowledge.md +4 -4
  8. package/docs/official-catalog.md +4 -4
  9. package/docs/packages.md +14 -14
  10. package/docs/release-notes/v0.59.0.md +288 -0
  11. package/docs/servers.md +4 -1
  12. package/docs/souls-and-instances.md +21 -0
  13. package/docs/tui.md +644 -118
  14. package/docs/workspaces.md +2 -2
  15. package/lib/core.mjs +216 -42
  16. package/lib/read-ahead-worker.mjs +119 -0
  17. package/lib/read-ahead.mjs +115 -0
  18. package/lib/retire-state.mjs +33 -0
  19. package/lib/servers.mjs +9 -1
  20. package/lib/session-input.mjs +14 -4
  21. package/package-catalog.json +3 -3
  22. package/package.json +1 -1
  23. package/packages/client/cli-locator.mjs +2 -2
  24. package/packages/client/deployment-data.mjs +4 -0
  25. package/packages/client/deployment-panel.mjs +3 -0
  26. package/packages/client/instance-acts.mjs +23 -8
  27. package/packages/client/instance-presentation.mjs +3 -2
  28. package/packages/client/instance-tree.mjs +84 -39
  29. package/packages/client/lifecycle-confirmation.mjs +9 -3
  30. package/packages/client/remote-roster.mjs +4 -1
  31. package/packages/client/retire-in-flight.mjs +65 -0
  32. package/packages/client/retire-state.mjs +30 -0
  33. package/packages/client/spawn-apply.mjs +13 -4
  34. package/packages/tui/README.md +23 -10
  35. package/packages/tui/lib/actions.mjs +63 -5
  36. package/packages/tui/lib/client.mjs +12 -1
  37. package/packages/tui/lib/config.mjs +7 -2
  38. package/packages/tui/lib/main.mjs +315 -82
  39. package/packages/tui/lib/model.mjs +523 -56
  40. package/packages/tui/lib/panel.mjs +436 -125
  41. package/packages/tui/lib/read.mjs +52 -26
  42. package/packages/tui/lib/store.mjs +908 -65
  43. package/packages/tui/lib/term/keys.mjs +9 -2
  44. package/packages/tui/lib/term/text.mjs +4 -0
  45. package/packages/tui/lib/term/through.mjs +12 -1
  46. package/packages/tui/lib/views/frame.mjs +394 -95
  47. package/packages/tui/lib/views/help.mjs +54 -13
  48. package/packages/tui/lib/views/instances.mjs +43 -25
  49. package/packages/tui/lib/views/palette.mjs +61 -0
  50. package/packages/tui/lib/views/souls.mjs +268 -0
  51. package/packages/tui/lib/views/spawn.mjs +299 -0
  52. package/packages/tui/lib/views/split.mjs +29 -0
  53. 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
@@ -99,6 +135,17 @@
99
135
  // follows at the next check, and the panel waits for it, a bounded time: a viewer heard so is over
100
136
  // without a status once STATUS_WAIT_MS have passed with no other line, its pane killed, so a
101
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.
102
149
  // tmux 3.2 has no `pane_dead_signal` (3.3 added it), so there a signal's end reads `1 ` for good,
103
150
  // and the wait is the shorter DEAD_WAIT_MS. A pane-died hook cannot do it: tmux sends no
104
151
  // notification for a command a hook runs. A pane the panel kills (close(), an open given up) is
@@ -117,15 +164,17 @@ import { closeSync, constants as FS, fstatSync, lstatSync, openSync, readSync, r
117
164
  import { tmpdir as osTmpdir } from "node:os";
118
165
  import { join } from "node:path";
119
166
 
120
- /** How many terminals a run may hold open at once in the next version. This version opens one at
121
- * 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). */
122
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;
123
172
  /** The most of a viewer's stderr that is kept, in bytes: the last ones. */
124
173
  export const STDERR_KEPT = 4096;
125
174
  /** The frame tick, in milliseconds: a capture follows the output that asked for it by one tick, so
126
175
  * a burst of output is drawn once. The tick is not what bounds the rate: a fresh capture (open,
127
- * resize, refresh, showing again) skips it, and what bounds them all is that at most one capture
128
- * 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. */
129
178
  export const FRAME_MS = 16;
130
179
  /** The pane's command around the viewer, a CONSTANT: its stderr to the file named by E, then the
131
180
  * viewer itself in the shell's place (`exec "$0" "$@"`: its argv, which follows this script as
@@ -153,6 +202,11 @@ export const DEAD_WAIT_MS = 2500;
153
202
  * moment after the hang-up; a viewer that closed its terminal and lives on keeps it longer, and
154
203
  * one whose status never comes is over without one when this has passed. */
155
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";
156
210
  /** The first tmux whose `pane_dead_signal` says which signal ended a pane. */
157
211
  const DEAD_SIGNAL_TMUX = Object.freeze([3, 3]);
158
212
  /** What a dead line with no status and no signal says of a viewer: its status is still to come. */
@@ -317,8 +371,9 @@ function readPart(file, max, fromEnd) {
317
371
  } finally { quietly(() => closeSync(fd)); }
318
372
  }
319
373
 
320
- /** The panel of a run: the private server, its control client and the viewer open in it.
321
- * -> { 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 }
322
377
  *
323
378
  * Options:
324
379
  * dir() the run's private directory: called at the first open, and expected to answer
@@ -327,8 +382,13 @@ function readPart(file, max, fromEnd) {
327
382
  * capture(text, { cols, rows }) REQUIRED: the caller's cell builder, handed what
328
383
  * `capture-pane -e -N` captured (its lines joined by "\n") and the pane's size;
329
384
  * what it answers is handed on as `screen`.
330
- * onScreen({ id, screen, cursor: { x, y, visible } }) a capture of the open viewer.
331
- * 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
332
392
  * kept it for its dead pane (null when there is none: a signal ended the viewer,
333
393
  * its pane was killed, or its server went away), `stderr` the last STDERR_KEPT
334
394
  * bytes it wrote to its file, as text, `asked`
@@ -347,33 +407,68 @@ function readPart(file, max, fromEnd) {
347
407
  * A callback that throws does not break the panel: what it threw is thrown again in a microtask,
348
408
  * where the run hears it as any uncaught error.
349
409
  *
350
- * open({ argv, cols, rows }) -> Promise<{ id }>: start the viewer `argv` ([node, bin, ...args],
351
- * the kernel's `oats session attach …`) in a new window of cols x rows. `id` is tmux's window id.
352
- * The first open starts the server; so does the first after the server went away. Rejected with
353
- * a coded Error: E_PANEL_BUSY (a viewer is open, or an open is under way: the caller closes it
354
- * first, and may open the next as soon as close() has returned),
355
- * 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
356
428
  * client did not start; `detail` holds what tmux said, untrusted text), E_PANEL_OPEN (the
357
- * window was not made; `detail` likewise, or a bad argv), E_PANEL_ENDED (after end()).
358
- * close(): end the open viewer (`kill-pane`: its terminal hangs up, the viewer gets SIGHUP and
359
- * cleans up after itself). THE SLOT IS FREE WHEN IT RETURNS: the next open may follow at once,
360
- * and the closed viewer is reported by onClosed with `asked: true` when its window has ended.
361
- * Asked while an open is under way, that open still answers its `{ id }`, and its window is
362
- * killed as soon as it exists (reported likewise). With no viewer and no open, nothing.
363
- * resize(cols, rows): the window's new size, then a fresh capture.
364
- * input(bytes): bytes (a Buffer, or a string as UTF-8) typed into the viewer, in order. With no
365
- * viewer window yet (an open under way) or none at all, they are dropped.
366
- * paste(text): `text` as a bracketed paste (any end mark inside it removed); the agent's own
367
- * server decides whether its program sees the marks (the viewer is a tmux client).
368
- * setVisible(on): hidden, no capture runs and output only marks the screen stale; shown again,
369
- * one fresh capture. refresh(): one fresh capture now (after `fg`, Ctrl+L).
370
- * pause() / resume(): around a suspend of the TUI: tmux stops sending the pane's output (a
371
- * stopped TUI does not read its pipe), then sends it again, and a fresh capture follows.
372
- * end(): leave, synchronously: kill the server, end the control client, remove the socket,
373
- * owner.json and the view files. Idempotent.
374
- * 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.
375
470
  * No method but open() throws or rejects: a server that went away makes each of them do nothing. */
376
- 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",
377
472
  spawn = nodeSpawn, execFile = nodeExecFile, execFileSync = nodeExecFileSync, fs: givenFs = {}, timers = { setTimeout, clearTimeout },
378
473
  clock = () => new Date().toISOString(), pid = process.pid, trace = null } = {}) {
379
474
  if (typeof dir !== "function") throw new TypeError("createPanel needs dir(): the run's private directory");
@@ -393,19 +488,28 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
393
488
  * block being read), startLeft (the blocks of the start list still to come), attached, gone,
394
489
  * onAttach, stderr }, or null. A start under way is `starting` (its promise). */
395
490
  let server = null, starting = null;
396
- /** THE SLOT: the viewer open now ({ id, pane, cols, rows, files, asked, over, status }), or the open
397
- * under way that will be it (`opening`: { closeAsked, files }), or neither. close() frees it at
398
- * once: the viewer it closed waits in `closing` (window id -> viewer) for its window's end, and
399
- * an open it gave up goes on to kill its window as soon as it exists. Every open under way, the
400
- * 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.
401
503
  * `closedSeen`: the window ids whose end was heard while an open was under way. A viewer that
402
504
  * exits at once can end before new-window has answered with its id; ids are never reused by a
403
505
  * server, and the set is emptied when no open is under way, and at every new server.
404
506
  * `diedSeen`: the same for a pane heard dead (window id -> its status, null, or PENDING). */
405
- let viewer = null, opening = null;
406
- const closing = new Map(), openings = new Set(), closedSeen = new Set(), diedSeen = new Map();
407
- /** The frames: the screen is stale (`dirty`), a tick is armed (`tick`), a capture is in flight. */
408
- let dirty = false, tick = null, capturing = false, visible = true, paused = false;
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;
409
513
  let ended = false, files = 0;
410
514
 
411
515
  /** A callback of the caller's, called so that what it throws cannot break the panel. */
@@ -451,7 +555,9 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
451
555
  * `%end` or `%error` line that repeats its `%begin`'s time, number and flags EXACTLY (tmux
452
556
  * prints the same time and number on both lines of a block). No pane's text is ever in a block
453
557
  * (THE CAPTURE); the exact end is kept all the same. Outside a block a line is a notification
454
- * (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
455
561
  * the start list, answer the start itself; every later one answers the oldest command waiting. */
456
562
  function heard(s, line) {
457
563
  if (s.block) {
@@ -483,8 +589,9 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
483
589
  return;
484
590
  }
485
591
  const [kind, first] = line.split(" ", 2);
486
- if (kind === "%output" || kind === "%extended-output") { if (viewer && first === viewer.pane) stale(); }
487
- else if (kind === "%layout-change") { if (viewer && first === viewer.id) stale(); }
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); }
488
595
  else if (kind === "%window-close" || kind === "%unlinked-window-close") { traced(line); windowClosed(first); }
489
596
  else if (kind === "%exit") { traced(line); lost(s); }
490
597
  else if (kind === "%subscription-changed") {
@@ -503,8 +610,8 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
503
610
  }
504
611
 
505
612
  /** The control client is gone (`%exit`, its pipe closed, it did not start): the server with it,
506
- * as far as this run is concerned. Every command waiting is answered as failed, the open viewer
507
- * 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. */
508
615
  function lost(s) {
509
616
  if (s.gone) return;
510
617
  s.gone = true;
@@ -516,8 +623,7 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
516
623
  quietly(() => s.child.kill("SIGTERM"));
517
624
  quietly(() => s.child.unref());
518
625
  stopFrames();
519
- if (viewer) finish(viewer, { lost: true });
520
- for (const v of [...closing.values()]) finish(v, { lost: true });
626
+ for (const v of [...tabs.values(), ...closing.values()]) finish(v, { lost: true });
521
627
  }
522
628
 
523
629
  /** Start the server through the control client, with startCommands as its list, and wait for
@@ -639,37 +745,90 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
639
745
 
640
746
  // FRAMES ---------------------------------------------------------------------------------------
641
747
 
642
- /** Whether a capture may run now. */
643
- const showing = () => viewer !== null && !viewer.over && visible && !paused && !ended;
644
- /** 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. */
645
756
  function arm() {
646
- if (!showing() || tick !== null || capturing) return;
647
- 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);
648
764
  }
649
765
  function stopFrames() {
650
766
  if (tick !== null) { quietly(() => timers.clearTimeout(tick)); tick = null; }
651
767
  }
652
- /** A notification said the screen changed: stale, and a capture one tick later. NO TIMER RUNS
653
- * BUT THIS ONE: nothing is ever captured unless tmux said something changed, or the caller asked. */
654
- function stale() { dirty = true; arm(); }
655
- /** A capture now (or right after the one in flight), whatever the tick. */
656
- function fresh() {
657
- dirty = true;
658
- 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;
659
805
  stopFrames();
660
- 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);
661
819
  }
662
820
  /** A capture whose promise nobody awaits: it never rejects. */
663
- const startCapture = () => { captureNow().catch(() => { capturing = false; }); };
664
- /** One capture: the pane's cells into the capture's file, and its cursor, asked through the
665
- * control client in one go (see THE CAPTURE). At most one in flight; what was marked stale
666
- * meanwhile arms the next tick after it. A capture that fails (the pane gone, the file missing,
667
- * too large or not a file) draws nothing, and the next change tries again. */
668
- async function captureNow() {
669
- const v = viewer;
670
- 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;
671
829
  capturing = true;
672
- dirty = false;
830
+ v.dirty = false;
831
+ v.due = false;
673
832
  const [taken, saved, , cursor] = await Promise.all([
674
833
  ask(`capture-pane -e -N -b ${CAPTURE_BUFFER} -t ${v.pane}`),
675
834
  ask(`save-buffer -b ${CAPTURE_BUFFER} ${captureWord}`),
@@ -677,9 +836,12 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
677
836
  ask(`display -p -t ${v.pane} '#{cursor_x} #{cursor_y} #{cursor_flag}'`, SAYS_CURSOR),
678
837
  ]);
679
838
  capturing = false;
680
- 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();
681
843
  // Hidden or paused while it was in flight: not drawn; the capture that showing again asks for is.
682
- if (!showing()) { dirty = true; return; }
844
+ if (!capturable()) { soil(v); return; }
683
845
  const held = taken.ok && saved.ok && cursor.ok ? quietly(() => fs.whole(capturePath, CAPTURE_MAX)) : null;
684
846
  if (typeof held === "string") {
685
847
  const at = CURSOR_LINE.exec(cursor.lines[0]);
@@ -688,7 +850,7 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
688
850
  const text = held.endsWith("\n") ? held.slice(0, -1) : held;
689
851
  tell(() => onScreen({ id: v.id, screen: capture(text, { cols: v.cols, rows: v.rows }), cursor: where }));
690
852
  }
691
- if (dirty) arm();
853
+ pump();
692
854
  }
693
855
 
694
856
  // VIEWERS --------------------------------------------------------------------------------------
@@ -699,7 +861,7 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
699
861
  * known (an open under way) is remembered with what was heard; any other is not a viewer's (the
700
862
  * keeper's, one already over). */
701
863
  function paneDied(id, status) {
702
- const v = viewer?.id === id ? viewer : closing.get(id);
864
+ const v = tabs.get(id) ?? closing.get(id);
703
865
  if (v && status === PENDING) return waitStatus(v);
704
866
  if (v) { v.status = status; ask(`kill-pane -t ${v.pane}`); return finish(v, {}); }
705
867
  if (openings.size > 0 && !(status === PENDING && diedSeen.has(id))) diedSeen.set(id, status);
@@ -707,11 +869,13 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
707
869
  /** A viewer heard dead with no status: it stays open until the line with its status or its
708
870
  * signal, a close, or its server's end, and at most STATUS_WAIT_MS (DEAD_WAIT_MS on tmux 3.2,
709
871
  * which says a signal's end no other way): then it is over without a status, and its pane is
710
- * killed. Armed once. */
872
+ * killed. Armed once. Meanwhile the server reaps its children, at once and every REAP_ASK_MS
873
+ * (`reap`). */
711
874
  function waitStatus(v) {
712
875
  if (v.over || v.waiting !== null) return;
713
876
  const ms = signals ? STATUS_WAIT_MS : DEAD_WAIT_MS;
714
877
  traced(`${v.id} dead, waiting ${ms} ms for its status`);
878
+ reap(v);
715
879
  v.waiting = timers.setTimeout(() => {
716
880
  v.waiting = null;
717
881
  if (ended || v.over) return;
@@ -721,10 +885,18 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
721
885
  finish(v, {});
722
886
  }, ms);
723
887
  }
724
- /** A window ended: the open viewer's, one closing, or (an open under way) one to remember. */
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);
895
+ }
896
+ /** A window ended: a tab's, shown or hidden, one closing, or (an open under way) one to remember. */
725
897
  function windowClosed(id) {
726
- if (viewer && viewer.id === id) return finish(viewer, {});
727
- if (closing.has(id)) return finish(closing.get(id), {});
898
+ const v = tabs.get(id) ?? closing.get(id);
899
+ if (v) return finish(v, {});
728
900
  if (openings.size > 0) closedSeen.add(id);
729
901
  }
730
902
  /** A viewer is over: read what it left, remove its file, and say so. Its status is what tmux kept
@@ -737,16 +909,85 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
737
909
  v.over = true;
738
910
  unwait(v);
739
911
  closing.delete(v.id);
740
- if (viewer === v) free();
912
+ leave(v);
741
913
  const stderr = quietly(() => fs.tail(v.files.err, STDERR_KEPT)) ?? "";
742
914
  traced(`${v.id} over, status ${gone ? null : status}${gone ? ", its server gone" : ""}${v.asked ? ", closed" : ""}`);
743
915
  forget(v.files);
744
916
  if (!ended) tell(() => onClosed({ id: v.id, status: gone ? null : status, stderr, asked: v.asked }));
745
917
  }
746
- /** A viewer's wait for its status (waitStatus), put away. */
747
- function unwait(v) { if (v.waiting !== null) { quietly(() => timers.clearTimeout(v.waiting)); v.waiting = null; } }
748
- /** The slot is free: no viewer, no frame to come. */
749
- 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
+
750
991
  const forget = (made) => { for (const path of [made?.err, made?.status]) if (path) quietly(() => fs.unlink(path)); };
751
992
  /** End a viewer the caller closed (or gave up while it opened): its pane killed through the
752
993
  * control client, and its end awaited in `closing`. With no server, it is over now. */
@@ -758,12 +999,21 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
758
999
  }
759
1000
 
760
1001
  /** See createPanel. */
761
- function open({ argv, cols, rows } = {}) {
1002
+ function open({ argv, cols, rows, instead } = {}) {
762
1003
  if (ended) return Promise.reject(refusal("E_PANEL_ENDED", "the panel has ended"));
763
- 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"));
764
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"));
765
- const size = { cols: cells(cols, 80), rows: cells(rows, 24) };
766
- 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;
767
1017
  openings.add(mine);
768
1018
  /** This open is no longer under way. */
769
1019
  const settle = () => {
@@ -780,7 +1030,7 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
780
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) }); }
781
1031
  let answer;
782
1032
  try {
783
- 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}`,
784
1034
  ";", "new-window", "-d", "-P", "-F", "#{window_id} #{pane_id}", "-t", `${SESSION}:`,
785
1035
  "-e", tmuxArgument(`E=${made.err}`),
786
1036
  "/bin/sh", "-c", VIEW_SCRIPT, ...argv.map(tmuxArgument)]);
@@ -794,7 +1044,7 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
794
1044
  throw refusal("E_PANEL_OPEN", "tmux did not name the window it opened");
795
1045
  }
796
1046
  if (ended) throw refusal("E_PANEL_ENDED", "the panel has ended");
797
- const v = { id: ids[1], pane: ids[2], ...size, files: made, asked: false, over: false, status: null, waiting: 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 };
798
1048
  mine.files = null; // the viewer's now: finish() removes them
799
1049
  // Heard dead with no status yet: opened as any other, and waiting for the line with it.
800
1050
  const pending = diedSeen.get(v.id) === PENDING;
@@ -802,13 +1052,16 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
802
1052
  const already = closedSeen.has(v.id) || died, gone = server !== s;
803
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" : ""}`);
804
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);
805
1059
  if (already || gone) {
806
1060
  // Over before its id was known (it exited at once, or the server went away meanwhile):
807
1061
  // said after open() has answered, so the caller knows the id onClosed names. A pane that
808
1062
  // died is killed, as paneDied does.
809
1063
  v.asked = mine.closeAsked;
810
- if (!mine.closeAsked) viewer = v;
811
- 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);
812
1065
  // The status is the viewer's from here: the window's end that answers this kill-pane can
813
1066
  // come before the finish below, and finishes it with this status (CI, under load).
814
1067
  v.status = status;
@@ -816,44 +1069,95 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
816
1069
  setImmediate(() => finish(v, { lost: gone && !already }));
817
1070
  } else if (mine.closeAsked) kill(v); // given up while it opened: killed at once
818
1071
  else {
819
- viewer = v;
820
- ask(`resize-window -t ${v.id} -x ${v.cols} -y ${v.rows}`);
821
- 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);
822
1080
  if (pending) waitStatus(v);
823
1081
  }
824
1082
  return { id: v.id };
825
1083
  } catch (error) {
826
1084
  settle();
1085
+ release(mine);
827
1086
  forget(mine.files);
828
1087
  throw error;
829
1088
  }
830
1089
  })();
831
1090
  }
832
1091
 
833
- /** See createPanel. The slot is free when this returns. */
834
- function close() {
1092
+ /** See createPanel. */
1093
+ function show(id, { instead } = {}) {
835
1094
  if (ended) return;
836
- if (viewer) {
837
- const v = viewer;
838
- free();
839
- return kill(v);
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) {
1120
+ if (ended) return;
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;
840
1125
  }
841
- 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);
842
1130
  }
843
1131
 
844
- function resize(cols, rows) {
845
- const v = viewer;
846
- if (ended || !v || v.over) return;
847
- v.cols = cells(cols, v.cols);
848
- 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;
849
1136
  ask(`resize-window -t ${v.id} -x ${v.cols} -y ${v.rows}`);
850
- 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);
851
1155
  }
852
1156
 
853
- /** Bytes to the open pane, in commands of at most INPUT_CHUNK bytes, in order (one pipe, and
854
- * 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. */
855
1159
  function send(bytes) {
856
- const v = viewer;
1160
+ const v = shown;
857
1161
  if (ended || !v || v.over || !server || bytes.length === 0) return;
858
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))}`);
859
1163
  }
@@ -878,10 +1182,13 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
878
1182
  function setVisible(on) {
879
1183
  if (ended) return;
880
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);
881
1188
  if (!visible) stopFrames();
882
- else fresh();
1189
+ else freshAll();
883
1190
  }
884
- function refresh() { if (!ended) fresh(); }
1191
+ function refresh() { if (!ended) freshAll(); }
885
1192
 
886
1193
  /** `refresh-client -f no-output` (tmux 3.2): tmux keeps no pane output for this client while the
887
1194
  * TUI is stopped, so the pipe does not fill and tmux does not drop a client that falls behind.
@@ -896,7 +1203,7 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
896
1203
  if (ended || !paused) return;
897
1204
  paused = false;
898
1205
  ask("refresh-client -f '!no-output'");
899
- fresh();
1206
+ freshAll();
900
1207
  }
901
1208
 
902
1209
  /** Kill this run's server, synchronously and bounded: it runs in the exit path. An end() that
@@ -922,11 +1229,13 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
922
1229
  quietly(() => s.child.kill("SIGTERM"));
923
1230
  quietly(() => s.child.unref());
924
1231
  }
925
- // 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
926
1233
  // under way (which then rejects with E_PANEL_ENDED and makes nothing more).
927
- for (const v of [viewer, ...closing.values()]) if (v) { v.over = true; unwait(v); forget(v.files); }
928
- 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();
929
1237
  closing.clear();
1238
+ places.clear();
930
1239
  for (const under of openings) forget(under.files);
931
1240
  if (runDir !== null) {
932
1241
  quietly(() => fs.unlink(socket));
@@ -937,7 +1246,9 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
937
1246
  }
938
1247
  }
939
1248
 
940
- 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; } };
941
1252
  }
942
1253
 
943
1254
  /** What the sweep reads and removes, each replaceable by a test (see PANEL_FS). */