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
@@ -1,12 +1,13 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
- import { mkdirSync, readFileSync, renameSync, writeFileSync, realpathSync, unlinkSync, } from "node:fs";
5
- import { dirname } from "node:path";
4
+ import { mkdirSync, readFileSync, renameSync, writeFileSync, realpathSync, statSync, unlinkSync, } from "node:fs";
5
+ import { dirname, join } from "node:path";
6
+ import { createConnection } from "node:net";
6
7
  import { z } from "zod";
7
8
  import { tmuxClientEnvironment } from "./tmux-client-execution.js";
8
9
  import { captureUnixSocketIdentity, revalidateUnixSocketIdentity, } from "./unix-socket-authority.js";
9
- import { MAX_TMUX_SERVER_OWNERS, TmuxServerRegistrationSchemaZ, } from "./tmux-server-owners.js";
10
+ import { MAX_TMUX_SERVER_OWNERS, TmuxServerRegistrationSchemaZ, isTmuxServerObservation, } from "./tmux-server-owners.js";
10
11
  const exec = promisify(execFile);
11
12
  const FileSchema = z
12
13
  .object({
@@ -45,13 +46,131 @@ export function writeTmuxServerRegistrations(path, registrations) {
45
46
  }
46
47
  }
47
48
  }
49
+ export const TMUX_SERVER_PROBE_TIMEOUT_MS = 500;
50
+ /**
51
+ * Where the daemon's tmux clients find this selector's socket. They run with
52
+ * a scrubbed environment (no TMUX_TMPDIR), so a named socket is always in
53
+ * /tmp/tmux-<uid>/.
54
+ */
55
+ export function tmuxSelectorSocketPath(selector) {
56
+ return selector.kind === "path"
57
+ ? selector.path
58
+ : join("/tmp", `tmux-${String(process.getuid?.() ?? 0)}`, selector.name);
59
+ }
60
+ /** One stat: is there a socket file a server could be listening on? */
61
+ export function tmuxServerSocketPresent(selector) {
62
+ try {
63
+ return statSync(tmuxSelectorSocketPath(selector)).isSocket();
64
+ }
65
+ catch (error) {
66
+ // Only "it is not there" means absent; anything else is left to the probe.
67
+ const code = error.code;
68
+ return code !== "ENOENT" && code !== "ENOTDIR";
69
+ }
70
+ }
71
+ /**
72
+ * PURE. Given what `ps -o etime=,comm= -p <pid>` printed for the pid a tmux
73
+ * server had, is this provably another process? Yes when its command does not
74
+ * mention tmux at all, or when it started at another time than the server
75
+ * reported (`#{start_time}`, epoch seconds). Elapsed time is used rather than
76
+ * a start date so that neither locale nor time zone can make a live server
77
+ * look replaced. Unreadable output decides nothing.
78
+ */
79
+ export const SERVER_START_TOLERANCE_SECONDS = 10;
80
+ export function processIsNotTmuxServer(psLine, startTime, nowSeconds) {
81
+ // "[[dd-]hh:]mm:ss command…", e.g. "12-07:10:40 /opt/…/tmux" or "02:13 tmux: server".
82
+ const match = /^\s*(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+)\s+(\S.*)$/u.exec(psLine);
83
+ if (!match)
84
+ return false;
85
+ if (!/tmux/iu.test(match[5]))
86
+ return true;
87
+ const elapsed = Number(match[1] ?? 0) * 86_400 +
88
+ Number(match[2] ?? 0) * 3_600 +
89
+ Number(match[3]) * 60 +
90
+ Number(match[4]);
91
+ const reported = Number(startTime);
92
+ if (!Number.isSafeInteger(reported) || reported <= 0)
93
+ return false;
94
+ return Math.abs(nowSeconds - elapsed - reported) > SERVER_START_TOLERANCE_SECONDS;
95
+ }
96
+ /** One `ps`, and only when a probe missed while the server's pid is alive. */
97
+ export async function tmuxServerProcessReplaced(identity) {
98
+ if (!/^[1-9][0-9]*$/u.test(identity.pid))
99
+ return false;
100
+ try {
101
+ const { stdout } = await exec("/bin/ps", ["-o", "etime=,comm=", "-p", identity.pid], {
102
+ env: { LC_ALL: "C" },
103
+ encoding: "utf8",
104
+ timeout: 1_000,
105
+ maxBuffer: 4_096,
106
+ });
107
+ return processIsNotTmuxServer(stdout.split("\n", 1)[0] ?? "", identity.startTime, Date.now() / 1_000);
108
+ }
109
+ catch {
110
+ return false;
111
+ }
112
+ }
113
+ export const SOCKET_CONNECT_TIMEOUT_MS = 250;
114
+ /**
115
+ * Does this unix socket refuse connections outright (nobody listening, or no
116
+ * socket at all)? A connection that is accepted is closed at once; a timeout
117
+ * or any other error is not a refusal.
118
+ *
119
+ * A refusal is NOT proof that no server exists: a live server with a full
120
+ * accept queue is refused too. Use it only where a wrong "refused" is
121
+ * harmless, i.e. to skip probing a registration that is already offline.
122
+ */
123
+ export function unixSocketRefusesConnections(path, timeoutMs = SOCKET_CONNECT_TIMEOUT_MS) {
124
+ return new Promise((resolve) => {
125
+ const socket = createConnection({ path });
126
+ const settle = (refused) => {
127
+ socket.removeAllListeners();
128
+ socket.on("error", () => undefined);
129
+ socket.destroy();
130
+ resolve(refused);
131
+ };
132
+ socket.setTimeout(timeoutMs, () => settle(false));
133
+ socket.once("connect", () => settle(false));
134
+ socket.once("error", (error) => settle(error.code === "ECONNREFUSED" || error.code === "ENOENT" || error.code === "ENOTSOCK"));
135
+ });
136
+ }
137
+ /**
138
+ * Say why a probe produced nothing. Only tmux itself answering "no server"
139
+ * (a clean non-zero exit) is a statement about the server; a timeout or a
140
+ * failed spawn says nothing about it (#840).
141
+ */
142
+ export function classifyTmuxServerProbeError(error, durationMs) {
143
+ const failed = error;
144
+ const detail = ((typeof failed?.stderr === "string" && failed.stderr.trim()) ||
145
+ (error instanceof Error ? error.message : String(error))).slice(0, 200);
146
+ const failure = failed?.killed === true || (typeof failed?.signal === "string" && failed.signal.length > 0)
147
+ ? "timeout"
148
+ : typeof failed?.code === "number"
149
+ ? "no-server"
150
+ : "exec-error";
151
+ return { failure, detail, durationMs: Math.round(durationMs) };
152
+ }
48
153
  /** Discovery never creates a server, loads configuration, or attaches a client. */
