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
@@ -7,9 +7,11 @@ import {
7
7
  renameSync,
8
8
  writeFileSync,
9
9
  realpathSync,
10
+ statSync,
10
11
  unlinkSync,
11
12
  } from "node:fs";
12
- import { dirname } from "node:path";
13
+ import { dirname, join } from "node:path";
14
+ import { createConnection } from "node:net";
13
15
  import { z } from "zod";
14
16
  import { tmuxClientEnvironment } from "./tmux-client-execution.ts";
15
17
  import {
@@ -19,7 +21,10 @@ import {
19
21
  import {
20
22
  MAX_TMUX_SERVER_OWNERS,
21
23
  TmuxServerRegistrationSchemaZ,
24
+ isTmuxServerObservation,
22
25
  type TmuxServerObservation,
26
+ type TmuxServerProbeFailure,
27
+ type TmuxServerProbeResult,
23
28
  type TmuxServerRegistration,
24
29
  } from "./tmux-server-owners.ts";
25
30
 
@@ -60,20 +65,162 @@ export function writeTmuxServerRegistrations(
60
65
  }
61
66
  }
62
67
  }
68
+ export const TMUX_SERVER_PROBE_TIMEOUT_MS = 500;
69
+
70
+ /**
71
+ * Where the daemon's tmux clients find this selector's socket. They run with
72
+ * a scrubbed environment (no TMUX_TMPDIR), so a named socket is always in
73
+ * /tmp/tmux-<uid>/.
74
+ */
75
+ export function tmuxSelectorSocketPath(selector: TmuxServerRegistration["selector"]): string {
76
+ return selector.kind === "path"
77
+ ? selector.path
78
+ : join("/tmp", `tmux-${String(process.getuid?.() ?? 0)}`, selector.name);
79
+ }
80
+ /** One stat: is there a socket file a server could be listening on? */
81
+ export function tmuxServerSocketPresent(selector: TmuxServerRegistration["selector"]): boolean {
82
+ try {
83
+ return statSync(tmuxSelectorSocketPath(selector)).isSocket();
84
+ } catch (error) {
85
+ // Only "it is not there" means absent; anything else is left to the probe.
86
+ const code = (error as NodeJS.ErrnoException).code;
87
+ return code !== "ENOENT" && code !== "ENOTDIR";
88
+ }
89
+ }
90
+ /**
91
+ * PURE. Given what `ps -o etime=,comm= -p <pid>` printed for the pid a tmux
92
+ * server had, is this provably another process? Yes when its command does not
93
+ * mention tmux at all, or when it started at another time than the server
94
+ * reported (`#{start_time}`, epoch seconds). Elapsed time is used rather than
95
+ * a start date so that neither locale nor time zone can make a live server
96
+ * look replaced. Unreadable output decides nothing.
97
+ */
98
+ export const SERVER_START_TOLERANCE_SECONDS = 10;
99
+ export function processIsNotTmuxServer(
100
+ psLine: string,
101
+ startTime: string,
102
+ nowSeconds: number,
103
+ ): boolean {
104
+ // "[[dd-]hh:]mm:ss command…", e.g. "12-07:10:40 /opt/…/tmux" or "02:13 tmux: server".
105
+ const match = /^\s*(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+)\s+(\S.*)$/u.exec(psLine);
106
+ if (!match) return false;
107
+ if (!/tmux/iu.test(match[5]!)) return true;
108
+ const elapsed =
109
+ Number(match[1] ?? 0) * 86_400 +
110
+ Number(match[2] ?? 0) * 3_600 +
111
+ Number(match[3]) * 60 +
112
+ Number(match[4]);
113
+ const reported = Number(startTime);
114
+ if (!Number.isSafeInteger(reported) || reported <= 0) return false;
115
+ return Math.abs(nowSeconds - elapsed - reported) > SERVER_START_TOLERANCE_SECONDS;
116
+ }
117
+ /** One `ps`, and only when a probe missed while the server's pid is alive. */
118
+ export async function tmuxServerProcessReplaced(identity: {
119
+ readonly pid: string;
120
+ readonly startTime: string;
121
+ }): Promise<boolean> {
122
+ if (!/^[1-9][0-9]*$/u.test(identity.pid)) return false;
123
+ try {
124
+ const { stdout } = await exec("/bin/ps", ["-o", "etime=,comm=", "-p", identity.pid], {
125
+ env: { LC_ALL: "C" },
126
+ encoding: "utf8",
127
+ timeout: 1_000,
128
+ maxBuffer: 4_096,
129
+ });
130
+ return processIsNotTmuxServer(
131
+ stdout.split("\n", 1)[0] ?? "",
132
+ identity.startTime,
133
+ Date.now() / 1_000,
134
+ );
135
+ } catch {
136
+ return false;
137
+ }
138
+ }
139
+ export const SOCKET_CONNECT_TIMEOUT_MS = 250;
140
+ /**
141
+ * Does this unix socket refuse connections outright (nobody listening, or no
142
+ * socket at all)? A connection that is accepted is closed at once; a timeout
143
+ * or any other error is not a refusal.
144
+ *
145
+ * A refusal is NOT proof that no server exists: a live server with a full
146
+ * accept queue is refused too. Use it only where a wrong "refused" is
147
+ * harmless, i.e. to skip probing a registration that is already offline.
148
+ */
149
+ export function unixSocketRefusesConnections(
150
+ path: string,
151
+ timeoutMs: number = SOCKET_CONNECT_TIMEOUT_MS,
152
+ ): Promise<boolean> {
153
+ return new Promise((resolve) => {
154
+ const socket = createConnection({ path });
155
+ const settle = (refused: boolean): void => {
156
+ socket.removeAllListeners();
157
+ socket.on("error", () => undefined);
158
+ socket.destroy();
159
+ resolve(refused);
160
+ };
161
+ socket.setTimeout(timeoutMs, () => settle(false));
162
+ socket.once("connect", () => settle(false));
163
+ socket.once("error", (error: NodeJS.ErrnoException) =>
164
+ settle(error.code === "ECONNREFUSED" || error.code === "ENOENT" || error.code === "ENOTSOCK"),
165
+ );
166
+ });
167
+ }
168
+ /**
169
+ * Say why a probe produced nothing. Only tmux itself answering "no server"
170
+ * (a clean non-zero exit) is a statement about the server; a timeout or a
171
+ * failed spawn says nothing about it (#840).
172
+ */
173
+ export function classifyTmuxServerProbeError(
174
+ error: unknown,
175
+ durationMs: number,
176
+ ): TmuxServerProbeFailure {
177
+ const failed = error as NodeJS.ErrnoException & {
178
+ killed?: boolean;
179
+ signal?: string | null;
180
+ stderr?: string;
181
+ };
182
+ const detail = (
183
+ (typeof failed?.stderr === "string" && failed.stderr.trim()) ||
184
+ (error instanceof Error ? error.message : String(error))
185
+ ).slice(0, 200);
186
+ const failure: TmuxServerProbeFailure["failure"] =
187
+ failed?.killed === true || (typeof failed?.signal === "string" && failed.signal.length > 0)
188
+ ? "timeout"
189
+ : typeof failed?.code === "number"
190
+ ? "no-server"
191
+ : "exec-error";
192
+ return { failure, detail, durationMs: Math.round(durationMs) };
193
+ }
63
194
  /** Discovery never creates a server, loads configuration, or attaches a client. */
