tmux-ide 2.9.22 → 2.9.24

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 (104) hide show
  1. package/bin/cli.js +3718 -7603
  2. package/package.json +3 -3
  3. package/packages/contracts/src/index.ts +1 -0
  4. package/packages/contracts/src/websocket-heartbeat.ts +41 -0
  5. package/packages/daemon/dist/command-center/automation.js +1 -1
  6. package/packages/daemon/dist/command-center/daemon-fleet-facts-observer.js +37 -5
  7. package/packages/daemon/dist/command-center/discovery.js +28 -2
  8. package/packages/daemon/dist/command-center/server.js +8 -2
  9. package/packages/daemon/dist/command-center/tmux-servers.js +12 -1
  10. package/packages/daemon/dist/doctor.js +41 -0
  11. package/packages/daemon/dist/lib/bounded-tmux-read.js +34 -12
  12. package/packages/daemon/dist/lib/daemon-embed.js +127 -63
  13. package/packages/daemon/dist/lib/daemon-stop-progress.js +58 -0
  14. package/packages/daemon/dist/lib/embedded-daemon-lifecycle.js +11 -0
  15. package/packages/daemon/dist/lib/embedded-tmux-server-owners.js +88 -12
  16. package/packages/daemon/dist/lib/headless-daemon.js +177 -10
  17. package/packages/daemon/dist/lib/home-agent-observer.js +50 -0
  18. package/packages/daemon/dist/lib/log.js +18 -1
  19. package/packages/daemon/dist/lib/machine-agents.js +18 -1
  20. package/packages/daemon/dist/lib/orphaned-control-clients.js +162 -0
  21. package/packages/daemon/dist/lib/tmux-external-interaction-observer.js +172 -28
  22. package/packages/daemon/dist/lib/tmux-native-browser.js +4 -2
  23. package/packages/daemon/dist/lib/tmux-pane-reader.js +4 -2
  24. package/packages/daemon/dist/lib/tmux-server-agent-admission.js +6 -1
  25. package/packages/daemon/dist/lib/tmux-server-owner-teardown.js +33 -0
  26. package/packages/daemon/dist/lib/tmux-server-owner.js +55 -41
  27. package/packages/daemon/dist/lib/tmux-server-owners.js +310 -20
  28. package/packages/daemon/dist/lib/tmux-server-registration.js +128 -9
  29. package/packages/daemon/dist/lib/unix-socket-authority.js +58 -3
  30. package/packages/daemon/dist/lib/workspace-pane-creation.js +10 -1
  31. package/packages/daemon/dist/lib/workspace-promotion.js +24 -3
  32. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  33. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  34. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  35. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  36. package/packages/daemon/dist/plugins/cli.js +1 -2
  37. package/packages/daemon/dist/server/pane-stream-upgrade.js +5 -1
  38. package/packages/daemon/dist/server/websocket-heartbeat.js +103 -0
  39. package/packages/daemon/dist/terminal/attachments/native-runtime.js +49 -16
  40. package/packages/daemon/dist/terminal/mirror/layout-content-rows.js +11 -0
  41. package/packages/daemon/dist/terminal/mirror/mirror-service.js +61 -3
  42. package/packages/daemon/dist/terminal/mirror/session-channel.js +11 -12
  43. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +119 -22
  44. package/packages/daemon/dist/terminal/pane-stream/runtime.js +3 -2
  45. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +23 -0
  46. package/packages/daemon/dist/terminal/protocol/stock-split-resize.js +4 -1
  47. package/packages/daemon/dist/terminal/session-runtime/registry.js +17 -0
  48. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +81 -3
  49. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +60 -3
  50. package/packages/daemon/dist/tui/mirror/runtime/application-home-agent-navigation.js +57 -4
  51. package/packages/daemon/dist/tui/mirror/runtime/application-home-agents-owner.js +18 -7
  52. package/packages/daemon/dist/tui/mirror/runtime/application-machine-agent-navigation.js +17 -0
  53. package/packages/daemon/dist/tui/mirror/runtime/application-machine-navigation.js +4 -2
  54. package/packages/daemon/dist/tui/mirror/runtime/application-terminal-interaction-controller.js +55 -14
  55. package/packages/daemon/src/command-center/automation.ts +1 -1
  56. package/packages/daemon/src/command-center/daemon-fleet-facts-observer.ts +49 -8
  57. package/packages/daemon/src/command-center/discovery.ts +35 -2
  58. package/packages/daemon/src/command-center/server.ts +22 -8
  59. package/packages/daemon/src/command-center/tmux-servers.ts +12 -1
  60. package/packages/daemon/src/doctor.ts +46 -0
  61. package/packages/daemon/src/lib/bounded-tmux-read.ts +29 -9
  62. package/packages/daemon/src/lib/daemon-embed.ts +211 -71
  63. package/packages/daemon/src/lib/daemon-stop-progress.ts +78 -0
  64. package/packages/daemon/src/lib/embedded-daemon-lifecycle.ts +12 -0
  65. package/packages/daemon/src/lib/embedded-tmux-server-owners.ts +115 -11
  66. package/packages/daemon/src/lib/headless-daemon.ts +205 -12
  67. package/packages/daemon/src/lib/home-agent-observer.ts +53 -0
  68. package/packages/daemon/src/lib/log.ts +18 -1
  69. package/packages/daemon/src/lib/machine-agents.ts +25 -1
  70. package/packages/daemon/src/lib/orphaned-control-clients.ts +215 -0
  71. package/packages/daemon/src/lib/tmux-external-interaction-observer.ts +195 -33
  72. package/packages/daemon/src/lib/tmux-native-browser.ts +4 -3
  73. package/packages/daemon/src/lib/tmux-pane-reader.ts +4 -3
  74. package/packages/daemon/src/lib/tmux-server-agent-admission.ts +6 -1
  75. package/packages/daemon/src/lib/tmux-server-owner-teardown.ts +54 -0
  76. package/packages/daemon/src/lib/tmux-server-owner.ts +60 -38
  77. package/packages/daemon/src/lib/tmux-server-owners.ts +427 -22
  78. package/packages/daemon/src/lib/tmux-server-registration.ts +155 -7
  79. package/packages/daemon/src/lib/unix-socket-authority.ts +72 -3
  80. package/packages/daemon/src/lib/workspace-pane-creation.ts +11 -1
  81. package/packages/daemon/src/lib/workspace-promotion.ts +26 -3
  82. package/packages/daemon/src/plugins/cli.ts +1 -2
  83. package/packages/daemon/src/server/pane-stream-upgrade.ts +6 -0
  84. package/packages/daemon/src/server/websocket-heartbeat.ts +135 -0
  85. package/packages/daemon/src/terminal/attachments/native-runtime.ts +79 -16
  86. package/packages/daemon/src/terminal/mirror/layout-content-rows.ts +11 -0
  87. package/packages/daemon/src/terminal/mirror/mirror-service.ts +61 -2
  88. package/packages/daemon/src/terminal/mirror/session-channel.ts +11 -14
  89. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +133 -21
  90. package/packages/daemon/src/terminal/pane-stream/runtime.ts +4 -2
  91. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +31 -0
  92. package/packages/daemon/src/terminal/protocol/stock-split-resize.ts +6 -1
  93. package/packages/daemon/src/terminal/session-runtime/registry.ts +23 -0
  94. package/packages/daemon/src/terminal/session-runtime/runtime-observability.ts +2 -0
  95. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +100 -3
  96. package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +60 -3
  97. package/packages/daemon/src/tui/mirror/runtime/application-home-agent-navigation.ts +69 -4
  98. package/packages/daemon/src/tui/mirror/runtime/application-home-agents-owner.ts +30 -13
  99. package/packages/daemon/src/tui/mirror/runtime/application-machine-agent-navigation.ts +38 -1
  100. package/packages/daemon/src/tui/mirror/runtime/application-machine-navigation.ts +7 -2
  101. package/packages/daemon/src/tui/mirror/runtime/application-root-v2.tsx +4 -4
  102. package/packages/daemon/src/tui/mirror/runtime/application-terminal-interaction-controller.ts +71 -17
  103. package/packages/daemon-client/src/direct-application-shell-transport.ts +21 -3
  104. package/packages/daemon-client/src/workspace-event-supervisor.ts +63 -2
