@awebai/oats 0.57.1 → 0.58.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.
package/bin/oats.mjs CHANGED
@@ -104,7 +104,7 @@ const OWN_ARGV_COMMANDS = new Set(["capture", "recall", "setup", "experimental",
104
104
  * probe) and in `status --json`, which a remote roster relays as the host's (feature
105
105
  * server-probe-features, lib/servers.mjs hostFeatures). ONE list for both, emitted at output
106
106
  * time, never stored. A name must pass hostFeatures's check (test/cli-json-contract.test.mjs). */
107
- const KERNEL_FEATURES = ["retire-home", "session-start", "session-restart", "launch-config", "schedule", "schedule-host-caps", "session-upload", "operations", "instance-git", "instance-git-remote", "souls-declarations", "lifecycle-plans", "retire-retention", "readiness", "spawn-preview", "instance-events", "instance-events-2", "schedule-history", "schedule-read-2", "spawn-preview-2", "spawn-idempotency", "spawn-idempotency-2", "spawn-apply-2", "workspace-v2", "instance-modules", "spawn-provider-payload", "served-identity", "packages-no-approval", "spawn-name", "settings-origins", "team-model-3", "settings-declared", "capabilities-private", "layers-from", "harness", "package-souls", "triggers", "automations", "desktop-facts", "launch-preference", "preview-composed-from", "observe-max-age", "spawn-preview-max-age", "launch-config-default", "capability-show", "capture-file", "workspace-identity", "server-connect", "capability-route", "servers-per-workspace", "operator-default-soul", "waiting-on-you", "automation-descriptions", "souls-capabilities", "soul-composed-instructions", "teams-conditional-default", "server-probe-features", "worktree-event", "trigger-sources", "session-attach-detach-key", "lifecycle-kernel-codes", "schedule-run-warnings", "lifecycle-claim-stop", "launch-prompt-dev-channel", "soul-launch", "retire-plan-own-worktree", "spawn-kernel-codes", "soul-skills", "roster-workspace-key"];
107
+ const KERNEL_FEATURES = ["retire-home", "session-start", "session-restart", "launch-config", "schedule", "schedule-host-caps", "session-upload", "operations", "instance-git", "instance-git-remote", "souls-declarations", "lifecycle-plans", "retire-retention", "readiness", "spawn-preview", "instance-events", "instance-events-2", "schedule-history", "schedule-read-2", "spawn-preview-2", "spawn-idempotency", "spawn-idempotency-2", "spawn-apply-2", "workspace-v2", "instance-modules", "spawn-provider-payload", "served-identity", "packages-no-approval", "spawn-name", "settings-origins", "team-model-3", "settings-declared", "capabilities-private", "layers-from", "harness", "package-souls", "triggers", "automations", "desktop-facts", "launch-preference", "preview-composed-from", "observe-max-age", "spawn-preview-max-age", "launch-config-default", "capability-show", "capture-file", "workspace-identity", "server-connect", "capability-route", "servers-per-workspace", "operator-default-soul", "waiting-on-you", "automation-descriptions", "souls-capabilities", "soul-composed-instructions", "teams-conditional-default", "server-probe-features", "worktree-event", "trigger-sources", "session-attach-detach-key", "lifecycle-kernel-codes", "schedule-run-warnings", "lifecycle-claim-stop", "launch-prompt-dev-channel", "soul-launch", "retire-plan-own-worktree", "spawn-kernel-codes", "soul-skills", "roster-workspace-key", "spawn-apply-max-age"];
108
108
  /** Commands `--server <id>` runs on a registered server. */
109
109
  const ROUTED_COMMANDS = new Set(["spawn", "retire", "status", "session", "okf", "schedule", "inspect", "operation", "launch-config", "readiness", "instance"]);
