tmux-ide 2.9.22 → 2.9.23

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 (85) hide show
  1. package/bin/cli.js +3434 -7568
  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 +1 -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 +111 -55
  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/log.js +18 -1
  18. package/packages/daemon/dist/lib/tmux-external-interaction-observer.js +140 -19
  19. package/packages/daemon/dist/lib/tmux-native-browser.js +4 -2
  20. package/packages/daemon/dist/lib/tmux-pane-reader.js +4 -2
  21. package/packages/daemon/dist/lib/tmux-server-agent-admission.js +6 -1
  22. package/packages/daemon/dist/lib/tmux-server-owner-teardown.js +33 -0
  23. package/packages/daemon/dist/lib/tmux-server-owner.js +29 -37
  24. package/packages/daemon/dist/lib/tmux-server-owners.js +310 -20
  25. package/packages/daemon/dist/lib/tmux-server-registration.js +128 -9
  26. package/packages/daemon/dist/lib/unix-socket-authority.js +58 -3
  27. package/packages/daemon/dist/lib/workspace-pane-creation.js +10 -1
  28. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  29. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  30. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  31. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  32. package/packages/daemon/dist/plugins/cli.js +1 -2
  33. package/packages/daemon/dist/server/pane-stream-upgrade.js +5 -1
  34. package/packages/daemon/dist/server/websocket-heartbeat.js +103 -0
  35. package/packages/daemon/dist/terminal/attachments/native-runtime.js +32 -14
  36. package/packages/daemon/dist/terminal/mirror/layout-content-rows.js +11 -0
  37. package/packages/daemon/dist/terminal/mirror/mirror-service.js +61 -3
  38. package/packages/daemon/dist/terminal/mirror/session-channel.js +9 -11
  39. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +111 -22
  40. package/packages/daemon/dist/terminal/pane-stream/runtime.js +3 -2
  41. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +23 -0
  42. package/packages/daemon/dist/terminal/protocol/stock-split-resize.js +4 -1
  43. package/packages/daemon/dist/terminal/session-runtime/registry.js +17 -0
  44. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +81 -3
  45. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +60 -3
  46. package/packages/daemon/src/command-center/automation.ts +1 -1
  47. package/packages/daemon/src/command-center/daemon-fleet-facts-observer.ts +49 -8
  48. package/packages/daemon/src/command-center/discovery.ts +35 -2
  49. package/packages/daemon/src/command-center/server.ts +22 -8
  50. package/packages/daemon/src/command-center/tmux-servers.ts +1 -1
  51. package/packages/daemon/src/doctor.ts +46 -0
  52. package/packages/daemon/src/lib/bounded-tmux-read.ts +29 -9
  53. package/packages/daemon/src/lib/daemon-embed.ts +159 -64
  54. package/packages/daemon/src/lib/daemon-stop-progress.ts +78 -0
  55. package/packages/daemon/src/lib/embedded-daemon-lifecycle.ts +12 -0
  56. package/packages/daemon/src/lib/embedded-tmux-server-owners.ts +115 -11
  57. package/packages/daemon/src/lib/headless-daemon.ts +205 -12
  58. package/packages/daemon/src/lib/log.ts +18 -1
  59. package/packages/daemon/src/lib/tmux-external-interaction-observer.ts +163 -25
  60. package/packages/daemon/src/lib/tmux-native-browser.ts +4 -3
  61. package/packages/daemon/src/lib/tmux-pane-reader.ts +4 -3
  62. package/packages/daemon/src/lib/tmux-server-agent-admission.ts +6 -1
  63. package/packages/daemon/src/lib/tmux-server-owner-teardown.ts +54 -0
  64. package/packages/daemon/src/lib/tmux-server-owner.ts +32 -35
  65. package/packages/daemon/src/lib/tmux-server-owners.ts +427 -22
  66. package/packages/daemon/src/lib/tmux-server-registration.ts +155 -7
  67. package/packages/daemon/src/lib/unix-socket-authority.ts +72 -3
  68. package/packages/daemon/src/lib/workspace-pane-creation.ts +11 -1
  69. package/packages/daemon/src/plugins/cli.ts +1 -2
  70. package/packages/daemon/src/server/pane-stream-upgrade.ts +6 -0
  71. package/packages/daemon/src/server/websocket-heartbeat.ts +135 -0
  72. package/packages/daemon/src/terminal/attachments/native-runtime.ts +58 -14
  73. package/packages/daemon/src/terminal/mirror/layout-content-rows.ts +11 -0
  74. package/packages/daemon/src/terminal/mirror/mirror-service.ts +61 -2
  75. package/packages/daemon/src/terminal/mirror/session-channel.ts +9 -13
  76. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +125 -21
  77. package/packages/daemon/src/terminal/pane-stream/runtime.ts +4 -2
  78. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +31 -0
  79. package/packages/daemon/src/terminal/protocol/stock-split-resize.ts +6 -1
  80. package/packages/daemon/src/terminal/session-runtime/registry.ts +23 -0
  81. package/packages/daemon/src/terminal/session-runtime/runtime-observability.ts +2 -0
  82. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +100 -3
  83. package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +60 -3
  84. package/packages/daemon-client/src/direct-application-shell-transport.ts +21 -3
  85. package/packages/daemon-client/src/workspace-event-supervisor.ts +63 -2
