@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,16 +1,20 @@
1
1
  // `oats tui` (preview): the loop. Events from the keyboard and from the reader go through one
2
2
  // pure reduce(state, event); what only the loop can do comes back as an effect; the frame is
3
3
  // drawn from the state. This version shows a workspace's instances, on this machine and on the
4
- // machines registered here, follows them, opens an agent's terminal in a panel beside the list
5
- // (the kernel's own viewer, in a pane of the run's private tmux server: lib/panel.mjs), and
6
- // stops, starts, restarts and retires an instance after a confirmation, through the shared
7
- // lifecycle boundary and start rule (docs/tui.md).
4
+ // machines registered here, follows them, opens agents' terminals as tabs of a panel beside the
5
+ // list (up to four, each the kernel's own viewer in a pane of the run's private tmux server:
6
+ // lib/panel.mjs; `viewers` maps each tab's instance to its window), in one group or two (a split;
7
+ // after every frame `fitPanel` tells the panel which windows the frame's regions display, at what
8
+ // size, and which has the keys), stops,
9
+ // starts, restarts and retires an instance after a confirmation, through the shared lifecycle
10
+ // boundary and start rule, and spawns an agent on this machine from the shared preview and apply
11
+ // (docs/tui.md).
8
12
  import { homedir } from "node:os";
9
13
  import { resolve } from "node:path";
10
14
  import { bindings } from "./actions.mjs";
11
- import { TERMS, createLifecycleBoundary, createLifecycleConfirmation, displayLine, heldHome, pendingEntry, prepareRemoteTerm, sessionAttachArgv, startInstance } from "./client.mjs";
15
+ import { TERMS, createLifecycleBoundary, createLifecycleConfirmation, createRetiresInFlight, createSoulCatalog, createSpawnApplyBoundary, createSpawnPreview, createSpawnTransaction, displayLine, heldHome, pendingEntry, prepareRemoteTerm, sessionAttachArgv, soulCatalogKey, startInstance } from "./client.mjs";
12
16
  import { loadConfig } from "./config.mjs";
13
- import { ACT_WORDS, actContext, actCwd, localDeployments, model, roster } from "./model.mjs";
17
+ import { ACT_WORDS, actContext, actCwd, localDeployments, model, outcomeOf, reachedMachines, roster, spawnContext } from "./model.mjs";
14
18
  import { createPanel, sweep } from "./panel.mjs";
15
19
  import { CHANGE_FILES, admitDeployment, createReader, findDeployment, leaveInstance, offeredDeployments, probeKernel, realpath, tellable } from "./read.mjs";
16
20
  import { initialState, reduce } from "./store.mjs";
@@ -20,16 +24,17 @@ import { createScreen, glyphs } from "./term/screen.mjs";
20
24
  import { colorEnabled } from "./term/style.mjs";
21
25
  import { backKeySequences, createThrough } from "./term/through.mjs";
22
26
  import { createGuard, isTerminal } from "./term/tty.mjs";
23
- import { frame, layout } from "./views/frame.mjs";
27
+ import { frame, layout, panelPlace } from "./views/frame.mjs";
24
28
 
25
29
  export const USAGE = "oats tui [--dir <path>] [--ascii]";
