@awebai/oats 0.69.1 → 0.69.2

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 (67) hide show
  1. package/bin/oats.mjs +79 -15
  2. package/docs/capabilities.md +24 -5
  3. package/docs/capability-manifest.schema.json +1 -1
  4. package/docs/design/2026-09-23-workspace-module-contracts.md +6 -4
  5. package/docs/design/2026-10-22-module-upgrade.md +1 -1
  6. package/docs/desktop-cli-api.md +260 -28
  7. package/docs/desktop-instance-start.md +8 -37
  8. package/docs/desktop.md +76 -9
  9. package/docs/execution-targets.md +27 -5
  10. package/docs/implementation.md +6 -5
  11. package/docs/integrations.md +1 -1
  12. package/docs/knowledge.md +25 -16
  13. package/docs/official-catalog.md +3 -3
  14. package/docs/packages.md +12 -12
  15. package/docs/release-notes/v0.69.2.md +259 -0
  16. package/docs/servers.md +7 -2
  17. package/docs/soul.schema.json +1 -0
  18. package/docs/souls-and-instances.md +35 -2
  19. package/docs/tui.md +100 -9
  20. package/docs/upgrading.md +9 -5
  21. package/docs/workspaces.md +2 -2
  22. package/injects/instance-boundary.md +19 -33
  23. package/injects/work-attached.md +8 -13
  24. package/injects/work-checkout.md +16 -30
  25. package/injects/work-directory.md +9 -15
  26. package/injects/work-workspace.md +8 -19
  27. package/injects/work-worktree.md +18 -33
  28. package/lib/capability-contract.mjs +2 -2
  29. package/lib/core.mjs +162 -49
  30. package/lib/instance-background.mjs +54 -0
  31. package/lib/instance-inspect.mjs +3 -0
  32. package/lib/instance-lifecycle.mjs +35 -0
  33. package/lib/instance-resolution.mjs +3 -2
  34. package/lib/instance-same-work.mjs +67 -0
  35. package/lib/instance-upgrade.mjs +18 -0
  36. package/lib/materialize.mjs +23 -2
  37. package/lib/resolve.mjs +32 -5
  38. package/lib/servers.mjs +19 -4
  39. package/lib/session-resume-contract.mjs +1 -0
  40. package/lib/session-resume.mjs +36 -9
  41. package/lib/soul-composition.mjs +13 -10
  42. package/lib/workspace.mjs +3 -2
  43. package/package-catalog.json +2 -2
  44. package/package.json +1 -1
  45. package/packages/client/cli-adapter.mjs +30 -8
  46. package/packages/client/deployment-data.mjs +9 -0
  47. package/packages/client/deployment-panel.mjs +4 -0
  48. package/packages/client/instance-tree.mjs +64 -14
  49. package/packages/client/panel-views.mjs +11 -3
  50. package/packages/client/remote-roster.mjs +5 -1
  51. package/packages/client/roster-sections.mjs +50 -6
  52. package/packages/client/same-work.mjs +49 -0
  53. package/packages/client/session-resume.mjs +1 -1
  54. package/packages/client/soul-rows.mjs +2 -0
  55. package/packages/client/spawn-apply-contract.mjs +2 -1
  56. package/packages/client/spawn-decision.mjs +4 -1
  57. package/packages/client/spawn-preview-contract.mjs +12 -1
  58. package/packages/client/spawn-preview.mjs +2 -0
  59. package/packages/tui/README.md +2 -2
  60. package/packages/tui/lib/client.mjs +6 -2
  61. package/packages/tui/lib/main.mjs +44 -11
  62. package/packages/tui/lib/model.mjs +101 -43
  63. package/packages/tui/lib/store.mjs +76 -20
  64. package/packages/tui/lib/views/frame.mjs +2 -0
  65. package/packages/tui/lib/views/help.mjs +2 -0
  66. package/packages/tui/lib/views/instances.mjs +38 -1
  67. package/skills/oats-getting-started/SKILL.md +2 -2
@@ -12,9 +12,9 @@
12
12
  import { homedir } from "node:os";
13
13
  import { resolve } from "node:path";
14
14
  import { bindings } from "./actions.mjs";
15
- import { TERMS, capabilityCatalogKey, cliDeploymentList, deploymentsListSupported, createCapabilityCatalog, createLifecycleBoundary, createLifecycleConfirmation, createRetiresInFlight, createSoulCatalog, createSpawnApplyBoundary, createSpawnPreview, createSpawnTransaction, displayLine, heldHome, pendingEntry, prepareRemoteTerm, sessionAttachArgv, soulCatalogKey, startInstance } from "./client.mjs";
15
+ import { TERMS, capabilityCatalogKey, cliDeploymentList, deploymentsListSupported, createCapabilityCatalog, createLifecycleBoundary, createLifecycleConfirmation, createRetiresInFlight, createSoulCatalog, createSpawnApplyBoundary, createSpawnPreview, createSpawnTransaction, createResumeTrigger, displayLine, heldHome, pendingEntry, prepareRemoteTerm, runResumeSweep, sessionAttachArgv, soulCatalogKey, startInstance } from "./client.mjs";
16
16
  import { loadConfig, loadKeys } from "./config.mjs";
17
- import { ACT_WORDS, LIST_WORDS, actContext, actCwd, listRowsOf, localDeployments, model, outcomeOf, reachedMachines, roster, spawnContext } from "./model.mjs";
17
+ import { ACT_WORDS, LIST_WORDS, actContext, actCwd, listRowsOf, localDeployments, model, outcomeOf, reachedMachines, resumeObservation, roster, spawnContext } from "./model.mjs";
18
18
  import { createPanel, sweep } from "./panel.mjs";
19
19
  import { CHANGE_FILES, admitDeployment, createIdentityReads, createReader, findDeployment, leaveInstance, probeKernel, realpath, startExec, tellable } from "./read.mjs";
20
20
  import { initialState, reduce } from "./store.mjs";