@@ -4,7 +4,34 @@ import { canonicalDaemonUrl, matchesCanonicalDaemonPredecessor, getCanonicalDaem
4
4
  import { DAEMON_WIRE_PROTOCOL_VERSION, isDaemonWireProtocolCompatible, } from "@tmux-ide/contracts";
5
5
  import { startEmbeddedDaemon, } from "./daemon-embed.js";
6
6
  import { DaemonStartupError, IdeError } from "./errors.js";
7
+ import { logger, reserveStdoutForProtocol } from "./log.js";
7
8
  import { generateAuthToken } from "./auth-token.js";
9
+ /**
10
+ * A SIGTERM or SIGINT is a promise to the supervisor that this process ends.
11
+ * A teardown that has not finished by then is abandoned: the daemon says what
12
+ * was still open, withdraws daemon.json and exits non-zero (#839).
13
+ */
14
+ export const SIGNAL_STOP_DEADLINE_MS = 10_000;
15
+ /**
16
+ * A slow stop that still completes teardown steps is not hung: the deadline
17
+ * above counts from the last step that settled, and this bounds the whole
18
+ * stop. So a teardown that hangs exits 10 s after its last progress, and one
19
+ * that keeps moving exits at 25 s at the latest. That stays under the 30 s the
20
+ * launchd and systemd units grant before they kill the process themselves.
21
+ */
22
+ export const SIGNAL_STOP_MAX_MS = 25_000;
23
+ export const SIGNAL_STOP_TIMEOUT_EXIT_CODE = 1;
24
+ function activeResourceCounts() {
25
+ const counts = {};
26
+ try {
27
+ for (const name of process.getActiveResourcesInfo())
28
+ counts[name] = (counts[name] ?? 0) + 1;
29
+ }
30
+ catch {
31
+ /* Diagnostics only. */
32
+ }
33
+ return counts;
34
+ }
8
35
  const defaultDependencies = {
9
36
  inspectCanonicalDaemonInfo: prepareCanonicalDaemonInfoForBootstrap,
10
37
  isCanonicalDaemonAlive,
@@ -190,7 +217,11 @@ export async function runHeadlessDaemon(options = {}, deps = defaultDependencies
190
217
  tmuxServerIntent: options.tmuxServerIntent === undefined ? resolveTmuxServerIntent() : options.tmuxServerIntent,
191
218
  };
192
219
  let restoreTmuxWorkspaces = false;
193
- const lifecycle = {};
220
+ // With --json, stdout is the status document for whoever started the
221
+ // daemon; log records, also warnings and "stream closed", go to stderr.
222
+ if (options.json === true)
223
+ reserveStdoutForProtocol();
224
+ const lifecycle = { generations: 0, startReason: "initial" };
194
225
  while (true) {
195
226
  const result = await runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces, lifecycle);
196
227
  if (result !== "restart")
@@ -199,19 +230,111 @@ export async function runHeadlessDaemon(options = {}, deps = defaultDependencies
199
230
  }
200
231
  }
201
232
  async function runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces, lifecycle) {
202
- const port = parsePort(lifecycle.restart?.port ?? options.port);
233
+ const requestedPort = parsePort(lifecycle.restart?.port ?? options.port);
234
+ // Nobody asked for a port: prefer the one the previous generation had.
235
+ let port = requestedPort ?? lifecycle.lastPort;
236
+ const generation = (lifecycle.generations += 1);
237
+ const startReason = lifecycle.startReason;
238
+ const generationStartedAt = performance.now();
203
239
  let restartRequested = false;
204
240
  let stopStarted = false;
205
241
  let handle = null;
206
242
  let signalRequested = false;
207
- const requestStop = () => {
243
+ /** What asked this generation to retire; logged with the timings. */
244
+ let retireTrigger = null;
245
+ const deadlineMs = deps.signalStopDeadlineMs ?? SIGNAL_STOP_DEADLINE_MS;
246
+ let deadlineTimer = null;
247
+ let rejectDeadline;
248
+ const deadlineExceeded = new Promise((_resolve, reject) => {
249
+ rejectDeadline = reject;
250
+ });
251
+ deadlineExceeded.catch(() => undefined);
252
+ const maxMs = Math.max(deadlineMs, deps.signalStopMaxMs ?? SIGNAL_STOP_MAX_MS);
253
+ let signalledAt = 0;
254
+ let lastProgress = "";
255
+ let lastProgressAt = 0;
256
+ const readStop = () => {
257
+ try {
258
+ return handle?.stopDiagnostics?.() ?? null;
259
+ }
260
+ catch {
261
+ return null; // Diagnostics never block the exit.
262
+ }
263
+ };
264
+ const progressOf = (stop) => stop ? `${stop.completed.length}:${stop.stepsSettled}` : "";
265
+ const abandonStop = (signal, stop) => {
266
+ const now = performance.now();
267
+ logger.error("daemon-lifecycle", "stop missed the signal deadline; exiting anyway", {
268
+ signal,
269
+ trigger: retireTrigger,
270
+ deadlineMs,
271
+ maxMs,
272
+ waitedMs: Math.round(now - signalledAt),
273
+ sinceLastProgressMs: Math.round(now - lastProgressAt),
274
+ generation,
275
+ startReason,
276
+ generationInstanceId: handle?.instanceId ?? null,
277
+ phase: !handle ? "starting" : stopStarted ? "stopping" : "running",
278
+ stuckStage: stop?.stage ?? null,
279
+ stuckStageMs: stop?.stageMs ?? null,
280
+ openSteps: stop?.openSteps ?? [],
281
+ stepsSettled: stop?.stepsSettled ?? 0,
282
+ completedStages: stop?.completed ?? [],
283
+ activeResources: activeResourceCounts(),
284
+ });
285
+ try {
286
+ handle?.abandon?.();
287
+ }
288
+ catch {
289
+ /* The exit below still ends the owner. */
290
+ }
291
+ (deps.exit ?? ((code) => process.exit(code)))(SIGNAL_STOP_TIMEOUT_EXIT_CODE);
292
+ rejectDeadline(new IdeError(`Daemon stop did not finish within its deadline after ${signal}`, {
293
+ code: "DAEMON_STOP_TIMEOUT",
294
+ exitCode: SIGNAL_STOP_TIMEOUT_EXIT_CODE,
295
+ }));
296
+ };
297
+ /** Looked at a few times per deadline: has the teardown moved, and how long has it been? */
298
+ const watchStop = (signal) => {
299
+ const stop = readStop();
300
+ const now = performance.now();
301
+ const progress = progressOf(stop);
302
+ if (progress !== lastProgress) {
303
+ lastProgress = progress;
304
+ lastProgressAt = now;
305
+ }
306
+ if (now - lastProgressAt < deadlineMs && now - signalledAt < maxMs)
307
+ return;
308
+ if (deadlineTimer)
309
+ clearInterval(deadlineTimer);
310
+ abandonStop(signal, stop);
311
+ };
312
+ /**
313
+ * Start the watch over a stop. A signal starts it, and so does a restart in
314
+ * place: a restart whose teardown hangs would otherwise leave a process that
315
+ * serves nothing and waits for ever, with no signal to end it.
316
+ * Armed once; repeating the signal buys no time.
317
+ */
318
+ const watchThisStop = (cause) => {
319
+ if (deadlineTimer)
320
+ return;
321
+ signalledAt = lastProgressAt = performance.now();
322
+ lastProgress = progressOf(readStop());
323
+ // Deliberately not unref'd: a hung teardown must not outlive the deadline.
324
+ deadlineTimer = setInterval(() => watchStop(cause), Math.max(1, Math.min(1_000, Math.floor(deadlineMs / 8))));
325
+ };
326
+ const requestStop = (signal) => {
208
327
  signalRequested = true;
328
+ retireTrigger ??= `signal:${signal}`;
329
+ watchThisStop(signal);
209
330
  if (handle)
210
331
  void handle.stop().catch(() => undefined);
211
332
  };
212
- deps.onSignal("SIGINT", requestStop);
213
- deps.onSignal("SIGTERM", requestStop);
214
- try {
333
+ const onSigint = () => requestStop("SIGINT");
334
+ const onSigterm = () => requestStop("SIGTERM");
335
+ deps.onSignal("SIGINT", onSigint);
336
+ deps.onSignal("SIGTERM", onSigterm);
337
+ const runGeneration = async () => {
215
338
  let existing;
216
339
  try {
217
340
  existing = await findLiveCanonicalDaemon(deps, options, lifecycle.predecessor);
@@ -256,6 +379,8 @@ async function runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces,
256
379
  return;
257
380
  lifecycle.restart = request;
258
381
  restartRequested = true;
382
+ retireTrigger ??= `restart-request:${"kind" in request ? request.kind : "settings"}`;
383
+ watchThisStop("restart");
259
384
  await handle.stop();
260
385
  },
261
386
  localBypassToken: generateAuthToken(),
@@ -265,6 +390,19 @@ async function runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces,
265
390
  });
266
391
  }
267
392
  catch (error) {
393
+ // The remembered port is a preference, not a requirement: if the new
394
+ // generation cannot start on it, it starts on a free one as before.
395
+ if (requestedPort === undefined && port !== undefined) {
396
+ logger.warn("daemon-lifecycle", "could not keep the previous port; picking a free one", {
397
+ generation,
398
+ port,
399
+ error: error instanceof Error ? error.message.slice(0, 200) : String(error),
400
+ });
401
+ port = undefined;
402
+ lifecycle.lastPort = undefined;
403
+ startAttempt -= 1;
404
+ continue;
405
+ }
268
406
  // Another process may hold the complete startup claim before its
269
407
  // daemon.json and endpoints are visible. Wait for that exact winner;
270
408
  // if it dies before publication, retry the claim once.
@@ -296,9 +434,19 @@ async function runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces,
296
434
  const originalStop = handle.stop.bind(handle);
297
435
  const mutableHandle = handle;
298
436
  mutableHandle.stop = async (stopOptions) => {
437
+ if (!stopStarted) {
438
+ retireTrigger ??= "stop-requested";
439
+ // An ordinary stop is routine (debug); an in-place restart is not (info).
440
+ logger[restartRequested && !signalRequested ? "info" : "debug"]("daemon-lifecycle", "generation retiring", {
441
+ generation,
442
+ generationInstanceId: handle?.instanceId ?? null,
443
+ trigger: retireTrigger,
444
+ uptimeMs: Math.round(performance.now() - generationStartedAt),
445
+ });
446
+ }
299
447
  stopStarted = true;
300
448
  try {
301
- await originalStop(stopOptions);
449
+ await originalStop(restartRequested && !signalRequested ? { ...stopOptions, restarting: true } : stopOptions);
302
450
  if (restartRequested && !signalRequested && options.supervisionId && ownedPublication)
303
451
  lifecycle.predecessor = ownedPublication;
304
452
  }
@@ -359,7 +507,16 @@ async function runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces,
359
507
  }
360
508
  throw error;
361
509
  }
510
+ lifecycle.lastPort = info.port;
362
511
  emitStatus(deps, options.json === true, "ready", info);
512
+ // The first generation already says so with its status line on stdout.
513
+ logger[generation > 1 ? "info" : "debug"]("daemon-lifecycle", "generation ready", {
514
+ generation,
515
+ startReason,
516
+ generationInstanceId: info.instanceId,
517
+ port: info.port,
518
+ startMs: Math.round(performance.now() - generationStartedAt),
519
+ });
363
520
  let probing = false;
364
521
  const timer = handle.tmuxAuthorityReplaced
365
522
  ? setInterval(() => {
@@ -371,6 +528,8 @@ async function runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces,
371
528
  if (!replaced || stopStarted || signalRequested)
372
529
  return;
373
530
  restartRequested = true;
531
+ retireTrigger ??= "tmux-authority-replaced";
532
+ watchThisStop("restart");
374
533
  return handle.stop();
375
534
  })
376
535
  .catch(() => undefined)
@@ -389,10 +548,18 @@ async function runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces,
389
548
  }