@@ -0,0 +1,162 @@
1
+ import { execFile } from "node:child_process";
2
+ import { logger } from "./log.js";
3
+ export const ORPHAN_KILL_GRACE_MS = 500;
4
+ /** PURE. `ps -o pid=,ppid=,command=` output, one process per line. */
5
+ export function parseProcessTable(text) {
6
+ const rows = [];
7
+ for (const line of text.split("\n")) {
8
+ const match = /^\s*([0-9]+)\s+([0-9]+)\s+(.+)$/u.exec(line);
9
+ if (match)
10
+ rows.push({ pid: Number(match[1]), ppid: Number(match[2]), command: match[3] });
11
+ }
12
+ return rows;
13
+ }
14
+ /** The attach flags only this daemon's control client uses (mirrorControlAttachArgs). */
15
+ export function isTmuxIdeControlClientCommand(command) {
16
+ return (/(?:^|\s)-C(?:\s|$)/u.test(command) &&
17
+ /ignore-size,pause-after=[0-9]+,active-pane/u.test(command));
18
+ }
19
+ const withoutPrivate = (path) => path.replace(/^\/private(?=\/)/u, "");
20
+ /** PURE. Does this tmux command line address the given server? */
21
+ export function commandTargetsServer(command, selector) {
22
+ const words = command.split(/\s+/u);
23
+ for (let index = 0; index < words.length; index += 1) {
24
+ const word = words[index];
25
+ if (word === "-C")
26
+ return false;
27
+ const flag = selector.kind === "path" ? "-S" : "-L";
28
+ const value = word === flag ? words[index + 1] : word.startsWith(flag) ? word.slice(2) : null;
29
+ if (value === null || value === undefined || value === "")
30
+ continue;
31
+ return selector.kind === "path"
32
+ ? withoutPrivate(value) === withoutPrivate(selector.path)
33
+ : value === selector.name;
34
+ }
35
+ return false;
36
+ }
37
+ /** init, or a service manager that adopts orphans in its place. */
38
+ function adoptsOrphans(pid, command) {
39
+ if (pid === 1)
40
+ return true;
41
+ // The command's own name (its first word, with or without a path), never a
42
+ // word further on: a daemon run as `… --supervised launchd-user` is no manager.
43
+ return command !== null && /^(?:\S*\/)?(?:systemd|launchd|init)(?:\s|$)/u.test(command);
44
+ }
45
+ /**
46
+ * Ends tmux-ide control clients of this server whose daemon is gone. Never
47
+ * this daemon's own clients, another live daemon's, another server's, or any
48
+ * other program's. Returns the pids it ended. Failures end the pass; they
49
+ * never throw.
50
+ */
51
+ export async function evictOrphanedControlClients(io, ownPid, selector) {
52
+ let processes;
53
+ try {
54
+ processes = await io.listProcesses();
55
+ }
56
+ catch {
57
+ return [];
58
+ }
59
+ const byPid = new Map(processes.map((row) => [row.pid, row]));
60
+ const evicted = [];
61
+ for (const client of processes) {
62
+ if (client.pid <= 1 ||
63
+ client.pid === ownPid ||
64
+ client.ppid === ownPid ||
65
+ !isTmuxIdeControlClientCommand(client.command) ||
66
+ !commandTargetsServer(client.command, selector) ||
67
+ !adoptsOrphans(client.ppid, byPid.get(client.ppid)?.command ?? null))
68
+ continue;
69
+ try {
70
+ io.kill(client.pid, "SIGTERM");
71
+ await io.delay(ORPHAN_KILL_GRACE_MS);
72
+ if (io.isAlive(client.pid))
73
+ io.kill(client.pid, "SIGKILL");
74
+ evicted.push(client.pid);
75
+ }
76
+ catch {
77
+ // One client that cannot be signalled does not stop the pass.
78
+ }
79
+ }
80
+ return evicted;
81
+ }
82
+ /** The real process table and signals. */
83
+ export function orphanedControlClientIo() {
84
+ return {
85
+ listProcesses: () => new Promise((resolve, reject) => {
86
+ execFile("/bin/ps", ["-xww", "-o", "pid=,ppid=,command="], {
87
+ encoding: "utf8",
88
+ timeout: 3_000,
89
+ maxBuffer: 16 * 1024 * 1024,
90
+ env: { LC_ALL: "C", PATH: "/usr/bin:/bin" },
91
+ }, (error, stdout) => (error ? reject(error) : resolve(parseProcessTable(stdout))));
92
+ }),
93
+ kill: (pid, signal) => {
94
+ process.kill(pid, signal);
95
+ },
96
+ isAlive: (pid) => {
97
+ try {
98
+ process.kill(pid, 0);
99
+ return true;
100
+ }
101
+ catch (error) {
102
+ return error.code === "EPERM";
103
+ }
104
+ },
105
+ delay: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
106
+ };
107
+ }
108
+ export const EMPTY_SERVER_PASS_INTERVAL_MS = 10_000;
109
+ export const EMPTY_SERVER_LOG_INTERVAL_MS = 60_000;
110
+ /**
111
+ * One per owned server. Neither call is awaited by the owner, delays it or
112
+ * fails it.
113
+ * - `onOwnership`: one pass when the daemon takes the server.
114
+ * - `onTrouble`: a catalog read found the server with no sessions, or got no
115
+ * answer from a server whose socket is still there. A tmux server normally
116
+ * exits with its last session, so either it is configured to stay or it
117
+ * cannot exit. At most one pass per 10 s, and one warning per minute that
118
+ * names the state: scoped reads fail in it, and nothing else says why.
119
+ */
120
+ export function createOrphanedControlClientWatch(options) {
121
+ const io = options.io ?? orphanedControlClientIo();
122
+ const now = options.now ?? Date.now;
123
+ const fields = options.serverId ? { serverId: options.serverId } : {};
124
+ let lastPassAt = Number.NEGATIVE_INFINITY;
125
+ let lastLogAt = Number.NEGATIVE_INFINITY;
126
+ let running = null;
127
+ const pass = () => {
128
+ if (running)
129
+ return running;
130
+ lastPassAt = now();
131
+ const current = evictOrphanedControlClients(io, process.pid, options.selector)
132
+ .catch(() => [])
133
+ .then((pids) => {
134
+ if (pids.length > 0)
135
+ logger.warn("tmux-server-owners", "ended control clients a dead daemon left attached", {
136
+ ...fields,
137
+ pids,
138
+ });
139
+ return pids;
140
+ })
141
+ .finally(() => {
142
+ if (running === current)
143
+ running = null;
144
+ });
145
+ running = current;
146
+ return current;
147
+ };
148
+ return {
149
+ onOwnership: () => pass().then(() => undefined),
150
+ async onTrouble(kind) {
151
+ if (now() - lastPassAt < EMPTY_SERVER_PASS_INTERVAL_MS)
152
+ return;
153
+ const pids = await pass();
154
+ if (now() - lastLogAt < EMPTY_SERVER_LOG_INTERVAL_MS)
155
+ return;
156
+ lastLogAt = now();
157
+ logger.warn("tmux-server-owners", kind === "no-sessions"
158
+ ? "tmux server answers with no sessions"
159
+ : "tmux server does not answer its catalog", { ...fields, endedControlClients: pids.length });
160
+ },
161
+ };
162
+ }
@@ -9,20 +9,46 @@ import { getDefaultWorkspaceRegistry } from "./workspace-registry.js";
9
9
  import { AuthenticatedInternalReadVerifier, consumeInternalReadOperation, INTERNAL_READ_OPERATION_OPTION, INTERNAL_SEND_OPERATION_OPTION, } from "./tmux-interaction-options.js";