@@ -72,6 +72,9 @@ export function parseArgs(argv) {
72
72
 
73
73
  /** The label of a change to this computer's deployments list (an add or a remove), for the line after leaving. */
74
74
  const LIST_CHANGE = Object.freeze({ verb: "list" });
75
+ /** The label of the kernel's machine sweep (`oats session resume --json`), every one the run starts: a
76
+ * change, never signalled, and never named after leaving (the TUI says nothing of a sweep). */
77
+ const RESUME_CHANGE = Object.freeze({ verb: "resume" });
75
78
  /** Why a call to this computer's deployments list has no answer at all: it threw before the kernel
76
79
  * could answer. The shared adapter's own code for a kernel call that failed (deployment-list-cli.mjs). */
77
80
  const NOT_ASKED = Object.freeze({ code: "E_CLI_FAILED", message: "the kernel could not be asked" });
@@ -94,10 +97,11 @@ function errorLines(error) {
94
97
  * can answer them. `deploymentList` is the shared cliDeploymentList (this computer's deployments
95
98
  * list, through the kernel: awebai/oats#1390), and `startExec` the exec it is handed before the
96
99
  * terminal is taken; replaceable so a test can answer the list. `loadKeys` reads keys.json, the
97
- * chord family (lib/config.mjs), replaceable so no test reads a user's file. */
100
+ * chord family (lib/config.mjs), replaceable so no test reads a user's file. `createResumeTrigger`
101
+ * is the shared trigger of the kernel's machine sweep (packages/client session-resume-trigger.mjs). */
98
102
  const EFFECTS = Object.freeze({ loadConfig, loadKeys, findDeployment, probeKernel, createReader, createIdentityReads, deploymentList: cliDeploymentList, startExec, admitDeployment, prepareRemoteTerm, createPanel, sweep,
99
103
  runDir: CHANGE_FILES.dir, removeDir: CHANGE_FILES.remove, realpath, tellable, startInstance, createLifecycleConfirmation, createLifecycleBoundary, createSoulCatalog,
100
- createCapabilityCatalog, createSpawnPreview, createSpawnApplyBoundary, createSpawnTransaction });
104
+ createCapabilityCatalog, createSpawnPreview, createSpawnApplyBoundary, createSpawnTransaction, createResumeTrigger });
101
105
 
102
106
  /** The timers a run lends the shared spawn: the apply's deadline and its grace (the boundary's
103
107
  * `applyTimer`), the boundary's wait for an answer (`timer`) and the transaction's polls
@@ -214,7 +218,13 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
214
218
  * covers nothing, whatever entry it kept. */
215
219
  function entered(event) {
216
220
  heard(event);
217
- if (event.read === true && state.numbers.get(event.id) === event.number) retires.landed(event.number, (t) => !t.server && t.workspace === event.id);
221
+ if (event.read !== true || state.numbers.get(event.id) !== event.number) return;
222
+ retires.landed(event.number, (t) => !t.server && t.workspace === event.id);
223
+ // The rows of the view that holds it, with its deployments of this machine: a lost row of one of those
224
+ // sweeps again; another machine's row never does (the shared trigger's locality).
225
+ if (ended) return;
226
+ const { rows, localDeploymentIds } = resumeObservation(state, event.id, clock());
227
+ resume.observed(rows, { localDeploymentIds });
218
228
  }
219
229
  /** An event of the roster read: taken, then an outcome covers the rows of each machine it reached
220
230
  * (a read that failed marks every machine not reached, and covers none). */
@@ -235,6 +245,22 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
235
245
  onEntry: entered, onRoster: rostered,
236
246
  files: { ...CHANGE_FILES, dir: runDir },
237
247
  });
248
+ // LOST SESSIONS RESUMED (docs/tui.md, "Resuming lost sessions"; #1559): the kernel's machine sweep,
249
+ // `oats session resume --json`, which resumes every lost session of every local deployment of this
250
+ // computer. The shared trigger decides when: once the run has started (`launch`, after the add of the
251
+ // deployment it started in has settled, so the sweep's registry holds it), then whenever a read of a
252
+ // served deployment shows a row of a deployment of this machine whose session was lost (`observed`,
253
+ // given the view's rows and its local deployment ids: lib/model.mjs resumeObservation), never two at
254
+ // a time nor more often than its floor, and only with a kernel that has the sweep. The TUI decides nothing of what
255
+ // resumes. The sweep is a change of the run (the reader's changeExec: detached, its output in files,
256
+ // never signalled), which outlives the TUI and is let go in silence on the way out; what it read goes
257
+ // to the store as `{ resumed }`, which says nothing of it and at most reads the rows live.
258
+ const resume = effects.createResumeTrigger({
259
+ cli: () => probe.cli,
260
+ run: (cli) => runResumeSweep(cli, { exec: (bin, argv, options, callback) => reader.changeExec(bin, argv, { ...options, label: RESUME_CHANGE }, callback), env }),
261
+ now,
262
+ onReading: (reading) => heard({ resumed: reading }),
263
+ });
238
264
  // THE TABS AND THE SPLIT (docs/tui.md, "Tabs", "Splits"): the terminals open in the panel, at
239
265
  // most the store's TAB_LIMIT across its groups. `viewers` maps each tab's instanceId to its
240
266
  // viewer, `{ id, panel, cols, rows }` (the panel's own id once the window exists, null before,
@@ -521,10 +547,11 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
521
547
  }
522
548
  /** The deployment the run started in (from where it was started, or `--dir`), added to the list
523
549
  * once, as the TUI's: best effort. A failure opens nothing less, and is said once, in the line
524
- * under the sidebar's title. A row opened from the switcher is on the list already. */
550
+ * under the sidebar's title. A row opened from the switcher is on the list already. Settles once
551
+ * the add has, whatever it answered; at once without one. */
525
552
  function listStart(path) {
526
- if (!listing) return;
527
- Promise.resolve()
553
+ if (!listing) return Promise.resolve();
554
+ return Promise.resolve()
528
555
  .then(() => effects.deploymentList(probe.cli, { action: "add", path, via: "tui" }, { exec: listChange, env }))
529
556
  .then((answer) => { if (!answer.ok) heard({ notListed: answer.reason }); }, () => heard({ notListed: NOT_ASKED }));
530
557
  }
@@ -813,7 +840,8 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
813
840
  // The run's directory goes last, made for whichever of the two needed it first: the reader
814
841
  // removes it only when it wrote a change there, and one it cannot remove (a change still
815
842
  // writing) stays.
816
- onEnd() { ended = true; spawnTimers.end(); dismiss(confirmation?.n); panel.end(); identities.stop(); reader.stop(); if (dir !== null) { try { effects.removeDir(dir); } catch { /* not empty, or gone */ } } },
843
+ // The machine sweep in flight is let go with the other changes: its answer is no longer shown.
844
+ onEnd() { ended = true; resume.dispose(); spawnTimers.end(); dismiss(confirmation?.n); panel.end(); identities.stop(); reader.stop(); if (dir !== null) { try { effects.removeDir(dir); } catch { /* not empty, or gone */ } } },
817
845
  });
818
846
  function refresh(how) { Promise.resolve(reader.request(how)).catch(() => {}); }