390
549
  if (stopFailure)
391
550
  throw stopFailure;
392
- return restartRequested && !signalRequested ? "restart" : "stopped";
551
+ const outcome = restartRequested && !signalRequested ? "restart" : "stopped";
552
+ if (outcome === "restart")
553
+ lifecycle.startReason = retireTrigger ?? "restart";
554
+ return outcome;
555
+ };
556
+ try {
557
+ return await Promise.race([runGeneration(), deadlineExceeded]);
393
558
  }
394
559
  finally {
395
- deps.offSignal("SIGINT", requestStop);
396
- deps.offSignal("SIGTERM", requestStop);
560
+ if (deadlineTimer)
561
+ clearInterval(deadlineTimer);
562
+ deps.offSignal("SIGINT", onSigint);
563
+ deps.offSignal("SIGTERM", onSigterm);
397
564
  }
398
565
  }
@@ -29,8 +29,21 @@ export function registerLogSecret(secret) {
29
29
  if (typeof secret === "string" && secret.length >= 8)
30
30
  secrets.add(secret);
31
31
  }
32
+ /**
33
+ * Where records below error level go. stdout by default (the service log).
34
+ * A process whose stdout is a protocol, like `tmux-ide --headless --json`
35
+ * with its one status line, reserves it: every record then goes to stderr.
36
+ */
37
+ let recordStream = "stdout";
38
+ export function reserveStdoutForProtocol() {
39
+ recordStream = "stderr";
40
+ }
41
+ export function structuredLogStream() {
42
+ return recordStream;
43
+ }
32
44
  /** @internal test seam */
