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
@@ -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())
@@ -81,6 +81,11 @@ const ERROR_MESSAGES = {
81
81
  operation_conflict: "The operation id was already used for another promotion intent.",
82
82
  operation_capacity: "The daemon has reached its bounded workspace-promote operation capacity.",
83
83
  };
84
+ /**
85
+ * How often a promotion stamps and proves a session whose pane inventory
86
+ * changed between the proof's two reads, before it refuses.
87
+ */
88
+ export const PROMOTION_PROOF_ATTEMPTS = 3;
84
89
  export class WorkspacePromotionError extends Error {
85
90
  code;
86
91
  context;
@@ -392,9 +397,25 @@ export class WorkspacePromotionAuthority {
392
397
  ? { workspaceName: alreadyRegistered.name, sessionName: session.sessionName }
393
398
  : derivePromotionIdentity(session.sessionName);
394
399
  this.#assertConflictFreeIdentity(identity);
395
- const canonicalRoot = await this.#stampSession(request, session, identity);
396
- this.#assertActive(request.operationId);
397
- await this.#verifyPromotedInventory(session.sessionId, identity);
400
+ // Another tmux client may split or close a pane while the session is
401
+ // being proved (an agent does it all day). The proof then cannot hold:
402
+ // stamp what is there now and prove again, a bounded number of times.
403
+ let canonicalRoot;
404
+ for (let attempt = 1;; attempt += 1) {
405
+ canonicalRoot = await this.#stampSession(request, session, identity);
406
+ this.#assertActive(request.operationId);
407
+ try {
408
+ await this.#verifyPromotedInventory(session.sessionId, identity);
409
+ break;
410
+ }
411
+ catch (error) {
412
+ if (attempt >= PROMOTION_PROOF_ATTEMPTS ||
413
+ !(error instanceof WorkspacePromotionError) ||
414
+ error.context.reason !== "inventory_changed_during_proof")
415
+ throw error;
416
+ this.#assertActive(request.operationId);
417
+ }
418
+ }
398
419
  await this.#publishFleetEnrollment(request, session, identity);
399
420
  // Catalog discovery can admit this session while the native stamping
400
421
  // and verification awaits run. Reuse that exact registry identity instead
@@ -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.24</string>
25
25
  <key>CFBundleVersion</key>
26
- <string>2.9.22</string>
26
+ <string>2.9.24</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
+ GCWmy3k4L/Ut1Iml1My4dWKAUXA=
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
+ mxm/LqezJ+GdXPR4Ujh+KGO7Z0Fod7ULKDxJsNy91/A=
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
+ }