10
10
  const HOOK_MARKER = "tmux-ide-interaction-v3";
11
11
  const OWNED_HOOK_MARKER = "tmux-ide-interaction-v";
12
+ /** The retention name of one observer: the marker plus its daemon id. */
13
+ const OWNER_NAME = /tmux-ide-interaction-v3-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/u;
14
+ const OWNER_RECORD = /^retention-owner pid=([1-9][0-9]{0,9})$/u;
15
+ /** Observers of THIS process that are installed and not yet disposed. */
16
+ const liveLocalObservers = new Set();
17
+ function processIsAlive(pid) {
18
+ try {
19
+ process.kill(pid, 0);
20
+ return true;
21
+ }
22
+ catch (error) {
23
+ return error.code !== "ESRCH";
24
+ }
25
+ }
12
26
  const FIELD_SEPARATOR = "|tmux-ide-input-field-v1|";
13
27
  const EVENT_SEPARATOR = "|tmux-ide-input-event-v1|";
14
28
  const RUNTIME_PANE = /^%[0-9]+$/u;
15
29
  const RETRY_MS = 1_000;
16
30
  export const DEFAULT_HOOK_HEALTHCHECK_SCHEDULE = Object.freeze({
17
31
  baseMs: 1_000,
18
- maxMs: 30_000,
32
+ // A healthy idle server is checked 12 times an hour, not 120. Since daemons
33
+ // no longer remove each other's hooks, only a user action (a config reload,
34
+ // `set-hook -gu`) can take them away; that is then noticed within 5 minutes.
35
+ maxMs: 300_000,
19
36
  });