33
45
  export function _resetLogStateForTests() {
46
+ recordStream = "stdout";
34
47
  identity = {};
35
48
  secrets.clear();
36
49
  logBuffer.length = 0;
@@ -91,6 +104,10 @@ function markStreamFailed(name, error) {
91
104
  const other = name === "stdout" ? "stderr" : "stdout";
92
105
  // The fallback can fail asynchronously too. Install the same error handling
93
106
  // before writing it; failed flags prevent a warning loop if both streams fail.
107
+ // A reserved stdout carries a protocol: the warning about a failed stderr
108
+ // has nowhere to go then, and the records stay in the ring.
109
+ if (other === "stdout" && recordStream === "stderr")
110
+ return;
94
111
  if (!streamState[other].failed)
95
112
  writeToStream(other, warning);
96
113
  }
@@ -164,7 +181,7 @@ function writeStructuredLog(level, component, message, data) {
164
181
  };
165
182
  if (payload.renamedKeys.length > 0)
166
183
  wire.reservedKeysRenamed = payload.renamedKeys;
167
- writeToStream(level === "error" ? "stderr" : "stdout", JSON.stringify(wire) + "\n");
184
+ writeToStream(level === "error" ? "stderr" : recordStream, JSON.stringify(wire) + "\n");
168
185
  }