26
30
  const HELP = `Usage:
27
31
  ${USAGE}
28
32
 
29
33
  The OATS terminal client (preview): a full-screen view of a workspace's instances,
30
- on this machine and on the machines registered here. It follows them, opens an
31
- agent's terminal beside the list with Enter, and stops, retires, starts or
32
- restarts an instance (X, D, S, R) after a confirmation.
34
+ on this machine and on the machines registered here. It follows them, opens
35
+ agents' terminals beside the list with Enter, as tabs, stops, retires, starts or
36
+ restarts an instance (X, D, S, R) after a confirmation, and spawns an agent
37
+ on this machine (n, or N for another of the selected one's soul).
33
38
  Keys: ? help, Enter open, w workspaces, q quit.
34
39
  docs/tui.md has the rest.
35
40
 
@@ -71,9 +76,35 @@ function errorLines(error) {
71
76
  * are the shared home's, replaceable so a test can drive the loop's wiring. `runDir` makes the
72
77
  * run's private directory (the reader's change output and the panel's tmux server share it), and
73
78
  * `removeDir` removes it on the way out once both have removed their files; `sweep` removes what
74
- * runs that are gone left of theirs (lib/panel.mjs). */
79
+ * runs that are gone left of theirs (lib/panel.mjs). `createSoulCatalog` is the shared home's
80
+ * catalog of a workspace's souls, replaceable so a test can count its reads; the three spawn
81
+ * factories are the shared home's preview, apply boundary and transaction, replaceable so a test
82
+ * can answer them. */
75
83
  const EFFECTS = Object.freeze({ loadConfig, findDeployment, probeKernel, createReader, offeredDeployments, admitDeployment, prepareRemoteTerm, createPanel, sweep,
76
- runDir: CHANGE_FILES.dir, removeDir: CHANGE_FILES.remove, realpath, tellable, startInstance, createLifecycleConfirmation, createLifecycleBoundary });
84
+ runDir: CHANGE_FILES.dir, removeDir: CHANGE_FILES.remove, realpath, tellable, startInstance, createLifecycleConfirmation, createLifecycleBoundary, createSoulCatalog,
85
+ createSpawnPreview, createSpawnApplyBoundary, createSpawnTransaction });
86
+
87
+ /** The timers a run lends the shared spawn: the apply's deadline and its grace (the boundary's
88
+ * `applyTimer`), the boundary's wait for an answer (`timer`) and the transaction's polls
89
+ * (`sleep`). They are the run's: `end()`, as the run ends, clears every one still armed, so a
90
+ * TUI that has gone neither signals a spawn it let go nor is kept alive by one: the spawn
91
+ * finishes, or the kernel's own limits bound it (Spec 6-spawn, Settled 4). `timer(fn, ms)`
92
+ * returns its cancel, as the shared home's timers do. */
93
+ export function createRunTimers({ setTimer, clearTimer }) {
94
+ const armed = new Set();
95
+ let over = false;
96
+ function timer(fn, ms) {
97
+ if (over) return () => {};
98
+ const handle = setTimer(() => { armed.delete(handle); if (!over) fn(); }, ms);
99
+ armed.add(handle);
100
+ return () => { if (armed.delete(handle)) clearTimer(handle); };
101
+ }
102
+ return {
103
+ timer,
104
+ sleep: (ms) => new Promise((resolve) => { timer(resolve, ms); }),
105
+ end() { over = true; for (const handle of armed) clearTimer(handle); armed.clear(); },
106
+ };
107
+ }
77
108
 
78
109
  /** Run. Resolves with the exit status; never calls process.exit, so what was written drains.
79
110
  * Before the alternate screen, in this order, each failure one line on stderr and status 1:
@@ -111,7 +142,8 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
111
142
  let through = createThrough({ sequences: backKey, now }), throughTimer = null;
112
143
  if (offered) state = reduce(state, { offered }, keymap).state;
113
144
  // What the last frame drew, for the store: how tall the list pane is and how far the other
114
- // pane scrolls. The store holds no size of its own.
145
+ // pane scrolls. The store holds no size of its own; the panel's room goes with each key as it
146
+ // is when the key is read (placed), whatever the last frame drew.
115
147
  let drawn = { page: 1, extent: 0, room: 1, cols: 1 };
116
148
  let full = true, escTimer = null, ended = false, reads = 0;
117
149
  /** The preflight of another machine's agent under way: `{ id, controller, prepared }`, where
@@ -123,6 +155,30 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
123
155
  let dir = null;
124
156
  const runDir = () => (dir ??= effects.runDir());
125
157
 
158
+ // THIS RUN'S RETIRES IN FLIGHT (#1247, packages/client retire-in-flight.mjs): a row whose retire
159
+ // this run sent reads Retiring… from the send, before any read says so, until its answer is in
160
+ // and a read begun after that answer covers the row; a refused or stale answer lets it go at once.
161
+ // The mark is the reader's count of cycles begun (lib/read.mjs `begun`), never the clock: the
162
+ // live read a settled answer asks for begins in the same millisecond. The store holds the ids.
163
+ const retires = createRetiresInFlight({ mark: () => reader.begun(), onChange: () => heard({ retiring: retires.ids() }) });
164
+ /** The cycle that began the roster read in flight: lib/read.mjs says `collecting` as it begins one. */
165
+ let rosterBegun = 0;
166
+ /** A served deployment's entry: taken, then, when it is a read the store took (its cycle is the
167
+ * newest of that deployment), it covers that deployment's rows of this machine. A failed read
168
+ * covers nothing, whatever entry it kept. */
169
+ function entered(event) {
170
+ heard(event);
171
+ if (event.read === true && state.numbers.get(event.id) === event.number) retires.landed(event.number, (t) => !t.server && t.workspace === event.id);
172
+ }
173
+ /** An event of the roster read: taken, then an outcome covers the rows of each machine it reached
174
+ * (a read that failed marks every machine not reached, and covers none). */
175
+ function rostered(event) {
176
+ if (event.collecting === true) rosterBegun = reader.begun();
177
+ heard(event);
178
+ if (event.roster === undefined || ended) return;
179
+ const reached = reachedMachines(state, clock());
180
+ if (reached.size) retires.landed(rosterBegun, (t) => !!t.server && reached.has(t.workspace));
181
+ }
126
182
  // What the reader reads for, it asks of the state at that moment: the served deployments, the
127
183
  // entry a failed read keeps, and the roster and the memory the next outcome is made from.
128
184
  const reader = effects.createReader({
@@ -130,24 +186,33 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
130
186
  getServed: () => state.ctxs,
131
187
  getEntry: (id) => state.entries.get(id) ?? null,
132
188
  getRoster: () => ({ remote: state.remote, memory: state.memory, notes: state.notes }),
133
- onEntry: heard, onRoster: heard,
189
+ onEntry: entered, onRoster: rostered,
134
190
  files: { ...CHANGE_FILES, dir: runDir },
135
191
  });
136
- // THE OPEN TERMINAL (docs/tui.md, "Open an agent's terminal"): one at a time, in the panel.
137
- // `viewing` is its viewer, `{ id, panel }` (the row's instanceId, and the panel's own id once
138
- // the window exists, null before); `screenNow` the last capture (`{ lines, cursor }`), drawn
139
- // until the next; `panelSize` and `panelShown` what the panel was last told.
140
- let viewing = null, screenNow = null, panelSize = null, panelShown = true;
192
+ // THE TABS AND THE SPLIT (docs/tui.md, "Tabs", "Splits"): the terminals open in the panel, at
193
+ // most the store's TAB_LIMIT across its groups. `viewers` maps each tab's instanceId to its
194
+ // viewer, `{ id, panel, cols, rows }` (the panel's own id once the window exists, null before,
195
+ // and the size its window was last given); the store holds their groups, their order and which
196
+ // are shown, and after every frame the panel is brought to what the frame drew (fitPanel): the
197
+ // tabs it displays (each group's shown one, as the frame has room for), the one that takes the
198
+ // keys (the focused group's), and each group's size for every tab of it. `screens` is each
199
+ // displayed tab's last capture (`{ lines, cursor }`), drawn until the next; `displayed`, `keysTo`
200
+ // and `panelShown` what the panel was last told.
201
+ const viewers = new Map(), screens = new Map(), displayed = new Set();
202
+ let keysTo = null, panelShown = true;
203
+ const viewerOf = (panelId) => [...viewers.values()].find((each) => each.panel === panelId) ?? null;
141
204
  const panel = effects.createPanel({
142
205
  dir: runDir, env, capture: captureRows,
143
- onScreen: ({ id, screen: lines, cursor }) => { if (!ended && viewing !== null && viewing.panel === id) { screenNow = { lines, cursor }; guard.attempt(() => guard.draw()); } },
144
- // The viewer ended. The store is told, whatever ended it; a terminal the person closed is no
145
- // longer `viewing`, and the store says nothing of it.
206
+ onScreen: ({ id, screen: lines, cursor }) => { const v = viewerOf(id); if (!ended && v !== null && displayed.has(id)) { screens.set(v.id, { lines, cursor }); guard.attempt(() => guard.draw()); } },
207
+ // A hidden tab's agent wrote: its mark.
208
+ onActivity: ({ id }) => { const v = viewerOf(id); if (!ended && v !== null) heard({ activity: { id: v.id } }); },
209
+ // A viewer ended. The store is told, whatever ended it; a tab the person closed is no longer
210
+ // in `viewers`, and the store says nothing of it.
146
211
  onClosed: ({ id, status = null, stderr = "", asked = false }) => {
147
- if (viewing === null || viewing.panel !== id) return;
148
- const row = viewing.id;
149
- viewing = null; screenNow = null;
150
- heard({ returned: { id: row, status, stderr, asked } });
212
+ const v = viewerOf(id);
213
+ if (v === null) return;
214
+ forgetViewer(v);
215
+ heard({ returned: { id: v.id, status, stderr, asked } });
151
216
  },
152
217
  });
153
218
  // THE ACTS (docs/tui.md, "Stopping, starting, restarting and retiring"). One lifecycle boundary
@@ -163,8 +228,114 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
163
228
  /** The confirmation open now: `{ n, made }`, `made` the shared confirmation; or null. */
164
229
  let confirmation = null;
165
230
 
166
- /** What the reader gave, into the state, and the screen after it. */
167
- function heard(event) { if (!ended) guard.attempt(() => { if (!took(reduce(state, event, keymap))) guard.draw(); }); }
231
+ // THE SOULS (docs/tui.md, "The Souls view"): one catalog per run, the shared home's, over the
232
+ // reader's exec: its `oats souls` is a read like any other (kind "read", the reader's time limit,
233
+ // ended on every way out). It is settled for the open workspace with that workspace's own
234
+ // `workspace status`, so it is read only when nothing is held for the workspace as it is now
235
+ // (the shared key), and never before the Souls view was first shown.
236
+ const souls = effects.createSoulCatalog({ terms: TERMS, exec: reader.exec });
237
+ /** The catalog of workspace `id` settled now, and the store told what is held and whether a read
238
+ * is in flight; once that read lands, told again. Nothing for a workspace not read yet: its
239
+ * first observed entry settles it. */
240
+ function settleSouls(id) {
241
+ const deployment = state.entries.get(id)?.deployment;
242
+ if (ended || deployment?.status !== "observed") return;
243
+ // The workspace moved (its catalog's key): what the spawn preview holds of it goes too (Settled 7).
244
+ const key = soulsKeyNow(id);
245
+ if (catalogKeys.has(id) && catalogKeys.get(id) !== key) { try { preview.cache.invalidate(id); } catch { /* never blocks a read */ } }
246
+ catalogKeys.set(id, key);
247
+ let settled;
248
+ try { settled = souls.settle(id, probe.cli, deployment.workspaceStatus); } catch { return; } // the reader has stopped
249
+ const { entry, pending } = settled;
250
+ heard({ souls: { id, entry, reading: pending !== null } });
251
+ // A read lands with its own entry, even one a newer key has since replaced (the shared
252
+ // catalog keeps its held entry from it): only the read of the workspace as it is now is told.
253
+ if (pending) pending.then((landed) => { if (landed?.key === soulsKeyNow(id)) heard({ souls: { id, entry: landed, reading: souls.refreshing(id) } }); }, () => {});
254
+ }
255
+ /** The catalog's key for the workspace as the loop holds it now, or null when it is not observed. */
256
+ function soulsKeyNow(id) {
257
+ const deployment = state.entries.get(id)?.deployment;
258
+ return deployment?.status === "observed" ? soulCatalogKey(probe.cli, deployment.workspaceStatus) : null;
259
+ }
260
+ /** `r` in the Souls view: what is held for the workspace is forgotten and settled again, so one
261
+ * read starts; never a second while one is in flight. */
262
+ function rereadSouls(id) {
263
+ if (souls.refreshing(id)) return;
264
+ souls.forget(id);
265
+ settleSouls(id);
266
+ }
267
+
268
+ // THE SPAWN (docs/tui.md, "Spawning an agent"; Spec 6-spawn). One preview, one apply boundary and
269
+ // one transaction per run, the shared home's. The preview's kernel reads are reads (the reader's
270
+ // exec, ended on every way out). The apply is a change (`detached: true`, the shared apply's
271
+ // mark), which the reader never ends on its own: on a kernel without worktree-event it honours
272
+ // the deadline the shared apply gives it (lib/read.mjs changeExec); on one with it, the shared
273
+ // boundary ends it at its deadline through the child returned. `spawnLabel` names the spawn for
274
+ // the line after leaving (one at a time); `job` is the transaction's record of the last spawn,
275
+ // kept for a check (C) in this run only: the TUI keeps nothing on disk. `catalogKeys`: the key
276
+ // each workspace's catalog was last settled at, to tell when the workspace moved. Every timer
277
+ // the shared spawn arms is the run's (`spawnTimers`), cleared as the run ends: a spawn let go is
278
+ // never signalled after the TUI has gone, on any kernel.
279
+ const spawnTimers = createRunTimers({ setTimer, clearTimer });
280
+ const preview = effects.createSpawnPreview({ exec: reader.exec });
281
+ let spawnLabel = null, job = null;
282
+ const catalogKeys = new Map();
283
+ const spawnApply = effects.createSpawnApplyBoundary({ read: preview.prepareRead, exec: (bin, argv, { detached, ...options }, callback) => (detached
284
+ ? reader.changeExec(bin, argv, { ...options, label: spawnLabel }, callback)
285
+ : reader.exec(bin, argv, options, callback)),
286
+ timer: spawnTimers.timer, applyTimer: spawnTimers.timer });
287
+ /** As the Desktop's (server/oats-web.mjs): a spawn in the air changes what a preview answers, so
288
+ * held previews go when it is applied, and again when a pending apply settles, with a read. */
289
+ const forgetPreviews = (id) => { try { preview.cache.invalidate(id); } catch { /* never blocks a spawn */ } };
290
+ const transaction = effects.createSpawnTransaction({ request: (body, tx) => {
291
+ if (body?.action === "apply") forgetPreviews(tx.address);
292
+ return spawnApply(body, () => spawnContext(state, tx.address, clock()), { settled: () => { forgetPreviews(tx.address); refresh({ live: true }); } });
293
+ }, sleep: spawnTimers.sleep });
294
+ /** What a spawn's call is told: its owner is gone once the TUI leaves (`alive`), and the job is
295
+ * kept once it is submitted, for a check. */
296
+ const spawnCall = { alive: () => !ended, progress: (event, made) => { if (event === "submitted") { job = made; heard({ spawnProgress: { event } }); } } };
297
+ /** A transaction's outcome as the store takes it: the shared one, with the instance it names. */
298
+ const spawnTold = (outcome) => {
299
+ const receipt = outcome.view?.receipt ?? null, prepared = outcome.view?.preview ?? null;
300
+ return { kind: outcome.kind, view: outcome.view, reason: outcome.reason, instance: receipt?.instance ?? prepared?.instance ?? null, home: receipt?.home ?? prepared?.home ?? null };
301
+ };
302
+ /** A call that threw instead of answering: what it did is not known. */
303
+ const UNKNOWN = Object.freeze({ kind: "unknown", reason: Object.freeze({ code: "E_OUTCOME_UNKNOWN" }) });
304
+ /** The preview the store asked for (`{ n, workspace, request }`), read against the workspace as
305
+ * it is at that moment; its answer goes to the store. It arms Spawn only once a frame that
306
+ * shows it is written (the guard's `frame`). */
307
+ function previewRead({ n, workspace, request }) {
308
+ Promise.resolve()
309
+ .then(() => preview.read(request, () => spawnContext(state, workspace, clock())))
310
+ .then((answer) => heard({ spawnRead: { n, answer } }), () => heard({ spawnRead: { n, answer: null } }));
311
+ }
312
+ /** The spawn the store decided on: submitted once; its outcome goes to the store. */
313
+ function spawnNow({ workspace, selector, input, decision, name }) {
314
+ spawnLabel = { verb: "spawn", name };
315
+ job = null;
316
+ Promise.resolve()
317
+ .then(() => transaction.submit({ address: workspace, selector, input, decision }, spawnCall))
318
+ .then((outcome) => { if (outcome) heard({ spawnDone: spawnTold(outcome) }); }, () => heard({ spawnDone: UNKNOWN }));
319
+ }
320
+ /** C: the last spawn's result read once (an unknown one applies the same reference again). */
321
+ function checkSpawn() {
322
+ const mine = job;
323
+ if (mine === null) return void heard({ spawnDone: UNKNOWN });
324
+ Promise.resolve()
325
+ .then(() => transaction.check(mine, spawnCall))
326
+ .then((outcome) => { if (outcome) heard({ spawnDone: spawnTold(outcome) }); }, () => heard({ spawnDone: UNKNOWN }));
327
+ }
328
+
329
+ /** What the reader gave, into the state, and the screen after it. A read of the open workspace,
330
+ * once the Souls view was shown, settles its catalog: read again only when the workspace moved. */
331
+ function heard(event) {
332
+ if (ended) return;
333
+ guard.attempt(() => {
334
+ if (took(reduce(state, event, keymap))) return;
335
+ if (event.entry !== undefined && event.id === state.open && state.souls.wanted) settleSouls(event.id);
336
+ guard.draw();
337
+ });
338
+ }
168
339
  /** One step of the reducer taken: the state, then what only the loop can do. True once the
169
340
  * TUI is leaving. Listing ~/Agents and asking whether a picked folder is a deployment read the
170
341
  * file system (lib/read.mjs); what they find is an event of its own. */
@@ -181,7 +352,8 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
181
352
  took(reduce(state, admitted.ok ? { admitted: admitted.deployment, at: clock() } : { refused: effect.admit }, keymap));
182
353
  }
183
354
  if (effect.abandon) giveUpPreflight();
184
- if (effect.close !== undefined) closeTerminal();
355
+ // A tab shown (`show`) needs nothing here: the frame after it brings the panel to it (fitPanel).
356
+ if (effect.close !== undefined) for (const id of effect.close) closeTerminal(id);
185
357
  if (effect.open) open(effect.open);
186
358
  if (effect.panel !== undefined) {
187
359
  const ready = preflight;
@@ -193,6 +365,11 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
193
365
  if (effect.call) callConfirmation(effect.call);
194
366
  if (effect.start) startAct(effect.start);
195
367
  if (effect.refresh) refresh(effect.refresh);
368
+ if (effect.souls === "settle" && state.open !== null) settleSouls(state.open);
369
+ if (effect.souls === "reread" && state.open !== null) rereadSouls(state.open);
370
+ if (effect.spawnPreview) previewRead(effect.spawnPreview);
371
+ if (effect.spawn) spawnNow(effect.spawn);
372
+ if (effect.spawnCheck) checkSpawn();
196
373
  return false;
197
374
  }
198
375
 
@@ -200,7 +377,8 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
200
377
  const contextOf = (id) => actContext(state, id, clock());
201
378
  /** Open the shared confirmation of a stop or a retire the store decided on (`{ n, verb, row,
202
379
  * label }`). Every step it tells goes to the store as `{ acted }`; an answer that settles asks
203
- * for a live read of the rows (onSettled), and nothing else after an apply does. */
380
+ * for a live read of the rows (onSettled), and nothing else after an apply does. A retire's
381
+ * apply is held in `retires` from its send, whether or not the confirmation is still open. */
204
382
  function openConfirmation({ n, verb, row, label }) {
205
383
  dismiss(confirmation?.n);
206
384
  const id = row.deployment?.id, name = row.instance;
@@ -211,7 +389,7 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
211
389
  mine.made = effects.createLifecycleConfirmation({
212
390
  request: (body) => { if (body?.action === "apply") applying = { verb, name }; return boundary(body, () => contextOf(id)); },
213
391
  target, operation: verb, terms: TERMS, label, leftover: heldHome(row)?.kind === "spawn-incomplete",
214
- onChange: tell, onSettled: () => refresh({ live: true }),
392
+ onChange: tell, onSettled: () => refresh({ live: true }), retires,
215
393
  });
216
394
  tell();
217
395
  }
@@ -269,74 +447,126 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
269
447
  preflight = null;
270
448
  }
271
449
  /** Start the viewer of row `id` (`node <bin> <args…>`) in the panel, at the size the frame gives
272
- * the terminal, and tell the store when its window exists. One the panel could not start is a
273
- * viewer that ended, with the panel's refusal: no tmux (or one too old), or tmux's own words.
274
- * Nothing is lent: the reads and the screen go on. */
450
+ * the focused group, and tell the store when its window exists. The tab it takes the place of is
451
+ * no longer displayed from then on (the frame for the new state is fitted first). One the panel
452
+ * could not start is a viewer that ended, with the panel's refusal: no tmux (or one too old), or
453
+ * tmux's own words. Nothing is lent: the reads and the screen go on. */
275
454
  function view(id, bin, args) {
276
- const mine = viewing = { id, panel: null };
277
- const size = guard.size(), area = composed().made.terminal ?? { cols: size.cols, rows: Math.max(1, size.rows - 6) };
278
- panelSize = { cols: area.cols, rows: area.rows };
279
- // Shown: the panel keeps hidden or shown across its viewers, and the last one may have been
280
- // closed hidden (behind the detail, or the list alone under 80 columns).
281
- if (!panelShown) panel.setVisible(true);
282
- panelShown = true;
455
+ const size = guard.size();
456
+ // The focused group's screen as the Instances view gives it, also behind the help or another
457
+ // overlay, which draw no panel (round 1 of T3's review).
458
+ const region = placed()?.focused ?? { cols: Math.max(1, size.cols), rows: Math.max(1, size.rows - 6) };
459
+ const mine = { id, panel: null, cols: region.cols, rows: region.rows };
460
+ viewers.set(id, mine);
461
+ // Shown or hidden as this frame draws the panel: behind an overlay it shows once that closes.
462
+ fitPanel(composed().made);
283
463
  Promise.resolve()
284
- .then(() => panel.open({ argv: [process.execPath, bin, ...args], cols: area.cols, rows: area.rows }))
464
+ .then(() => panel.open({ argv: [process.execPath, bin, ...args], cols: region.cols, rows: region.rows, instead: null }))
285
465
  .then(({ id: made }) => {
286
- if (viewing !== mine) return;
466
+ if (viewers.get(id) !== mine) return;
287
467
  mine.panel = made;
288
- // A frame of another size while the window was being made told a panel with no window yet.
289
- if (panelSize.cols !== area.cols || panelSize.rows !== area.rows) panel.resize(panelSize.cols, panelSize.rows);
468
+ // The panel displays it, and it takes the keys; a frame of another size meanwhile is the
469
+ // next fitPanel's.
470
+ displayed.add(made);
471
+ keysTo = made;
290
472
  heard({ shown: { id } });
291
473
  },
292
- (error) => { if (viewing === mine) { viewing = null; heard({ returned: { id, status: null, stderr: typeof error?.detail === "string" ? error.detail : "", refused: error?.code === "E_PANEL_TMUX" ? "tmux" : "start" } }); } });
293
- }
294
- /** Close the open terminal's viewer (also one whose window is still being made): the agent keeps
295
- * running, and the panel reports the end as asked for, which nobody waits for. */
296
- function closeTerminal() {
297
- if (viewing === null) return;
298
- viewing = null; screenNow = null;
299
- panel.close();
300
- }
301
- /** The panel told what the frame gives the terminal: shown or not (no capture runs while it is
302
- * hidden, and one runs when it shows again), and its size (the viewer's window follows it). */
303
- function fitPanel(given) {
304
- // A view that draws no terminal (the help, the switcher, a confirmation) gives none.
305
- const area = given ?? null;
306
- if (viewing === null) return;
307
- if ((area !== null) !== panelShown) { panelShown = area !== null; panel.setVisible(panelShown); }
308
- if (area !== null && (area.cols !== panelSize.cols || area.rows !== panelSize.rows)) { panelSize = { cols: area.cols, rows: area.rows }; panel.resize(area.cols, area.rows); }
474
+ (error) => { if (viewers.get(id) === mine) { forgetViewer(mine); heard({ returned: { id, status: null, stderr: typeof error?.detail === "string" ? error.detail : "", refused: error?.code === "E_PANEL_TMUX" ? "tmux" : "start" } }); } });
475
+ }
476
+ /** What the loop holds of viewer `v` let go: the panel no longer displays it, or gives it keys. */
477
+ function forgetViewer(v) {
478
+ viewers.delete(v.id);
479
+ screens.delete(v.id);
480
+ if (v.panel !== null) { displayed.delete(v.panel); if (keysTo === v.panel) keysTo = null; }
481
+ }
482
+ /** Close tab `id`'s viewer (also one whose window is still being made: the open under way): the
483
+ * agent keeps running, and the panel reports the end as asked for, which nobody waits for. */
484
+ function closeTerminal(id) {
485
+ const v = viewers.get(id);
486
+ if (v === undefined) return;
487
+ forgetViewer(v);
488
+ if (v.panel === null) panel.close(); else panel.close(v.panel);
489
+ }
490
+ /** The panel brought to what the frame drew (`made.regions`, one per group drawn): shown or not
491
+ * (no capture runs while it is hidden, and one runs when it shows again); every tab of a drawn
492
+ * group at that group's size (the viewer's window follows it); each region's shown tab
493
+ * displayed, and no other; and the focused region's taking the keys. A group not drawn (the
494
+ * focused one alone, zoomed or with no room for both) keeps its tabs at their size, and its
495
+ * shown tab only marks. */
496
+ function fitPanel(made) {
497
+ if (viewers.size === 0) return;
498
+ const regions = made.regions ?? [];
499
+ if ((regions.length > 0) !== panelShown) { panelShown = regions.length > 0; panel.setVisible(panelShown); }
500
+ if (!panelShown) return;
501
+ const groupOf = (id) => state.tabs.find((tab) => tab.id === id)?.group ?? null;
502
+ for (const r of regions) {
503
+ const resized = [...viewers.values()].filter((v) => v.panel !== null && groupOf(v.id) === r.group && (v.cols !== r.cols || v.rows !== r.rows));
504
+ if (resized.length === 0) continue;
505
+ panel.resize(r.cols, r.rows, resized.map((v) => v.panel));
506
+ for (const v of resized) { v.cols = r.cols; v.rows = r.rows; }
507
+ }
508
+ const wanted = regions.map((r) => ({ r, v: r.id === null ? null : viewers.get(r.id) ?? null })).filter(({ v }) => v !== null && v.panel !== null);
509
+ const pids = new Set(wanted.map(({ v }) => v.panel));
510
+ // The shown tab hidden: the panel shows the other displayed one, or none (lib/panel.mjs hide).
511
+ for (const pid of [...displayed]) if (!pids.has(pid)) { panel.hide(pid); displayed.delete(pid); if (keysTo === pid) keysTo = [...displayed][0] ?? null; const v = viewerOf(pid); if (v) screens.delete(v.id); }
512
+ for (const { v } of wanted) if (!displayed.has(v.panel)) { panel.show(v.panel, { instead: null }); displayed.add(v.panel); keysTo = v.panel; }
513
+ const keys = wanted.find(({ r }) => r.focused)?.v.panel ?? null;
514
+ if (keys !== null && keys !== keysTo) { panel.focus(keys); keysTo = keys; }
309
515
  }
310
516
  /** The frame for the state now, with what the loop needs of it: the layout first, because the
311
517
  * model's window is as tall, and its sentences as wide, as the list pane it gives. The switcher
312
- * takes the whole body and has no notice of a deployment. The last capture of the open
313
- * terminal goes with the model: it is the panel's, not the store's. */
518
+ * takes the whole body and has no notice of a deployment. The last captures of the displayed
519
+ * tabs go with the model: they are the panel's, not the store's. */
314
520
  function composed() {
521
+ const { size, g, m } = modelled();
522
+ return { size, g, made: frame(m, size) };
523
+ }
524
+ function modelled() {
315
525
  const size = guard.size(), at = clock();
316
526
  const listing = (state.view === "help" ? state.back : state.view) === "switcher";
317
527
  const r = listing ? { notice: null, note: null, observed: true } : roster(state, at);
318
- const g = layout(r.notice, size, { observed: r.observed, note: r.note, ascii: state.ascii, outcome: listing ? null : state.outcome });
319
- const m = { ...model(state, { page: g.page, now: now(), at, cols: g.listCols }), screen: screenNow };
320
- return { size, g, made: frame(m, size) };
528
+ const g = layout(r.notice, size, { observed: r.observed, note: r.note, ascii: state.ascii, outcome: listing ? null : outcomeOf(state), terminal: state.tabs.length > 0 });
529
+ const m = { ...model(state, { page: g.page, now: now(), at, cols: g.listCols }), screen: screens.get(state.terminal?.id) ?? null, screens };
530
+ return { size, g, m };
531
+ }
532
+ /** Where the panel stands for the state and the size now, as the Instances view gives it with
533
+ * the terminal's focus (views/frame.mjs panelPlace): measured whatever is drawn over it, and
534
+ * while no frame can be written. */
535
+ function placed() {
536
+ const { size, m } = modelled();
537
+ return panelPlace(m, size);
321
538
  }
322
- /** Whether what is typed goes to the agent: the open terminal has the focus. */
323
- const typing = () => state.terminal?.focus === "terminal" && state.view === "instances";
539
+ /** Whether what is typed goes to the agent: the open terminal has the focus, and the leader
540
+ * does not wait for its key (docs/tui.md, "The leader"). */
541
+ const typing = () => state.terminal?.focus === "terminal" && state.view === "instances" && state.leader?.waiting !== true && state.palette === null && state.spawn === null;
324
542
  /** Bytes typed while the terminal has the focus: to the agent as they came, a paste as a paste,
325
- * and the back key to the store, which gives the focus to the list; what came after the back key
326
- * in the same read is read as keys, by a parser that starts afresh. */
543
+ * and the leader to the store, which waits for the key after it: from the next read on, the
544
+ * bytes are read as keys, by a parser that starts afresh. What came after the leader in its own
545
+ * read is dropped: it cancels the leader (a paste), and it is not the agent's either. */
327
546
  function typed(events) {
328
547
  for (const event of events) {
329
- if (event.input) panel.input(event.input);
330
- else if (event.paste !== undefined) panel.paste(event.paste);
548
+ if (event.input) { if (keysReady()) panel.input(event.input); }
549
+ else if (event.paste !== undefined) { if (keysReady()) panel.paste(event.paste); }
331
550
  else if (event.back) {
332
551
  parser = createKeyParser({ now });
333
- if (took(reduce(state, { back: true }, keymap))) return;
334
- if (event.rest.length) act(parser.feed(event.rest)); else guard.draw();
335
- watchEscape();
552
+ if (took(reduce(state, { back: true, read: ++reads, rest: event.rest.length > 0 }, keymap))) return;
553
+ guard.draw();
336
554
  }
337
555
  }
338
556
  watchThrough();
339
557
  }
558
+ /** Whether the keys typed now reach the agent the state gives them to, the focused group's shown
559
+ * tab: the panel is fitted to the state first when it was not, also while no frame is written
560
+ * (the output blocked), so a tab or a group switched to takes what is typed after the switch,
561
+ * never the one before it. A tab whose window is still being made takes nothing (round 1 of
562
+ * T3's review). */
563
+ function keysReady() {
564
+ const v = state.terminal === null ? undefined : viewers.get(state.terminal.id);
565
+ if (v === undefined || v.panel === null) return false;
566
+ const ready = () => keysTo === v.panel && displayed.has(v.panel);
567
+ if (!ready()) fitPanel(composed().made);
568
+ return ready();
569
+ }
340
570
  /** A beginning of the back key that nothing has followed for the parser's timeout is the agent's. */
341
571
  function watchThrough() {
342
572
  if (throughTimer !== null) { clearTimer(throughTimer); throughTimer = null; }
@@ -348,9 +578,12 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
348
578
  frame() {
349
579
  const { size, g, made } = composed();
350
580
  drawn = { page: made.page, extent: made.extent, room: made.room, cols: g.listCols };
351
- fitPanel(made.terminal);
581
+ fitPanel(made);
352
582
  const bytes = screen.render(made.rows, size, { full, cursor: made.cursor });
353
583
  full = false;
584
+ // This frame is written (the guard makes one only to write it): a ready preview on it is
585
+ // seen, and Enter on Spawn is taken from the next read of input on (the paste guard).
586
+ if (made.armed && state.spawn !== null) state = reduce(state, { spawnDrawn: { n: state.spawn.n, read: reads } }, keymap).state;
354
587
  return bytes;
355
588
  },
356
589
  onInput(bytes) {
@@ -360,7 +593,7 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
360
593
  },
361
594
  onResize() { full = true; guard.draw(); },
362
595
  // Ctrl+L and the return from a stop: the whole screen, and the open terminal captured afresh.
363
- onRedraw() { full = true; if (viewing !== null) panel.refresh(); guard.draw(); },
596
+ onRedraw() { full = true; if (viewers.size) panel.refresh(); guard.draw(); },
364
597
  // A cycle in flight when the process stops is no evidence about the deployment (lib/read.mjs):
365
598
  // it is dropped before the stop, and again after a stop nobody here asked for; the return
366
599
  // reads at once.
@@ -368,15 +601,15 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
368
601
  // timeout. The person opens the agent again.
369
602
  // The open terminal's server and viewer live on through a stop; the panel stops sending output
370
603
  // while nothing reads it, and captures afresh on the way back.
371
- onStop() { stopPreflight(); dropReads(); if (viewing !== null) panel.pause(); },
372
- onResume(asked) { if (!asked) { stopPreflight(); dropReads(); } if (viewing !== null) panel.resume(); refresh({ live: true }); },
604
+ onStop() { stopPreflight(); dropReads(); if (viewers.size) panel.pause(); },
605
+ onResume(asked) { if (!asked) { stopPreflight(); dropReads(); } if (viewers.size) panel.resume(); refresh({ live: true }); },
373
606
  // On the way out the confirmation is closed, the private tmux server is ended (its viewer with
374
607
  // it) and the reads end; a change in flight is let go, never signalled (lib/read.mjs
375
608
  // changeExec), and named after the screen is left.
376
609
  // The run's directory goes last, made for whichever of the two needed it first: the reader
377
610
  // removes it only when it wrote a change there, and one it cannot remove (a change still
378
611
  // writing) stays.
379
- onEnd() { ended = true; dismiss(confirmation?.n); panel.end(); reader.stop(); if (dir !== null) { try { effects.removeDir(dir); } catch { /* not empty, or gone */ } } },
612
+ onEnd() { ended = true; spawnTimers.end(); dismiss(confirmation?.n); panel.end(); reader.stop(); if (dir !== null) { try { effects.removeDir(dir); } catch { /* not empty, or gone */ } } },
380
613
  });
381
614
  function refresh(how) { Promise.resolve(reader.request(how)).catch(() => {}); }
382
615
  /** A preflight under way when the process stops: given up, and the store told. */
@@ -396,7 +629,7 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
396
629
  function act(events) {
397
630
  const read = ++reads;
398
631
  for (const event of events) {
399
- if (took(reduce(state, "paste" in event ? { paste: event.paste } : { key: keyId(event), ...(typeof event.text === "string" && !event.alt ? { text: event.text } : {}), read, ...drawn }, keymap))) return;
632
+ if (took(reduce(state, "paste" in event ? { paste: event.paste, read } : { key: keyId(event), ...(typeof event.text === "string" && !event.alt ? { text: event.text } : {}), read, ...drawn, panel: placed()?.panel ?? null }, keymap))) return;
400
633
  if (typing()) {
401
634
  if (escTimer !== null) { clearTimer(escTimer); escTimer = null; }
402
635
  through = createThrough({ sequences: backKey, now });