819
847
  /** A preflight under way when the process stops: given up, and the store told. Its state alone is
@@ -855,7 +883,11 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
855
883
  // At the wait's end what the key parser kept as a possible beginning of the answer is read as typed.
856
884
  if (kb === "asking" && !ended) kbTimer = setTimer(() => { kbTimer = null; guard.attempt(() => { const released = parser.giveUp(); answered(null); if (released.length && !typing()) act(released); watchEscape(); }); }, Math.max(0, answerBy - now()));
857
885
  guard.attempt(() => { if (!ended) Promise.resolve(reader.start()).catch(() => {}); });
858
- if (found.ok) guard.attempt(() => { if (!ended) listStart(found.deployment); });
886
+ // The machine sweep, once the add of the deployment the run started in has settled (a start in the
887
+ // switcher has none): after the first frame and the first read cycle have begun, never before them.
888
+ let added = Promise.resolve();
889
+ if (found.ok) guard.attempt(() => { if (!ended) added = listStart(found.deployment); });
890
+ added.then(() => { if (!ended) guard.attempt(() => { resume.launch(); }); });
859
891
  // Once a run, at the start: the identities of this computer's listed deployments, the list read first
860
892
  // when the run did not read it before the terminal was taken.
861
893
  guard.attempt(() => { if (!ended) { if (listedAtStart) identify(); else readList({ identify: true }); } });
@@ -869,7 +901,8 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
869
901
  if (kbTimer !== null) clearTimer(kbTimer);
870
902
  // After the alternate screen is left, so the message stays on the screen the user returns to.
871
903
  // One line per change still running, to a terminal or a file only; the status never depends on it.
872
- const running = reader.changes?.() ?? [];
904
+ // The machine sweep is no change of the person's: none for it.
905
+ const running = (reader.changes?.() ?? []).filter(({ label }) => label !== RESUME_CHANGE);
873
906
  if (running.length && effects.tellable(stderr)) {
874
907
  try { stderr.write(running.map(({ label }) => `${label === LIST_CHANGE ? LIST_WORDS.leaving : ACT_WORDS.leaving(label?.verb ?? "change", displayLine(label?.name) ?? "an instance")}\n`).join("")); } catch { /* nothing to tell it to */ }
875
908
  }
@@ -6,8 +6,8 @@
6
6
  // their answers, and holds no rule of its own about which group a row is in or what state it is
7
7
  // in. What it adds is the TUI's: the window, the clock times, and which fact stands on which line.
