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,215 @@
1
+ import { execFile } from "node:child_process";
2
+ import { logger } from "./log.ts";
3
+
4
+ /**
5
+ * A daemon that dies without running its stop (SIGKILL, a crash) can leave a
6
+ * tmux control client behind. Measured on a private server: with pane output
7
+ * flowing and the daemon stopped for a few seconds before the kill, the
8
+ * client stays alive with init as its parent. tmux no longer lists it as a
9
+ * client, yet a later `kill-server` never finishes while it lives: the socket
10
+ * keeps a server with no sessions and no new server can take its place.
11
+ * A daemon therefore ends the control clients a dead daemon left on a server
12
+ * it owns: when it takes ownership, and when that server answers a catalog
13
+ * read with no sessions or does not answer it at all.
14
+ */
15
+ export type TmuxServerSelector =
16
+ | { readonly kind: "path"; readonly path: string }
17
+ | { readonly kind: "name"; readonly name: string };
18
+
19
+ export interface ProcessRow {
20
+ readonly pid: number;
21
+ readonly ppid: number;
22
+ readonly command: string;
23
+ }
24
+
25
+ export interface OrphanedControlClientIo {
26
+ /** Every process of this user: tmux does not list a client that is leaving. */
27
+ readonly listProcesses: () => Promise<readonly ProcessRow[]>;
28
+ kill: (pid: number, signal: "SIGTERM" | "SIGKILL") => void;
29
+ readonly isAlive: (pid: number) => boolean;
30
+ readonly delay: (ms: number) => Promise<void>;
31
+ }
32
+
33
+ export const ORPHAN_KILL_GRACE_MS = 500;
34
+
35
+ /** PURE. `ps -o pid=,ppid=,command=` output, one process per line. */
36
+ export function parseProcessTable(text: string): ProcessRow[] {
37
+ const rows: ProcessRow[] = [];
38
+ for (const line of text.split("\n")) {
39
+ const match = /^\s*([0-9]+)\s+([0-9]+)\s+(.+)$/u.exec(line);
40
+ if (match) rows.push({ pid: Number(match[1]), ppid: Number(match[2]), command: match[3]! });
41
+ }
42
+ return rows;
43
+ }
44
+
45
+ /** The attach flags only this daemon's control client uses (mirrorControlAttachArgs). */
46
+ export function isTmuxIdeControlClientCommand(command: string): boolean {
47
+ return (
48
+ /(?:^|\s)-C(?:\s|$)/u.test(command) &&
49
+ /ignore-size,pause-after=[0-9]+,active-pane/u.test(command)
50
+ );
51
+ }
52
+
53
+ const withoutPrivate = (path: string): string => path.replace(/^\/private(?=\/)/u, "");
54
+
55
+ /** PURE. Does this tmux command line address the given server? */
56
+ export function commandTargetsServer(command: string, selector: TmuxServerSelector): boolean {
57
+ const words = command.split(/\s+/u);
58
+ for (let index = 0; index < words.length; index += 1) {
59
+ const word = words[index]!;
60
+ if (word === "-C") return false;
61
+ const flag = selector.kind === "path" ? "-S" : "-L";
62
+ const value = word === flag ? words[index + 1] : word.startsWith(flag) ? word.slice(2) : null;
63
+ if (value === null || value === undefined || value === "") continue;
64
+ return selector.kind === "path"
65
+ ? withoutPrivate(value) === withoutPrivate(selector.path)
66
+ : value === selector.name;
67
+ }
68
+ return false;
69
+ }
70
+
71
+ /** init, or a service manager that adopts orphans in its place. */
72
+ function adoptsOrphans(pid: number, command: string | null): boolean {
73
+ if (pid === 1) return true;
74
+ // The command's own name (its first word, with or without a path), never a
75
+ // word further on: a daemon run as `… --supervised launchd-user` is no manager.
76
+ return command !== null && /^(?:\S*\/)?(?:systemd|launchd|init)(?:\s|$)/u.test(command);
77
+ }
78
+
79
+ /**
80
+ * Ends tmux-ide control clients of this server whose daemon is gone. Never
81
+ * this daemon's own clients, another live daemon's, another server's, or any
82
+ * other program's. Returns the pids it ended. Failures end the pass; they
83
+ * never throw.
84
+ */
85
+ export async function evictOrphanedControlClients(
86
+ io: OrphanedControlClientIo,
87
+ ownPid: number,
88
+ selector: TmuxServerSelector,
89
+ ): Promise<number[]> {
90
+ let processes: readonly ProcessRow[];
91
+ try {
92
+ processes = await io.listProcesses();
93
+ } catch {
94
+ return [];
95
+ }
96
+ const byPid = new Map(processes.map((row) => [row.pid, row]));
97
+ const evicted: number[] = [];
98
+ for (const client of processes) {
99
+ if (
100
+ client.pid <= 1 ||
101
+ client.pid === ownPid ||
102
+ client.ppid === ownPid ||
103
+ !isTmuxIdeControlClientCommand(client.command) ||
104
+ !commandTargetsServer(client.command, selector) ||
105
+ !adoptsOrphans(client.ppid, byPid.get(client.ppid)?.command ?? null)
106
+ )
107
+ continue;
108
+ try {
109
+ io.kill(client.pid, "SIGTERM");
110
+ await io.delay(ORPHAN_KILL_GRACE_MS);
111
+ if (io.isAlive(client.pid)) io.kill(client.pid, "SIGKILL");
112
+ evicted.push(client.pid);
113
+ } catch {
114
+ // One client that cannot be signalled does not stop the pass.
115
+ }
116
+ }
117
+ return evicted;
118
+ }
119
+
120
+ /** The real process table and signals. */
121
+ export function orphanedControlClientIo(): OrphanedControlClientIo {
122
+ return {
123
+ listProcesses: () =>
124
+ new Promise((resolve, reject) => {
125
+ execFile(
126
+ "/bin/ps",
127
+ ["-xww", "-o", "pid=,ppid=,command="],
128
+ {
129
+ encoding: "utf8",
130
+ timeout: 3_000,
131
+ maxBuffer: 16 * 1024 * 1024,
132
+ env: { LC_ALL: "C", PATH: "/usr/bin:/bin" },
133
+ },
134
+ (error, stdout) => (error ? reject(error) : resolve(parseProcessTable(stdout))),
135
+ );
136
+ }),
137
+ kill: (pid, signal) => {
138
+ process.kill(pid, signal);
139
+ },
140
+ isAlive: (pid) => {
141
+ try {
142
+ process.kill(pid, 0);
143
+ return true;
144
+ } catch (error) {
145
+ return (error as NodeJS.ErrnoException).code === "EPERM";
146
+ }
147
+ },
148
+ delay: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
149
+ };
150
+ }
151
+
152
+ /** What a catalog read found: an answer without sessions, or no answer. */
153
+ export type TmuxServerTrouble = "no-sessions" | "unanswered";
154
+
155
+ export const EMPTY_SERVER_PASS_INTERVAL_MS = 10_000;
156
+ export const EMPTY_SERVER_LOG_INTERVAL_MS = 60_000;
157
+
158
+ /**
159
+ * One per owned server. Neither call is awaited by the owner, delays it or
160
+ * fails it.
161
+ * - `onOwnership`: one pass when the daemon takes the server.
162
+ * - `onTrouble`: a catalog read found the server with no sessions, or got no
163
+ * answer from a server whose socket is still there. A tmux server normally
164
+ * exits with its last session, so either it is configured to stay or it
165
+ * cannot exit. At most one pass per 10 s, and one warning per minute that
166
+ * names the state: scoped reads fail in it, and nothing else says why.
167
+ */
168
+ export function createOrphanedControlClientWatch(options: {
169
+ readonly selector: TmuxServerSelector;
170
+ readonly serverId: string | null;
171
+ readonly io?: OrphanedControlClientIo;
172
+ readonly now?: () => number;
173
+ }): { onOwnership(): Promise<void>; onTrouble(kind: TmuxServerTrouble): Promise<void> } {
174
+ const io = options.io ?? orphanedControlClientIo();
175
+ const now = options.now ?? Date.now;
176
+ const fields = options.serverId ? { serverId: options.serverId } : {};
177
+ let lastPassAt = Number.NEGATIVE_INFINITY;
178
+ let lastLogAt = Number.NEGATIVE_INFINITY;
179
+ let running: Promise<number[]> | null = null;
180
+ const pass = (): Promise<number[]> => {
181
+ if (running) return running;
182
+ lastPassAt = now();
183
+ const current = evictOrphanedControlClients(io, process.pid, options.selector)
184
+ .catch((): number[] => [])
185
+ .then((pids) => {
186
+ if (pids.length > 0)
187
+ logger.warn("tmux-server-owners", "ended control clients a dead daemon left attached", {
188
+ ...fields,
189
+ pids,
190
+ });
191
+ return pids;
192
+ })
193
+ .finally(() => {
194
+ if (running === current) running = null;
195
+ });
196
+ running = current;
197
+ return current;
198
+ };
199
+ return {
200
+ onOwnership: () => pass().then(() => undefined),
201
+ async onTrouble(kind) {
202
+ if (now() - lastPassAt < EMPTY_SERVER_PASS_INTERVAL_MS) return;
203
+ const pids = await pass();
204
+ if (now() - lastLogAt < EMPTY_SERVER_LOG_INTERVAL_MS) return;
205
+ lastLogAt = now();
206
+ logger.warn(
207
+ "tmux-server-owners",
208
+ kind === "no-sessions"
209
+ ? "tmux server answers with no sessions"
210
+ : "tmux server does not answer its catalog",
211
+ { ...fields, endedControlClients: pids.length },
212
+ );
213
+ },
214
+ };
215
+ }
@@ -23,6 +23,20 @@ import {
23
23
 
24
24
  const HOOK_MARKER = "tmux-ide-interaction-v3";
25
25
  const OWNED_HOOK_MARKER = "tmux-ide-interaction-v";
26
+ /** The retention name of one observer: the marker plus its daemon id. */
27
+ const OWNER_NAME =
28
+ /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;
29
+ const OWNER_RECORD = /^retention-owner pid=([1-9][0-9]{0,9})$/u;
30
+ /** Observers of THIS process that are installed and not yet disposed. */
31
+ const liveLocalObservers = new Set<string>();
32
+ function processIsAlive(pid: number): boolean {
33
+ try {
34
+ process.kill(pid, 0);
35
+ return true;
36
+ } catch (error) {
37
+ return (error as NodeJS.ErrnoException).code !== "ESRCH";
38
+ }
39
+ }
26
40
  const FIELD_SEPARATOR = "|tmux-ide-input-field-v1|";
27
41
  const EVENT_SEPARATOR = "|tmux-ide-input-event-v1|";
28
42
  export interface ExternalTmuxInteractionGap {
@@ -55,20 +69,34 @@ export interface HookHealthcheckSchedule {
55
69
 
56
70
  export const DEFAULT_HOOK_HEALTHCHECK_SCHEDULE: HookHealthcheckSchedule = Object.freeze({
57
71
  baseMs: 1_000,
58
- maxMs: 30_000,
72
+ // A healthy idle server is checked 12 times an hour, not 120. Since daemons
73
+ // no longer remove each other's hooks, only a user action (a config reload,
74
+ // `set-hook -gu`) can take them away; that is then noticed within 5 minutes.
75
+ maxMs: 300_000,
59
76
  });
60
77
 
61
78
  export type HookHealthcheckOutcome = "healthy" | "repaired" | "failed";
62
79
 
63
- /** Pure cadence rule: healthy checks double the wait up to the cap; anything else resets it. */
80
+ /**
81
+ * Pure cadence rule: healthy checks double the wait up to the cap; a repair or
82
+ * failure resets it to the base. A check that is unhealthy again right after
83
+ * one that was (`consecutiveUnhealthy` of 2 or more) backs off as well: on a
84
+ * tmux server that is shutting down but cannot exit, every repair "succeeds"
85
+ * and is gone at the next check, and the base cadence then cost about 400 tmux
86
+ * calls a minute for as long as the server lingered.
87
+ */
64
88
  export function nextHookHealthcheckDelay(
65
89
  previousMs: number,
66
90
  outcome: HookHealthcheckOutcome,
67
91
  schedule: HookHealthcheckSchedule = DEFAULT_HOOK_HEALTHCHECK_SCHEDULE,
92
+ consecutiveUnhealthy = 1,
68
93
  ): number {
69
94
  const base = Math.max(1, Math.floor(schedule.baseMs));
70
95
  const max = Math.max(base, Math.floor(schedule.maxMs));
71
- if (outcome !== "healthy") return base;
96
+ if (outcome !== "healthy") {
97
+ const streak = Math.max(1, Math.min(32, Math.floor(consecutiveUnhealthy) || 1));
98
+ return Math.min(base * 2 ** (streak - 1), max);
99
+ }
72
100
  const previous = Number.isFinite(previousMs) ? Math.max(base, Math.floor(previousMs)) : base;
73
101
  return Math.min(previous * 2, max);
74
102
  }
@@ -162,18 +190,66 @@ function defaultWaiter(
162
190
  ): ExternalTmuxInteractionObserverIo["waitForSignal"] {
163
191
  const prefix = socketArguments(authority);
164
192
  return (channel, signal) =>
165
- new Promise<void>((resolve, reject) => {
166
- execFile(
167
- authority.executablePath,
168
- [...prefix, ...tmuxInteractionWaitCommand(bufferName, channel)],
169
- { signal, encoding: "utf8", windowsHide: true },
170
- (error) => {
171
- if (!error) resolve();
172
- else if (signal.aborted) resolve();
173
- else reject(error);
174
- },
175
- );
193
+ waitForBlockingTmuxClient(
194
+ authority.executablePath,
195
+ [...prefix, ...tmuxInteractionWaitCommand(bufferName, channel)],
196
+ signal,
197
+ );
198
+ }
199
+
200
+ export const BLOCKING_CLIENT_KILL_GRACE_MS = 250;
201
+
202
+ /**
203
+ * Run a tmux client that blocks until signalled (`wait-for`). It has no
204
+ * deadline by design, so cancellation must not depend on the client's
205
+ * cooperation: TERM on abort, KILL after a grace, and settle when the process
206
+ * exits. Observer disposal awaits this, and with it every daemon stop (#839).
207
+ */
208
+ export function waitForBlockingTmuxClient(
209
+ executable: string,
210
+ args: readonly string[],
211
+ signal: AbortSignal,
212
+ killGraceMs: number = BLOCKING_CLIENT_KILL_GRACE_MS,
213
+ ): Promise<void> {
214
+ if (signal.aborted) return Promise.resolve();
215
+ return new Promise<void>((resolve, reject) => {
216
+ let settled = false;
217
+ let failure: Error | null = null;
218
+ let escalation: ReturnType<typeof setTimeout> | null = null;
219
+ const child = execFile(
220
+ executable,
221
+ [...args],
222
+ { encoding: "utf8", windowsHide: true },
223
+ (error) => {
224
+ failure ??= error;
225
+ },
226
+ );
227
+ const settle = (): void => {
228
+ if (settled) return;
229
+ settled = true;
230
+ if (escalation) clearTimeout(escalation);
231
+ signal.removeEventListener("abort", cancel);
232
+ if (!failure || signal.aborted) resolve();
233
+ else reject(failure);
234
+ };
235
+ const cancel = (): void => {
236
+ if (escalation) return;
237
+ child.kill("SIGTERM");
238
+ escalation = setTimeout(() => child.kill("SIGKILL"), killGraceMs);
239
+ };
240
+ signal.addEventListener("abort", cancel, { once: true });
241
+ child.once("error", (error) => {
242
+ failure ??= error;
243
+ settle();
176
244
  });
245
+ // "exit", not "close": a lingering holder of the pipes must not keep the
246
+ // waiter, and so the stop, pending after the client itself is gone.
247
+ child.once("exit", (code, exitSignal) => {
248
+ if (code !== 0 && !failure)
249
+ failure = new Error(`tmux wait client ended with ${exitSignal ?? `code ${String(code)}`}`);
250
+ settle();
251
+ });
252
+ });
177
253
  }
178
254
 
179
255
  function abortableDelay(milliseconds: number, signal: AbortSignal): Promise<void> {
@@ -265,17 +341,19 @@ export function parseTmuxInputHookRecords(raw: string): readonly TmuxInputHookRe
265
341
  return records;
266
342
  }
267
343
 
268
- function hookIndexes(
344
+ /** Every tmux-ide hook of this array, with the observer it belongs to (null: a legacy hook). */
345
+ function ownedHooks(
269
346
  output: string,
270
347
  hookName: "after-send-keys" | "after-capture-pane",
271
- ): readonly number[] {
348
+ ): readonly { readonly index: number; readonly owner: string | null }[] {
272
349
  const row = new RegExp(`^${hookName}\\[([0-9]+)\\]\\s+(.+)$`, "u");
273
- const indexes: number[] = [];
350
+ const hooks: { index: number; owner: string | null }[] = [];
274
351
  for (const line of output.split("\n")) {
275
352
  const match = row.exec(line);
276
- if (match && match[2]!.includes(OWNED_HOOK_MARKER)) indexes.push(Number(match[1]!));
353
+ if (match && match[2]!.includes(OWNED_HOOK_MARKER))
354
+ hooks.push({ index: Number(match[1]!), owner: OWNER_NAME.exec(match[2]!)?.[0] ?? null });
277
355
  }
278
- return indexes;
356
+ return hooks;
279
357
  }
280
358
 
281
359
  /**
@@ -304,6 +382,8 @@ export class TmuxExternalInteractionObserver {
304
382
  readonly #healthcheckSchedule: HookHealthcheckSchedule;
305
383
  #healthcheckDelayMs: number;
306
384
  #lastHealthcheckOutcome: HookHealthcheckOutcome = "failed";
385
+ /** Scheduled checks in a row that did not find the hooks intact. */
386
+ #unhealthyChecks = 0;
307
387
  readonly #onAvailability: ((available: boolean) => void) | undefined;
308
388
  readonly #onGap: ((gap: ExternalTmuxInteractionGap) => void) | undefined;
309
389
  #tmuxWork: Promise<unknown> = Promise.resolve();
@@ -311,6 +391,7 @@ export class TmuxExternalInteractionObserver {
311
391
  #diagnostics: ExternalTmuxObserverDiagnostics | null;
312
392
  #diagnosticActiveOperations = 0;
313
393
  readonly #authenticatedInternalReads: AuthenticatedInternalReadVerifier;
394
+ readonly #ownerProcess: { readonly pid: number; readonly isAlive: (pid: number) => boolean };
314
395
 
315
396
  constructor(options: {
316
397
  daemonInstanceId: string;
@@ -334,7 +415,10 @@ export class TmuxExternalInteractionObserver {
334
415
  onGap?: (gap: ExternalTmuxInteractionGap) => void;
335
416
  /** Health-check cadence bounds. Tests inject small values; production uses the default. */
336
417
  healthcheck?: Partial<HookHealthcheckSchedule>;
418
+ /** This daemon's process and the liveness test for another's. Tests inject both. */
419
+ ownerProcess?: { readonly pid: number; readonly isAlive: (pid: number) => boolean };
337
420
  }) {
421
+ this.#ownerProcess = options.ownerProcess ?? { pid: process.pid, isAlive: processIsAlive };
338
422
  this.#daemonInstanceId = options.daemonInstanceId;
339
423
  this.#healthcheckSchedule = Object.freeze({
340
424
  baseMs: options.healthcheck?.baseMs ?? DEFAULT_HOOK_HEALTHCHECK_SCHEDULE.baseMs,
@@ -401,6 +485,7 @@ export class TmuxExternalInteractionObserver {
401
485
  });
402
486
  if (!isTmuxServerUnavailable(error)) {
403
487
  this.#active = false;
488
+ liveLocalObservers.delete(this.#bufferName);
404
489
  throw error;
405
490
  }
406
491
  // A configless first run legitimately has no tmux server yet. Keep the
@@ -414,6 +499,7 @@ export class TmuxExternalInteractionObserver {
414
499
  await this.#removeOwnedHooks();
415
500
  await this.#deleteRetention();
416
501
  });
502
+ liveLocalObservers.delete(this.#bufferName);
417
503
  throw new Error("tmux external interaction observer was disposed during startup");
418
504
  }
419
505
  this.#loop = this.#run();
@@ -447,12 +533,14 @@ export class TmuxExternalInteractionObserver {
447
533
  if (!this.#abort.signal.aborted) this.#reportGap("hook-repair-failed");
448
534
  outcome = "failed";
449
535
  }
536
+ this.#unhealthyChecks = outcome === "healthy" ? 0 : this.#unhealthyChecks + 1;
450
537
  // A signal-path reset that landed during this check wins over the outcome.
451
538
  if (this.#healthcheckDelayMs === delayBefore) {
452
539
  this.#healthcheckDelayMs = nextHookHealthcheckDelay(
453
540
  delayBefore,
454
541
  outcome,
455
542
  this.#healthcheckSchedule,
543
+ this.#unhealthyChecks,
456
544
  );
457
545
  }
458
546
  if (this.#hookHealthcheck === null) this.#scheduleHealthcheck();
@@ -471,6 +559,8 @@ export class TmuxExternalInteractionObserver {
471
559
  }
472
560
 
473
561
  async dispose(): Promise<void> {
562
+ // From here on another observer of this process may clear what this one leaves.
563
+ liveLocalObservers.delete(this.#bufferName);
474
564
  if (!this.#active && !this.#loop && !this.#starting && !this.#installed) return;
475
565
  const starting = this.#starting;
476
566
  this.#active = false;
@@ -491,12 +581,24 @@ export class TmuxExternalInteractionObserver {
491
581
  }
492
582
 
493
583
  async #install(signal?: AbortSignal): Promise<void> {
494
- await this.#removeOwnedHooks(signal);
495
- await this.#deleteOwnedBuffers(signal);
584
+ const others = await this.#liveOtherObservers(signal);
585
+ await this.#removeOwnedHooks(signal, others);
586
+ await this.#deleteOwnedBuffers(signal, others);
496
587
  signal?.throwIfAborted();
497
- // The small named buffer indexes retention options for crash cleanup;
498
- // event data lives only in bounded options, never in this buffer.
499
- await this.#io.runTmux(["set-buffer", "-b", this.#bufferName, "retention-owner"], signal);
588
+ liveLocalObservers.add(this.#bufferName);
589
+ // The small named buffer indexes retention options for crash cleanup and
590
+ // names the owning process: another daemon on this server leaves these
591
+ // hooks alone while that process lives, and clears them once it is gone.
592
+ // Event data lives only in bounded options, never in this buffer.
593
+ await this.#io.runTmux(
594
+ [
595
+ "set-buffer",
596
+ "-b",
597
+ this.#bufferName,
598
+ `retention-owner pid=${String(this.#ownerProcess.pid)}`,
599
+ ],
600
+ signal,
601
+ );
500
602
  const hook = (
501
603
  operationKind: ExternalTmuxInteraction["operationKind"],
502
604
  markerOption: string,
@@ -560,11 +662,20 @@ export class TmuxExternalInteractionObserver {
560
662
  const work = this.#serializeTmux(async () => {
561
663
  const finish = this.#beginDiagnostic("healthcheck");
562
664
  try {
563
- if (await this.#ownedHooksPresent(this.#abort.signal)) {
665
+ const hooks = await this.#ownedHooksPresent(this.#abort.signal);
666
+ if (hooks === "present") {
564
667
  this.#lastHealthcheckOutcome = "healthy";
565
668
  finish(true);
566
669
  return;
567
670
  }
671
+ if (hooks === "unknown") {
672
+ // The check could not be made (tmux timed out or could not be
673
+ // started). That says nothing about the hooks: leave them, report
674
+ // no gap, and ask again at the base cadence.
675
+ this.#lastHealthcheckOutcome = "failed";
676
+ finish(false);
677
+ return;
678
+ }
568
679
  // Hooks that were installed and are now gone dropped every interaction
569
680
  // since their removal; the repair restores future observation only.
570
681
  if (this.#installed) this.#reportGap("hooks-replaced");
@@ -765,7 +876,51 @@ export class TmuxExternalInteractionObserver {
765
876
  });
766
877
  }
767
878
 
768
- async #removeOwnedHooks(signal?: AbortSignal): Promise<void> {
879
+ /**
880
+ * The other observers on this tmux server whose owner is alive: another
881
+ * daemon process, or another owner generation of this one. Their hooks,
882
+ * buffers and options are not ours to remove. Null when the server would
883
+ * not say; then nothing foreign is touched at all.
884
+ */
885
+ async #liveOtherObservers(signal?: AbortSignal): Promise<ReadonlySet<string> | null> {
886
+ let output: string;
887
+ try {
888
+ output = await this.#io.runTmux(["list-buffers", "-F", "#{buffer_name}"], signal);
889
+ } catch {
890
+ return null;
891
+ }
892
+ const live = new Set<string>();
893
+ for (const name of output.split("\n")) {
894
+ if (name === this.#bufferName || OWNER_NAME.exec(name)?.[0] !== name) continue;
895
+ let record: string;
896
+ try {
897
+ record = (await this.#io.runTmux(["show-buffer", "-b", name], signal)).trim();
898
+ } catch {
899
+ continue;
900
+ }
901
+ const pid = Number(OWNER_RECORD.exec(record)?.[1]);
902
+ // A marker without a pid was written by an older daemon; as before, it is cleared.
903
+ if (!Number.isSafeInteger(pid)) continue;
904
+ if (
905
+ pid === this.#ownerProcess.pid
906
+ ? liveLocalObservers.has(name)
907
+ : this.#ownerProcess.isAlive(pid)
908
+ )
909
+ live.add(name);
910
+ }
911
+ return live;
912
+ }
913
+
914
+ /**
915
+ * Remove this observer's hooks, and those nobody alive owns (a crashed
916
+ * daemon's, legacy ones). Never another live observer's: two daemons on one
917
+ * tmux server would otherwise keep taking each other's hooks away.
918
+ */
919
+ async #removeOwnedHooks(
920
+ signal?: AbortSignal,
921
+ others?: ReadonlySet<string> | null,
922
+ ): Promise<void> {
923
+ const live = others === undefined ? await this.#liveOtherObservers(signal) : others;
769
924
  for (const hookName of ["after-send-keys", "after-capture-pane"] as const) {
770
925
  let output: string;
771
926
  try {
@@ -773,7 +928,9 @@ export class TmuxExternalInteractionObserver {
773
928
  } catch {
774
929
  continue;
775
930
  }
776
- for (const index of hookIndexes(output, hookName)) {
931
+ for (const { index, owner } of ownedHooks(output, hookName)) {
932
+ if (owner !== this.#bufferName && (live === null || (owner !== null && live.has(owner))))
933
+ continue;
777
934
  try {
778
935
  await this.#io.runTmux(["set-hook", "-gu", `${hookName}[${index}]`], signal);
779
936
  } catch {
@@ -784,7 +941,7 @@ export class TmuxExternalInteractionObserver {
784
941
  this.#setInstalled(false);
785
942
  }
786
943
 
787
- async #ownedHooksPresent(signal?: AbortSignal): Promise<boolean> {
944
+ async #ownedHooksPresent(signal?: AbortSignal): Promise<"present" | "missing" | "unknown"> {
788
945
  // One client verifies both hook arrays: tmux runs the `;`-separated list in
789
946
  // a single command queue and prints each array's lines in order.
790
947
  let output: string;
@@ -794,12 +951,12 @@ export class TmuxExternalInteractionObserver {
794
951
  signal,
795
952
  );
796
953
  } catch {
797
- return false;
954
+ return "unknown";
798
955
  }
799
- return (
800
- ownedHookInstalled(output, "after-send-keys", this.#bufferName) &&
956
+ return ownedHookInstalled(output, "after-send-keys", this.#bufferName) &&
801
957
  ownedHookInstalled(output, "after-capture-pane", this.#bufferName)
802
- );
958
+ ? "present"
959
+ : "missing";
803
960
  }
804
961
 
805
962
  get available(): boolean {
@@ -848,7 +1005,11 @@ export class TmuxExternalInteractionObserver {
848
1005
  await this.#deleteBuffer(this.#bufferName);
849
1006
  }
850
1007
 
851
- async #deleteOwnedBuffers(signal?: AbortSignal): Promise<void> {
1008
+ async #deleteOwnedBuffers(
1009
+ signal: AbortSignal | undefined,
1010
+ live: ReadonlySet<string> | null,
1011
+ ): Promise<void> {
1012
+ if (live === null) return;
852
1013
  let output: string;
853
1014
  try {
854
1015
  output = await this.#io.runTmux(["list-buffers", "-F", "#{buffer_name}"], signal);
@@ -857,6 +1018,7 @@ export class TmuxExternalInteractionObserver {
857
1018
  }
858
1019
  for (const name of output.split("\n")) {
859
1020
  if (!name.startsWith(OWNED_HOOK_MARKER) || name === this.#bufferName) continue;
1021
+ if (live.has(name)) continue;
860
1022
  if (/^[A-Za-z0-9._-]{1,256}$/u.test(name)) {
861
1023
  await this.#deleteOption(tmuxInteractionOption(name), signal);
862
1024
  await this.#deleteOption(`${tmuxInteractionOption(name)}-drain`, signal);
@@ -64,8 +64,9 @@ export function createNativeBrowserResolver(options: {
64
64
  );
65
65
  if (matches.length !== 1) throw new NativeBrowserUnavailable();
66
66
  const pane = { ...matches[0]! };
67
- if (!pane.nativePaneBirthId || !/^%[0-9]+$/u.test(pane.runtimePaneId))
68
- throw new NativeBrowserUnavailable();
67
+ // A stock tmux server has no pane birth id; it reads empty there, both times.
68
+ const paneBirth = pane.nativePaneBirthId ?? "";
69
+ if (!/^%[0-9]+$/u.test(pane.runtimePaneId)) throw new NativeBrowserUnavailable();
69
70
  const observe = async () => {
70
71
  const raw = await options.run(
71
72
  [
@@ -80,7 +81,7 @@ export function createNativeBrowserResolver(options: {
80
81
  assertCurrent();
81
82
  if (raw.length > 8192) throw new NativeBrowserUnavailable();
82
83
  const [semantic, birth, endpoint] = raw.trimEnd().split("\t").map(decodeTmuxArgument);
83
- if (semantic !== target.semanticPaneId || birth !== pane.nativePaneBirthId)
84
+ if (semantic !== target.semanticPaneId || birth !== paneBirth)
84
85
  throw new NativeBrowserUnavailable();
85
86
  const parsed = NativeBrowserEndpointSchema.parse(JSON.parse(endpoint ?? "null"));
86
87
  if (parsed.pane !== pane.runtimePaneId) throw new NativeBrowserUnavailable();
@@ -84,8 +84,9 @@ export function createPaneReaderResolver(options: {
84
84
  );
85
85
  if (matches.length !== 1) throw new PaneReaderUnavailable();
86
86
  const pane = { ...matches[0]! };
87
- if (!pane.nativePaneBirthId || !/^%[0-9]+$/u.test(pane.runtimePaneId))
88
- throw new PaneReaderUnavailable();
87
+ // A stock tmux server has no pane birth id; it reads empty there, both times.
88
+ const paneBirth = pane.nativePaneBirthId ?? "";
89
+ if (!/^%[0-9]+$/u.test(pane.runtimePaneId)) throw new PaneReaderUnavailable();
89
90
  const observe = async (): Promise<ReaderOption> => {
90
91
  const raw = await options.run(
91
92
  [
@@ -103,7 +104,7 @@ export function createPaneReaderResolver(options: {
103
104
  .trimEnd()
104
105
  .split("\t")
105
106
  .map(decodeTmuxArgument);
106
- if (semantic !== target.semanticPaneId || birth !== pane.nativePaneBirthId)
107
+ if (semantic !== target.semanticPaneId || birth !== paneBirth)
107
108
  throw new PaneReaderUnavailable();
108
109
  const reader = readerOption(option ?? "", panePid ?? "", options.alive);
109
110
  if (!reader) throw new PaneReaderUnavailable();
@@ -42,12 +42,17 @@ export async function captureAgentAdmission(
42
42
  id !== session.id ||
43
43
  !/^@\d+$/.test(window!) ||
44
44
  !/^%\d+$/.test(pane!) ||
45
- !/^[1-9]\d*$/.test(birth!)
45
+ !/^(?:[1-9]\d*)?$/.test(birth!)
46
46
  )
47
47
  throw new Error("Agent native identity is unavailable");
48
48
  return { window: window!, pane: pane!, birth: birth!, stamp: stamp! };
49
49
  });
50
50
  if (rows.length > 512) throw new Error("Agent inventory exceeds admission bounds");
51
+ // A stock tmux server has no pane birth id: every row reads empty. Its pane
52
+ // ids are never reused while it runs, and each command already checks the
53
+ // session id and creation time, so the pane and window ids fence the lifetime.
54
+ if (rows.some((row) => row.birth === "") && rows.some((row) => row.birth !== ""))
55
+ throw new Error("Agent native identity is unavailable");
51
56
  return rows;
52
57
  };
53
58
  const initial = await scan();