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
@@ -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.
@@ -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
+ }
@@ -111,11 +111,17 @@ const ERROR_MESSAGES: Readonly<Record<NativeTerminalAttachmentRuntimeErrorCode,
111
111
 
112
112
  export class NativeTerminalAttachmentRuntimeError extends Error {
113
113
  readonly code: NativeTerminalAttachmentRuntimeErrorCode;
114
+ /**
115
+ * Which of the several origins of this code it was. For diagnostics only:
116
+ * the message a client sees stays the same.
117
+ */
118
+ readonly detail: string | undefined;
114
119
 
115
- constructor(code: NativeTerminalAttachmentRuntimeErrorCode) {
120
+ constructor(code: NativeTerminalAttachmentRuntimeErrorCode, detail?: string) {
116
121
  super(ERROR_MESSAGES[code]);
117
122
  this.name = "NativeTerminalAttachmentRuntimeError";
118
123
  this.code = code;
124
+ this.detail = detail;
119
125
  }
120
126
  }
121
127
 
@@ -730,7 +736,10 @@ async function requiredTmuxResult(
730
736
  const result = await runner.run({ executable: "tmux", argv }, signal);
731
737
  if (result.status === "not-found") return null;
732
738
  if (result.status !== "ok") {
733
- throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
739
+ throw new NativeTerminalAttachmentRuntimeError(
740
+ "discovery-failed",
741
+ `tmux-command-${result.status}`,
742
+ );
734
743
  }
735
744
  return result.stdout;
736
745
  }
@@ -919,6 +928,18 @@ function parsePaneSnapshot(
919
928
  * before any pane query, and a second identity/topology snapshot closes races.
920
929
  */
921
930
  const INVENTORY_FENCE_ATTEMPTS = 4;
931
+ /**
932
+ * A read that was overtaken by an inventory invalidation is not a failed
933
+ * read: the answer it was computing is simply out of date, so it is read
934
+ * again. One retry was not enough while tmux topology is in motion: creating
935
+ * an agent pane invalidates the inventory several times within a few hundred
936
+ * milliseconds, a read overtaken twice failed with "discovery-failed", the
937
+ * inventory route answered 503, and a click on the new agent's row landed on
938
+ * "That agent changed or disappeared" until the client's backoff recovered
939
+ * seconds later (#764, journey soak 43257599866). Still bounded: a server
940
+ * whose topology never stops moving must not hold a reader for ever.
941
+ */
942
+ export const INVENTORY_STALE_RETRIES = 4;
922
943
  /** 25, 50, 100 ms: enough for a mutation's identity stamps, bounded for every reader. */
923
944
  const settleDelay = (attempt: number) =>
924
945
  new Promise<void>((resolve) => setTimeout(resolve, 25 * 2 ** (attempt - 1)));
@@ -977,12 +998,17 @@ export async function discoverWorkspaceRegistryTerminalInventory(
977
998
  for (let attempt = 0; attempt < INVENTORY_FENCE_ATTEMPTS && !stable; attempt += 1) {
978
999
  if (attempt > 0) await settleDelay(attempt);
979
1000
  const after = await requiredTmuxResult(runner, argv, signal);
980
- if (after === null) throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
1001
+ if (after === null)
1002
+ throw new NativeTerminalAttachmentRuntimeError(
1003
+ "discovery-failed",
1004
+ "session-vanished-mid-read",
1005
+ );
981
1006
  const next = parsePaneSnapshot(after, identity);
982
1007
  if (matches(previous, next)) stable = next;
983
1008
  else previous = next;
984
1009
  }
985
- if (!stable) throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
1010
+ if (!stable)
1011
+ throw new NativeTerminalAttachmentRuntimeError("discovery-failed", "topology-not-settled");
986
1012
  bySessionName.set(sessionName, stable.panes);
987
1013
  }
988
1014
 
@@ -1609,15 +1635,23 @@ export class WorkspaceTerminalInventoryRuntime {
1609
1635
  snapshot = await this.#readInventoryAttempt(signal);
1610
1636
  } catch (error) {
1611
1637
  if (this.#inventoryEpoch !== epoch) {
1612
- if (staleRetry < 1) return this.#readInventory(signal, staleRetry + 1);
1613
- throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
1638
+ if (staleRetry < INVENTORY_STALE_RETRIES)
1639
+ return this.#readInventory(signal, staleRetry + 1);
1640
+ throw new NativeTerminalAttachmentRuntimeError(
1641
+ "discovery-failed",
1642
+ "overtaken-by-invalidations",
1643
+ );
1614
1644
  }
1615
1645
  throw error;
1616
1646
  }
1617
1647
  if (signal.aborted) throw new NativeTerminalAttachmentRuntimeError("runtime-disposed");
1618
1648
  if (this.#inventoryEpoch !== epoch) {
1619
- if (staleRetry < 1) return this.#readInventory(signal, staleRetry + 1);
1620
- throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
1649
+ if (staleRetry < INVENTORY_STALE_RETRIES)
1650
+ return this.#readInventory(signal, staleRetry + 1);
1651
+ throw new NativeTerminalAttachmentRuntimeError(
1652
+ "discovery-failed",
1653
+ "overtaken-by-invalidations",
1654
+ );
1621
1655
  }
1622
1656
  return this.#publishInventory(snapshot, nativeEpoch, signal, epoch);
1623
1657
  }
@@ -1629,14 +1663,22 @@ export class WorkspaceTerminalInventoryRuntime {
1629
1663
  value = await this.#readInventoryAttempt(abort.signal);
1630
1664
  } catch (error) {
1631
1665
  if (abort.signal.aborted || this.#inventoryEpoch !== epoch) {
1632
- if (staleRetry < 1) return this.#readInventory(undefined, staleRetry + 1);
1633
- throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
1666
+ if (staleRetry < INVENTORY_STALE_RETRIES)
1667
+ return this.#readInventory(undefined, staleRetry + 1);
1668
+ throw new NativeTerminalAttachmentRuntimeError(
1669
+ "discovery-failed",
1670
+ "overtaken-by-invalidations",
1671
+ );
1634
1672
  }
1635
1673
  throw error;
1636
1674
  }
1637
1675
  if (abort.signal.aborted || this.#inventoryEpoch !== epoch) {
1638
- if (staleRetry < 1) return this.#readInventory(undefined, staleRetry + 1);
1639
- throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
1676
+ if (staleRetry < INVENTORY_STALE_RETRIES)
1677
+ return this.#readInventory(undefined, staleRetry + 1);
1678
+ throw new NativeTerminalAttachmentRuntimeError(
1679
+ "discovery-failed",
1680
+ "overtaken-by-invalidations",
1681
+ );
1640
1682
  }
1641
1683
  return this.#publishInventory(value, nativeEpoch, abort.signal, epoch);
1642
1684
  })().finally(() => {
@@ -1703,9 +1745,11 @@ export class WorkspaceTerminalInventoryRuntime {
1703
1745
  const retryIfReplaced = (): Promise<NativeTerminalRuntimeSessionSnapshot | null> | null => {
1704
1746
  assertLive();
1705
1747
  if (this.#inventoryEpoch === epoch) return null;
1706
- if (staleRetry < 1)
1748
+ if (staleRetry < INVENTORY_STALE_RETRIES)
1707
1749
  return this.#discoverTerminalRuntimeSession(requestedSessionName, signal, staleRetry + 1);
1708
- return Promise.reject(new NativeTerminalAttachmentRuntimeError("discovery-failed"));
1750
+ return Promise.reject(
1751
+ new NativeTerminalAttachmentRuntimeError("discovery-failed", "overtaken-by-invalidations"),
1752
+ );
1709
1753
  };
1710
1754
  assertLive();
1711
1755
  const nativeEpoch = this.#nativeServerEpoch?.() ?? null;