8
8
  import {
9
- TERMS, panelData, displayLine, DETAIL_WITHHELD, originLead, instanceId, instanceVisibleInTree, waitingRollup, collapseKey, filterInstanceTree,
10
- hasInstanceChildren, heldHome, instanceSiblings, siblingText, rosterSections, deploymentState, rowStale, primaryDeployment, isMultiDeployment, runtimeState, runtimeCounts, instanceColor, instanceDisplayName,
9
+ TERMS, panelData, localDeploymentIds, displayLine, DETAIL_WITHHELD, originLead, instanceId, instanceVisibleInTree, waitingRollup, collapseKey, filterInstanceTree,
10
+ hasInstanceChildren, heldHome, instanceSiblings, siblingText, rosterSections, rosterSectionKey, sidebarSections, backgroundPlacement, BACKGROUND_FEATURE, deploymentState, rowStale, primaryDeployment, isMultiDeployment, runtimeState, runtimeCounts, instanceColor, instanceDisplayName,
11
11
  waitingClaim, waitingLabel, waitedText, waitingClock, waitingBelowText, instanceActs, rowReason,
12
12
  identityMemory, viewModel, listedViews, workspaceChoices, workspaceChoiceRows, choiceMatches, UNMATCHED_SECTION, shortPath, machineLabels,
13
13
  openAct, deployments as heldDeployments, localScrollKeys, hostScrollKeys, attachExit, preflightFailure, kernelLines,
@@ -58,6 +58,15 @@ export function panelOf(state, at) {
58
58
  return state.open === null ? null : panelData(heldOf(state, at), state.open, TERMS);
59
59
  }
60
60
 
61
+ /** What the shared resume trigger observes after a read of served deployment `id` (lib/main.mjs): the rows of
62
+ * the view that holds it, each tagged with its deployment, and the ids of that view's deployments of this
63
+ * machine, as the Desktop's panel gives them (panel-views.mjs `panelData`, session-resume-trigger.mjs
64
+ * `localDeploymentIds`). Another machine's rows in the view are there, and are never local. */
65
+ export function resumeObservation(state, id, at) {
66
+ const panel = panelData(heldOf(state, at), id, TERMS);
67
+ return { rows: panel.instances ?? [], localDeploymentIds: localDeploymentIds(panel) };
68
+ }
69
+
61
70
  /** The workspace (the shared view's id: panel-views.mjs viewModel) that holds deployment `id` in `state`,
62
71
  * or null: what the tabs belong to, so a change of `state.open` within one workspace (its deployment of
63
72
  * this machine opened beside another machine's) is not taken for opening another. */
@@ -132,6 +141,15 @@ function markOf(row) {
132
141
  * map (views/souls.mjs SOUL_COLOURS), or null: which colour a row shows is the shared rule (instanceColor). */
133
142
  const rowColour = (row) => SOUL_COLOURS[instanceColor(row)] ?? null;
134
143
 
144
+ /** The id the Background section's heading is selected by (#1579): it stands in `state.selected` as an
145
+ * instance's id does, so the movement keys stop on it. No instanceId can be it: a home and an agents root
146
+ * are paths, an instance's name is made of letters, digits and `-`, and none starts with NUL. */
147
+ export const BACKGROUND_ID = "\u0000background";
148
+ /** Whether the Background section of workspace `open` is drawn open in `state`: closed in every new run,
149
+ * and kept for the run per workspace as `collapsed` is (by `state.open`): `state.background` holds the
150
+ * ones open. */
151
+ export const backgroundOpen = (state) => state.background.has(state.open);
152
+
135
153
  /** The key prefix of each run of instances related to no other, as the shared grouping names it
136
154
  * (`independent:<id>`). Read by key, not by label: a cluster whose root is named `independent` has that
137
155
  * label too, and its key is `cluster:<n>:independent`. */
@@ -151,22 +169,31 @@ function build(state, at) {
151
169
  // The filter: the text typed after `/`, or the exact soul filter the Souls view's `i` sets
152
170
  // (`soul`: the names an instance's soul may carry), matched by the shared walk all the same.
153
171
  const query = state.filter.query, soul = state.filter.soul ?? null, filtering = query.trim() !== "" || soul !== null;
154
- // The section (deployment) each row is drawn in, read from the shared split itself: the
155
- // sections of all rows. A collapse hides, and rolls up, only rows of its own section, as in the
156
- // Desktop: a parent's name can resolve to a row of another deployment of the view.
157
- // `ordered`: every row in that order, whatever is filtered or folded (the palette's).
158
- const sectionOf = new Map(), ordered = [];
159
- for (const part of rosterSections(instances, instances, deployments, TERMS)) for (const group of part.groups) for (const cluster of group.clusters) for (const row of cluster.instances) { sectionOf.set(instanceId(row), part.deployment?.id ?? null); ordered.push(row); }
160
- const section = (row) => sectionOf.get(instanceId(row)) ?? null;
172
+ // `ordered`: every row in the shared order of the whole roster, whatever is filtered, folded or in the
173
+ // Background section (the lists of a soul's instances read it).
174
+ const ordered = [];
175
+ for (const part of rosterSections(instances, instances, deployments, TERMS)) for (const group of part.groups) for (const cluster of group.clusters) ordered.push(...cluster.instances);
176
+ // The rows the Background section holds (#1579), the shared placement's: only when this run's kernel
177
+ // lists the feature; without it a row's `background` is ignored and nothing below changes.
178
+ const placement = backgroundPlacement(instances, Array.isArray(state.cli?.features) && state.cli.features.includes(BACKGROUND_FEATURE));
179
+ // The section each row is drawn in, as the shared key says it: its deployment's, in the main tree or in
180
+ // the Background section. A collapse hides, and rolls up, only rows of its own section, as in the
181
+ // Desktop: a parent's name can resolve to a row of another deployment of the view, or of the other part.
182
+ const section = rosterSectionKey(deployments, placement);
161
183
  // Each instance's siblings by explicit link, both ends, as the shared home resolves them (#1312):
162
- // asked of each section's full roster on its own, whatever is filtered or folded, so a name never
163
- // resolves to an instance of another deployment, nor a dropped row makes an ambiguous name unique.
164
- const bySection = new Map();
165
- for (const row of instances) { const key = section(row); if (!bySection.has(key)) bySection.set(key, []); bySection.get(key).push(row); }
184
+ // asked of each deployment's full roster on its own, whatever is filtered, folded or in the Background
185
+ // section, so a name never resolves to an instance of another deployment, nor a row of the other part
186
+ // left out makes an ambiguous name unique. The key without a placement is the deployment's alone.
187
+ const deploymentOf = rosterSectionKey(deployments), bySection = new Map();
188
+ for (const row of instances) { const key = deploymentOf(row); if (!bySection.has(key)) bySection.set(key, []); bySection.get(key).push(row); }
166
189
  const siblings = new Map([...bySection.values()].flatMap((own) => [...instanceSiblings(own)]));
167
190
  const matched = soul !== null ? filterInstanceTree(instances, soul.name, (row) => soul.names.includes(row.agent)) : filterInstanceTree(instances, query);
168
191
  const visible = matched.filter((i) => instanceVisibleInTree(i, instances, state.collapsed, state.open, filtering, { section }));
169
- const sections = rosterSections(instances, visible, deployments, TERMS);
192
+ const stale = (row) => rowStale(row, deployments);
193
+ // The main tree's sections, and the Background section after them, each a tree of its own (the shared
194
+ // sidebarSections). A filter draws the section open, so its matches show, and changes nothing stored;
195
+ // the heading counts the rows the filter leaves in it.
196
+ const { main: sections, background } = sidebarSections(instances, visible, deployments, TERMS, { placement, open: backgroundOpen(state) || filtering, listed: matched, stale });
170
197
  // How many instances each collapse folds away under its row: every descendant of the row in its
171
198
  // own section, as the shared walk finds them when it is asked with that collapse alone (so a
172
199
  // fold further down hides none of them from the count). A filter folds nothing away.
@@ -177,7 +204,6 @@ function build(state, at) {
177
204
  const alone = new Set([key]);
178
205
  folded.set(instanceId(row), instances.filter((other) => !instanceVisibleInTree(other, instances, alone, state.open, false, { section })).length);
179
206
  }
180
- const stale = (row) => rowStale(row, deployments);
181
207
  const primary = primaryDeployment(deployments), said = deploymentState(primary);
182
208
  const live = primary !== null && said.key === "live";
183
209
  // The time of the read the screen shows: the cycle's own (`generatedAt`), never
@@ -191,19 +217,7 @@ function build(state, at) {
191
217
  // given, every cluster's members in order, with one gap at every boundary between a run of single
192
218
  // instances and a cluster, both ways (#1262).
193
219
  const parts = [], rows = [];
194
- const heading = (deployment, label, path = null) => {
195
- const its = deploymentState(deployment), up = its.key === "live";
196
- // A machine's rows are what it reported at the last roster read: that time stands on its
197
- // heading only when the time of this read (the help's top row) is another, so the heading of a machine read with
198
- // this one is its name alone. A deployment that is not live has its state and short reason
199
- // in the shared words instead, and no time.
200
- const read = up && deployment.local === false ? clockTime(state.rosterAt) : null;
201
- return {
202
- kind: "heading", label, path, state: up ? null : its.text, short: up || !text(deployment.short) ? null : deployment.short,
203
- readAt: read !== readAt ? read : null,
204
- };
205
- };
206
- for (const part of sections) {
220
+ const drawn = (part, background = false) => {
207
221
  if (text(part.label)) {
208
222
  parts.push(heading(part.deployment, part.label));
209
223
  if (text(part.deployment.note)) parts.push({ kind: "sentence", value: part.deployment.note });
@@ -215,20 +229,44 @@ function build(state, at) {
215
229
  if (previous !== null && singles !== previous) parts.push({ kind: "gap" });
216
230
  previous = singles;
217
231
  for (const cluster of group.clusters) for (const row of cluster.instances) {
218
- const item = { kind: "row", row, id: instanceId(row), depth: Number.isInteger(row.depth) ? row.depth : 0 };
232
+ const item = { kind: "row", row, id: instanceId(row), depth: Number.isInteger(row.depth) ? row.depth : 0, ...(background ? { background: true } : {}) };
219
233
  parts.push(item); rows.push(item);
220
234
  }
221
235
  }
222
- }
236
+ };
237
+ const heading = (deployment, label, path = null) => {
238
+ const its = deploymentState(deployment), up = its.key === "live";
239
+ // A machine's rows are what it reported at the last roster read: that time stands on its
240
+ // heading only when the time of this read (the help's top row) is another, so the heading of a machine read with
241
+ // this one is its name alone. A deployment that is not live has its state and short reason
242
+ // in the shared words instead, and no time.
243
+ const read = up && deployment.local === false ? clockTime(state.rosterAt) : null;
244
+ return {
245
+ kind: "heading", label, path, state: up ? null : its.text, short: up || !text(deployment.short) ? null : deployment.short,
246
+ readAt: read !== readAt ? read : null,
247
+ };
248
+ };
249
+ for (const part of sections) drawn(part);
223
250
  // A deployment of the view that is not live and has no row is in no section: it is named
224
- // after them, with its state, and its reason on rows of its own.
251
+ // after them, with its state, and its reason on rows of its own. One whose rows are all in the
252
+ // Background section has its heading there while the section is open; closed, it is named here, so
253
+ // that it is not reached is still said.
254
+ const held = new Set(background?.sections.map((part) => part.deployment?.id) ?? []);
225
255
  if (multi) for (const deployment of deployments) {
226
256
  const its = deploymentState(deployment);
227
- if (its.key === "live" || sections.some((part) => part.deployment?.id === deployment.id)) continue;
257
+ if (its.key === "live" || sections.some((part) => part.deployment?.id === deployment.id) || held.has(deployment.id)) continue;
228
258
  parts.push(heading(deployment, deployment.machine, deployment.label));
229
259
  if (text(its.detail)) parts.push({ kind: "sentence", value: its.detail });
230
260
  if (text(deployment.note)) parts.push({ kind: "sentence", value: deployment.note });
231
261
  }
262
+ // The Background section (#1579), after the whole main tree: its heading, which can be selected and
263
+ // opens and closes it (lib/store.mjs), and while it is open its own tree, drawn as the main one is,
264
+ // with a heading per deployment in a view of two or more. Its rows wait as any row does; the heading
265
+ // says that one of them waits, open or closed.
266
+ if (background !== null) {
267
+ parts.push({ kind: "background", id: BACKGROUND_ID, open: background.open, count: background.count, waiting: background.waiting });
268
+ for (const part of background.sections) drawn(part, true);
269
+ }
232
270
  // The roster read failed and no answer has arrived yet: there is no machine to say it.
233
271
  // It is about no row above it: an empty row sets it apart when something stands there.
234
272
  if (state.remote.rosterFailure !== null) parts.push(...(parts.length ? [{ kind: "gap" }] : []), { kind: "own", words: ROSTER_FAILED }, { kind: "sentence", value: state.remote.rosterFailure });
@@ -238,6 +276,7 @@ function build(state, at) {
238
276
  const status = panel?.deployment?.status ?? null;
239
277
  const local = panel !== null && !!panel.deployment;
240
278
  const counted = runtimeCounts(instances);
279
+ // Every row of the workspace that waits, the Background section's too, open or closed (#1579).
241
280
  const waiting = instances.filter((row) => waitingClaim(row, { stale: stale(row) })).length;
242
281
  const withheld = Array.isArray(panel?.deployment?.withheld) ? panel.deployment.withheld.length : 0;
243
282
  // The machines of the view other than this one, each once, and whether a deployment of this
@@ -249,6 +288,9 @@ function build(state, at) {
249
288
  const observed = panel !== null && !gone && (local ? status === "observed" : live || instances.length > 0);
250
289
  return {
251
290
  panel, gone, instances, ordered, deployments, multi, parts, rows, filtering, stale, section, siblings, live, observed, folded,
291
+ // What the selection stands on, in drawn order: the instances' rows and the Background heading.
292
+ stops: parts.filter((part) => part.id !== undefined),
293
+ placement, background,
252
294
  below: waitingRollup(instances, state.collapsed, state.open, { filtering, stale, section }),
253
295
  status,
254
296
  workspace: text(panel?.workspace?.name) ? panel.workspace.name : "",
@@ -276,7 +318,8 @@ function build(state, at) {
276
318
  // Why no instance is listed. "none" is a statement about the deployment, so it is made only
277
319
  // of one that was read: a machine that is not live and has no row kept is not known to have
278
320
  // none (it is not `observed`), and its notice is all there is to say.
279
- empty: status === "pending" ? "reading" : !observed ? null : !instances.length ? "none" : !rows.length ? "nomatch" : null,
321
+ // A Background heading is something listed: every instance in a closed section is no "nomatch".
322
+ empty: status === "pending" ? "reading" : !observed ? null : !instances.length ? "none" : !parts.some((part) => part.id !== undefined) ? "nomatch" : null,
280
323
  // As wide as the widest word among all the rows of the list, so the column does not move
281
324
  // while the list scrolls.
282
325
  wordWidth: Math.min(WORD_MAX, rows.reduce((widest, { row }) => Math.max(widest, textWidth(displayLine(wordOf(row, state.ascii)) ?? "")), 0)),
@@ -287,10 +330,11 @@ function build(state, at) {
287
330
  export const ROSTER_FAILED = "Other machines were not read.";
288
331
 
289
332
  /** The list as rows of the screen for a pane `cols` wide: every part on one row, a sentence on
290
- * as many as it needs. An item is null (an empty row), an instance (`{ row, id, depth }`, the
291
- * only kind that can be selected), `{ heading }`, `{ line }` (one row of a sentence, safe text),
292
- * `{ own }` (the TUI's words) or `{ empty }` (why no instance is listed). `index`: an
293
- * instance's id to its place. */
333
+ * as many as it needs. An item is null (an empty row), an instance (`{ row, id, depth }`), the
334
+ * Background heading (`{ kind: "background", id: BACKGROUND_ID, open, count, waiting }`): the two
335
+ * kinds that can be selected, both with an `id`; `{ heading }`, `{ line }` (one row of a sentence,
336
+ * safe text), `{ own }` (the TUI's words) or `{ empty }` (why no instance is listed). `index`: the
337
+ * id of what can be selected to its place. */
294
338
  function flatten(base, cols, ascii) {
295
339
  const items = [];
296
340
  const room = Math.max(1, cols - SENTENCE_INDENT - 1);
@@ -298,7 +342,7 @@ function flatten(base, cols, ascii) {
298
342
  if (base.empty) items.push({ empty: base.empty }, ...(base.parts.length ? [null] : []));
299
343
  for (const part of base.parts) {
300
344
  if (part.kind === "gap") items.push(null);
301
- else if (part.kind === "row") items.push(part);
345
+ else if (part.kind === "row" || part.kind === "background") items.push(part);
302
346
  else if (part.kind === "heading") items.push({ heading: part });
303
347
  else if (part.kind === "own") items.push({ own: part.words });
304
348
  else for (const line of shownLines(part.value, room, SENTENCE_ROWS, { ascii })) items.push({ line });
@@ -310,11 +354,11 @@ function flatten(base, cols, ascii) {
310
354
  * from read it again without asking the shared home again (its grouping walks the whole roster
311
355
  * for each row). The state's values are never changed in place, so their identity says whether
312
356
  * they changed. The flattening for the last width asked is kept beside it. */
313
- const MADE_FROM = ["entries", "remote", "memory", "notes", "rosterAt", "collecting", "ctxs", "open", "collapsed", "cli", "home", "retiring", "ascii"];
357
+ const MADE_FROM = ["entries", "remote", "memory", "notes", "rosterAt", "collecting", "ctxs", "open", "collapsed", "background", "cli", "home", "retiring", "ascii"];
314
358
  let kept = null;
315
359
  /** The roster of a state: the rows in drawn order and what the sidebar's title says, for a list pane
316
360
  * `cols` wide. Only `items` and `index` depend on the width; `rows`, the instances in drawn
317
- * order, do not. `at` stamps a machine's panel before any roster outcome was taken, which
361
+ * order, and `stops`, those and the Background heading (what the selection stands on), do not. `at` stamps a machine's panel before any roster outcome was taken, which
318
362
  * never shows; it is passed on. */
319
363
  export function roster(state, at = new Date(0).toISOString(), cols = ANY_WIDTH) {
320
364
  const same = kept && MADE_FROM.every((name) => kept.state[name] === state[name]) && kept.state.filter.query === state.filter.query && kept.state.filter.soul === state.filter.soul;
@@ -357,6 +401,16 @@ function listRow(state, r, item) {
357
401
  };
358
402
  }
359
403
 
404
+ /** The Background section's heading as its row draws it (#1579): open or closed, how many rows the
405
+ * section holds (those a filter leaves), whether one of them waits (said by the needs-input tag,
406
+ * open or closed), and the selection, as an instance row has it. */
407
+ function backgroundRow(state, item) {
408
+ return {
409
+ kind: "background", id: item.id, open: item.open, count: item.count, waiting: item.waiting,
410
+ selected: item.id === state.selected, cursor: item.id === state.selected && state.focus !== "workspaces",
411
+ };
412
+ }
413
+
360
414
  /** A text the TUI did not write, as the detail and the outcome line draw it, or null when it has
361
415
  * nothing to show. Who made it is the shared home's to say: after the words originLead gives for
362
416
  * `origin` when it names a speaker; as it is when the shared home vouches for it (`vouched`: it
@@ -975,15 +1029,19 @@ export function model(state, { page, body = page, now, at, cols, area = cols })
975
1029
  }
976
1030
  const selected = state.selected === null ? -1 : r.index.get(state.selected) ?? -1;
977
1031
  // What the detail and Enter read of the selected row is worked out once per paint.
978
- const row = selected >= 0 ? r.items[selected].row : null, acts = row ? instanceActs(row) : null;
1032
+ // The Background heading selected is no instance: it has no detail and nothing to open.
1033
+ const row = selected >= 0 ? r.items[selected].row ?? null : null, acts = row ? instanceActs(row) : null;
979
1034
  const decision = row ? openDecision(state, row, acts) : null;
980
1035
  // The window holds the selection, unless the list was scrolled away from it on purpose.
981
1036
  const win = windowOf({ top: state.top, count: r.items.length, height: page, keep: state.loose ? -1 : selected });
982
1037
  return {
983
1038
  ...common, under,
984
- list: r.items.slice(win.top, win.top + win.size).map((item) => (item?.id !== undefined ? { kind: "row", ...listRow(state, r, item) } : item)),
1039
+ list: r.items.slice(win.top, win.top + win.size).map((item) => (item?.kind === "background" ? backgroundRow(state, item) : item?.id !== undefined ? { kind: "row", ...listRow(state, r, item) } : item)),
985
1040
  above: win.above, below: win.below, wordWidth: r.wordWidth,
986
- detail: selected >= 0 ? detailOf(state, r, r.items[selected], now, acts) : null,
1041
+ detail: row !== null ? detailOf(state, r, r.items[selected], now, acts) : null,
1042
+ // The Background heading selected (#1579): whether Enter opens the section or closes it (the cheat
1043
+ // sheet); null while a filter is on, which draws it open and lets it change nothing.
1044
+ onBackground: !r.filtering && selected >= 0 && r.items[selected].kind === "background" ? (r.items[selected].open ? "open" : "closed") : null,
987
1045
  // Enter opens the selected agent's terminal now, or (`onTerminal`) goes to the one open on it.
988
1046
  openable: decision?.open === true && state.opening === null,
989
1047
  onTerminal: row !== null && state.terminal !== null && state.terminal.id === instanceId(row),
@@ -12,7 +12,7 @@
12
12
  import { ACTIONS, LEADER_KEYS, backKeyLabel, bindings, chordKeys, chordsRead, paletteKeys } from "./actions.mjs";
13
13
  import { CHORDS, chordFamilyFrom, collapseKey, workspaceStep, displayLine, instanceActs, instanceId, outcomeWords, pendingEntry, spawnProblem } from "./client.mjs";
14
14
  import { defaultDetachKey } from "./config.mjs";
15
- import { BUTTON_ORDER, SPAWN_WORDS, LEADER_WORDS, SPLIT_WORDS, TAB_WORDS, actDecision, capabilitiesHeight, capabilitiesOf, capabilityUsersOf, disclosure, openDecision, paletteItems, paletteStep, preflightLine, returnedLine, roster, soulNames, soulOfAgent, soulsOf, spawnChoices, spawnChoicesKey, spawnLine, spawnPickerItems, spawnReady, spawnRing, spawnSelector, spawnedRow, switcher, switcherHeight, switcherWindow, memoryKey, memoryKeys, LIST_WORDS, WORKSPACE_WORDS, listChoice, listChoices, workspaceList } from "./model.mjs";
15
+ import { BACKGROUND_ID, backgroundOpen, BUTTON_ORDER, SPAWN_WORDS, LEADER_WORDS, SPLIT_WORDS, TAB_WORDS, actDecision, capabilitiesHeight, capabilitiesOf, capabilityUsersOf, disclosure, openDecision, paletteItems, paletteStep, preflightLine, returnedLine, roster, soulNames, soulOfAgent, soulsOf, spawnChoices, spawnChoicesKey, spawnLine, spawnPickerItems, spawnReady, spawnRing, spawnSelector, spawnedRow, switcher, switcherHeight, switcherWindow, memoryKey, memoryKeys, LIST_WORDS, WORKSPACE_WORDS, listChoice, listChoices, workspaceList } from "./model.mjs";
16
16
  import { backKeyId, backKeySequences, isBackKey } from "./term/through.mjs";
17
17
  import { windowOf } from "./views/scroll.mjs";
18
18
  import { SPLIT_MIN, splitFits } from "./views/split.mjs";
@@ -53,7 +53,8 @@ const NO_CAPABILITIES = Object.freeze({ wanted: false, held: new Map(), selected
53
53
  * on purpose (see `scrolledList`); the switcher has its own.
54
54
  * `selected`, `top`, `detailTop` are the open view's; `places` keeps them, with the filter, for
55
55
  * the workspaces left behind (per lib/model.mjs memoryKey; see `opened`), and `collapsed` holds
56
- * every view's keys (each carries its `open`).
56
+ * every view's keys (each carries its `open`). `background`: the `open` of every view whose
57
+ * Background section is open (#1579; lib/model.mjs backgroundOpen): none at the start of a run.
57
58
  * `back`: the view under the help. `listed`: this computer's deployments list as it was last read
58
59
  * (awebai/oats#1390): `rows`, the shared reader's `{ path, name, state }` in the kernel's order, of
59
60
  * the last read that answered, and `failure`, the reason (`{ code, message }`) the last read failed
@@ -128,7 +129,7 @@ export function initialState({ deployment = null, cli, home, entry = null, actio
128
129
  entries: new Map(deployment === null ? [] : [[deployment, entry]]), numbers: new Map(),
129
130
  remote: Object.freeze({ remoteGroups: Object.freeze([]), rosterAnswered: false, rosterFailure: null }), rosterAt: null,
130
131
  memory: new Map(), notes: new Map(), collecting: false, cli, home,
131
- selected: null, collapsed: new Set(), filter: NO_FILTER, focus: "list", top: 0, loose: false, detailTop: 0, places: new Map(), unread: new Map(), unreadKeys: new Map(), workspaceCursor: null, colour,
132
+ selected: null, collapsed: new Set(), background: new Set(), filter: NO_FILTER, focus: "list", top: 0, loose: false, detailTop: 0, places: new Map(), unread: new Map(), unreadKeys: new Map(), workspaceCursor: null, colour,
132
133
  switcher: NO_SWITCHER,
133
134
  listed: NO_LIST, identities: new Map(),
134
135
  helpTop: 0, actions, ascii, detachKey, opening: null, terminal: null, outcome: null, act: null, acted: 0, starting: new Map(), retiring: new Set(),
@@ -150,8 +151,10 @@ const NO_SWITCHER = Object.freeze({ editing: false, query: "", selected: null, t
150
151
  /** This computer's deployments list before its first read. */
151
152
  const NO_LIST = Object.freeze({ rows: Object.freeze([]), failure: null });
152
153
  const indexOf = (r, id) => (id === null ? -1 : r.index.get(id) ?? -1);
153
- /** Whether an item of the list is an instance: the only kind the selection stands on. */
154
+ /** Whether an item of the list is one the selection stands on: an instance, or the Background heading. */
154
155
  const isRow = (item) => item?.id !== undefined;
156
+ /** Whether an item of the list is an instance. */
157
+ const isInstance = (item) => item?.row !== undefined;
155
158
 
156
159
  /** The list's `top` as the screen shows it for this state in a pane `page` rows tall. The
157
160
  * window holds the selected instance, unless it was scrolled away from it on purpose (`loose`). */
@@ -164,12 +167,12 @@ const settledTop = (state, r, page) => windowOf({ top: state.top, count: r.items
164
167
  * A new selection starts its detail at the top. */
165
168
  function selectAt(state, r, index, page, step = 1) {
166
169
  const count = r.items.length;
167
- if (!r.rows.length) return state;
170
+ if (!r.stops.length) return state;
168
171
  let at = Math.min(Math.max(0, index), count - 1);
169
172
  while (at >= 0 && at < count && !isRow(r.items[at])) at += step;
170
173
  if (at < 0 || at >= count) { at = Math.min(Math.max(0, index), count - 1); while (!isRow(r.items[at])) at -= step; }
171
174
  const id = r.items[at].id;
172
- const from = id === r.rows[0].id ? 0 : id === r.rows.at(-1).id ? count : settledTop(state, r, page);
175
+ const from = id === r.stops[0].id ? 0 : id === r.stops.at(-1).id ? count : settledTop(state, r, page);
173
176
  const top = windowOf({ top: from, count, height: page, keep: at }).top;
174
177
  return next(state, { selected: id, top, loose: false, detailTop: id === state.selected ? state.detailTop : 0 });
175
178
  }
@@ -185,16 +188,19 @@ function scrolledList(state, r, action, page) {
185
188
  }
186
189
 
187
190
  /** After the rows changed (a read, the filter, a collapse): the selection stays on its instance
188
- * while that is still drawn; else it moves to the row now at the same place in the drawn order,
189
- * else to the last row, else there is none. With none selected, the first row is.
190
- * A filter that matches nothing leaves no row to move to: the selection then stays on its
191
- * instance while the view still has it, and is found again when the filter is cleared. */
191
+ * (or on the Background heading) while that is still drawn; an instance now in the Background
192
+ * section while it is closed hands it to the heading (#1579); else it moves to the row now at the
193
+ * same place in the drawn order, else to the last row, else there is none. With none selected, the
194
+ * first row is. A filter that matches nothing leaves no row to move to: the selection then stays
195
+ * on its instance while the view still has it, and is found again when the filter is cleared. */
192
196
  function rehomed(before, state) {
193
197
  const now = roster(state);
194
198
  if (state.selected !== null && now.index.has(state.selected)) return state;
195
- if (state.selected !== null && now.rows.length === 0 && now.instances.some((row) => instanceId(row) === state.selected)) return state;
196
- const place = state.selected === null ? 0 : Math.max(0, before.rows.findIndex((item) => item.id === state.selected));
197
- const item = now.rows[Math.min(place, now.rows.length - 1)] ?? null;
199
+ if (state.selected !== null && now.stops.length === 0 && now.instances.some((row) => instanceId(row) === state.selected)) return state;
200
+ // The heading has no detail: a focus there goes back to the list.
201
+ if (now.placement.has(state.selected) && now.index.has(BACKGROUND_ID)) return next(state, { selected: BACKGROUND_ID, loose: false, detailTop: 0, ...(state.focus === "detail" ? { focus: "list" } : {}) });
202
+ const place = state.selected === null ? 0 : Math.max(0, before.stops.findIndex((item) => item.id === state.selected));
203
+ const item = now.stops[Math.min(place, now.stops.length - 1)] ?? null;
198
204
  return next(state, { selected: item ? item.id : null, loose: false, detailTop: 0 });
199
205
  }
200
206
 
@@ -280,7 +286,7 @@ function opened(state, id) {
280
286
  const places = new Map(state.places);
281
287
  if (state.open !== null) places.set(memoryKey(state, state.open), Object.freeze({ selected: state.selected, top: state.top, detailTop: state.detailTop, filter: Object.freeze({ ...state.filter, editing: false }) }));
282
288
  const place = places.get(memoryKey(state, id)) ?? { selected: null, top: 0, detailTop: 0, filter: NO_FILTER };
283
- return rehomed({ rows: [] }, next(shown, { open: id, places, focus: "list", loose: false, ...place }));
289
+ return rehomed({ stops: [] }, next(shown, { open: id, places, focus: "list", loose: false, ...place }));
284
290
  }
285
291
 
286
292
  /** A picked row of this computer's deployments list that is a deployment (lib/read.mjs made it
@@ -720,6 +726,16 @@ function listedHeard(state, { rows, failure }) {
720
726
  return { state: next(state, { listed: Object.freeze({ rows: Object.freeze(rows.map((row) => Object.freeze({ path: row.path, name: row.name, state: row.state }))), failure: null }) }), effect: null };
721
727
  }
722
728
 
729
+ /** The kernel's machine sweep read (lib/main.mjs; the shared readResumeSweep's `{ kind, summary?, code? }`).
730
+ * The TUI says nothing of a sweep (docs/tui.md, "Resuming lost sessions"): no line, whatever it read,
731
+ * and the list shows each instance as it is after the next read. A sweep that ran (`notice`, `quiet`)
732
+ * asks for that read live, so a resumed row reads running; one that failed, found the machine's sweep
733
+ * busy, or a kernel without it, asks for nothing. */
734
+ function resumedHeard(state, reading) {
735
+ if (reading?.kind === "notice" || reading?.kind === "quiet") return { state, effect: { refresh: { live: true } } };
736
+ return { state, effect: null };
737
+ }
738
+
723
739
  /** A Remove answered (lib/main.mjs): the switcher says how, and the list is read again. */
724
740
  function removedHeard(state, { name, ok, reason = null }) {
725
741
  const line = Object.freeze(ok ? { removed: name } : { notRemoved: name, message: reason?.message ?? "" });
@@ -739,7 +755,8 @@ function removedHeard(state, { name, ok, reason = null }) {
739
755
  * workspace picked in the switcher are deployments now, and the ones it may open, in order),
740
756
  * `{ identity: { path, read } }` (what an identity read answered of a row of the list),
741
757
  * `{ removed: { path, name, ok, reason } }` (a Remove's answer) and
742
- * `{ notListed: <reason> }` (the deployment the run started in was not added to the list), and
758
+ * `{ notListed: <reason> }` (the deployment the run started in was not added to the list),
759
+ * `{ resumed: <reading> }` (the kernel's machine sweep read, which says nothing: see `resumedHeard`), and
743
760
  * `{ passed: true }` (bytes typed to the agent, or a resize: what the loop saw that the store does
744
761
  * not, which ends a line of one key).
745
762
  * Opening an agent gives five more: `{ prepared: { id, error? } }` (the preflight of another
@@ -1010,9 +1027,15 @@ function showTab(state, id, { focus = state.terminal?.focus ?? "list", zoom = st
1010
1027
 
1011
1028
  /** The row of instance `id` selected and on view in the list (Settled 5 of T2): a text filter
1012
1029
  * that hides it is cleared, and a collapsed instance above it is opened. The focus is not moved,
1013
- * and nothing is selected when the row is not in the roster at all (it went away). */
1030
+ * and nothing is selected when the row is not in the roster at all (it went away), nor when it is
1031
+ * in the closed Background section. */
1014
1032
  function revealed(state, id) {
1015
1033
  if (state.view !== "instances" || state.open === null) return state;
1034
+ // An instance of the Background section while it is closed stays out of sight (#1579): showing its
1035
+ // terminal opens no section, clears no filter and opens no collapse, and the selection stays. (A filter
1036
+ // that matches it draws it, in the section drawn open: it is selected there.)
1037
+ const r = roster(state);
1038
+ if (!r.index.has(id) && r.placement.has(id) && !backgroundOpen(state)) return state;
1016
1039
  let s = state;
1017
1040
  if (!roster(s).index.has(id) && (s.filter.query !== "" || s.filter.soul)) s = rehomed(roster(s), next(s, { filter: NO_FILTER, top: 0, loose: false }));
1018
1041
  if (!roster(s).index.has(id) && s.collapsed.size) {
@@ -1523,7 +1546,7 @@ function stepped(state, step, event) {
1523
1546
  if (from < 0) return stay;
1524
1547
  for (let i = from + step; i >= 0 && i < r.items.length; i += step) {
1525
1548
  const item = r.items[i];
1526
- if (!isRow(item) || !openDecision(s, item.row, instanceActs(item.row)).open) continue;
1549
+ if (!isInstance(item) || !openDecision(s, item.row, instanceActs(item.row)).open) continue;
1527
1550
  const opened = openAgent(selectAt(s, r, i, page, step), item.row);
1528
1551
  return { state: opened.state, effect: both(settled.effect, opened.effect) };
1529
1552
  }
@@ -1634,6 +1657,8 @@ function reduced(state, event, keymap) {
1634
1657
  if (event.retiring !== undefined) return { state: next(state, { retiring: new Set(event.retiring) }), effect: null };
1635
1658
  if (event.listed !== undefined) return listedHeard(state, event.listed);
1636
1659
  if (event.removed !== undefined) return removedHeard(state, event.removed);
1660
+ // The machine sweep's reading: no line, at most a live read.
1661
+ if (event.resumed !== undefined) return resumedHeard(state, event.resumed);
1637
1662
  // Shown once, in the line under the sidebar's title, as the line after an open is.
1638
1663
  // Held while nothing may draw such a line (the switcher, the help): it is said once a view that does is shown.
1639
1664
  if (event.notListed !== undefined) return { state: next(state, { notice: Object.freeze({ said: LIST_WORDS.notAdded(event.notListed?.message ?? ""), under: Object.freeze([]) }) }), effect: null };
@@ -1718,6 +1743,10 @@ function reduced(state, event, keymap) {
1718
1743
  }
1719
1744
  const r = roster(state, undefined, Number.isInteger(event.cols) ? event.cols : undefined);
1720
1745
  const at = indexOf(r, state.selected);
1746
+ if (at >= 0 && r.items[at].kind === "background") {
1747
+ const step = onBackground(state, r, at, action, event, page);
1748
+ if (step !== null) return step;
1749
+ }
1721
1750
  switch (action) {
1722
1751
  // A soul filter gives way to the text one.
1723
1752
  case "filter": return { state: rehomed(roster(state), next(state, { focus: "list", filter: Object.freeze({ editing: true, query: state.filter.query }) })), effect: null };
@@ -1750,17 +1779,44 @@ function reduced(state, event, keymap) {
1750
1779
  // level less deep; expand to the first child, the next row when it is one level deeper.
1751
1780
  // Both are read from the drawn order, which is the shared grouping's, and neither leaves
1752
1781
  // the run of rows the instance stands in (a gap or a heading ends it).
1782
+ // A root of the Background section's tree has the section's heading for its parent (#1579).
1753
1783
  if (action === "collapse") {
1754
- for (let i = at - 1; i >= 0 && isRow(r.items[i]); i--) if (r.items[i].depth === item.depth - 1) return { state: selectAt(state, r, i, page), effect: null };
1755
- return stay;
1784
+ for (let i = at - 1; i >= 0 && isInstance(r.items[i]); i--) if (r.items[i].depth === item.depth - 1) return { state: selectAt(state, r, i, page), effect: null };
1785
+ return item.background && item.depth === 0 ? { state: selectAt(state, r, indexOf(r, BACKGROUND_ID), page), effect: null } : stay;
1756
1786
  }
1757
1787
  const below = r.items[at + 1];
1758
- return isRow(below) && below.depth === item.depth + 1 ? { state: selectAt(state, r, at + 1, page), effect: null } : stay;
1788
+ return isInstance(below) && below.depth === item.depth + 1 ? { state: selectAt(state, r, at + 1, page), effect: null } : stay;
1759
1789
  }
1760
1790
  default: return stay;
1761
1791
  }
1762
1792
  }
1763
1793
 
1794
+ /** A key on the Background section's heading (#1579), selected at `at` of `r`: Enter and Space open the
1795
+ * section or close it, Right opens it and Left closes it, as a parent row's fold does; Right on it open
1796
+ * goes to its first row. Its open state is the view's, kept for the run (lib/model.mjs backgroundOpen),
1797
+ * and the selection stays on the heading. While a filter is on, the section is drawn open whatever is
1798
+ * stored, and the heading changes nothing, as a filter folds nothing. The heading is no instance: the
1799
+ * acts, the detail and opening a terminal do nothing on it. Null: the key is not the heading's (a
1800
+ * movement, the filter, a view, a tab). */
1801
+ function onBackground(state, r, at, action, event, page) {
1802
+ const stay = { state, effect: null };
1803
+ // Space has no action of its own in the list (a tui.json that binds it keeps its binding).
1804
+ const toggles = action === "open" || (action === undefined && event.key === "space");
1805
+ if (toggles || action === "collapse" || action === "expand") {
1806
+ if (state.focus !== "list") return stay;
1807
+ const open = backgroundOpen(state), wanted = toggles ? !open : action === "expand";
1808
+ if (!r.filtering && wanted !== open) {
1809
+ const background = new Set(state.background);
1810
+ if (wanted) background.add(state.open); else background.delete(state.open);
1811
+ return { state: rehomed(r, next(state, { background, top: settledTop(state, r, page), loose: false })), effect: null };
1812
+ }
1813
+ // Its first row: the first instance after it, past the deployments' headings and notes of a view of two or more.
1814
+ const first = action === "expand" && r.items[at].open ? r.items.findIndex((item, i) => i > at && isInstance(item)) : -1;
1815
+ return first >= 0 ? { state: selectAt(state, r, first, page), effect: null } : stay;
1816
+ }
1817
+ return ["stop", "retire", "start", "restart", "detail"].includes(action) ? stay : null;
1818
+ }
1819
+
1764
1820
  // ── SPAWNING (docs/tui.md, "Spawning an agent"; Spec 6-spawn) ───────────────────────────────────
1765
1821
 
1766
1822
  /** The longest name the name field takes: the kernel's instance-name limit (spawn-preview-contract