110
110
  const flag = (name) => {
@@ -1484,16 +1484,24 @@ function sayReadNotices() {
1484
1484
  for (const notice of readSession?.notices.splice(0) ?? []) process.stderr.write(`oats: warning: ${notice}\n`);
1485
1485
  }
1486
1486
  /** Which kernel command forms take --max-age: THE allow-list (docs/desktop-cli-api.md "Observation reuse").
1487
- * → null when this form reads with observation reuse, else the E_BAD_ARGS message. `head` is argv before `--`. */
1488
- const MAX_AGE_READS = "status, workspace status, souls, capabilities, capabilities show, inspect --soul|--home, spawn --preview, trigger poll, and the read forms of teams and soul teams";
1487
+ * → null when this form reads with observation reuse, else the E_BAD_ARGS message. `head` is argv before `--`.
1488
+ * Write verbs refuse it: a writer acting on a reused observation could persist a fact the workspace no
1489
+ * longer holds. A preview-bound spawn apply is the exception: its fence (--expect-decision) binds it to
1490
+ * the decision the operator confirmed, so a reused head applies nothing beyond that decision. */
1491
+ const MAX_AGE_READS = "status, workspace status, souls, capabilities, capabilities show, inspect --soul|--home, spawn --preview, spawn --expect-decision <revision>, trigger poll, and the read forms of teams and soul teams";
1489
1492
  function maxAgeRefusal(command, head) {
1490
1493
  const word = (i) => (head[i] !== undefined && !head[i].startsWith("--") ? head[i] : undefined);
1491
- const refuse = (form) => `--max-age is not accepted by \`oats ${form}\`: only the read verbs reuse observations (${MAX_AGE_READS})`;
1494
+ const refuse = (form) => `--max-age is not accepted by \`oats ${form}\`: only the read verbs and a preview-bound spawn apply reuse observations (${MAX_AGE_READS})`;
1492
1495
  if (head.includes("--server")) return "--max-age cannot be combined with --server: observation reuse is local to this machine";
1493
1496
  switch (command) {
1494
1497
  case "status": case "souls": case "capabilities": case "inspect": return null;
1495
- // A preview reads (feature spawn-preview-max-age); an apply always observes live.
1496
- case "spawn": return head.includes("--preview") ? null : refuse("spawn");
1498
+ // A preview reads (feature spawn-preview-max-age); an apply only when a confirmed decision binds it
1499
+ // (feature spawn-apply-max-age), with a value as spawn reads it: a bare --expect-decision binds nothing.
1500
+ case "spawn": {
1501
+ const expected = flag("expect-decision");
1502
+ if (head.includes("--preview") || (expected !== undefined && expected !== true)) return null;
1503
+ return "--max-age is not accepted by `oats spawn` without --expect-decision: a spawn apply reuses observations only with --expect-decision <revision>, which binds it to the decision a preview showed";
1504
+ }
1497
1505
  case "workspace": return word(1) === "status" ? null : refuse(["workspace", word(1)].filter(Boolean).join(" "));
1498
1506
  case "teams": return word(1) === undefined ? null : refuse(`teams ${word(1)}`);
1499
1507
  // `soul teams` only reads (its edit flags were removed in 0.38.0, and refuse as such).
@@ -2686,8 +2694,8 @@ async function status() {
2686
2694
  const livenessWord = (i) => i.running === true ? "RUNNING" : i.running === false ? "idle" : "unknown";
2687
2695
  /** The flags `oats spawn` reads: those taking a value, and switches. `--provider` takes two words.
2688
2696
  * `--instance` is refused by a local spawn (with its replacement) but still travels to an older
2689
- * host through `--server`, whose route reads it. `--max-age` reaches here only on a preview: the
2690
- * dispatch allow-list (maxAgeRefusal) refuses it on an apply. */
2697
+ * host through `--server`, whose route reads it. `--max-age` reaches here only on a preview or an
2698
+ * apply bound by --expect-decision: the dispatch allow-list (maxAgeRefusal) refuses it otherwise. */
2691
2699
  const SPAWN_VALUE_FLAGS = new Set(["agents-root", "backend", "base", "branch", "dir", "expect-decision", "harness", "idempotency-key", "instance", "launch-config", "max-age", "model", "name", "parent", "purpose", "relation", "relative-root", "relative-to", "repo", "runtime", "task", "task-file", "trigger-event", "wake-cron", "wake-every", "wake-file", "wake-json", "wake-message", "wake-message-file", "wake-tz", "work", "work-dir"]);
2692
2700
  const SPAWN_SWITCHES = new Set(["allow-child-spawns", "json", "no-child-spawns", "no-launch", "no-yolo", "preview", "yolo"]);
2693
2701
  /** Why `argv` (after `spawn`, the soul first) is not a spawn, or undefined: a positional after the
@@ -4803,7 +4811,8 @@ Usage:
4803
4811
  instance.json providers.<capability>)
4804
4812
  [--preview [--max-age <s>]] decide everything, create nothing; the JSON's
4805
4813
  decision binds an apply (--expect-decision <rev>);
4806
- --max-age reuses recent heads (preview only)
4814
+ --max-age reuses recent heads, on a preview and
4815
+ on an apply bound by --expect-decision only
4807
4816
  oats retire <instance> [--force] retire an instance (window, hooks,
4808
4817
  [--self] worktree, home); --self = retire the
4809
4818
  [--keep-dir] [--json] CALLING instance: the window dies, then
@@ -4981,9 +4990,13 @@ Observation reuse (feature observe-max-age):
4981
4990
  remote again; the JSON
4982
4991
  then carries observation { observedAt (the oldest
4983
4992
  head used), reused, localRevision (a digest of
4984
- the local configuration read) }. Refused
4993
+ the local configuration read) }. A spawn apply
4994
+ bound by --expect-decision takes it too (feature
4995
+ spawn-apply-max-age): its decision fence holds,
4996
+ and its JSON carries no observation. Refused
4985
4997
  (E_BAD_ARGS) by every other command, an edit form,
4986
- a spawn apply, and with --server
4998
+ a spawn apply without --expect-decision, and with
4999
+ --server
4987
5000
 
4988
5001
  Layers: ${LAYERS.join(", ")}. Workspace model v2: docs/design/2026-09-23-workspace-module-contracts.md.`;
4989
5002
  }
@@ -611,5 +611,6 @@ the bounded parsed-read cache and the observations `--max-age` reuses; all of
611
611
  it is safe to delete); `OATS_PACKAGE_CATALOG` names an alternative package
612
612
  catalog file. The read verbs (`status`, `workspace status`, `souls`,
613
613
  `capabilities`, `inspect`, the read forms of `teams` and `soul teams`, and
614
- `spawn --preview`) take `--max-age <seconds>` to reuse a remote head observed that recently
614
+ `spawn --preview`), and a spawn apply bound by `--expect-decision`, take
615
+ `--max-age <seconds>` to reuse a remote head observed that recently
615
616
  ([Observation reuse](desktop-cli-api.md#observation-reuse-feature-observe-max-age-oats-0311)).
@@ -45,7 +45,7 @@ see the [official catalog](official-catalog.md) for current pins.
45
45
  "automation-descriptions","souls-capabilities","soul-composed-instructions","teams-conditional-default",
46
46
  "server-probe-features","worktree-event","trigger-sources","session-attach-detach-key",
47
47
  "lifecycle-kernel-codes","schedule-run-warnings","lifecycle-claim-stop","launch-prompt-dev-channel",
48
- "soul-launch","retire-plan-own-worktree","spawn-kernel-codes","soul-skills","roster-workspace-key"],
48
+ "soul-launch","retire-plan-own-worktree","spawn-kernel-codes","soul-skills","roster-workspace-key","spawn-apply-max-age"],
49
49
  "automationsApi":1,"workspaceApi":2,"instanceGitApi":1,"spawnApplyApi":1,"soulsApi":2,"lifecycleApi":1,
50
50
  "readinessApi":2,"spawnPreviewApi":2,"eventsApi":2,"scheduleHistoryApi":3,"scheduleApi":2,"operationsApi":2,
51
51
  "capabilityShowApi":1}
@@ -131,6 +131,7 @@ see the [official catalog](official-catalog.md) for current pins.
131
131
  | `retire-plan-own-worktree` | a retire plan carries `facts.ownWorktree`, a boolean: whether `work/` is the instance's own work tree, the one the retire retains or removes; in `oats retire --plan` and in the fresh plan (`details.plan`) of `E_PLAN_STALE` and `E_CHILDREN_RUNNING`; a stop plan does not carry it; OATS 0.53.0 ([the retire plan](#retire)) | |
132
132
  | `spawn-kernel-codes` | `oats spawn`, apply and `--preview`, answers the kernel's own code, as raised, whatever stage of the spawn raised it; `E_SPAWN_FAILED` is for an error with no kernel code (with `details.cause`, as the lifecycle commands' general codes have it). A code says nothing about how far the spawn got: `details.unconfirmed` does. Details are those each code had before; OATS 0.56.0 ([spawn errors](#spawn-errors)). A kernel without it answers `E_SPAWN_FAILED` for most kernel codes its kernel stage raised: there, that code may hide one | |
133
133
  | `roster-workspace-key` | `oats server roster --workspace-key <key>`, repeatable: only the groups that can belong to one of the given workspaces are probed and returned (registered for one of them, registered with no known `workspaceKey`, or saved routes only); the answer's shape is unchanged, OATS 0.56.0 ([The remote roster](#roster-workspace-key)). Gate on the probe: a kernel without it ignores the flag and probes and answers every group | |
134
+ | `spawn-apply-max-age` | `--max-age <s>` on a spawn apply bound by `--expect-decision <revision>`: the apply reuses member heads as the preview does, its decision fence unchanged, and its answer carries no `observation` block, OATS 0.58.0 ([Apply](#apply)). Gate on the probe: a kernel without it refuses the flag on an apply (`E_BAD_ARGS`) | |
134
135
 
135
136
  Payload-only integers, never in the probe: `onboardApi: 2`, `syncApi: 1`,
136
137
  `workspaceStatusApi: 1`, `capabilitiesApi: 1`, the `oats souls` document's
@@ -308,6 +309,7 @@ it and answer live, without the block.
308
309
  oats status | workspace status | souls | capabilities | inspect --soul|--home
309
310
  | teams | soul teams <soul> … --max-age <seconds> --json
310
311
  oats spawn <soul> … --preview --max-age <seconds> --json (feature spawn-preview-max-age)
312
+ oats spawn <soul> … --expect-decision <revision> --max-age <seconds> --json (feature spawn-apply-max-age)
311
313
  oats capabilities show <name> … --max-age <seconds> --json (feature capability-show)
312
314
  oats trigger poll <id> --run-source … --max-age <seconds> --json (feature trigger-sources)
313
315
  ```
@@ -327,10 +329,13 @@ oats trigger poll <id> --run-source … --max-age <seconds> --json (feature tr
327
329
  - **Spawn preview** (feature `spawn-preview-max-age`, OATS 0.33.0): the
328
330
  preview's `result` gains the same block, so you can say "as of
329
331
  `<observedAt>`". The `decision` covers the heads the preview used, reused
330
- or live: a reused head the member has since moved from makes the apply
331
- (which always observes live) refuse `E_DECISION_STALE`, and the apply
332
- records the head it observed, so the next preview under `--max-age` shows
333
- it with a new `decision.revision`. The apply itself refuses the flag.
332
+ or live: a reused head the member has since moved from makes an apply
333
+ that observes live refuse `E_DECISION_STALE`, and the apply records the
334
+ head it observed, so the next preview under `--max-age` shows it with a new
335
+ `decision.revision`. The preview-bound apply takes the flag from
336
+ `spawn-apply-max-age` (OATS 0.58.0): with `--expect-decision`, it reuses
337
+ heads as the preview does, and its decision fence is unchanged
338
+ ([Apply](#apply)). Its answer carries no block.
334
339
  - **`localRevision`:** 24 lowercase hex characters, opaque. It digests every
335
340
  piece of local configuration the kernel read for this answer:
336
341
  `oats-local.yaml` (and each closer `oats-local.yaml` it looked for and did
@@ -361,18 +366,25 @@ oats trigger poll <id> --run-source … --max-age <seconds> --json (feature tr
361
366
  spelling of the same repository (ssh vs https) or for a different ref; its
362
367
  commit can no longer be fetched. Each is observed live, as without the flag.
363
368
  A live observation that fails is the usual error, never an older head.
364
- - **Refusals:** every other command, a spawn apply (with or without
365
- `--expect-decision`; the form named is `spawn`), every edit form (`teams add|remove|default`)
369
+ - **Refusals:** every other command, every edit form (`teams add|remove|default`)
366
370
  and any `--server`
367
371
  invocation refuse the flag before reading or writing anything (the removed
368
372
  `soul teams --add|--remove|--default|--clear-default` answer their own
369
373
  `E_BAD_ARGS` first), with
370
374
  `E_BAD_ARGS` "--max-age is not accepted by \`oats <form>\`: only the read
371
- verbs reuse observations (status, workspace status, souls, capabilities,
372
- capabilities show, inspect --soul|--home, spawn --preview, trigger poll,
373
- and the read forms of teams and soul teams)" and,
375
+ verbs and a preview-bound spawn apply reuse observations (status, workspace
376
+ status, souls, capabilities, capabilities show, inspect --soul|--home,
377
+ spawn --preview, spawn --expect-decision <revision>, trigger poll, and the
378
+ read forms of teams and soul teams)" and,
374
379
  with `--server`, "--max-age cannot be combined with --server: observation
375
- reuse is local to this machine".
380
+ reuse is local to this machine". A spawn apply without `--expect-decision`
381
+ (or with no value after it) refuses it with `E_BAD_ARGS` "--max-age is not
382
+ accepted by \`oats spawn\` without --expect-decision: a spawn apply reuses
383
+ observations only with --expect-decision <revision>, which binds it to the
384
+ decision a preview showed". Write verbs refuse the flag because a writer
385
+ acting on a reused observation could persist a fact the workspace no longer
386
+ holds; a preview-bound apply is the exception because its fence binds it to
387
+ the decision the operator confirmed.
376
388
  A capability command's argv (`oats <namespace> …`) is its provider's: the
377
389
  kernel neither reads nor refuses `--max-age` there. The same holds for
378
390
  `capture`, `recall`, `setup` and `experimental`, which parse their own argv:
@@ -2316,10 +2328,11 @@ it to a temporary copy (`soulFetched: true`).
2316
2328
  localRevision}`, shaped exactly as the read verbs' block; without it the
2317
2329
  preview is exactly as before, and no other field changes shape.
2318
2330
  - `decision.revision` covers the heads the preview used, reused or live.
2319
- Apply never reuses (it refuses `--max-age`): a head that moved since the
2320
- reused observation refuses `E_DECISION_STALE`, and the apply records what
2321
- it observed, so re-preview under `--max-age` to get the new head and
2322
- revision.
2331
+ An apply without `--max-age` (or with `--max-age 0`) observes live: a head
2332
+ that moved since the reused observation refuses `E_DECISION_STALE`, and the
2333
+ apply records what it observed, so re-preview under `--max-age` to get the
2334
+ new head and revision. An apply with `--expect-decision` may reuse heads
2335
+ too (feature `spawn-apply-max-age`, [Apply](#apply)).
2323
2336
 
2324
2337
  **Provider settings.**
2325
2338
  - `providers` is the `--provider` map as typed.
@@ -2363,6 +2376,16 @@ Feature `spawn-apply-2`, `spawnApplyApi: 1`. The Desktop gates on
2363
2376
  `E_INSTANCE_NAME_TAKEN` (for `--name`) or `E_PLACEMENT_TAKEN`.
2364
2377
  - A refused child spawn appends `child-spawn-refused` to the parent's log (on
2365
2378
  apply only).
2379
+ - `--max-age <s>` with `--expect-decision <revision>` (feature
2380
+ `spawn-apply-max-age`, OATS 0.58.0) reuses member heads this machine
2381
+ observed at most `<s>` seconds ago, exactly as the preview does (the same
2382
+ values and fallbacks to a live observation), so an apply right after its
2383
+ preview asks no remote again. The decision is computed from those heads, and
2384
+ one that differs from `<revision>` is `E_DECISION_STALE`, as without the
2385
+ flag. The answer (success, replay, every refusal) has no `observation`
2386
+ block: the preview already gave its "as of".
2387
+ Without `--expect-decision` the flag is `E_BAD_ARGS`
2388
+ ([Observation reuse](#observation-reuse-feature-observe-max-age-oats-0311)).
2366
2389
 
2367
2390
  **Idempotency** (feature `spawn-idempotency-2`): `--idempotency-key <key>`
2368
2391
  with `--expect-decision` records the key and decision in `instance.json`.
@@ -349,6 +349,10 @@ than the server's checked one account and launched with another
349
349
  given the pane's `PATH` as the pane reads it, a relative entry (and an
350
350
  empty one) resolved against the pane's working directory, the home.
351
351
  The command a refusal names keeps the harness's name as declared.
352
+ The Claude probe (`claude plugin list --json`) sets `DISABLE_TELEMETRY=1`
353
+ for its own run, so Claude skips its telemetry flush at exit: that selects
354
+ no account and changes no answer, and no launch, install step or other
355
+ probe gets it.
352
356
  - **The folder-trust check only warns**: `<harness> folder trust: the
353
357
  configuration file this launch will read could not be established
354
358
  (<why, and what would make it readable>); nothing is said about its
@@ -0,0 +1,107 @@
1
+ # OATS 0.58.0
2
+
3
+ 2026-10-15
4
+
5
+ ## Upgrade
6
+
7
+ - **Install the Desktop first and the CLI second,** as
8
+ [Upgrading](../upgrading.md) says: a 0.57 Desktop refuses a 0.58.0 CLI. The
9
+ 0.58.0 Desktop accepts OATS CLIs `>=0.26.0 <0.59.0`.
10
+
11
+ - **On a Mac, upgrade the CLI before the next reboot.** Up to 0.57.1, every
12
+ directory-mode instance refused `oats session start` after a macOS reboot
13
+ ("directory home was exchanged"). With 0.58.0 those homes start again, with
14
+ no edit, including homes spawned before the upgrade. A host that is already
15
+ stuck needs only the new CLI. See Fixed
16
+ ([#1261](https://github.com/awebai/oats/issues/1261)).
17
+
18
+ - **A client that drives `oats spawn` itself** may pass `--max-age` on an
19
+ apply bound by `--expect-decision`, when `oats version --json` lists
20
+ `spawn-apply-max-age`. An older kernel refuses the flag (`E_BAD_ARGS`). See
21
+ Added ([#1246](https://github.com/awebai/oats/issues/1246)).
22
+
23
+ - **The official catalog's versions are unchanged in this release:**
24
+ oats.framework 1.12.0, oats.okf 5.2.0, oats.aweb 1.27.3, oats.engineering
25
+ 1.10.0, oats.cloning 1.0.1, oats.authoring 1.0.3, oats.jira 1.0.1,
26
+ oats.linear 1.0.1 and oats.apps 1.0.0.
27
+
28
+ ## Added
29
+
30
+ - **`oats spawn … --expect-decision <revision> --max-age <seconds>`: a
31
+ confirmed spawn reuses its preview's observations** (feature
32
+ `spawn-apply-max-age`, [#1246](https://github.com/awebai/oats/issues/1246)).
33
+ An apply bound by `--expect-decision` now takes `--max-age`, as
34
+ `spawn --preview` already did: it reuses member heads this machine observed
35
+ at most that many seconds ago instead of asking each remote again, which
36
+ saves the apply's `git ls-remote` round (about 0.3–0.45 s). The decision is
37
+ computed from those heads, and one that differs from the confirmed revision
38
+ is still `E_DECISION_STALE`, with nothing created. `--max-age 0` is live, as
39
+ without the flag. The apply's answer is unchanged: it carries no
40
+ `observation` block. A spawn apply without `--expect-decision` still refuses
41
+ the flag (`E_BAD_ARGS`), now with a message that says so, and `--server`
42
+ still refuses it. A client passes the flag on an apply only when
43
+ `oats version --json` lists `spawn-apply-max-age`: an older kernel refuses
44
+ it ([Apply](../desktop-cli-api.md#apply)).
45
+
46
+ ## Changed
47
+
48
+ - **Desktop: a spawn no longer re-reads every member repository at the
49
+ press** ([#1246](https://github.com/awebai/oats/issues/1246)). With a
50
+ kernel that can reuse them, the Desktop's spawn lets the kernel use the
51
+ member repositories' heads it observed in the last minute instead of
52
+ reading each one again when you press Spawn. If the kernel then works out
53
+ a different spawn from what the dialog showed, the spawn is still refused
54
+ as before ("Something changed before the spawn went through…") and the
55
+ values are read again.
56
+
57
+ - **Desktop: a spawn reaches its terminal sooner**
58
+ ([#1246](https://github.com/awebai/oats/issues/1246)). Pressing Spawn no
59
+ longer runs a second spawn preview when the dialog has been open more than
60
+ a minute: the press uses the preview on screen for up to five minutes, and
61
+ if anything changed meanwhile the spawn is refused as before ("Something
62
+ changed before the spawn went through…") and the values are read again.
63
+ Once the spawn is created, the Desktop reads that one workspace at once
64
+ instead of waiting for its next full refresh, so the new instance's row and
65
+ terminal appear without the extra second or more.
66
+
67
+ - **Spawn preview and apply are about 0.4 s faster on Claude souls whose
68
+ capabilities require a Claude plugin**
69
+ ([#1246](https://github.com/awebai/oats/issues/1246)). The harness-package
70
+ check's probe, `claude plugin list --json`, now runs with
71
+ `DISABLE_TELEMETRY=1` set for its own run, so Claude no longer flushes
72
+ telemetry before it exits. The probe's answer, and so the check, is
73
+ unchanged; the launch, the install steps and every other probe run as
74
+ before ([The checks read the pane](../execution-targets.md#the-checks-read-the-pane)).
75
+
76
+ - **The Desktop accepts OATS CLIs `>=0.26.0 <0.59.0`**
77
+ ([#1261](https://github.com/awebai/oats/issues/1261)). The compatibility band
78
+ admits 0.58; a 0.57 Desktop refuses a 0.58 CLI. No new gate on the band.
79
+ `oats tui` runs the kernel it ships with and is held to the same band.
80
+
81
+ ## Fixed
82
+
83
+ - **A directory-mode instance starts again after a macOS reboot**
84
+ ([#1261](https://github.com/awebai/oats/issues/1261)). macOS gives a volume a
85
+ new device number each time it is mounted, so after every reboot
86
+ `oats session start` refused every directory-mode home with "directory home
87
+ was exchanged; restore the owned root before retrying start", although its
88
+ home and `work/` were the same directories. On macOS a start now accepts a
89
+ root whose inode matches the one the spawn recorded, and whose birth time
90
+ matches too when one was recorded. A spawn now records each root's birth
91
+ time; homes spawned earlier, whose baselines hold none, start with no edit.
92
+ A real exchange, another directory renamed into the home's or `work/`'s
93
+ place, is still refused with the same error, and Linux keeps comparing
94
+ device and inode. Captured Pi sessions on macOS had the same problem at the
95
+ next start after a reboot ("original Pi session directory was replaced");
96
+ the same rule now applies to their session directory
97
+ ([`directory` — independent execution](../souls-and-instances.md#directory--independent-execution)).
98
+
99
+ - **`oats tui`: an agent's terminal that ends says why again.** On tmux 3.2 to
100
+ 3.4, a terminal whose viewer ended at once, for example because the agent's
101
+ window had just gone, could close with the line that the viewer "ended
102
+ without saying why", and without the viewer's error output under it. The
103
+ cause: tmux reports a pane as dead a moment before it has the exit status.
104
+ The panel now waits for that status, for at most 10 seconds (2.5 seconds
105
+ on tmux 3.2), so the line and the viewer's error output show again
106
+ ([#855](https://github.com/awebai/oats/issues/855); see
107
+ [`oats tui`](../tui.md)).
@@ -1721,6 +1721,15 @@ change to work is in the same recovery, under
1721
1721
  nothing needed preserving before the hooks). The work-root cannot be
1722
1722
  exchanged for a symlink. Recovery does not replace the worker's delivery protocol.
1723
1723
 
1724
+ A start refuses a directory home whose home or `work/` is no longer the
1725
+ directory the spawn recorded (`directory home was exchanged` or `directory work
1726
+ was exchanged`), for example when another directory was renamed into its
1727
+ place. The spawn records each root's device, inode and birth time. A root is
1728
+ the same directory when its device and inode match. On macOS, which gives a
1729
+ volume a new device number each time it is mounted (every reboot), an equal
1730
+ inode is enough, provided the birth time also matches when one was recorded
1731
+ (a home spawned by a kernel that recorded none is judged by the inode alone).
1732
+
1724
1733
  ### `workspace` — cross-repo coordinator
1725
1734
 
1726
1735
  `work/` is a symlink to the **whole deployment**: the directory holding
package/docs/tui.md CHANGED
@@ -268,7 +268,10 @@ fit; the detail shows them whole.
268
268
  - **A terminal also closes by itself** when its viewer ends: the agent's
269
269
  window ended, its session went away, or the link to its machine dropped.
270
270
  It closes within a second of that (tmux tells `oats tui` of a viewer's
271
- end once a second). The instances are then read again at once, and one line above the panes
271
+ end once a second), or a second more when tmux took a moment more to
272
+ have the viewer's exit status: once tmux has reported the viewer ended,
273
+ `oats tui` waits ten seconds at most for that status, and closes the
274
+ terminal without it when it has not come. The instances are then read again at once, and one line above the panes
272
275
  says what happened: that it could not be opened, that the connection to
273
276
  its machine ended, or that the viewer ended without saying why. What the
274
277
  viewer printed on its error output stands under that line in quotation
@@ -651,7 +654,14 @@ with the Desktop (`packages/client/`).
651
654
  of the run's directory (0600), read back when it ends and deleted. Its
652
655
  exit status is the one tmux keeps for a pane whose process ended
653
656
  (`remain-on-exit`), which the server reports to `oats tui` within a
654
- second; `oats tui` then closes that pane. What the terminal
657
+ second; `oats tui` then closes that pane. tmux can report a pane ended
658
+ before it has that status (3.4 does, when the viewer's terminal hangs up a
659
+ moment before its process is reaped): `oats tui` then waits for the
660
+ status, which follows at the next report, for ten seconds at most (2.5
661
+ on tmux 3.2, which never says which signal ended a pane). A pane whose
662
+ status has not come by then is taken as ended without one, and closed:
663
+ the terminal closes with the line that the viewer ended without saying
664
+ why. What the terminal
655
665
  shows is captured into `capture` in that directory, which the server
656
666
  writes and `oats tui` reads back, so nothing an agent prints passes
657
667
  through the stream on which `oats tui` reads the server's answers. An
package/lib/core.mjs CHANGED
@@ -43,6 +43,7 @@ import { recordLocalInput } from "./local-inputs.mjs";
43
43
  import { createHash, randomUUID } from "node:crypto";
44
44
  import { fileURLToPath } from "node:url";
45
45
  import { initializeNativeHistory, prepareNativeStart } from "../packages/record/lib/native-history.mjs";
46
+ import { sameDirectory } from "../packages/record/lib/directory-identity.mjs";
46
47
  import { noteRuntimeName } from "./deprecation.mjs";
47
48
  import { attachSessionTarget, requireDetachKey } from "./session-viewer.mjs";
48
49
  import { inspectSessionTarget, inputSessionTarget } from "./session-input.mjs";
@@ -1442,8 +1443,9 @@ export const HARNESS_PACKAGE_MANAGERS = {
1442
1443
  list: (env = process.env, opts = {}) => {
1443
1444
  let out;
1444
1445
  try {
1446
+ // DISABLE_TELEMETRY: this listing alone skips Claude's telemetry flush at exit (~0.4 s), same answer; never a launch's (it turns channels off).
1445
1447
  out = probeExecFile(HARNESS_PACKAGE_MANAGERS.claude.bin(opts), ["plugin", "list", "--json"],
1446
- { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 60000, env });
1448
+ { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 60000, env: { ...env, DISABLE_TELEMETRY: "1" } });
1447
1449
  } catch { return []; }
1448
1450
  let rows;
1449
1451
  try { rows = JSON.parse(out); } catch { return []; }
@@ -5468,6 +5470,12 @@ function directoryIdentity(path) {
5468
5470
  const st = lstatSync(path);
5469
5471
  return { dev: st.dev, ino: st.ino };
5470
5472
  }
5473
+ /** A directory-mode root as the spawn baseline records it: its identity and its birth time,
5474
+ * a decimal string of ns (JSON holds no BigInt), which sameDirectory reads on darwin. */
5475
+ function directoryRootIdentity(path) {
5476
+ const st = lstatSync(path, { bigint: true });
5477
+ return { dev: Number(st.dev), ino: Number(st.ino), birthtimeNs: String(st.birthtimeNs) };
5478
+ }
5471
5479
 
5472
5480
  // Read independently of mutable instance bytes, BEFORE realpath(home), hooks,
5473
5481
  // lock creation or backend observation. A metadata mode edit cannot disable it.
@@ -5481,8 +5489,7 @@ function sessionDirectoryGuard(home) {
5481
5489
  if (baseline.version !== RETIRE_BASELINE_VERSION || !receiptRecordsHome(baseline, receiptHomeIdentity(home))) throw oatsError("E_WORK_INSPECTION_FAILED", "invalid independent directory home authority");
5482
5490
  assertDirectoryRoots(home, expected);
5483
5491
  for (const [name, path] of [["home", home], ["work", join(home, "work")]]) {
5484
- const actual = directoryIdentity(path), recorded = baseline.directoryRoots?.[name];
5485
- if (!recorded || actual.dev !== recorded.dev || actual.ino !== recorded.ino) throw oatsError("E_WORK_INSPECTION_FAILED", `directory ${name} was exchanged; restore the owned root before retrying start`);
5492
+ if (!sameDirectory(baseline.directoryRoots?.[name], directoryRootIdentity(path))) throw oatsError("E_WORK_INSPECTION_FAILED", `directory ${name} was exchanged; restore the owned root before retrying start`);
5486
5493
  }
5487
5494
  }
5488
5495
  let meta;
@@ -6426,7 +6433,7 @@ function writeRetirementBaseline(home, work, mode, capabilities, runtime, { excl
6426
6433
  version: RETIRE_BASELINE_VERSION,
6427
6434
  digestVersion: BASELINE_DIGEST_VERSION,
6428
6435
  ...(incarnationId ? { incarnationId, executionBinding } : {}),
6429
- ...(mode === "directory" ? { directoryWork: true, directoryRoots: { home: directoryIdentity(home), work: directoryIdentity(work) } } : {}),
6436
+ ...(mode === "directory" ? { directoryWork: true, directoryRoots: { home: directoryRootIdentity(home), work: directoryRootIdentity(work) } } : {}),
6430
6437
  home: canonicalHomePath(home),
6431
6438
  homeFingerprint: storedTreeDigest(home, BASELINE_DIGEST_VERSION, { excludeRoot: resolveHomeExclusions(home, disposableHome).excludeRoot, instanceHome: true }),
6432
6439
  disposableReceipts,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@awebai/oats",
3
- "version": "0.57.1",
3
+ "version": "0.58.0",
4
4
  "description": "OATS (Open Agent Team Specification) — durable souls, disposable instances, targetable capability packages, and the runtime-neutral oats CLI/kernel.",
5
5
  "keywords": [
6
6
  "agents",
@@ -13,7 +13,7 @@
13
13
  // Every candidate is canonicalized to an absolute executable and accepted
14
14
  // ONLY if executable and `<bin> version --json` returns the v1 probe:
15
15
  // {"schemaVersion":1,"name":"@awebai/oats","version":"0.24.x","desktopApi":1}
16
- // Desktop accepts desktopApi === 1 and semver >=0.26.0 <0.58.0 (the band is
16
+ // Desktop accepts desktopApi === 1 and semver >=0.26.0 <0.59.0 (the band is
17
17
  // spelled ONCE, in ACCEPT_RANGE below — this line only paraphrases it).
18
18
  // API version — not source adjacency — is authoritative.
19
19
  //
@@ -52,7 +52,7 @@ export const DESKTOP_API = 1;
52
52
  // carry a `description` for every kind and `<kind> update <id> --description`
53
53
  // sets one (feature `automation-descriptions`, which gates the Desktop's
54
54
  // summary writes). The Desktop v1 surface is otherwise unchanged.
55
- export const ACCEPT_RANGE = { min: [0, 26, 0], maxExclusive: [0, 58, 0] };
55
+ export const ACCEPT_RANGE = { min: [0, 26, 0], maxExclusive: [0, 59, 0] };
56
56
  /** The band as humans read it — derived, never hand-spelled, so the probe
57
57
  * rejection reason, the backend's /api status and the degradation card can
58
58
  * never disagree with the numbers actually enforced above. */
@@ -14,7 +14,7 @@
14
14
  * rosterAnswered, // boolean: a roster answer arrived under the current CLI
15
15
  * rosterFailure, // string | null: the roster read's failure while no answer has arrived
16
16
  * cli, // the kernel record (cli-locator.mjs)
17
- * observing, // Set<deployment id>: a read in flight
17
+ * observing, // keyed by deployment id (`has`): a read in flight
18
18
  * remoteCollecting, // boolean: the remote roster is being read
19
19
  * home, // string: the user's home directory, for the short label
20
20
  * at, // string: the ISO time of this call
@@ -45,7 +45,13 @@ function refusal(doc, cli) {
45
45
  export async function cliSpawnApply(cli, options = {}, io = {}) {
46
46
  // Repeat the complete positive mode fence here, before even creating inputs.
47
47
  if (!spawnApplySupported(cli)) return failure('E_APPLY_UNAVAILABLE');
48
- if (!record(options) || Object.keys(options).some(k => !['target', 'choices', 'task', 'wake', 'decision', 'key', 'deadlineMs'].includes(k))) return failure('E_BAD_ARGS');
48
+ if (!record(options) || Object.keys(options).some(k => !['target', 'choices', 'task', 'wake', 'decision', 'key', 'deadlineMs', 'maxAge'].includes(k))) return failure('E_BAD_ARGS');
49
+ // Feature spawn-apply-max-age (#1246 K1): the kernel may reuse deployment observations up to maxAge seconds old.
50
+ // Only beside --expect-decision, which fences a drifted decision, and only where the CLI lists it (an older
51
+ // kernel refuses the flag).
52
+ const maxAge = options.maxAge;
53
+ if (maxAge !== undefined && (!Number.isInteger(maxAge) || maxAge < 1 || maxAge > 3600)) return failure('E_BAD_ARGS');
54
+ const reuse = maxAge !== undefined && Array.isArray(cli.features) && cli.features.includes('spawn-apply-max-age') ? ['--max-age', String(maxAge)] : [];
49
55
  // The broker derives the deadline from the confirmed preview (spawnApplyDeadlineMs); 60 s without one.
50
56
  const timeout = options.deadlineMs ?? SPAWN_APPLY_MS;
51
57
  if (!spawnApplyDeadline(timeout)) return failure('E_BAD_ARGS');
@@ -60,7 +66,7 @@ export async function cliSpawnApply(cli, options = {}, io = {}) {
60
66
  if (input.wake) wakeFile = writeTaskFile(JSON.stringify(input.wake), io);
61
67
  const choices = input.choices;
62
68
  const argv = ['spawn', target.selector.soul, '--dir', target.context, '--agents-root', target.selector.agentsRoot, ...choiceArgv(choices, cli)];
63
- argv.push('--expect-decision', decision.revision, '--idempotency-key', options.key, '--task-file', taskFile.file);
69
+ argv.push('--expect-decision', decision.revision, ...reuse, '--idempotency-key', options.key, '--task-file', taskFile.file);
64
70
  if (wakeFile) argv.push('--wake-file', wakeFile.file);
65
71
  argv.push('--json');
66
72
  const env = { ...(io.env ?? process.env) };
@@ -12,7 +12,7 @@ import { retainedSpawnDetails, LAUNCH_DIAGNOSTIC_BYTES, FLAG_IGNORED_BYTES } fro
12
12
  import { randomBytes } from 'node:crypto';
13
13
  import { performance } from 'node:perf_hooks';
14
14
  import { cliSpawnApply } from './spawn-apply-cli.mjs';
15
- import { admitSpawnSelection } from './spawn-preview.mjs';
15
+ import { admitSpawnSelection, PREVIEW_MAX_AGE_S } from './spawn-preview.mjs';
16
16
  import { record } from './spawn-preview-contract.mjs';
17
17
  import { spawnApplySupported, spawnApplyChoicesSupported, spawnPrepareInput, spawnRefInput, spawnPreparedData, spawnReference,
18
18
  spawnCreationReceipt, spawnApplyFailure, spawnApplyDeadlineMs, ROLLED_BACK_CODES, WAKE_OUTCOME_UNKNOWN } from './spawn-apply-contract.mjs';
@@ -34,8 +34,11 @@ const scopeKey = c => JSON.stringify([c?.workspace?.id, c?.workspace?.scope, c?.
34
34
  * (`child.kill`): a given exec must return the child. One that returns nothing leaves that apply
35
35
  * unended at its deadline; there is no fallback here. On a kernel without worktree-event the options'
36
36
  * `timeout` is the apply's only deadline: exec must honour it as execFileInSession does, killing the
37
- * child when it passes and reporting `killed` even if the child then exits cleanly. */
38
- export function createSpawnApplyBoundary({ read, invoke = cliSpawnApply, exec,
37
+ * child when it passes and reporting `killed` even if the child then exits cleanly.
38
+ * maxAge seconds the kernel may reuse its deployment observations for the apply (#1246 K1: the member heads'
39
+ * ls-remote wave at the press). Passed to `invoke` only where the apply's CLI lists spawn-apply-max-age;
40
+ * null never. The fence is unchanged: apply's --expect-decision refuses a drifted decision (E_DECISION_STALE). */
41
+ export function createSpawnApplyBoundary({ read, invoke = cliSpawnApply, exec, maxAge = PREVIEW_MAX_AGE_S,
39
42
  now = () => performance.now(), mint = () => randomBytes(32).toString('hex'), answerWithinMs = ANSWER_WITHIN_MS,
40
43
  timer = (fn, ms) => { const t = setTimeout(fn, ms); return () => clearTimeout(t); } } = {}) {
41
44
  if (typeof read !== 'function') throw new TypeError('createSpawnApplyBoundary: read (the client\'s prepareRead) is required');
@@ -170,7 +173,8 @@ export function createSpawnApplyBoundary({ read, invoke = cliSpawnApply, exec,
170
173
  if (!same(entry, latest)) reply = denied('E_PLAN_CHANGED', entry, 'refused');
171
174
  else {
172
175
  const result = await invoke(latest.cli, { target: clone(entry.target), choices: clone(entry.input.choices), task: entry.input.task,
173
- ...(entry.input.wake ? { wake: clone(entry.input.wake) } : {}), decision: clone(entry.preview.decision), key: entry.key, deadlineMs: entry.deadlineMs }, ...io);
176
+ ...(entry.input.wake ? { wake: clone(entry.input.wake) } : {}), decision: clone(entry.preview.decision), key: entry.key, deadlineMs: entry.deadlineMs,
177
+ ...(maxAge !== null && latest.cli?.features?.includes('spawn-apply-max-age') ? { maxAge } : {}) }, ...io);
174
178
  reply = interpret(result, entry, latest.cli);
175
179
  }
176
180
  } catch { reply = denied('E_OUTCOME_UNKNOWN', entry, 'unknown'); }
@@ -16,7 +16,8 @@ export function cliSpawnPreview(cli, options = {}, io = {}) {
16
16
  const target = previewTarget(options.target), choices = previewChoices(options.choices);
17
17
  if (!target || !choices || Object.keys(options).some(k => !['target', 'choices', 'maxAge'].includes(k))) return Promise.resolve(failure('E_BAD_ARGS'));
18
18
  // Feature spawn-preview-max-age: reuse member heads the kernel observed within maxAge seconds. Only
19
- // where the CLI advertises it (an older kernel refuses the flag); prepare and apply never pass it.
19
+ // where the CLI advertises it (an older kernel refuses the flag); prepare never passes it. The apply's own
20
+ // --max-age is spawn-apply-max-age's (spawn-apply-cli.mjs).
20
21
  const maxAge = options.maxAge;
21
22
  if (maxAge !== undefined && (!Number.isInteger(maxAge) || maxAge < 1 || maxAge > 3600)) return Promise.resolve(failure('E_BAD_ARGS'));
22
23
  const reuse = maxAge !== undefined && Array.isArray(cli.features) && cli.features.includes('spawn-preview-max-age') ? ['--max-age', String(maxAge)] : [];
@@ -3,12 +3,14 @@
3
3
  *
4
4
  * A client makes its own preview (createSpawnPreview) and owns it: nothing here is
5
5
  * held at module level, so two clients' budgets, caches and flights never meet.
6
- * The cache (60 s, keyed by the admission identity) serves the dialog's preview
7
- * read and prepare's: an answer is still admitted against the current context
8
- * before it is returned, and a workspace's entries go when the client observes a
9
- * change that can alter a preview (the Desktop's: server/oats-web.mjs). Prepare taking
10
- * a held decision is safe because apply binds it with the kernel's --expect-decision:
11
- * a decision the kernel no longer makes is refused there (E_DECISION_STALE), never applied. */
6
+ * The cache (keyed by the admission identity) serves the dialog's preview read for
7
+ * 60 s and prepare's for PREPARE_REUSE_MS (#1246: the prepared intent's own lifetime,
8
+ * so a press after the operator lingered over the form runs no second kernel preview):
9
+ * an answer is still admitted against the current context before it is returned, and a
10
+ * workspace's entries go when the client observes a change that can alter a preview (the
11
+ * Desktop's: server/oats-web.mjs). Prepare taking a held decision is safe because apply
12
+ * binds it with the kernel's --expect-decision: a decision the kernel no longer makes is
13
+ * refused there (E_DECISION_STALE, read as drifted), never applied. */
12
14
  import { dirname } from 'node:path';
13
15
  import { performance } from 'node:perf_hooks';
14
16
  import { cliSpawnPreview } from './spawn-preview-cli.mjs';
@@ -24,24 +26,31 @@ export function createSpawnPreviewFlights() {
24
26
  }
25
27
  const missing = (factory, what) => new TypeError(`${factory}: ${what} is required`);
26
28
  export const PREVIEW_CACHE_TTL_MS = 60000;
29
+ /** How old a held answer prepare may take (#1246): the lifetime of the intent it prepares. */
30
+ export const PREPARE_REUSE_MS = 300000;
27
31
  // A name refusal answers the same name the same way until something changes.
28
32
  const CACHED_REFUSALS = ['E_INSTANCE_NAME_TAKEN', 'E_INSTANCE_NAME_INVALID'];
29
33
  const cacheable = result => result?.status === 'available' || result?.status === 'unavailable' && CACHED_REFUSALS.includes(result.reason?.code);
30
- /** `clock` is the flights' clock (createSpawnPreviewFlights): required, never a clock of its own. */
31
- export function createSpawnPreviewCache({ ttlMs = PREVIEW_CACHE_TTL_MS, limit = 64, now = () => performance.now(), clock } = {}) {
34
+ /** `clock` is the flights' clock (createSpawnPreviewFlights): required, never a clock of its own. An entry is kept
35
+ * for `keepMs` (at least `ttlMs`) from when it was read; `get(identity, maxAgeMs)` answers it only while it is
36
+ * younger than `maxAgeMs` (default `ttlMs`): the dialog's reads take 60 s, prepare's PREPARE_REUSE_MS. */
37
+ export function createSpawnPreviewCache({ ttlMs = PREVIEW_CACHE_TTL_MS, keepMs = ttlMs, limit = 64, now = () => performance.now(), clock } = {}) {
32
38
  if (typeof clock !== 'function') throw missing('createSpawnPreviewCache', 'clock (the flights\' clock)');
33
39
  const entries = new Map(), invalidatedAt = new Map();
34
40
  let clearedAt = 0;
41
+ const kept = Math.max(ttlMs, keepMs);
35
42
  return {
36
- get(identity) {
43
+ get(identity, maxAgeMs = ttlMs) {
37
44
  const entry = entries.get(identity);
38
45
  if (!entry) return null;
39
46
  if (now() >= entry.expires) { entries.delete(identity); return null; }
47
+ if (now() - entry.readAt >= maxAgeMs) return null; // too old for this reader; a longer-lived one may still take it
40
48
  return structuredClone(entry.result);
41
49
  },
42
50
  set(identity, workspace, result, startedAt) {
43
51
  if (!cacheable(result) || typeof startedAt !== 'number' || startedAt <= clearedAt || startedAt <= (invalidatedAt.get(workspace) ?? 0)) return;
44
- entries.delete(identity); entries.set(identity, { workspace, result: structuredClone(result), expires: now() + ttlMs });
52
+ const readAt = now();
53
+ entries.delete(identity); entries.set(identity, { workspace, result: structuredClone(result), readAt, expires: readAt + kept });
45
54
  for (const [key, entry] of entries) if (now() >= entry.expires) entries.delete(key);
46
55
  while (entries.size > limit) entries.delete(entries.keys().next().value);
47
56
  },
@@ -93,8 +102,9 @@ export function admitSpawnSelection(selector, choices, { workspace: w, cli, agen
93
102
  /** One read of a preview. `flights` (createSpawnPreviewFlights) is required: the reads of one preview share it,
94
103
  * and a cache given here must run on its clock. maxAge: the dialog's reads may reuse member heads the kernel
95
104
  * observed within that many seconds (feature spawn-preview-max-age, passed only when the admitted CLI
96
- * advertises it). Prepare's reads never do. exec: as createSpawnPreview's. */
97
- export function createSpawnPreviewBoundary({ invoke = cliSpawnPreview, cache = null, maxAge = null, flights, exec } = {}) {
105
+ * advertises it). Prepare's reads never do. heldMs: how old a held answer this read takes (default: the cache's
106
+ * TTL). exec: as createSpawnPreview's. */
107
+ export function createSpawnPreviewBoundary({ invoke = cliSpawnPreview, cache = null, maxAge = null, heldMs, flights, exec } = {}) {
98
108
  if (!flights?.slots || !flights.byInvoker || !flights.started || typeof flights.clock !== 'function') throw missing('createSpawnPreviewBoundary', 'flights (createSpawnPreviewFlights)');
99
109
  if (cache && cache.clock !== flights.clock) throw new TypeError('createSpawnPreviewBoundary: the cache must run on the flights\' clock');
100
110
  const { slots, byInvoker, started } = flights, io = exec ? [{ exec }] : [];
@@ -106,7 +116,7 @@ export function createSpawnPreviewBoundary({ invoke = cliSpawnPreview, cache = n
106
116
  const selected = admitSpawnSelection(selector, choices, getContext());
107
117
  if (selected.error) return previewFailure(selected.error);
108
118
  const { target, identity, cli } = selected;
109
- const held = cache?.get(identity);
119
+ const held = cache?.get(identity, heldMs);
110
120
  if (held) return held; // admitted above against the current context, like a fresh answer
111
121
  let pending = byInvoker.get(invoke); if (!pending) { pending = new Map(); byInvoker.set(invoke, pending); }
112
122
  const reuse = maxAge !== null && cli.features.includes('spawn-preview-max-age') ? { maxAge } : {};
@@ -134,19 +144,21 @@ export const PREVIEW_MAX_AGE_S = 60;
134
144
  * read the dialog's read, through the cache; its kernel reads may reuse recent member heads (maxAge,
135
145
  * where the CLI declares spawn-preview-max-age)
136
146
  * prepareRead prepare's read (spawn-apply.mjs createSpawnApplyBoundary's `read`), through the same cache,
137
- * never with maxAge; a reusing read and a live one never coalesce
147
+ * taking a held answer up to `prepareReuseMs` old (PREPARE_REUSE_MS), never with maxAge; a reusing
148
+ * read and a live one never coalesce
138
149
  * cache `invalidate(workspace?)` (no argument: every workspace's answers) and `size()`
139
150
  * The two reads share one two-slot budget, one set of coalesced flights and one clock, the cache's too.
140
151
  * exec optional: the client's own execFile, passed to `invoke` as `invoke(cli, options, { exec })` for both
141
152
  * reads (cli-adapter.mjs `runJson` has the rule); without it `invoke` is given no third argument and
142
153
  * cliSpawnPreview's own default runs. A read is a read: its options carry no `detached` and a 30 s
143
154
  * deadline, and it ends with its caller. */
144
- export function createSpawnPreview({ invoke = cliSpawnPreview, exec, now = () => performance.now(), ttlMs = PREVIEW_CACHE_TTL_MS, limit = 64, maxAge = PREVIEW_MAX_AGE_S } = {}) {
155
+ export function createSpawnPreview({ invoke = cliSpawnPreview, exec, now = () => performance.now(), ttlMs = PREVIEW_CACHE_TTL_MS,
156
+ prepareReuseMs = PREPARE_REUSE_MS, limit = 64, maxAge = PREVIEW_MAX_AGE_S } = {}) {
145
157
  const flights = createSpawnPreviewFlights();
146
- const cache = createSpawnPreviewCache({ ttlMs, limit, now, clock: flights.clock });
158
+ const cache = createSpawnPreviewCache({ ttlMs, keepMs: prepareReuseMs, limit, now, clock: flights.clock });
147
159
  return {
148
- read: createSpawnPreviewBoundary({ invoke, cache, maxAge, flights, exec }),
149
- prepareRead: createSpawnPreviewBoundary({ invoke, cache, flights, exec }),
160
+ read: createSpawnPreviewBoundary({ invoke, cache, maxAge, heldMs: ttlMs, flights, exec }),
161
+ prepareRead: createSpawnPreviewBoundary({ invoke, cache, heldMs: prepareReuseMs, flights, exec }),
150
162
  cache: { invalidate: workspace => cache.invalidate(workspace), size: () => cache.size() },
151
163
  };
152
164
  }
@@ -0,0 +1,14 @@
1
+ /** Whether `actual` ({dev, ino, birthtimeNs?}, read now) is the directory `recorded` names.
2
+ * The inode is the identity: on one volume a different directory has a different inode.
3
+ * macOS gives an APFS volume a new `dev` each time it is mounted, so after a reboot `dev`
4
+ * no longer matches; there an equal inode is enough, unless the record holds a birth time
5
+ * (a decimal string of ns), which must then match too. Birth time is not an identity (it can
6
+ * be set, and copies keep it): it closes only the gap a dropped `dev` opens, another volume
7
+ * showing the same inode. A record without one, or with "0" (no birth times on that volume),
8
+ * is judged by the inode alone. Elsewhere `dev` and `ino` must both match. */
9
+ export function sameDirectory(recorded, actual, platform = process.platform) {
10
+ if (!recorded || !actual || recorded.ino !== actual.ino) return false;
11
+ if (recorded.dev === actual.dev) return true;
12
+ if (platform !== "darwin") return false;
13
+ return recorded.birthtimeNs === undefined || recorded.birthtimeNs === "0" || recorded.birthtimeNs === actual.birthtimeNs;
14
+ }
@@ -6,6 +6,7 @@ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "nod
6
6
  import { isDeepStrictEqual } from "node:util";
7
7
  import { isUtf8 } from "node:buffer";
8
8
  import { nativeLaunchLocations } from "./session-roots.mjs";
9
+ import { sameDirectory } from "./directory-identity.mjs";
9
10
 
10
11
  function canonical(home) {
11
12
  try { return realpathSync(home); }
@@ -215,7 +216,7 @@ function validateReceipt(row, home, id) {
215
216
  function validateWitness(row, rows) {
216
217
  const witness = row.rootWitness, establishing = witness && rows.get(witness.establishedBy.nativeRecordId);
217
218
  if (!establishing || establishing.version !== 2 || !["root-established", "started"].includes(establishing.state) || establishing.home !== row.home || establishing.incarnationId !== row.incarnationId || establishing.rootWitness?.establishedBy.nativeRecordId !== establishing.id || !isDeepStrictEqual(establishing.intent, witness.establishedBy.intent) || !isDeepStrictEqual(establishing.rootWitness, witness)) custodyError("original establishing receipt is missing or contradictory");
218
- if (!isDeepStrictEqual(directoryIdentity(row.proposedRoot), witness.identity)) custodyError("original Pi session directory was replaced");
219
+ if (!sameDirectory(witness.identity, directoryIdentity(row.proposedRoot))) custodyError("original Pi session directory was replaced");
219
220
  }
220
221
  function selection(home, authority, withIntent = false, creating = false) {
221
222
  closed(authority, ["incarnationId", "sessionDir", ...(withIntent ? ["intent"] : []), ...(creating ? ["assertAuthority"] : [])]);
@@ -266,7 +267,7 @@ export function prepareCapturedPiStart(home, authority) {
266
267
  authority.assertAuthority();
267
268
  for (const [path, identity] of directories) if (!isDeepStrictEqual(directoryIdentity(path), identity)) custodyError("original native custody parent changed");
268
269
  for (const [id, row] of rows) if (!isDeepStrictEqual(privateJson(join(history, id + ".json")), row)) custodyError("original native receipt changed during preparation");
269
- if (witness && !isDeepStrictEqual(directoryIdentity(authority.sessionDir), witness.identity)) custodyError("original root changed during preparation");
270
+ if (witness && !sameDirectory(witness.identity, directoryIdentity(authority.sessionDir))) custodyError("original root changed during preparation");
270
271
  };
271
272
  const id = randomUUID(), pending = { version: 2, id, home, runtime: "pi", incarnationId: authority.incarnationId, intent: structuredClone(authority.intent), state: "pending", proposedRoot: authority.sessionDir, rootWitness: structuredClone(witness) };
272
273
  const claimed = validateManifest({ version: 2, home, completeHistory: header.completeHistory, capturedPi: { incarnationId: authority.incarnationId, nativeRecordIds: [...(header.capturedPi?.nativeRecordIds ?? []), id] } }, home);
@@ -282,7 +283,7 @@ export function prepareCapturedPiStart(home, authority) {
282
283
  const identity = directoryIdentity(authority.sessionDir); syncDirectory(dirname(authority.sessionDir)); claimCheck();
283
284
  established = { schemaVersion: 1, profile: "pi-zero-print-1", path: authority.sessionDir, identity, establishedBy: { nativeRecordId: id, intent: structuredClone(authority.intent) } };
284
285
  }
285
- const guard = () => { claimCheck(); if (!isDeepStrictEqual(directoryIdentity(authority.sessionDir), established.identity)) custodyError("captured root changed during establishment"); };
286
+ const guard = () => { claimCheck(); if (!sameDirectory(established.identity, directoryIdentity(authority.sessionDir))) custodyError("captured root changed during establishment"); };
286
287
  publishCaptured(home, { ...pending, state: "root-established", rootWitness: established }, pending, guard);
287
288
  inventory(home); // no unlisted/unfinished writes may be ignored before return
288
289
  return id;
@@ -310,7 +311,7 @@ function recordCapturedPiStart(home, id, runtime, args, env) {
310
311
  if (!isDeepStrictEqual(protectedManifest(home), header)) custodyError("expected-ID claim changed before execution");
311
312
  const current = privateJson(join(nativeHistoryPath(home), establish.id + ".json"));
312
313
  if (establish.id !== id && !isDeepStrictEqual(current, establish)) custodyError("establishing receipt changed");
313
- if (!isDeepStrictEqual(directoryIdentity(row.proposedRoot), row.rootWitness.identity)) custodyError("native root changed before execution");
314
+ if (!sameDirectory(row.rootWitness.identity, directoryIdentity(row.proposedRoot))) custodyError("native root changed before execution");
314
315
  };
315
316
  publishCaptured(home, { ...row, state: "started", startedAt: new Date().toISOString(), locations: [row.proposedRoot] }, row, check);
316
317
  }
@@ -344,7 +345,7 @@ export function assertCapturedPiProof(proof, path) {
344
345
  for (let current = path; ; current = dirname(current)) {
345
346
  const stat = physical(current, current !== path);
346
347
  if (current === row.proposedRoot) {
347
- if (!stat.isDirectory() || !isDeepStrictEqual({ dev: stat.dev, ino: stat.ino }, row.rootWitness.identity)) custodyError("native root changed during contained-path validation");
348
+ if (!stat.isDirectory() || !sameDirectory(row.rootWitness.identity, { dev: stat.dev, ino: stat.ino })) custodyError("native root changed during contained-path validation");
348
349
  break;
349
350
  }
350
351
  }
@@ -89,9 +89,18 @@
89
89
  // hang-up reaches it at once as SIGHUP, and it cleans up after itself. A pane is never closed by
90
90
  // its process's end: `remain-on-exit` is on, so tmux keeps a dead pane with its exit status, and
91
91
  // the control client is subscribed (`refresh-client -B`, DEAD_SUBSCRIPTION) to every pane's
92
- // `#{pane_dead} #{pane_dead_status}`. tmux checks a subscription once a second, so a viewer's end
93
- // is heard within a second: `1 <status>` (no status when a signal ended it). The panel then kills
94
- // the dead pane, which closes its window. A pane-died hook cannot do it: tmux sends no
92
+ // `#{pane_dead} #{pane_dead_status} #{pane_dead_signal}`. tmux checks a subscription once a second,
93
+ // so a viewer's end is heard within a second: `1 <status> ` when it exited, `1 <signal>` when a
94
+ // signal ended it. The panel then kills the dead pane, which closes its window. A pane can be
95
+ // heard dead BEFORE tmux has its status: tmux marks it dead when its terminal hangs up (the
96
+ // process's files closed as it exits) and takes the status only when it reaps the process, a
97
+ // moment later (server_destroy_pane, then server_child_exited; 3.2 to 3.4 at least, and CI on 3.4
98
+ // heard the dead pane between the two). That line, `1 `, is not the end: the line with the status
99
+ // follows at the next check, and the panel waits for it, a bounded time: a viewer heard so is over
100
+ // without a status once STATUS_WAIT_MS have passed with no other line, its pane killed, so a
101
+ // status that never comes never leaves a terminal open that nothing will close (CI, tmux 3.4).
102
+ // tmux 3.2 has no `pane_dead_signal` (3.3 added it), so there a signal's end reads `1 ` for good,
103
+ // and the wait is the shorter DEAD_WAIT_MS. A pane-died hook cannot do it: tmux sends no
95
104
  // notification for a command a hook runs. A pane the panel kills (close(), an open given up) is
96
105
  // gone at once, with no status. Verified with tmux 3.4 and 3.7c; read in 3.2's source (control.c,
97
106
  // format.c, server-fn.c), the same.
@@ -131,10 +140,23 @@ export const FRAME_MS = 16;
131
140
  * VIEWER). */
132
141
  export const VIEW_SCRIPT = 'exec "$0" "$@" 2>"$E"';
133
142
  /** The control client's subscription to every pane's end (THE END OF A VIEWER): its name, and
134
- * the line tmux prints when a pane's value changes, `1 <status>` for a dead pane (no status when
135
- * a signal ended it), `0 ` for a live one. */
143
+ * the line tmux prints when a pane's value changes, `1 <status> ` for a dead pane whose process
144
+ * exited, `1 <signal>` for one a signal ended (a name, or its number), `1 ` for one whose status
145
+ * tmux does not have yet (or, on tmux 3.2, a signal's), `0 ` for a live one. */
136
146
  const DEAD_SUBSCRIPTION = "oats-tui-dead";
137
- const DEAD_LINE = /^%subscription-changed oats-tui-dead \$\d+ (@\d+) \d+ %\d+ : ([01]) (\d{0,3})$/;
147
+ const DEAD_LINE = /^%subscription-changed oats-tui-dead \$\d+ (@\d+) \d+ %\d+ : ([01]) (\d{0,3}) ([A-Z0-9]{0,12})$/;
148
+ /** On tmux 3.2 (no `pane_dead_signal`), how long a viewer heard dead with no status and no signal
149
+ * (`1 `) waits for the line that has one, in milliseconds: two checks of the subscription past
150
+ * the one that heard it. */
151
+ export const DEAD_WAIT_MS = 2500;
152
+ /** On tmux 3.3 and later, the same wait: ten checks of the subscription. tmux has the status a
153
+ * moment after the hang-up; a viewer that closed its terminal and lives on keeps it longer, and
154
+ * one whose status never comes is over without one when this has passed. */
155
+ export const STATUS_WAIT_MS = 10000;
156
+ /** The first tmux whose `pane_dead_signal` says which signal ended a pane. */
157
+ const DEAD_SIGNAL_TMUX = Object.freeze([3, 3]);
158
+ /** What a dead line with no status and no signal says of a viewer: its status is still to come. */
159
+ const PENDING = Symbol("pending");
138
160
  /** The one session of the private server, and its keeper window's command. */
139
161
  export const SESSION = "oats-tui";
140
162
  /** The keeper's command (see THE KEEPER), a constant run as `sh -c KEEPER_SCRIPT oats-tui-keeper
@@ -169,7 +191,7 @@ export const startCommands = ({ alive }) => [
169
191
  ["set-option", "-gw", "remain-on-exit", "on"],
170
192
  // Nothing drawn over a dead pane (tmux 3.3 and later; -q: 3.2 has no such option).
171
193
  ["set-option", "-gwq", "remain-on-exit-format", ""],
172
- ["refresh-client", "-B", `${DEAD_SUBSCRIPTION}:%*:#{pane_dead} #{pane_dead_status}`],
194
+ ["refresh-client", "-B", `${DEAD_SUBSCRIPTION}:%*:#{pane_dead} #{pane_dead_status} #{pane_dead_signal}`],
173
195
  ["unbind-key", "-a"],
174
196
  ["unbind-key", "-a", "-T", "root"],
175
197
  ["unbind-key", "-a", "-T", "copy-mode"],
@@ -231,13 +253,13 @@ function tmuxEnvironment(env) {
231
253
  const cells = (n, fallback) => (Number.isInteger(n) && n > 0 ? Math.min(n, 10_000) : fallback);
232
254
  /** Bytes as tmux's `send-keys -H` takes them: two hex digits each, separated by spaces. */
233
255
  const hex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(" ");
234
- /** Whether a `tmux -V` answer names a version older than MIN_TMUX. A name without a version
235
- * (a build from the repository says `master` or `next-…`) is taken as new enough. */
236
- function tooOld(answer) {
256
+ /** Whether a `tmux -V` answer names a version older than `[major, minor]`. A name without a
257
+ * version (a build from the repository says `master` or `next-…`) is taken as new enough. */
258
+ function older(answer, [least, leastMinor]) {
237
259
  const found = /(\d+)\.(\d+)/.exec(String(answer));
238
260
  if (!found) return false;
239
261
  const [major, minor] = [Number(found[1]), Number(found[2])];
240
- return major < MIN_TMUX[0] || (major === MIN_TMUX[0] && minor < MIN_TMUX[1]);
262
+ return major < least || (major === least && minor < leastMinor);
241
263
  }
242
264
 
243
265
  /** What this module does to the file system, each replaceable by a test.
@@ -315,8 +337,13 @@ function readPart(file, max, fromEnd) {
315
337
  * env the environment tmux is given (TMUX and TMUX_PANE removed); default process.env.
316
338
  * tmux the program; default "tmux" on PATH.
317
339
  * spawn, execFile, execFileSync, fs (see PANEL_FS), timers ({ setTimeout, clearTimeout }: the
318
- * frame tick, the only timer of this module), clock (an ISO time, for
340
+ * frame tick and a dead viewer's wait for its status, STATUS_WAIT_MS or
341
+ * DEAD_WAIT_MS, the only timers of this module), clock (an ISO time, for
319
342
  * owner.json), pid (the TUI's, for owner.json): for tests.
343
+ * trace(text) told, when given, each notification of a viewer's end the control client printed
344
+ * (the dead-pane subscription's lines, a window's end, the client's own end) and
345
+ * what the panel made of it: tmux's ids and numbers and this module's words only,
346
+ * never a pane's text. For diagnosing an end in a test; default none.
320
347
  * A callback that throws does not break the panel: what it threw is thrown again in a microtask,
321
348
  * where the run hears it as any uncaught error.
322
349
  *
@@ -348,7 +375,7 @@ function readPart(file, max, fromEnd) {
348
375
  * No method but open() throws or rejects: a server that went away makes each of them do nothing. */
349
376
  export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () => {}, env = process.env, tmux = "tmux",
350
377
  spawn = nodeSpawn, execFile = nodeExecFile, execFileSync = nodeExecFileSync, fs: givenFs = {}, timers = { setTimeout, clearTimeout },
351
- clock = () => new Date().toISOString(), pid = process.pid } = {}) {
378
+ clock = () => new Date().toISOString(), pid = process.pid, trace = null } = {}) {
352
379
  if (typeof dir !== "function") throw new TypeError("createPanel needs dir(): the run's private directory");
353
380
  if (typeof capture !== "function") throw new TypeError("createPanel needs capture(text, { cols, rows }): the cell builder");
354
381
  const fs = { ...PANEL_FS, ...givenFs };
@@ -356,6 +383,8 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
356
383
  /** The run directory and the socket in it, once known; whether owner.json was written, tmux's
357
384
  * version checked, and a server ever started in this run. */
358
385
  let runDir = null, socket = null, ownerWritten = false, checked = false, everStarted = false;
386
+ /** Whether this tmux says which signal ended a pane (DEAD_SIGNAL_TMUX), known once checked. */
387
+ let signals = true;
359
388
  /** The capture's file, and that path as a word of a control line (see THE CAPTURE). */
360
389
  let capturePath = null, captureWord = null;
361
390
  /** The write end of `<run dir>/alive`, held for the run once made (see THE KEEPER), or null. */
@@ -372,7 +401,7 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
372
401
  * `closedSeen`: the window ids whose end was heard while an open was under way. A viewer that
373
402
  * exits at once can end before new-window has answered with its id; ids are never reused by a
374
403
  * server, and the set is emptied when no open is under way, and at every new server.
375
- * `diedSeen`: the same for a pane heard dead (window id -> its status, or null). */
404
+ * `diedSeen`: the same for a pane heard dead (window id -> its status, null, or PENDING). */
376
405
  let viewer = null, opening = null;
377
406
  const closing = new Map(), openings = new Set(), closedSeen = new Set(), diedSeen = new Map();
378
407
  /** The frames: the screen is stale (`dirty`), a tick is armed (`tick`), a capture is in flight. */
@@ -383,6 +412,8 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
383
412
  function tell(act) {
384
413
  try { act(); } catch (error) { queueMicrotask(() => { throw error; }); }
385
414
  }
415
+ /** One line of the trace, when the caller asked for one. */
416
+ const traced = (text) => { if (trace) tell(() => trace(text)); };
386
417
  /** The flags every call starts with. */
387
418
  const base = () => ["-u", "-f", "/dev/null", "-S", socket];
388
419
 
@@ -454,9 +485,13 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
454
485
  const [kind, first] = line.split(" ", 2);
455
486
  if (kind === "%output" || kind === "%extended-output") { if (viewer && first === viewer.pane) stale(); }
456
487
  else if (kind === "%layout-change") { if (viewer && first === viewer.id) stale(); }
457
- else if (kind === "%window-close" || kind === "%unlinked-window-close") windowClosed(first);
458
- else if (kind === "%exit") lost(s);
459
- else if (kind === "%subscription-changed") { const dead = DEAD_LINE.exec(line); if (dead && dead[2] === "1") paneDied(dead[1], dead[3] === "" ? null : Number(dead[3])); }
488
+ else if (kind === "%window-close" || kind === "%unlinked-window-close") { traced(line); windowClosed(first); }
489
+ else if (kind === "%exit") { traced(line); lost(s); }
490
+ else if (kind === "%subscription-changed") {
491
+ const dead = DEAD_LINE.exec(line);
492
+ if (first === DEAD_SUBSCRIPTION) traced(dead ? line : `${DEAD_SUBSCRIPTION}: a line not of its shape`);
493
+ if (dead && dead[2] === "1") paneDied(dead[1], dead[3] !== "" ? Number(dead[3]) : dead[4] !== "" ? null : PENDING);
494
+ }
460
495
  }
461
496
 
462
497
  /** The start's blocks are over, or one failed: the start waits for this (see `ensureServer`). */
@@ -549,7 +584,8 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
549
584
  try { answer = await call(["-V"]); } catch (error) {
550
585
  throw error?.code === "ENOENT" ? refusal("E_PANEL_TMUX", "tmux is not installed") : refusal("E_PANEL_TMUX", "tmux did not say its version", { detail: detail(error) });
551
586
  }
552
- if (tooOld(answer.stdout)) throw refusal("E_PANEL_TMUX", "the panel needs tmux 3.2 or later", { detail: answer.stdout.trim().slice(0, 80) });
587
+ if (older(answer.stdout, MIN_TMUX)) throw refusal("E_PANEL_TMUX", "the panel needs tmux 3.2 or later", { detail: answer.stdout.trim().slice(0, 80) });
588
+ signals = !older(answer.stdout, DEAD_SIGNAL_TMUX);
553
589
  checked = true;
554
590
  }
555
591
  if (ended) throw refusal("E_PANEL_ENDED", "the panel has ended");
@@ -658,12 +694,32 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
658
694
  // VIEWERS --------------------------------------------------------------------------------------
659
695
 
660
696
  /** A viewer's pane is dead (THE END OF A VIEWER): the viewer is over with the status tmux kept,
661
- * and its pane is killed, which closes its window. A pane not yet known (an open under way) is
662
- * remembered with its status; any other is not a viewer's (the keeper's, one already over). */
697
+ * and its pane is killed, which closes its window. PENDING (dead, and tmux has no status yet) is
698
+ * not the end: the viewer waits for the line with its status (`waitStatus`). A pane not yet
699
+ * known (an open under way) is remembered with what was heard; any other is not a viewer's (the
700
+ * keeper's, one already over). */
663
701
  function paneDied(id, status) {
664
702
  const v = viewer?.id === id ? viewer : closing.get(id);
703
+ if (v && status === PENDING) return waitStatus(v);
665
704
  if (v) { v.status = status; ask(`kill-pane -t ${v.pane}`); return finish(v, {}); }
666
- if (openings.size > 0) diedSeen.set(id, status);
705
+ if (openings.size > 0 && !(status === PENDING && diedSeen.has(id))) diedSeen.set(id, status);
706
+ }
707
+ /** A viewer heard dead with no status: it stays open until the line with its status or its
708
+ * signal, a close, or its server's end, and at most STATUS_WAIT_MS (DEAD_WAIT_MS on tmux 3.2,
709
+ * which says a signal's end no other way): then it is over without a status, and its pane is
710
+ * killed. Armed once. */
711
+ function waitStatus(v) {
712
+ if (v.over || v.waiting !== null) return;
713
+ const ms = signals ? STATUS_WAIT_MS : DEAD_WAIT_MS;
714
+ traced(`${v.id} dead, waiting ${ms} ms for its status`);
715
+ v.waiting = timers.setTimeout(() => {
716
+ v.waiting = null;
717
+ if (ended || v.over) return;
718
+ traced(`${v.id} no status after ${ms} ms`);
719
+ v.status = null;
720
+ if (server && !server.gone) ask(`kill-pane -t ${v.pane}`);
721
+ finish(v, {});
722
+ }, ms);
667
723
  }
668
724
  /** A window ended: the open viewer's, one closing, or (an open under way) one to remember. */
669
725
  function windowClosed(id) {
@@ -679,12 +735,16 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
679
735
  const status = v.status;
680
736
  if (v.over) return;
681
737
  v.over = true;
738
+ unwait(v);
682
739
  closing.delete(v.id);
683
740
  if (viewer === v) free();
684
741
  const stderr = quietly(() => fs.tail(v.files.err, STDERR_KEPT)) ?? "";
742
+ traced(`${v.id} over, status ${gone ? null : status}${gone ? ", its server gone" : ""}${v.asked ? ", closed" : ""}`);
685
743
  forget(v.files);
686
744
  if (!ended) tell(() => onClosed({ id: v.id, status: gone ? null : status, stderr, asked: v.asked }));
687
745
  }
746
+ /** A viewer's wait for its status (waitStatus), put away. */
747
+ function unwait(v) { if (v.waiting !== null) { quietly(() => timers.clearTimeout(v.waiting)); v.waiting = null; } }
688
748
  /** The slot is free: no viewer, no frame to come. */
689
749
  function free() { viewer = null; stopFrames(); dirty = false; }
690
750
  const forget = (made) => { for (const path of [made?.err, made?.status]) if (path) quietly(() => fs.unlink(path)); };
@@ -734,10 +794,13 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
734
794
  throw refusal("E_PANEL_OPEN", "tmux did not name the window it opened");
735
795
  }
736
796
  if (ended) throw refusal("E_PANEL_ENDED", "the panel has ended");
737
- const v = { id: ids[1], pane: ids[2], ...size, files: made, asked: false, over: false, status: null };
797
+ const v = { id: ids[1], pane: ids[2], ...size, files: made, asked: false, over: false, status: null, waiting: null };
738
798
  mine.files = null; // the viewer's now: finish() removes them
739
- const died = diedSeen.has(v.id), status = diedSeen.get(v.id) ?? null;
799
+ // Heard dead with no status yet: opened as any other, and waiting for the line with it.
800
+ const pending = diedSeen.get(v.id) === PENDING;
801
+ const died = diedSeen.has(v.id) && !pending, status = died ? diedSeen.get(v.id) : null;
740
802
  const already = closedSeen.has(v.id) || died, gone = server !== s;
803
+ traced(`${v.id} ${v.pane} opened${closedSeen.has(v.id) ? ", its window already closed" : died ? `, already dead with status ${status}` : pending ? ", already dead with no status yet" : ""}${gone ? ", its server gone" : ""}`);
741
804
  settle();
742
805
  if (already || gone) {
743
806
  // Over before its id was known (it exited at once, or the server went away meanwhile):
@@ -756,6 +819,7 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
756
819
  viewer = v;
757
820
  ask(`resize-window -t ${v.id} -x ${v.cols} -y ${v.rows}`);
758
821
  fresh();
822
+ if (pending) waitStatus(v);
759
823
  }
760
824
  return { id: v.id };
761
825
  } catch (error) {
@@ -860,7 +924,7 @@ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () =
860
924
  }
861
925
  // Nothing more is said: the run is leaving. Every viewer's files go, and so do those of an open
862
926
  // under way (which then rejects with E_PANEL_ENDED and makes nothing more).
863
- for (const v of [viewer, ...closing.values()]) if (v) { v.over = true; forget(v.files); }
927
+ for (const v of [viewer, ...closing.values()]) if (v) { v.over = true; unwait(v); forget(v.files); }
864
928
  viewer = null;
865
929
  closing.clear();
866
930
  for (const under of openings) forget(under.files);