20
- /** Pure cadence rule: healthy checks double the wait up to the cap; anything else resets it. */
21
- export function nextHookHealthcheckDelay(previousMs, outcome, schedule = DEFAULT_HOOK_HEALTHCHECK_SCHEDULE) {
37
+ /**
38
+ * Pure cadence rule: healthy checks double the wait up to the cap; a repair or
39
+ * failure resets it to the base. A check that is unhealthy again right after
40
+ * one that was (`consecutiveUnhealthy` of 2 or more) backs off as well: on a
41
+ * tmux server that is shutting down but cannot exit, every repair "succeeds"
42
+ * and is gone at the next check, and the base cadence then cost about 400 tmux
43
+ * calls a minute for as long as the server lingered.
44
+ */
45
+ export function nextHookHealthcheckDelay(previousMs, outcome, schedule = DEFAULT_HOOK_HEALTHCHECK_SCHEDULE, consecutiveUnhealthy = 1) {
22
46
  const base = Math.max(1, Math.floor(schedule.baseMs));
23
47
  const max = Math.max(base, Math.floor(schedule.maxMs));
24
- if (outcome !== "healthy")
25
- return base;
48
+ if (outcome !== "healthy") {
49
+ const streak = Math.max(1, Math.min(32, Math.floor(consecutiveUnhealthy) || 1));
50
+ return Math.min(base * 2 ** (streak - 1), max);
51
+ }
26
52
  const previous = Number.isFinite(previousMs) ? Math.max(base, Math.floor(previousMs)) : base;
27
53
  return Math.min(previous * 2, max);
28
54
  }
@@ -63,14 +89,54 @@ export function tmuxInteractionWaitCommand(bufferName, channel) {
63
89
  }
64
90
  function defaultWaiter(authority, bufferName) {
65
91
  const prefix = socketArguments(authority);
66
- return (channel, signal) => new Promise((resolve, reject) => {
67
- execFile(authority.executablePath, [...prefix, ...tmuxInteractionWaitCommand(bufferName, channel)], { signal, encoding: "utf8", windowsHide: true }, (error) => {
68
- if (!error)
69
- resolve();
70
- else if (signal.aborted)
92
+ return (channel, signal) => waitForBlockingTmuxClient(authority.executablePath, [...prefix, ...tmuxInteractionWaitCommand(bufferName, channel)], signal);
93
+ }
94
+ export const BLOCKING_CLIENT_KILL_GRACE_MS = 250;
95
+ /**
96
+ * Run a tmux client that blocks until signalled (`wait-for`). It has no
97
+ * deadline by design, so cancellation must not depend on the client's
98
+ * cooperation: TERM on abort, KILL after a grace, and settle when the process
99
+ * exits. Observer disposal awaits this, and with it every daemon stop (#839).
100
+ */
101
+ export function waitForBlockingTmuxClient(executable, args, signal, killGraceMs = BLOCKING_CLIENT_KILL_GRACE_MS) {
102
+ if (signal.aborted)
103
+ return Promise.resolve();
104
+ return new Promise((resolve, reject) => {
105
+ let settled = false;
106
+ let failure = null;
107
+ let escalation = null;
108
+ const child = execFile(executable, [...args], { encoding: "utf8", windowsHide: true }, (error) => {
109
+ failure ??= error;
110
+ });
111
+ const settle = () => {
112
+ if (settled)
113
+ return;
114
+ settled = true;
115
+ if (escalation)
116
+ clearTimeout(escalation);
117
+ signal.removeEventListener("abort", cancel);
118
+ if (!failure || signal.aborted)
71
119
  resolve();
72
120
  else
73
- reject(error);
121
+ reject(failure);
122
+ };
123
+ const cancel = () => {
124
+ if (escalation)
125
+ return;
126
+ child.kill("SIGTERM");
127
+ escalation = setTimeout(() => child.kill("SIGKILL"), killGraceMs);
128
+ };
129
+ signal.addEventListener("abort", cancel, { once: true });
130
+ child.once("error", (error) => {
131
+ failure ??= error;
132
+ settle();
133
+ });
134
+ // "exit", not "close": a lingering holder of the pipes must not keep the
135
+ // waiter, and so the stop, pending after the client itself is gone.
136
+ child.once("exit", (code, exitSignal) => {
137
+ if (code !== 0 && !failure)
138
+ failure = new Error(`tmux wait client ended with ${exitSignal ?? `code ${String(code)}`}`);
139
+ settle();
74
140
  });
75
141
  });
76
142
  }
@@ -157,15 +223,16 @@ export function parseTmuxInputHookRecords(raw) {
157
223
  }
158
224
  return records;
159
225
  }
160
- function hookIndexes(output, hookName) {
226
+ /** Every tmux-ide hook of this array, with the observer it belongs to (null: a legacy hook). */
227
+ function ownedHooks(output, hookName) {
161
228
  const row = new RegExp(`^${hookName}\\[([0-9]+)\\]\\s+(.+)$`, "u");
162
- const indexes = [];
229
+ const hooks = [];
163
230
  for (const line of output.split("\n")) {
164
231
  const match = row.exec(line);
165
232
  if (match && match[2].includes(OWNED_HOOK_MARKER))
166
- indexes.push(Number(match[1]));
233
+ hooks.push({ index: Number(match[1]), owner: OWNER_NAME.exec(match[2])?.[0] ?? null });
167
234
  }
168
- return indexes;
235
+ return hooks;
169
236
  }
170
237
  /**
171
238
  * Event-driven adapter from tmux's native send/capture hooks into the semantic
@@ -191,6 +258,8 @@ export class TmuxExternalInteractionObserver {
191
258
  #healthcheckSchedule;
192
259
  #healthcheckDelayMs;
193
260
  #lastHealthcheckOutcome = "failed";
261
+ /** Scheduled checks in a row that did not find the hooks intact. */
262
+ #unhealthyChecks = 0;
194
263
  #onAvailability;
195
264
  #onGap;
196
265
  #tmuxWork = Promise.resolve();
@@ -198,7 +267,9 @@ export class TmuxExternalInteractionObserver {
198
267
  #diagnostics;
199
268
  #diagnosticActiveOperations = 0;
200
269
  #authenticatedInternalReads;
270
+ #ownerProcess;
201
271
  constructor(options) {
272
+ this.#ownerProcess = options.ownerProcess ?? { pid: process.pid, isAlive: processIsAlive };
202
273
  this.#daemonInstanceId = options.daemonInstanceId;
203
274
  this.#healthcheckSchedule = Object.freeze({
204
275
  baseMs: options.healthcheck?.baseMs ?? DEFAULT_HOOK_HEALTHCHECK_SCHEDULE.baseMs,
@@ -264,6 +335,7 @@ export class TmuxExternalInteractionObserver {
264
335
  });
265
336
  if (!isTmuxServerUnavailable(error)) {
266
337
  this.#active = false;
338
+ liveLocalObservers.delete(this.#bufferName);
267
339
  throw error;
268
340
  }
269
341
  // A configless first run legitimately has no tmux server yet. Keep the
@@ -277,6 +349,7 @@ export class TmuxExternalInteractionObserver {
277
349
  await this.#removeOwnedHooks();
278
350
  await this.#deleteRetention();
279
351
  });
352
+ liveLocalObservers.delete(this.#bufferName);
280
353
  throw new Error("tmux external interaction observer was disposed during startup");
281
354
  }
282
355
  this.#loop = this.#run();
@@ -312,9 +385,10 @@ export class TmuxExternalInteractionObserver {
312
385
  this.#reportGap("hook-repair-failed");
313
386
  outcome = "failed";
314
387
  }
388
+ this.#unhealthyChecks = outcome === "healthy" ? 0 : this.#unhealthyChecks + 1;
315
389
  // A signal-path reset that landed during this check wins over the outcome.
316
390
  if (this.#healthcheckDelayMs === delayBefore) {
317
- this.#healthcheckDelayMs = nextHookHealthcheckDelay(delayBefore, outcome, this.#healthcheckSchedule);
391
+ this.#healthcheckDelayMs = nextHookHealthcheckDelay(delayBefore, outcome, this.#healthcheckSchedule, this.#unhealthyChecks);
318
392
  }
319
393
  if (this.#hookHealthcheck === null)
320
394
  this.#scheduleHealthcheck();
@@ -332,6 +406,8 @@ export class TmuxExternalInteractionObserver {
332
406
  this.#diagnostics = diagnostics;
333
407
  }
334
408
  async dispose() {
409
+ // From here on another observer of this process may clear what this one leaves.
410
+ liveLocalObservers.delete(this.#bufferName);
335
411
  if (!this.#active && !this.#loop && !this.#starting && !this.#installed)
336
412
  return;
337
413
  const starting = this.#starting;
@@ -352,12 +428,21 @@ export class TmuxExternalInteractionObserver {
352
428
  return this.#serializeTmux(() => this.#install(this.#abort.signal));
353
429
  }
354
430
  async #install(signal) {
355
- await this.#removeOwnedHooks(signal);
356
- await this.#deleteOwnedBuffers(signal);
431
+ const others = await this.#liveOtherObservers(signal);
432
+ await this.#removeOwnedHooks(signal, others);
433
+ await this.#deleteOwnedBuffers(signal, others);
357
434
  signal?.throwIfAborted();
358
- // The small named buffer indexes retention options for crash cleanup;
359
- // event data lives only in bounded options, never in this buffer.
360
- await this.#io.runTmux(["set-buffer", "-b", this.#bufferName, "retention-owner"], signal);
435
+ liveLocalObservers.add(this.#bufferName);
436
+ // The small named buffer indexes retention options for crash cleanup and
437
+ // names the owning process: another daemon on this server leaves these
438
+ // hooks alone while that process lives, and clears them once it is gone.
439
+ // Event data lives only in bounded options, never in this buffer.
440
+ await this.#io.runTmux([
441
+ "set-buffer",
442
+ "-b",
443
+ this.#bufferName,
444
+ `retention-owner pid=${String(this.#ownerProcess.pid)}`,
445
+ ], signal);
361
446
  const hook = (operationKind, markerOption, consumeMarker) => {
362
447
  // Reject arbitrary option text before expansion into a tmux command.
363
448
  // Bound markers at the producer, including across multibyte input.
@@ -412,11 +497,20 @@ export class TmuxExternalInteractionObserver {
412
497
  const work = this.#serializeTmux(async () => {
413
498
  const finish = this.#beginDiagnostic("healthcheck");
414
499
  try {
415
- if (await this.#ownedHooksPresent(this.#abort.signal)) {
500
+ const hooks = await this.#ownedHooksPresent(this.#abort.signal);
501
+ if (hooks === "present") {
416
502
  this.#lastHealthcheckOutcome = "healthy";
417
503
  finish(true);
418
504
  return;
419
505
  }
506
+ if (hooks === "unknown") {
507
+ // The check could not be made (tmux timed out or could not be
508
+ // started). That says nothing about the hooks: leave them, report
509
+ // no gap, and ask again at the base cadence.
510
+ this.#lastHealthcheckOutcome = "failed";
511
+ finish(false);
512
+ return;
513
+ }
420
514
  // Hooks that were installed and are now gone dropped every interaction
421
515
  // since their removal; the repair restores future observation only.
422
516
  if (this.#installed)
@@ -611,7 +705,49 @@ export class TmuxExternalInteractionObserver {
611
705
  ...(record.capturedTarget ? { capturedTarget: record.capturedTarget } : {}),
612
706
  });
613
707
  }
614
- async #removeOwnedHooks(signal) {
708
+ /**
709
+ * The other observers on this tmux server whose owner is alive: another
710
+ * daemon process, or another owner generation of this one. Their hooks,
711
+ * buffers and options are not ours to remove. Null when the server would
712
+ * not say; then nothing foreign is touched at all.
713
+ */
714
+ async #liveOtherObservers(signal) {
715
+ let output;
716
+ try {
717
+ output = await this.#io.runTmux(["list-buffers", "-F", "#{buffer_name}"], signal);
718
+ }
719
+ catch {
720
+ return null;
721
+ }
722
+ const live = new Set();
723
+ for (const name of output.split("\n")) {
724
+ if (name === this.#bufferName || OWNER_NAME.exec(name)?.[0] !== name)
725
+ continue;
726
+ let record;
727
+ try {
728
+ record = (await this.#io.runTmux(["show-buffer", "-b", name], signal)).trim();
729
+ }
730
+ catch {
731
+ continue;
732
+ }
733
+ const pid = Number(OWNER_RECORD.exec(record)?.[1]);
734
+ // A marker without a pid was written by an older daemon; as before, it is cleared.
735
+ if (!Number.isSafeInteger(pid))
736
+ continue;
737
+ if (pid === this.#ownerProcess.pid
738
+ ? liveLocalObservers.has(name)
739
+ : this.#ownerProcess.isAlive(pid))
740
+ live.add(name);
741
+ }
742
+ return live;
743
+ }
744
+ /**
745
+ * Remove this observer's hooks, and those nobody alive owns (a crashed
746
+ * daemon's, legacy ones). Never another live observer's: two daemons on one
747
+ * tmux server would otherwise keep taking each other's hooks away.
748
+ */
749
+ async #removeOwnedHooks(signal, others) {
750
+ const live = others === undefined ? await this.#liveOtherObservers(signal) : others;
615
751
  for (const hookName of ["after-send-keys", "after-capture-pane"]) {
616
752
  let output;
617
753
  try {
@@ -620,7 +756,9 @@ export class TmuxExternalInteractionObserver {
620
756
  catch {
621
757
  continue;
622
758
  }
623
- for (const index of hookIndexes(output, hookName)) {
759
+ for (const { index, owner } of ownedHooks(output, hookName)) {
760
+ if (owner !== this.#bufferName && (live === null || (owner !== null && live.has(owner))))
761
+ continue;
624
762
  try {
625
763
  await this.#io.runTmux(["set-hook", "-gu", `${hookName}[${index}]`], signal);
626
764
  }
@@ -639,10 +777,12 @@ export class TmuxExternalInteractionObserver {
639
777
  output = await this.#io.runTmux(["show-hooks", "-g", "after-send-keys", ";", "show-hooks", "-g", "after-capture-pane"], signal);
640
778
  }
641
779
  catch {
642
- return false;
780
+ return "unknown";
643
781
  }
644
- return (ownedHookInstalled(output, "after-send-keys", this.#bufferName) &&
645
- ownedHookInstalled(output, "after-capture-pane", this.#bufferName));
782
+ return ownedHookInstalled(output, "after-send-keys", this.#bufferName) &&
783
+ ownedHookInstalled(output, "after-capture-pane", this.#bufferName)
784
+ ? "present"
785
+ : "missing";
646
786
  }
647
787
  get available() {
648
788
  return this.#installed;
@@ -687,7 +827,9 @@ export class TmuxExternalInteractionObserver {
687
827
  await this.#deleteOption(`${option}-drain`);
688
828
  await this.#deleteBuffer(this.#bufferName);
689
829
  }
690
- async #deleteOwnedBuffers(signal) {
830
+ async #deleteOwnedBuffers(signal, live) {
831
+ if (live === null)
832
+ return;
691
833
  let output;
692
834
  try {
693
835
  output = await this.#io.runTmux(["list-buffers", "-F", "#{buffer_name}"], signal);
@@ -698,6 +840,8 @@ export class TmuxExternalInteractionObserver {
698
840
  for (const name of output.split("\n")) {
699
841
  if (!name.startsWith(OWNED_HOOK_MARKER) || name === this.#bufferName)
700
842
  continue;
843
+ if (live.has(name))
844
+ continue;
701
845
  if (/^[A-Za-z0-9._-]{1,256}$/u.test(name)) {
702
846
  await this.#deleteOption(tmuxInteractionOption(name), signal);
703
847
  await this.#deleteOption(`${tmuxInteractionOption(name)}-drain`, signal);
@@ -44,7 +44,9 @@ export function createNativeBrowserResolver(options) {
44
44
  if (matches.length !== 1)
45
45
  throw new NativeBrowserUnavailable();
46
46
  const pane = { ...matches[0] };
47
- if (!pane.nativePaneBirthId || !/^%[0-9]+$/u.test(pane.runtimePaneId))
47
+ // A stock tmux server has no pane birth id; it reads empty there, both times.
48
+ const paneBirth = pane.nativePaneBirthId ?? "";
49
+ if (!/^%[0-9]+$/u.test(pane.runtimePaneId))
48
50
  throw new NativeBrowserUnavailable();
49
51
  const observe = async () => {
50
52
  const raw = await options.run([
@@ -58,7 +60,7 @@ export function createNativeBrowserResolver(options) {
58
60
  if (raw.length > 8192)
59
61
  throw new NativeBrowserUnavailable();
60
62
  const [semantic, birth, endpoint] = raw.trimEnd().split("\t").map(decodeTmuxArgument);
61
- if (semantic !== target.semanticPaneId || birth !== pane.nativePaneBirthId)
63
+ if (semantic !== target.semanticPaneId || birth !== paneBirth)
62
64
  throw new NativeBrowserUnavailable();
63
65
  const parsed = NativeBrowserEndpointSchema.parse(JSON.parse(endpoint ?? "null"));
64
66
  if (parsed.pane !== pane.runtimePaneId)
@@ -49,7 +49,9 @@ export function createPaneReaderResolver(options) {
49
49
  if (matches.length !== 1)
50
50
  throw new PaneReaderUnavailable();
51
51
  const pane = { ...matches[0] };
52
- if (!pane.nativePaneBirthId || !/^%[0-9]+$/u.test(pane.runtimePaneId))
52
+ // A stock tmux server has no pane birth id; it reads empty there, both times.
53
+ const paneBirth = pane.nativePaneBirthId ?? "";
54
+ if (!/^%[0-9]+$/u.test(pane.runtimePaneId))
53
55
  throw new PaneReaderUnavailable();
54
56
  const observe = async () => {
55
57
  const raw = await options.run([
@@ -66,7 +68,7 @@ export function createPaneReaderResolver(options) {
66
68
  .trimEnd()
67
69
  .split("\t")
68
70
  .map(decodeTmuxArgument);
69
- if (semantic !== target.semanticPaneId || birth !== pane.nativePaneBirthId)
71
+ if (semantic !== target.semanticPaneId || birth !== paneBirth)
70
72
  throw new PaneReaderUnavailable();
71
73
  const reader = readerOption(option ?? "", panePid ?? "", options.alive);
72
74
  if (!reader)
@@ -30,12 +30,17 @@ export async function captureAgentAdmission(run, session, observed) {
30
30
  id !== session.id ||
31
31
  !/^@\d+$/.test(window) ||
32
32
  !/^%\d+$/.test(pane) ||
33
- !/^[1-9]\d*$/.test(birth))
33
+ !/^(?:[1-9]\d*)?$/.test(birth))
34
34
  throw new Error("Agent native identity is unavailable");
35
35
  return { window: window, pane: pane, birth: birth, stamp: stamp };
36
36
  });
37
37
  if (rows.length > 512)
38
38
  throw new Error("Agent inventory exceeds admission bounds");
39
+ // A stock tmux server has no pane birth id: every row reads empty. Its pane
40
+ // ids are never reused while it runs, and each command already checks the
41
+ // session id and creation time, so the pane and window ids fence the lifetime.
42
+ if (rows.some((row) => row.birth === "") && rows.some((row) => row.birth !== ""))
43
+ throw new Error("Agent native identity is unavailable");
39
44
  return rows;
40
45
  };
41
46
  const initial = await scan();
@@ -0,0 +1,33 @@
1
+ import { paneStreamCloseForRetirement, } from "../terminal/pane-stream/pane-stream-websocket.js";
2
+ /**
3
+ * One tmux server owner's teardown. The pane streams hear first, and hear why:
4
+ * a retired owner under a live daemon means "reconnect now", not "the daemon
5
+ * is shutting down" (#840). Every later step runs even if an earlier one
6
+ * fails; the failures are reported together. Idempotent.
7
+ */
8
+ export function createNativeOwnerTeardown(parts) {
9
+ let teardown = null;
10
+ return (retirement) => {
11
+ if (teardown)
12
+ return teardown;
13
+ parts.markRetired();
14
+ const streamsClosed = parts.paneStreams.dispose(paneStreamCloseForRetirement(retirement));
15
+ streamsClosed.catch(() => undefined);
16
+ const steps = parts.begin(streamsClosed);
17
+ const track = parts.track ?? (async (_step, work) => await work());
18
+ teardown = (async () => {
19
+ const failures = [];
20
+ for (const [step, close] of steps) {
21
+ try {
22
+ await track(`owner:${parts.serverId}:${step}`, close);
23
+ }
24
+ catch (error) {
25
+ failures.push(error);
26
+ }
27
+ }
28
+ if (failures.length)
29
+ throw new AggregateError(failures, "Tmux server owner retirement failed");
30
+ })();
31
+ return teardown;
32
+ };
33
+ }