169
186
  export const logger = {
170
187
  debug: (component, msg, data) => writeStructuredLog("debug", component, msg, data),
@@ -9,13 +9,30 @@ 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
37
  /** Pure cadence rule: healthy checks double the wait up to the cap; anything else resets it. */
21
38
  export function nextHookHealthcheckDelay(previousMs, outcome, schedule = DEFAULT_HOOK_HEALTHCHECK_SCHEDULE) {
@@ -63,14 +80,54 @@ export function tmuxInteractionWaitCommand(bufferName, channel) {
63
80
  }
64
81
  function defaultWaiter(authority, bufferName) {
65
82
  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)
83
+ return (channel, signal) => waitForBlockingTmuxClient(authority.executablePath, [...prefix, ...tmuxInteractionWaitCommand(bufferName, channel)], signal);
84
+ }
85
+ export const BLOCKING_CLIENT_KILL_GRACE_MS = 250;
86
+ /**
87
+ * Run a tmux client that blocks until signalled (`wait-for`). It has no
88
+ * deadline by design, so cancellation must not depend on the client's
89
+ * cooperation: TERM on abort, KILL after a grace, and settle when the process
90
+ * exits. Observer disposal awaits this, and with it every daemon stop (#839).
91
+ */
92
+ export function waitForBlockingTmuxClient(executable, args, signal, killGraceMs = BLOCKING_CLIENT_KILL_GRACE_MS) {
93
+ if (signal.aborted)
94
+ return Promise.resolve();
95
+ return new Promise((resolve, reject) => {
96
+ let settled = false;
97
+ let failure = null;
98
+ let escalation = null;
99
+ const child = execFile(executable, [...args], { encoding: "utf8", windowsHide: true }, (error) => {
100
+ failure ??= error;
101
+ });
102
+ const settle = () => {
103
+ if (settled)
104
+ return;
105
+ settled = true;
106
+ if (escalation)
107
+ clearTimeout(escalation);
108
+ signal.removeEventListener("abort", cancel);
109
+ if (!failure || signal.aborted)
71
110
  resolve();
72
111
  else
73
- reject(error);
112
+ reject(failure);
113
+ };
114
+ const cancel = () => {
115
+ if (escalation)
116
+ return;
117
+ child.kill("SIGTERM");
118
+ escalation = setTimeout(() => child.kill("SIGKILL"), killGraceMs);
119
+ };
120
+ signal.addEventListener("abort", cancel, { once: true });
121
+ child.once("error", (error) => {
122
+ failure ??= error;
123
+ settle();
124
+ });
125
+ // "exit", not "close": a lingering holder of the pipes must not keep the
126
+ // waiter, and so the stop, pending after the client itself is gone.
127
+ child.once("exit", (code, exitSignal) => {
128
+ if (code !== 0 && !failure)
129
+ failure = new Error(`tmux wait client ended with ${exitSignal ?? `code ${String(code)}`}`);
130
+ settle();
74
131
  });
75
132
  });
76
133
  }
@@ -157,15 +214,16 @@ export function parseTmuxInputHookRecords(raw) {
157
214
  }
158
215
  return records;
159
216
  }