64
195
  export function createTmuxServerProbe(
65
196
  executable: string,
66
197
  ): (selector: TmuxServerRegistration["selector"]) => Promise<TmuxServerObservation | null> {
198
+ const probe = createDiagnosedTmuxServerProbe(executable);
199
+ return async (selector) => {
200
+ const result = await probe(selector);
201
+ return isTmuxServerObservation(result) ? result : null;
202
+ };
203
+ }
204
+ /** The same probe, but a miss says why (timeout, failed spawn, no server, …). */
205
+ export function createDiagnosedTmuxServerProbe(
206
+ executable: string,
207
+ ): (selector: TmuxServerRegistration["selector"]) => Promise<TmuxServerProbeResult> {
67
208
  const executablePath = realpathSync(executable);
68
209
  const env = tmuxClientEnvironment(process.env, executablePath);
69
210
  return async (selector) => {
211
+ const started = performance.now();
212
+ const failed = (failure: TmuxServerProbeFailure["failure"], detail: string) => ({
213
+ failure,
214
+ detail,
215
+ durationMs: Math.round(performance.now() - started),
216
+ });
70
217
  const args = selector.kind === "path" ? ["-S", selector.path] : ["-L", selector.name];
71
218
  const read = async (selection: readonly string[]) =>
72
219
  (
73
220
  await exec(
74
221
  executablePath,
75
222
  [...selection, "-N", "display-message", "-p", "#{socket_path}|#{pid}|#{start_time}"],
76
- { env, encoding: "utf8", timeout: 500, maxBuffer: 8192 },
223
+ { env, encoding: "utf8", timeout: TMUX_SERVER_PROBE_TIMEOUT_MS, maxBuffer: 8192 },
77
224
  )
78
225
  ).stdout.trimEnd();
79
226
  try {
@@ -89,7 +236,7 @@ export function createTmuxServerProbe(
89
236
  }
90
237
  const first = await read(pinned ? ["-S", pinned.path] : args);
91
238
  const match = /^(.*)\|([1-9][0-9]*)\|([1-9][0-9]*)$/u.exec(first);
92
- if (!match) return null;
239
+ if (!match) return failed("unparsable", `${first.length} bytes of probe output`);
93
240
  const reportedSocket = captureUnixSocketIdentity(match[1]!);
94
241
  const socket = pinned ?? reportedSocket;
95
242
  if (pinned) {
@@ -98,8 +245,9 @@ export function createTmuxServerProbe(
98
245
  reportedSocket.dev !== pinned.dev ||
99
246
  reportedSocket.ino !== pinned.ino
100
247
  )
101
- return null;
102
- } else if ((await read(["-S", socket.path])) !== first) return null;
248
+ return failed("socket-mismatch", "the server answered from another socket");
249
+ } else if ((await read(["-S", socket.path])) !== first)
250
+ return failed("socket-mismatch", "the explicit-path proof differed");
103
251
  revalidateUnixSocketIdentity(socket);
104
252
  return {
105
253
  nativeServerIdentity: { pid: match[2]!, startTime: match[3]! },
@@ -116,8 +264,8 @@ export function createTmuxServerProbe(
116
264
  }
117
265
  },
118
266
  };
119
- } catch {
120
- return null;
267
+ } catch (error) {
268
+ return classifyTmuxServerProbeError(error, performance.now() - started);
121
269
  }