49
154
  export function createTmuxServerProbe(executable) {
155
+ const probe = createDiagnosedTmuxServerProbe(executable);
156
+ return async (selector) => {
157
+ const result = await probe(selector);
158
+ return isTmuxServerObservation(result) ? result : null;
159
+ };
160
+ }
161
+ /** The same probe, but a miss says why (timeout, failed spawn, no server, …). */
162
+ export function createDiagnosedTmuxServerProbe(executable) {
50
163
  const executablePath = realpathSync(executable);
51
164
  const env = tmuxClientEnvironment(process.env, executablePath);
52
165
  return async (selector) => {
166
+ const started = performance.now();
167
+ const failed = (failure, detail) => ({
168
+ failure,
169
+ detail,
170
+ durationMs: Math.round(performance.now() - started),
171
+ });
53
172
  const args = selector.kind === "path" ? ["-S", selector.path] : ["-L", selector.name];
54
- const read = async (selection) => (await exec(executablePath, [...selection, "-N", "display-message", "-p", "#{socket_path}|#{pid}|#{start_time}"], { env, encoding: "utf8", timeout: 500, maxBuffer: 8192 })).stdout.trimEnd();
173
+ const read = async (selection) => (await exec(executablePath, [...selection, "-N", "display-message", "-p", "#{socket_path}|#{pid}|#{start_time}"], { env, encoding: "utf8", timeout: TMUX_SERVER_PROBE_TIMEOUT_MS, maxBuffer: 8192 })).stdout.trimEnd();
55
174
  try {
56
175
  // A direct socket can be pinned before contacting tmux. Named servers
57
176
  // and aliases still need discovery followed by an explicit-path proof.
@@ -67,17 +186,17 @@ export function createTmuxServerProbe(executable) {
67
186
  const first = await read(pinned ? ["-S", pinned.path] : args);
68
187
  const match = /^(.*)\|([1-9][0-9]*)\|([1-9][0-9]*)$/u.exec(first);
69
188
  if (!match)
70
- return null;
189
+ return failed("unparsable", `${first.length} bytes of probe output`);
71
190
  const reportedSocket = captureUnixSocketIdentity(match[1]);
72
191
  const socket = pinned ?? reportedSocket;
73
192
  if (pinned) {
74
193
  if (reportedSocket.path !== pinned.path ||
75
194
  reportedSocket.dev !== pinned.dev ||
76
195
  reportedSocket.ino !== pinned.ino)
77
- return null;
196
+ return failed("socket-mismatch", "the server answered from another socket");
78
197
  }
79
198
  else if ((await read(["-S", socket.path])) !== first)
80
- return null;
199
+ return failed("socket-mismatch", "the explicit-path proof differed");
81
200
  revalidateUnixSocketIdentity(socket);
82
201
  return {
83
202
  nativeServerIdentity: { pid: match[2], startTime: match[3] },
@@ -96,8 +215,8 @@ export function createTmuxServerProbe(executable) {
96
215
  },
97
216
  };
98
217
  }
99
- catch {
100
- return null;
218
+ catch (error) {
219
+ return classifyTmuxServerProbeError(error, performance.now() - started);
101
220
  }
102
221
  };
103
222
  }
@@ -1,6 +1,19 @@
1
1
  import { lstatSync, realpathSync } from "node:fs";
2
2
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
3
3
  const MAX_SOCKET_PATH_BYTES = 4_096;
4
+ /**
5
+ * The longest socket path a client can connect to: `sockaddr_un.sun_path` less
6
+ * its terminating NUL. 108 bytes on Linux, 104 on macOS and the BSDs.
7
+ */
8
+ export function unixSocketPathLimit(platform = process.platform) {
9
+ return platform === "linux" ? 107 : 103;
10
+ }
11
+ export class UnixSocketPathTooLongError extends TypeError {
12
+ constructor(bytes, limit) {
13
+ super(`The tmux socket path is ${bytes} bytes; this platform allows ${limit}. Start the tmux server on a shorter socket path.`);
14
+ this.name = "UnixSocketPathTooLongError";
15
+ }
16
+ }
4
17
  function validSocketPath(path) {
5
18
  return (isAbsolute(path) &&
6
19
  resolve(path) === path &&
@@ -19,13 +32,40 @@ export function captureUnixSocketIdentity(path) {
19
32
  if (!canonical.isSocket() || canonical.dev !== source.dev || canonical.ino !== source.ino)
20
33
  throw new TypeError("Unix socket authority changed while resolving");
21
34
  return Object.freeze({
22
- path: canonicalPath,
35
+ path: reachableSpelling(path, canonicalPath, canonical),
23
36
  dev: Number(canonical.dev),
24
37
  ino: Number(canonical.ino),
25
38
  mtimeNs: canonical.mtimeNs,
26
39
  birthtimeNs: canonical.birthtimeNs,
27
40
  });
28
41
  }
42
+ /**
43
+ * tmux refuses a socket path longer than `sun_path` ("File name too long"). A
44
+ * server can still be running on such a socket when it was started through a
45
+ * shorter spelling. Use that spelling, but only when it names the same socket
46
+ * inode; `revalidateUnixSocketIdentity` checks that inode again before each use.
47
+ */
48
+ function reachableSpelling(given, canonicalPath, canonical) {
49
+ const limit = unixSocketPathLimit();
50
+ if (Buffer.byteLength(canonicalPath) <= limit)
51
+ return canonicalPath;
52
+ const candidates = [given];
53
+ if (process.platform === "darwin" && /^\/private\/(?:tmp|var)\//u.test(canonicalPath))
54
+ candidates.push(canonicalPath.slice("/private".length));
55
+ for (const candidate of candidates) {
56
+ if (candidate === canonicalPath || Buffer.byteLength(candidate) > limit)
57
+ continue;
58
+ try {
59
+ const socket = lstatSync(candidate, { bigint: true });
60
+ if (socket.isSocket() && socket.dev === canonical.dev && socket.ino === canonical.ino)
61
+ return candidate;
62
+ }
63
+ catch {
64
+ // Not a usable spelling; try the next one.
65
+ }
66
+ }
67
+ throw new UnixSocketPathTooLongError(Buffer.byteLength(canonicalPath), limit);
68
+ }
29
69
  export function revalidateUnixSocketIdentity(identity) {
30
70
  if (!validSocketPath(identity.path) ||
31
71
  !Number.isSafeInteger(identity.dev) ||
@@ -41,8 +81,23 @@ export function revalidateUnixSocketIdentity(identity) {
41
81
  if (!current.isSocket() ||
42
82
  current.dev !== BigInt(identity.dev) ||
43
83
  current.ino !== BigInt(identity.ino) ||
44
- current.mtimeNs !== identity.mtimeNs ||
45
- current.birthtimeNs !== identity.birthtimeNs)
84
+ current.birthtimeNs !== identity.birthtimeNs ||
85
+ (!birthtimeIdentifiesFile(process.platform) && current.mtimeNs !== identity.mtimeNs))
46
86
  throw new TypeError("Unix socket authority changed before use");
47
87
  return identity.path;
48
88
  }
89
+ /**
90
+ * A socket that was replaced at the same path can get the same inode number
91
+ * back, so device and inode alone do not identify it. Where the filesystem
92
+ * records a real creation time (macOS and the BSDs), that settles it, and the
93
+ * modification time must not: `touch` on the socket of a healthy tmux server
94
+ * changes mtime and would otherwise retire its owner and close every stream.
95
+ * Linux reports a creation time only on some filesystems and Node substitutes
96
+ * the change time elsewhere, so there mtime stays part of the identity.
97
+ */
98
+ export function birthtimeIdentifiesFile(platform) {
99
+ return (platform === "darwin" ||
100
+ platform === "freebsd" ||
101
+ platform === "openbsd" ||
102
+ platform === "netbsd");
103
+ }
@@ -144,6 +144,13 @@ export function resolveWorkspacePaneTmuxAuthority() {
144
144
  // consulting a later request's TMUX/PATH.
145
145
  return Object.freeze({ executablePath, socketSelector: namespace.tmuxSocket });
146
146
  }
147
+ /**
148
+ * Every synchronous tmux call blocks the daemon's only thread: requests,
149
+ * signal handlers and deadlines all wait for it. A tmux client that never
150
+ * returns must therefore never be waited for without a bound. Callers may
151
+ * pass their own; nobody gets "no timeout".
152
+ */
153
+ export const PINNED_SYNC_TMUX_TIMEOUT_MS = 5_000;
147
154
  export function createPinnedWorkspaceTmuxRunner(authority, options = {}) {
148
155
  const executablePath = realpathSync(authority.executablePath);
149
156
  accessSync(executablePath, constants.X_OK);
@@ -180,7 +187,9 @@ export function createPinnedWorkspaceTmuxRunner(authority, options = {}) {
180
187
  env: environment,
181
188
  maxBuffer: TMUX_OUTPUT_BYTES,
182
189
  stdio: ["ignore", "pipe", "pipe"],
183
- ...(options.timeoutMs === undefined ? {} : { timeout: options.timeoutMs }),
190
+ timeout: options.timeoutMs ?? PINNED_SYNC_TMUX_TIMEOUT_MS,
191
+ // A client that ignores TERM must not outlive the bound.
192
+ killSignal: "SIGKILL",
184
193
  }));
185
194
  // A cold named authority may create its first server with this command.
186
195
  if (namedFence && !namedFence.isPinned())
@@ -21,9 +21,9 @@
21
21
  <key>CFBundlePackageType</key>
22
22
  <string>APPL</string>
23
23
  <key>CFBundleShortVersionString</key>
24
- <string>2.9.22</string>
24
+ <string>2.9.23</string>
25
25
  <key>CFBundleVersion</key>
26
- <string>2.9.22</string>
26
+ <string>2.9.23</string>
27
27
  <key>LSMinimumSystemVersion</key>
28
28
  <string>11.0</string>
29
29
  <key>LSUIElement</key>
@@ -10,7 +10,7 @@
10
10
  </data>
11
11
  <key>Resources/Assets.car</key>
12
12
  <data>
13
- Cx0kflSNo25xIPuHfTvLfggPEdA=
13
+ eIcSkXParZcC4QAg0KZlGi3qdeA=
14
14
  </data>
15
15
  </dict>
16
16
  <key>files2</key>
@@ -26,7 +26,7 @@
26
26
  <dict>
27
27
  <key>hash2</key>
28
28
  <data>
29
- 6P/aOxWEmYu/LP87/6VutmD2v02KSwG2hwcfWcR90Xo=
29
+ s1pgcF7YhjrKOlxkEdh7I3iHyy1chYzX1V7z2eoz8Nk=
30
30
  </data>
31
31
  </dict>
32
32
  </dict>
@@ -5,7 +5,7 @@ import { execFileSync } from "node:child_process";
5
5
  import { closeSync, existsSync, realpathSync, mkdirSync, openSync, readFileSync, readSync, statSync, writeFileSync, } from "node:fs";
6
6
  import { basename, join } from "node:path";
7
7
  import { parseArgs } from "node:util";
8
- import { terminalSafe, terminalSafeBlock } from "@tmux-ide/contracts";
8
+ import { ACTION_NAMES, terminalSafe, terminalSafeBlock } from "@tmux-ide/contracts";
9
9
  import { grantConsent, hashPluginDirectory, revokeConsent } from "./consent.js";
10
10
  import { discoverPlugins, pluginPaths } from "./discovery.js";
11
11
  import { findOnPath } from "./exec-sandbox.js";
@@ -533,7 +533,6 @@ export async function defaultPluginCliIo() {
533
533
  }
534
534
  },
535
535
  dispatchBuiltin: async (name, input) => {
536
- const { ACTION_NAMES } = await import("@tmux-ide/contracts");
537
536
  if (!ACTION_NAMES.includes(name))
538
537
  throw new PluginCliError(`No command named '${name}'.`);
539
538
  const { tryDispatchAction } = await import("../lib/cli-action-bridge.js");
@@ -1,5 +1,6 @@
1
1
  import { WebSocketServer } from "ws";
2
2
  import { PANE_STREAM_REDEEM_PATH, PANE_STREAM_WEBSOCKET_SUBPROTOCOL } from "@tmux-ide/contracts";
3
+ import { daemonWebSocketHeartbeat } from "./websocket-heartbeat.js";
3
4
  import { PANE_STREAM_MAX_CONTROL_BYTES, PANE_STREAM_MAX_REDEMPTION_BYTES, } from "../terminal/pane-stream/pane-stream-websocket.js";
4
5
  function protocols(value) {
5
6
  if (typeof value !== "string")
@@ -38,7 +39,7 @@ function rejectUpgrade(socket, status) {
38
39
  * Origin, and pre-auth capacity decisions happen before `handleUpgrade`, so
39
40
  * rejected requests never become WebSockets.
40
41
  */
41
- export function attachPaneStreamWebSocket(server, coordinator, redemptionPath = PANE_STREAM_REDEEM_PATH, isCurrent = () => true) {
42
+ export function attachPaneStreamWebSocket(server, coordinator, redemptionPath = PANE_STREAM_REDEEM_PATH, isCurrent = () => true, heartbeat = daemonWebSocketHeartbeat()) {
42
43
  const wss = new WebSocketServer({
43
44
  noServer: true,
44
45
  clientTracking: false,
@@ -51,6 +52,8 @@ export function attachPaneStreamWebSocket(server, coordinator, redemptionPath =
51
52
  : false;
52
53
  },
53
54
  });
55
+ // Old clients ignore the header and answer the pings by protocol.
56
+ wss.on("headers", (headers) => heartbeat.advertise(headers));
54
57
  const upgrade = (request, socket, head) => {
55
58
  const rawPath = request.url ?? "";
56
59
  const pathname = rawPath.split("?", 1)[0] ?? "";
@@ -110,6 +113,7 @@ export function attachPaneStreamWebSocket(server, coordinator, redemptionPath =
110
113
  wss.handleUpgrade(request, socket, head, (ws) => {
111
114
  socket.off("close", cancelUnbound);
112
115
  socket.off("error", cancelUnbound);
116
+ heartbeat.watch(ws, `pane-stream ${redemptionPath}`);
113
117
  decision.admission.bind(ws);
114
118
  });
115
119
  }
@@ -0,0 +1,103 @@
1
+ import { WEBSOCKET_HEARTBEAT_HEADER, WEBSOCKET_HEARTBEAT_INTERVAL_MS, WEBSOCKET_HEARTBEAT_MAX_INTERVAL_MS, WEBSOCKET_HEARTBEAT_MIN_INTERVAL_MS, WEBSOCKET_HEARTBEAT_MISSED_LIMIT, formatWebSocketHeartbeatHeader, } from "@tmux-ide/contracts";
2
+ import { logger } from "../lib/log.js";
3
+ /**
4
+ * One timer for every watched socket, and none while nothing is watched: an
5
+ * idle daemon with no clients pays nothing. Each tick sends one ping frame
6
+ * (2 bytes) per connection and reads back one pong (6 bytes); a socket that
7
+ * answered none of `missedLimit` consecutive pings is terminated, which lets
8
+ * the owning transport release its leases through its ordinary close path.
9
+ */
10
+ export function createWebSocketHeartbeat(policy = {
11
+ intervalMs: WEBSOCKET_HEARTBEAT_INTERVAL_MS,
12
+ missedLimit: WEBSOCKET_HEARTBEAT_MISSED_LIMIT,
13
+ }) {
14
+ const sockets = new Map();
15
+ let timer = null;
16
+ const tick = () => {
17
+ for (const [socket, state] of [...sockets]) {
18
+ if (state.unanswered >= policy.missedLimit) {
19
+ logger.warn("websocket-heartbeat", "peer answered no ping; connection dropped", {
20
+ connection: state.label,
21
+ unansweredPings: state.unanswered,
22
+ intervalMs: policy.intervalMs,
23
+ });
24
+ forget(socket);
25
+ try {
26
+ socket.terminate();
27
+ }
28
+ catch {
29
+ /* Already gone. */
30
+ }
31
+ continue;
32
+ }
33
+ state.unanswered += 1;
34
+ try {
35
+ socket.ping();
36
+ }
37
+ catch {
38
+ /* A socket that cannot be pinged is closing; its close event removes it. */
39
+ }
40
+ }
41
+ };
42
+ const listeners = new Map();
43
+ const forget = (socket) => {
44
+ const attached = listeners.get(socket);
45
+ if (attached) {
46
+ socket.off("pong", attached.pong);
47
+ socket.off("close", attached.close);
48
+ listeners.delete(socket);
49
+ }
50
+ sockets.delete(socket);
51
+ if (sockets.size === 0 && timer) {
52
+ clearInterval(timer);
53
+ timer = null;
54
+ }
55
+ };
56
+ return {
57
+ policy,
58
+ watch(socket, label) {
59
+ if (sockets.has(socket))
60
+ return;
61
+ const state = { unanswered: 0, label };
62
+ sockets.set(socket, state);
63
+ const attached = {
64
+ pong: () => {
65
+ state.unanswered = 0;
66
+ },
67
+ close: () => forget(socket),
68
+ };
69
+ listeners.set(socket, attached);
70
+ socket.on("pong", attached.pong);
71
+ socket.on("close", attached.close);
72
+ if (!timer) {
73
+ timer = setInterval(tick, policy.intervalMs);
74
+ timer.unref?.();
75
+ }
76
+ },
77
+ advertise(headers) {
78
+ headers.push(`${WEBSOCKET_HEARTBEAT_HEADER}: ${formatWebSocketHeartbeatHeader(policy)}`);
79
+ },
80
+ get watched() {
81
+ return sockets.size;
82
+ },
83
+ get ticking() {
84
+ return timer !== null;
85
+ },
86
+ };
87
+ }
88
+ /** Soaks and tests may shorten the interval; anything out of range keeps the default. */
89
+ export function heartbeatPolicyFromEnvironment(environment = process.env) {
90
+ const configured = Number(environment.TMUX_IDE_WS_HEARTBEAT_INTERVAL_MS);
91
+ const intervalMs = Number.isSafeInteger(configured) &&
92
+ configured >= WEBSOCKET_HEARTBEAT_MIN_INTERVAL_MS &&
93
+ configured <= WEBSOCKET_HEARTBEAT_MAX_INTERVAL_MS
94
+ ? configured
95
+ : WEBSOCKET_HEARTBEAT_INTERVAL_MS;
96
+ return { intervalMs, missedLimit: WEBSOCKET_HEARTBEAT_MISSED_LIMIT };
97
+ }
98
+ let shared = null;
99
+ /** The daemon process's single heartbeat: every route shares its one timer. */
100
+ export function daemonWebSocketHeartbeat() {
101
+ shared ??= createWebSocketHeartbeat(heartbeatPolicyFromEnvironment());
102
+ return shared;
103
+ }
@@ -43,10 +43,16 @@ const ERROR_MESSAGES = {
43
43
  };
44
44
  export class NativeTerminalAttachmentRuntimeError extends Error {
45
45
  code;
46
- constructor(code) {
46
+ /**
47
+ * Which of the several origins of this code it was. For diagnostics only:
48
+ * the message a client sees stays the same.
49
+ */
50
+ detail;
51
+ constructor(code, detail) {
47
52
  super(ERROR_MESSAGES[code]);
48
53
  this.name = "NativeTerminalAttachmentRuntimeError";
49
54
  this.code = code;
55
+ this.detail = detail;
50
56
  }
51
57
  }
52
58
  let nativeTerminalAttachmentRuntimeConstructions = 0;
@@ -463,7 +469,7 @@ async function requiredTmuxResult(runner, argv, signal) {
463
469
  if (result.status === "not-found")
464
470
  return null;
465
471
  if (result.status !== "ok") {
466
- throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
472
+ throw new NativeTerminalAttachmentRuntimeError("discovery-failed", `tmux-command-${result.status}`);
467
473
  }
468
474
  return result.stdout;
469
475
  }
@@ -584,6 +590,18 @@ function parsePaneSnapshot(stdout, expected) {
584
590
  * before any pane query, and a second identity/topology snapshot closes races.
585
591
  */
586
592
  const INVENTORY_FENCE_ATTEMPTS = 4;
593
+ /**
594
+ * A read that was overtaken by an inventory invalidation is not a failed
595
+ * read: the answer it was computing is simply out of date, so it is read
596
+ * again. One retry was not enough while tmux topology is in motion: creating
597
+ * an agent pane invalidates the inventory several times within a few hundred
598
+ * milliseconds, a read overtaken twice failed with "discovery-failed", the
599
+ * inventory route answered 503, and a click on the new agent's row landed on
600
+ * "That agent changed or disappeared" until the client's backoff recovered
601
+ * seconds later (#764, journey soak 43257599866). Still bounded: a server
602
+ * whose topology never stops moving must not hold a reader for ever.
603
+ */
604
+ export const INVENTORY_STALE_RETRIES = 4;
587
605
  /** 25, 50, 100 ms: enough for a mutation's identity stamps, bounded for every reader. */
588
606
  const settleDelay = (attempt) => new Promise((resolve) => setTimeout(resolve, 25 * 2 ** (attempt - 1)));
589
607
  export async function discoverWorkspaceRegistryTerminalInventory(registry, runner, signal) {
@@ -634,7 +652,7 @@ export async function discoverWorkspaceRegistryTerminalInventory(registry, runne
634
652
  await settleDelay(attempt);
635
653
  const after = await requiredTmuxResult(runner, argv, signal);
636
654
  if (after === null)
637
- throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
655
+ throw new NativeTerminalAttachmentRuntimeError("discovery-failed", "session-vanished-mid-read");
638
656
  const next = parsePaneSnapshot(after, identity);
639
657
  if (matches(previous, next))
640
658
  stable = next;
@@ -642,7 +660,7 @@ export async function discoverWorkspaceRegistryTerminalInventory(registry, runne
642
660
  previous = next;
643
661
  }
644
662
  if (!stable)
645
- throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
663
+ throw new NativeTerminalAttachmentRuntimeError("discovery-failed", "topology-not-settled");
646
664
  bySessionName.set(sessionName, stable.panes);
647
665
  }
648
666
  const panes = [];
@@ -1066,18 +1084,18 @@ export class WorkspaceTerminalInventoryRuntime {
1066
1084
  }
1067
1085
  catch (error) {
1068
1086
  if (this.#inventoryEpoch !== epoch) {
1069
- if (staleRetry < 1)
1087
+ if (staleRetry < INVENTORY_STALE_RETRIES)
1070
1088
  return this.#readInventory(signal, staleRetry + 1);
1071
- throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
1089
+ throw new NativeTerminalAttachmentRuntimeError("discovery-failed", "overtaken-by-invalidations");
1072
1090
  }
1073
1091
  throw error;
1074
1092
  }
1075
1093
  if (signal.aborted)
1076
1094
  throw new NativeTerminalAttachmentRuntimeError("runtime-disposed");
1077
1095
  if (this.#inventoryEpoch !== epoch) {
1078
- if (staleRetry < 1)
1096
+ if (staleRetry < INVENTORY_STALE_RETRIES)
1079
1097
  return this.#readInventory(signal, staleRetry + 1);
1080
- throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
1098
+ throw new NativeTerminalAttachmentRuntimeError("discovery-failed", "overtaken-by-invalidations");
1081
1099
  }
1082
1100
  return this.#publishInventory(snapshot, nativeEpoch, signal, epoch);
1083
1101
  }
@@ -1091,16 +1109,16 @@ export class WorkspaceTerminalInventoryRuntime {
1091
1109
  }
1092
1110
  catch (error) {
1093
1111
  if (abort.signal.aborted || this.#inventoryEpoch !== epoch) {
1094
- if (staleRetry < 1)
1112
+ if (staleRetry < INVENTORY_STALE_RETRIES)
1095
1113
  return this.#readInventory(undefined, staleRetry + 1);
1096
- throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
1114
+ throw new NativeTerminalAttachmentRuntimeError("discovery-failed", "overtaken-by-invalidations");
1097
1115
  }
1098
1116
  throw error;
1099
1117
  }
1100
1118
  if (abort.signal.aborted || this.#inventoryEpoch !== epoch) {
1101
- if (staleRetry < 1)
1119
+ if (staleRetry < INVENTORY_STALE_RETRIES)
1102
1120
  return this.#readInventory(undefined, staleRetry + 1);
1103
- throw new NativeTerminalAttachmentRuntimeError("discovery-failed");
1121
+ throw new NativeTerminalAttachmentRuntimeError("discovery-failed", "overtaken-by-invalidations");
1104
1122
  }
1105
1123
  return this.#publishInventory(value, nativeEpoch, abort.signal, epoch);
1106
1124
  })().finally(() => {
@@ -1156,9 +1174,9 @@ export class WorkspaceTerminalInventoryRuntime {
1156
1174
  assertLive();
1157
1175
  if (this.#inventoryEpoch === epoch)
1158
1176
  return null;
1159
- if (staleRetry < 1)
1177
+ if (staleRetry < INVENTORY_STALE_RETRIES)
1160
1178
  return this.#discoverTerminalRuntimeSession(requestedSessionName, signal, staleRetry + 1);
1161
- return Promise.reject(new NativeTerminalAttachmentRuntimeError("discovery-failed"));
1179
+ return Promise.reject(new NativeTerminalAttachmentRuntimeError("discovery-failed", "overtaken-by-invalidations"));
1162
1180
  };
1163
1181
  assertLive();
1164
1182
  const nativeEpoch = this.#nativeServerEpoch?.() ?? null;
@@ -7,3 +7,14 @@ export function layoutContentRows(paneTop, paneHeight, windowRows, border) {
7
7
  const touchesStatusEdge = border === "top" ? paneTop === 0 : paneTop + paneHeight === windowRows;
8
8
  return paneHeight - (touchesStatusEdge ? 1 : 0);
9
9
  }
10
+ /**
11
+ * The status line a window's tiled panes have, from its `pane-border-status`.
12
+ * tmux 3.8's `top-floating` and `bottom-floating` put a status line on floating
13
+ * panes only (`window_get_pane_status`), so tiled panes are laid out as "off".
14
+ * Null for a value this daemon does not know.
15
+ */
16
+ export function tiledPaneBorderStatus(option) {
17
+ if (option === "off" || option === "top" || option === "bottom")
18
+ return option;
19
+ return option === "top-floating" || option === "bottom-floating" ? "off" : null;
20
+ }