160
- function hookIndexes(output, hookName) {
217
+ /** Every tmux-ide hook of this array, with the observer it belongs to (null: a legacy hook). */
218
+ function ownedHooks(output, hookName) {
161
219
  const row = new RegExp(`^${hookName}\\[([0-9]+)\\]\\s+(.+)$`, "u");
162
- const indexes = [];
220
+ const hooks = [];
163
221
  for (const line of output.split("\n")) {
164
222
  const match = row.exec(line);
165
223
  if (match && match[2].includes(OWNED_HOOK_MARKER))
166
- indexes.push(Number(match[1]));
224
+ hooks.push({ index: Number(match[1]), owner: OWNER_NAME.exec(match[2])?.[0] ?? null });
167
225
  }
168
- return indexes;
226
+ return hooks;
169
227
  }
170
228
  /**
171
229
  * Event-driven adapter from tmux's native send/capture hooks into the semantic
@@ -198,7 +256,9 @@ export class TmuxExternalInteractionObserver {
198
256
  #diagnostics;
199
257
  #diagnosticActiveOperations = 0;
200
258
  #authenticatedInternalReads;
259
+ #ownerProcess;
201
260
  constructor(options) {
261
+ this.#ownerProcess = options.ownerProcess ?? { pid: process.pid, isAlive: processIsAlive };
202
262
  this.#daemonInstanceId = options.daemonInstanceId;
203
263
  this.#healthcheckSchedule = Object.freeze({
204
264
  baseMs: options.healthcheck?.baseMs ?? DEFAULT_HOOK_HEALTHCHECK_SCHEDULE.baseMs,
@@ -264,6 +324,7 @@ export class TmuxExternalInteractionObserver {
264
324
  });
265
325
  if (!isTmuxServerUnavailable(error)) {
266
326
  this.#active = false;
327
+ liveLocalObservers.delete(this.#bufferName);
267
328
  throw error;
268
329
  }
269
330
  // A configless first run legitimately has no tmux server yet. Keep the
@@ -277,6 +338,7 @@ export class TmuxExternalInteractionObserver {
277
338
  await this.#removeOwnedHooks();
278
339
  await this.#deleteRetention();
279
340
  });
341
+ liveLocalObservers.delete(this.#bufferName);
280
342
  throw new Error("tmux external interaction observer was disposed during startup");
281
343
  }
282
344
  this.#loop = this.#run();
@@ -332,6 +394,8 @@ export class TmuxExternalInteractionObserver {
332
394
  this.#diagnostics = diagnostics;
333
395
  }
334
396
  async dispose() {
397
+ // From here on another observer of this process may clear what this one leaves.
398
+ liveLocalObservers.delete(this.#bufferName);
335
399
  if (!this.#active && !this.#loop && !this.#starting && !this.#installed)
336
400
  return;
337
401
  const starting = this.#starting;
@@ -352,12 +416,21 @@ export class TmuxExternalInteractionObserver {
352
416
  return this.#serializeTmux(() => this.#install(this.#abort.signal));
353
417
  }
354
418
  async #install(signal) {
355
- await this.#removeOwnedHooks(signal);
356
- await this.#deleteOwnedBuffers(signal);
419
+ const others = await this.#liveOtherObservers(signal);
420
+ await this.#removeOwnedHooks(signal, others);
421
+ await this.#deleteOwnedBuffers(signal, others);
357
422
  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);
423
+ liveLocalObservers.add(this.#bufferName);
424
+ // The small named buffer indexes retention options for crash cleanup and
425
+ // names the owning process: another daemon on this server leaves these
426
+ // hooks alone while that process lives, and clears them once it is gone.
427
+ // Event data lives only in bounded options, never in this buffer.
428
+ await this.#io.runTmux([
429
+ "set-buffer",
430
+ "-b",
431
+ this.#bufferName,
432
+ `retention-owner pid=${String(this.#ownerProcess.pid)}`,
433
+ ], signal);
361
434
  const hook = (operationKind, markerOption, consumeMarker) => {
362
435
  // Reject arbitrary option text before expansion into a tmux command.
363
436
  // Bound markers at the producer, including across multibyte input.
@@ -611,7 +684,49 @@ export class TmuxExternalInteractionObserver {
611
684
  ...(record.capturedTarget ? { capturedTarget: record.capturedTarget } : {}),
612
685
  });
613
686
  }
614
- async #removeOwnedHooks(signal) {
687
+ /**
688
+ * The other observers on this tmux server whose owner is alive: another
689
+ * daemon process, or another owner generation of this one. Their hooks,
690
+ * buffers and options are not ours to remove. Null when the server would
691
+ * not say; then nothing foreign is touched at all.
692
+ */
693
+ async #liveOtherObservers(signal) {
694
+ let output;
695
+ try {
696
+ output = await this.#io.runTmux(["list-buffers", "-F", "#{buffer_name}"], signal);
697
+ }
698
+ catch {
699
+ return null;
700
+ }
701
+ const live = new Set();
702
+ for (const name of output.split("\n")) {
703
+ if (name === this.#bufferName || OWNER_NAME.exec(name)?.[0] !== name)
704
+ continue;
705
+ let record;
706
+ try {
707
+ record = (await this.#io.runTmux(["show-buffer", "-b", name], signal)).trim();
708
+ }
709
+ catch {
710
+ continue;
711
+ }
712
+ const pid = Number(OWNER_RECORD.exec(record)?.[1]);
713
+ // A marker without a pid was written by an older daemon; as before, it is cleared.
714
+ if (!Number.isSafeInteger(pid))
715
+ continue;
716
+ if (pid === this.#ownerProcess.pid
717
+ ? liveLocalObservers.has(name)
718
+ : this.#ownerProcess.isAlive(pid))
719
+ live.add(name);
720
+ }
721
+ return live;
722
+ }
723
+ /**
724
+ * Remove this observer's hooks, and those nobody alive owns (a crashed
725
+ * daemon's, legacy ones). Never another live observer's: two daemons on one
726
+ * tmux server would otherwise keep taking each other's hooks away.
727
+ */
728
+ async #removeOwnedHooks(signal, others) {
729
+ const live = others === undefined ? await this.#liveOtherObservers(signal) : others;
615
730
  for (const hookName of ["after-send-keys", "after-capture-pane"]) {
616
731
  let output;
617
732
  try {
@@ -620,7 +735,9 @@ export class TmuxExternalInteractionObserver {
620
735
  catch {
621
736
  continue;
622
737
  }
623
- for (const index of hookIndexes(output, hookName)) {
738
+ for (const { index, owner } of ownedHooks(output, hookName)) {
739
+ if (owner !== this.#bufferName && (live === null || (owner !== null && live.has(owner))))
740
+ continue;
624
741
  try {
625
742
  await this.#io.runTmux(["set-hook", "-gu", `${hookName}[${index}]`], signal);
626
743
  }
@@ -687,7 +804,9 @@ export class TmuxExternalInteractionObserver {
687
804
  await this.#deleteOption(`${option}-drain`);
688
805
  await this.#deleteBuffer(this.#bufferName);
689
806
  }
690
- async #deleteOwnedBuffers(signal) {
807
+ async #deleteOwnedBuffers(signal, live) {
808
+ if (live === null)
809
+ return;
691
810
  let output;
692
811
  try {
693
812
  output = await this.#io.runTmux(["list-buffers", "-F", "#{buffer_name}"], signal);
@@ -698,6 +817,8 @@ export class TmuxExternalInteractionObserver {
698
817
  for (const name of output.split("\n")) {
699
818
  if (!name.startsWith(OWNED_HOOK_MARKER) || name === this.#bufferName)
700
819
  continue;
820
+ if (live.has(name))
821
+ continue;
701
822
  if (/^[A-Za-z0-9._-]{1,256}$/u.test(name)) {
702
823
  await this.#deleteOption(tmuxInteractionOption(name), signal);
703
824
  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
+ }