122
270
  };
123
271
  }
@@ -3,7 +3,29 @@ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
3
3
 
4
4
  const MAX_SOCKET_PATH_BYTES = 4_096;
5
5
 
6
+ /**
7
+ * The longest socket path a client can connect to: `sockaddr_un.sun_path` less
8
+ * its terminating NUL. 108 bytes on Linux, 104 on macOS and the BSDs.
9
+ */
10
+ export function unixSocketPathLimit(platform: NodeJS.Platform = process.platform): number {
11
+ return platform === "linux" ? 107 : 103;
12
+ }
13
+
14
+ export class UnixSocketPathTooLongError extends TypeError {
15
+ constructor(bytes: number, limit: number) {
16
+ super(
17
+ `The tmux socket path is ${bytes} bytes; this platform allows ${limit}. Start the tmux server on a shorter socket path.`,
18
+ );
19
+ this.name = "UnixSocketPathTooLongError";
20
+ }
21
+ }
22
+
6
23
  export interface UnixSocketIdentity {
24
+ /**
25
+ * The spelling to connect with. The canonical path when it fits
26
+ * {@link unixSocketPathLimit}; otherwise a shorter spelling proven to be the
27
+ * same socket, such as /tmp for /private/tmp on macOS (#384).
28
+ */
7
29
  readonly path: string;
8
30
  readonly dev: number;
9
31
  readonly ino: number;
@@ -31,7 +53,7 @@ export function captureUnixSocketIdentity(path: string): UnixSocketIdentity {
31
53
  if (!canonical.isSocket() || canonical.dev !== source.dev || canonical.ino !== source.ino)
32
54
  throw new TypeError("Unix socket authority changed while resolving");
33
55
  return Object.freeze({
34
- path: canonicalPath,
56
+ path: reachableSpelling(path, canonicalPath, canonical),
35
57
  dev: Number(canonical.dev),
36
58
  ino: Number(canonical.ino),
37
59
  mtimeNs: canonical.mtimeNs,
@@ -39,6 +61,35 @@ export function captureUnixSocketIdentity(path: string): UnixSocketIdentity {
39
61
  });
40
62
  }
41
63
 
64
+ /**
65
+ * tmux refuses a socket path longer than `sun_path` ("File name too long"). A
66
+ * server can still be running on such a socket when it was started through a
67
+ * shorter spelling. Use that spelling, but only when it names the same socket
68
+ * inode; `revalidateUnixSocketIdentity` checks that inode again before each use.
69
+ */
70
+ function reachableSpelling(
71
+ given: string,
72
+ canonicalPath: string,
73
+ canonical: { readonly dev: bigint; readonly ino: bigint },
74
+ ): string {
75
+ const limit = unixSocketPathLimit();
76
+ if (Buffer.byteLength(canonicalPath) <= limit) return canonicalPath;
77
+ const candidates = [given];
78
+ if (process.platform === "darwin" && /^\/private\/(?:tmp|var)\//u.test(canonicalPath))
79
+ candidates.push(canonicalPath.slice("/private".length));
80
+ for (const candidate of candidates) {
81
+ if (candidate === canonicalPath || Buffer.byteLength(candidate) > limit) continue;
82
+ try {
83
+ const socket = lstatSync(candidate, { bigint: true });
84
+ if (socket.isSocket() && socket.dev === canonical.dev && socket.ino === canonical.ino)
85
+ return candidate;
86
+ } catch {
87
+ // Not a usable spelling; try the next one.
88
+ }
89
+ }
90
+ throw new UnixSocketPathTooLongError(Buffer.byteLength(canonicalPath), limit);
91
+ }
92
+
42
93
  export function revalidateUnixSocketIdentity(identity: UnixSocketIdentity): string {
43
94
  if (
44
95
  !validSocketPath(identity.path) ||
@@ -57,9 +108,27 @@ export function revalidateUnixSocketIdentity(identity: UnixSocketIdentity): stri
57
108
  !current.isSocket() ||
58
109
  current.dev !== BigInt(identity.dev) ||
59
110
  current.ino !== BigInt(identity.ino) ||
60
- current.mtimeNs !== identity.mtimeNs ||
61
- current.birthtimeNs !== identity.birthtimeNs
111
+ current.birthtimeNs !== identity.birthtimeNs ||
112
+ (!birthtimeIdentifiesFile(process.platform) && current.mtimeNs !== identity.mtimeNs)
62
113
  )
63
114
  throw new TypeError("Unix socket authority changed before use");
64
115
  return identity.path;
65
116
  }
117
+
118
+ /**
119
+ * A socket that was replaced at the same path can get the same inode number
120
+ * back, so device and inode alone do not identify it. Where the filesystem
121
+ * records a real creation time (macOS and the BSDs), that settles it, and the
122
+ * modification time must not: `touch` on the socket of a healthy tmux server
123
+ * changes mtime and would otherwise retire its owner and close every stream.
124
+ * Linux reports a creation time only on some filesystems and Node substitutes
125
+ * the change time elsewhere, so there mtime stays part of the identity.
126
+ */
127
+ export function birthtimeIdentifiesFile(platform: NodeJS.Platform): boolean {
128
+ return (
129
+ platform === "darwin" ||
130
+ platform === "freebsd" ||
131
+ platform === "openbsd" ||
132
+ platform === "netbsd"
133
+ );
134
+ }
@@ -280,6 +280,14 @@ export interface WorkspaceTmuxAsyncRunOptions extends WorkspaceTmuxRunOptions {
280
280
  readonly maxOutputBytes?: number;
281
281
  }
282
282
 
283
+ /**
284
+ * Every synchronous tmux call blocks the daemon's only thread: requests,
285
+ * signal handlers and deadlines all wait for it. A tmux client that never
286
+ * returns must therefore never be waited for without a bound. Callers may
287
+ * pass their own; nobody gets "no timeout".
288
+ */
289
+ export const PINNED_SYNC_TMUX_TIMEOUT_MS = 5_000;
290
+
283
291
  export function createPinnedWorkspaceTmuxRunner(
284
292
  authority: WorkspacePaneTmuxAuthority,
285
293
  options: Readonly<{ timeoutMs?: number }> = {},
@@ -325,7 +333,9 @@ export function createPinnedWorkspaceTmuxRunner(
325
333
  env: environment,
326
334
  maxBuffer: TMUX_OUTPUT_BYTES,
327
335
  stdio: ["ignore", "pipe", "pipe"],
328
- ...(options.timeoutMs === undefined ? {} : { timeout: options.timeoutMs }),
336
+ timeout: options.timeoutMs ?? PINNED_SYNC_TMUX_TIMEOUT_MS,
337
+ // A client that ignores TERM must not outlive the bound.
338
+ killSignal: "SIGKILL",
329
339
  }),
330
340
  );
331
341
  // A cold named authority may create its first server with this command.
@@ -149,6 +149,12 @@ const ERROR_MESSAGES: Readonly<Record<WorkspacePromotionErrorCode, string>> = {
149
149
  operation_capacity: "The daemon has reached its bounded workspace-promote operation capacity.",
150
150
  };
151
151
 
152
+ /**
153
+ * How often a promotion stamps and proves a session whose pane inventory
154
+ * changed between the proof's two reads, before it refuses.
155
+ */
156
+ export const PROMOTION_PROOF_ATTEMPTS = 3;
157
+
152
158
  export class WorkspacePromotionError extends Error {
153
159
  readonly code: WorkspacePromotionErrorCode;
154
160
  readonly context: Readonly<Record<string, string>>;
@@ -594,9 +600,26 @@ export class WorkspacePromotionAuthority {
594
600
  : derivePromotionIdentity(session.sessionName);
595
601
  this.#assertConflictFreeIdentity(identity);
596
602
 
597
- const canonicalRoot = await this.#stampSession(request, session, identity);
598
- this.#assertActive(request.operationId);
599
- await this.#verifyPromotedInventory(session.sessionId, identity);
603
+ // Another tmux client may split or close a pane while the session is
604
+ // being proved (an agent does it all day). The proof then cannot hold:
605
+ // stamp what is there now and prove again, a bounded number of times.
606
+ let canonicalRoot!: string;
607
+ for (let attempt = 1; ; attempt += 1) {
608
+ canonicalRoot = await this.#stampSession(request, session, identity);
609
+ this.#assertActive(request.operationId);
610
+ try {
611
+ await this.#verifyPromotedInventory(session.sessionId, identity);
612
+ break;
613
+ } catch (error) {
614
+ if (
615
+ attempt >= PROMOTION_PROOF_ATTEMPTS ||
616
+ !(error instanceof WorkspacePromotionError) ||
617
+ error.context.reason !== "inventory_changed_during_proof"
618
+ )
619
+ throw error;
620
+ this.#assertActive(request.operationId);
621
+ }
622
+ }
600
623
  await this.#publishFleetEnrollment(request, session, identity);
601
624
 
602
625
  // Catalog discovery can admit this session while the native stamping
@@ -15,7 +15,7 @@ import {
15
15
  } from "node:fs";
16
16
  import { basename, join } from "node:path";
17
17
  import { parseArgs } from "node:util";
18
- import { terminalSafe, terminalSafeBlock } from "@tmux-ide/contracts";
18
+ import { ACTION_NAMES, terminalSafe, terminalSafeBlock } from "@tmux-ide/contracts";
19
19
  import { grantConsent, hashPluginDirectory, revokeConsent } from "./consent.ts";
20
20
  import { discoverPlugins, pluginPaths, type PluginAwaitingConsent } from "./discovery.ts";
21
21
  import { findOnPath } from "./exec-sandbox.ts";
@@ -609,7 +609,6 @@ export async function defaultPluginCliIo(): Promise<PluginCliIo> {
609
609
  }
610
610
  },
611
611
  dispatchBuiltin: async (name, input) => {
612
- const { ACTION_NAMES } = await import("@tmux-ide/contracts");
613
612
  if (!(ACTION_NAMES as readonly string[]).includes(name))
614
613
  throw new PluginCliError(`No command named '${name}'.`);
615
614
  const { tryDispatchAction } = await import("../lib/cli-action-bridge.ts");
@@ -3,6 +3,7 @@ import type { Socket } from "node:net";
3
3
  import { WebSocketServer } from "ws";
4
4
  import { PANE_STREAM_REDEEM_PATH, PANE_STREAM_WEBSOCKET_SUBPROTOCOL } from "@tmux-ide/contracts";
5
5
  import type { DirectTerminalSocket } from "../terminal/attachments/direct-websocket.ts";
6
+ import { daemonWebSocketHeartbeat, type WebSocketHeartbeat } from "./websocket-heartbeat.ts";
6
7
  import {
7
8
  PANE_STREAM_MAX_CONTROL_BYTES,
8
9
  PANE_STREAM_MAX_REDEMPTION_BYTES,
@@ -60,6 +61,7 @@ export function attachPaneStreamWebSocket(
60
61
  coordinator: PaneStreamAdmissionCoordinator,
61
62
  redemptionPath: string = PANE_STREAM_REDEEM_PATH,
62
63
  isCurrent: () => boolean = () => true,
64
+ heartbeat: WebSocketHeartbeat = daemonWebSocketHeartbeat(),
63
65
  ): PaneStreamWebSocketBoundary {
64
66
  const wss = new WebSocketServer({
65
67
  noServer: true,
@@ -74,6 +76,9 @@ export function attachPaneStreamWebSocket(
74
76
  },
75
77
  });
76
78
 
79
+ // Old clients ignore the header and answer the pings by protocol.
80
+ wss.on("headers", (headers) => heartbeat.advertise(headers));
81
+
77
82
  const upgrade = (
78
83
  request: import("node:http").IncomingMessage,
79
84
  socket: Socket,
@@ -140,6 +145,7 @@ export function attachPaneStreamWebSocket(
140
145
  wss.handleUpgrade(request, socket, head, (ws) => {
141
146
  socket.off("close", cancelUnbound);
142
147
  socket.off("error", cancelUnbound);
148
+ heartbeat.watch(ws, `pane-stream ${redemptionPath}`);
143
149
  decision.admission.bind(ws as unknown as DirectTerminalSocket);
144
150
  });
145
151
  } catch {
@@ -0,0 +1,135 @@
1
+ import {
2
+ WEBSOCKET_HEARTBEAT_HEADER,
3
+ WEBSOCKET_HEARTBEAT_INTERVAL_MS,
4
+ WEBSOCKET_HEARTBEAT_MAX_INTERVAL_MS,
5
+ WEBSOCKET_HEARTBEAT_MIN_INTERVAL_MS,
6
+ WEBSOCKET_HEARTBEAT_MISSED_LIMIT,
7
+ formatWebSocketHeartbeatHeader,
8
+ type WebSocketHeartbeatPolicy,
9
+ } from "@tmux-ide/contracts";
10
+ import { logger } from "../lib/log.ts";
11
+
12
+ /** The part of a `ws` socket the heartbeat needs. */
13
+ export interface HeartbeatSocket {
14
+ ping(): void;
15
+ terminate(): void;
16
+ on(event: "pong" | "close", listener: () => void): unknown;
17
+ off(event: "pong" | "close", listener: () => void): unknown;
18
+ }
19
+
20
+ export interface WebSocketHeartbeat {
21
+ readonly policy: WebSocketHeartbeatPolicy;
22
+ /** Start pinging this socket; it leaves by itself when it closes. */
23
+ watch(socket: HeartbeatSocket, label: string): void;
24
+ /** `ws` "headers" listener: advertises the cadence on the upgrade response. */
25
+ advertise(headers: string[]): void;
26
+ readonly watched: number;
27
+ /** True while the one shared timer exists, i.e. while anything is watched. */
28
+ readonly ticking: boolean;
29
+ }
30
+
31
+ /**
32
+ * One timer for every watched socket, and none while nothing is watched: an
33
+ * idle daemon with no clients pays nothing. Each tick sends one ping frame
34
+ * (2 bytes) per connection and reads back one pong (6 bytes); a socket that
35
+ * answered none of `missedLimit` consecutive pings is terminated, which lets
36
+ * the owning transport release its leases through its ordinary close path.
37
+ */
38
+ export function createWebSocketHeartbeat(
39
+ policy: WebSocketHeartbeatPolicy = {
40
+ intervalMs: WEBSOCKET_HEARTBEAT_INTERVAL_MS,
41
+ missedLimit: WEBSOCKET_HEARTBEAT_MISSED_LIMIT,
42
+ },
43
+ ): WebSocketHeartbeat {
44
+ const sockets = new Map<HeartbeatSocket, { unanswered: number; label: string }>();
45
+ let timer: ReturnType<typeof setInterval> | null = null;
46
+ const tick = (): void => {
47
+ for (const [socket, state] of [...sockets]) {
48
+ if (state.unanswered >= policy.missedLimit) {
49
+ logger.warn("websocket-heartbeat", "peer answered no ping; connection dropped", {
50
+ connection: state.label,
51
+ unansweredPings: state.unanswered,
52
+ intervalMs: policy.intervalMs,
53
+ });
54
+ forget(socket);
55
+ try {
56
+ socket.terminate();
57
+ } catch {
58
+ /* Already gone. */
59
+ }
60
+ continue;
61
+ }
62
+ state.unanswered += 1;
63
+ try {
64
+ socket.ping();
65
+ } catch {
66
+ /* A socket that cannot be pinged is closing; its close event removes it. */
67
+ }
68
+ }
69
+ };
70
+ const listeners = new Map<HeartbeatSocket, { pong: () => void; close: () => void }>();
71
+ const forget = (socket: HeartbeatSocket): void => {
72
+ const attached = listeners.get(socket);
73
+ if (attached) {
74
+ socket.off("pong", attached.pong);
75
+ socket.off("close", attached.close);
76
+ listeners.delete(socket);
77
+ }
78
+ sockets.delete(socket);
79
+ if (sockets.size === 0 && timer) {
80
+ clearInterval(timer);
81
+ timer = null;
82
+ }
83
+ };
84
+ return {
85
+ policy,
86
+ watch(socket, label) {
87
+ if (sockets.has(socket)) return;
88
+ const state = { unanswered: 0, label };
89
+ sockets.set(socket, state);
90
+ const attached = {
91
+ pong: () => {
92
+ state.unanswered = 0;
93
+ },
94
+ close: () => forget(socket),
95
+ };
96
+ listeners.set(socket, attached);
97
+ socket.on("pong", attached.pong);
98
+ socket.on("close", attached.close);
99
+ if (!timer) {
100
+ timer = setInterval(tick, policy.intervalMs);
101
+ timer.unref?.();
102
+ }
103
+ },
104
+ advertise(headers) {
105
+ headers.push(`${WEBSOCKET_HEARTBEAT_HEADER}: ${formatWebSocketHeartbeatHeader(policy)}`);
106
+ },
107
+ get watched() {
108
+ return sockets.size;
109
+ },
110
+ get ticking() {
111
+ return timer !== null;
112
+ },
113
+ };
114
+ }
115
+
116
+ /** Soaks and tests may shorten the interval; anything out of range keeps the default. */
117
+ export function heartbeatPolicyFromEnvironment(
118
+ environment: NodeJS.ProcessEnv = process.env,
119
+ ): WebSocketHeartbeatPolicy {
120
+ const configured = Number(environment.TMUX_IDE_WS_HEARTBEAT_INTERVAL_MS);
121
+ const intervalMs =
122
+ Number.isSafeInteger(configured) &&
123
+ configured >= WEBSOCKET_HEARTBEAT_MIN_INTERVAL_MS &&
124
+ configured <= WEBSOCKET_HEARTBEAT_MAX_INTERVAL_MS
125
+ ? configured
126
+ : WEBSOCKET_HEARTBEAT_INTERVAL_MS;
127
+ return { intervalMs, missedLimit: WEBSOCKET_HEARTBEAT_MISSED_LIMIT };
128
+ }
129
+
130
+ let shared: WebSocketHeartbeat | null = null;
131
+ /** The daemon process's single heartbeat: every route shares its one timer. */
132
+ export function daemonWebSocketHeartbeat(): WebSocketHeartbeat {
133
+ shared ??= createWebSocketHeartbeat(heartbeatPolicyFromEnvironment());
134
+ return shared;
135
+ }