tmux-ide 2.9.21 → 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 (131) hide show
  1. package/bin/cli.js +6235 -8473
  2. package/package.json +3 -3
  3. package/packages/contracts/src/index.ts +2 -0
  4. package/packages/contracts/src/pane-reader.ts +121 -0
  5. package/packages/contracts/src/pane-stream.ts +18 -0
  6. package/packages/contracts/src/visual-theme-presets.ts +58 -2
  7. package/packages/contracts/src/websocket-heartbeat.ts +41 -0
  8. package/packages/daemon/dist/command-center/automation.js +1 -1
  9. package/packages/daemon/dist/command-center/daemon-fleet-facts-observer.js +37 -5
  10. package/packages/daemon/dist/command-center/discovery.js +28 -2
  11. package/packages/daemon/dist/command-center/server.js +8 -2
  12. package/packages/daemon/dist/command-center/tmux-server-reader.js +41 -0
  13. package/packages/daemon/dist/command-center/tmux-servers.js +7 -1
  14. package/packages/daemon/dist/doctor.js +147 -43
  15. package/packages/daemon/dist/lib/bounded-tmux-read.js +34 -12
  16. package/packages/daemon/dist/lib/cli-command.js +13 -0
  17. package/packages/daemon/dist/lib/daemon-embed.js +126 -55
  18. package/packages/daemon/dist/lib/daemon-stop-progress.js +58 -0
  19. package/packages/daemon/dist/lib/embedded-daemon-lifecycle.js +11 -0
  20. package/packages/daemon/dist/lib/embedded-tmux-server-owners.js +88 -12
  21. package/packages/daemon/dist/lib/headless-daemon.js +177 -10
  22. package/packages/daemon/dist/lib/log.js +18 -1
  23. package/packages/daemon/dist/lib/pane-reader-files.js +226 -0
  24. package/packages/daemon/dist/lib/remote-tmux-command.js +8 -5
  25. package/packages/daemon/dist/lib/tmux-client-execution.js +73 -7
  26. package/packages/daemon/dist/lib/tmux-external-interaction-observer.js +140 -19
  27. package/packages/daemon/dist/lib/tmux-native-browser.js +4 -2
  28. package/packages/daemon/dist/lib/tmux-pane-reader.js +107 -0
  29. package/packages/daemon/dist/lib/tmux-server-agent-admission.js +6 -1
  30. package/packages/daemon/dist/lib/tmux-server-features.js +38 -0
  31. package/packages/daemon/dist/lib/tmux-server-owner-teardown.js +33 -0
  32. package/packages/daemon/dist/lib/tmux-server-owner.js +38 -37
  33. package/packages/daemon/dist/lib/tmux-server-owners.js +310 -20
  34. package/packages/daemon/dist/lib/tmux-server-registration.js +128 -9
  35. package/packages/daemon/dist/lib/unix-socket-authority.js +58 -3
  36. package/packages/daemon/dist/lib/workspace-pane-creation.js +10 -1
  37. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  38. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  39. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  40. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  41. package/packages/daemon/dist/open-browser.js +26 -12
  42. package/packages/daemon/dist/open-reader.js +84 -0
  43. package/packages/daemon/dist/plugins/cli.js +1 -2
  44. package/packages/daemon/dist/plugins/daemon-plugins.js +2 -10
  45. package/packages/daemon/dist/restore.js +57 -40
  46. package/packages/daemon/dist/server/pane-stream-upgrade.js +5 -1
  47. package/packages/daemon/dist/server/websocket-heartbeat.js +103 -0
  48. package/packages/daemon/dist/terminal/attachments/native-runtime.js +32 -14
  49. package/packages/daemon/dist/terminal/mirror/layout-content-rows.js +11 -0
  50. package/packages/daemon/dist/terminal/mirror/mirror-service.js +61 -3
  51. package/packages/daemon/dist/terminal/mirror/session-channel.js +13 -12
  52. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +123 -25
  53. package/packages/daemon/dist/terminal/pane-stream/runtime.js +3 -2
  54. package/packages/daemon/dist/terminal/protocol/reader-option.js +66 -0
  55. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +30 -2
  56. package/packages/daemon/dist/terminal/protocol/stock-split-resize.js +4 -1
  57. package/packages/daemon/dist/terminal/session-runtime/registry.js +17 -0
  58. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +81 -3
  59. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +60 -3
  60. package/packages/daemon/dist/tmux-upgrade/cli.js +106 -0
  61. package/packages/daemon/dist/tmux-upgrade/io.js +540 -0
  62. package/packages/daemon/dist/tmux-upgrade/plan.js +238 -0
  63. package/packages/daemon/dist/tmux-upgrade/run.js +199 -0
  64. package/packages/daemon/dist/tui/chrome/snapshot.js +3 -4
  65. package/packages/daemon/dist/tui/mirror/runtime/application-home-agent-navigation.js +64 -4
  66. package/packages/daemon/dist/tui/mirror/runtime/application-home-agents-owner.js +35 -5
  67. package/packages/daemon/dist/tui/mirror/runtime/application-machine-agent-navigation.js +12 -8
  68. package/packages/daemon/dist/tui/mirror/runtime/application-terminal-interaction-controller.js +125 -111
  69. package/packages/daemon/src/command-center/automation.ts +1 -1
  70. package/packages/daemon/src/command-center/daemon-fleet-facts-observer.ts +49 -8
  71. package/packages/daemon/src/command-center/discovery.ts +35 -2
  72. package/packages/daemon/src/command-center/server.ts +22 -8
  73. package/packages/daemon/src/command-center/tmux-server-reader.ts +62 -0
  74. package/packages/daemon/src/command-center/tmux-servers.ts +7 -1
  75. package/packages/daemon/src/doctor.ts +164 -45
  76. package/packages/daemon/src/lib/bounded-tmux-read.ts +29 -9
  77. package/packages/daemon/src/lib/cli-command.ts +16 -0
  78. package/packages/daemon/src/lib/daemon-embed.ts +176 -64
  79. package/packages/daemon/src/lib/daemon-stop-progress.ts +78 -0
  80. package/packages/daemon/src/lib/embedded-daemon-lifecycle.ts +12 -0
  81. package/packages/daemon/src/lib/embedded-tmux-server-owners.ts +115 -11
  82. package/packages/daemon/src/lib/headless-daemon.ts +205 -12
  83. package/packages/daemon/src/lib/log.ts +18 -1
  84. package/packages/daemon/src/lib/pane-reader-files.ts +294 -0
  85. package/packages/daemon/src/lib/remote-tmux-command.ts +13 -6
  86. package/packages/daemon/src/lib/tmux-client-execution.ts +79 -7
  87. package/packages/daemon/src/lib/tmux-external-interaction-observer.ts +163 -25
  88. package/packages/daemon/src/lib/tmux-native-browser.ts +4 -3
  89. package/packages/daemon/src/lib/tmux-pane-reader.ts +145 -0
  90. package/packages/daemon/src/lib/tmux-server-agent-admission.ts +6 -1
  91. package/packages/daemon/src/lib/tmux-server-features.ts +43 -0
  92. package/packages/daemon/src/lib/tmux-server-owner-teardown.ts +54 -0
  93. package/packages/daemon/src/lib/tmux-server-owner.ts +41 -35
  94. package/packages/daemon/src/lib/tmux-server-owners.ts +427 -22
  95. package/packages/daemon/src/lib/tmux-server-registration.ts +155 -7
  96. package/packages/daemon/src/lib/unix-socket-authority.ts +72 -3
  97. package/packages/daemon/src/lib/workspace-pane-creation.ts +11 -1
  98. package/packages/daemon/src/open-browser.ts +59 -18
  99. package/packages/daemon/src/open-reader.ts +148 -0
  100. package/packages/daemon/src/plugins/cli.ts +1 -2
  101. package/packages/daemon/src/plugins/daemon-plugins.ts +2 -12
  102. package/packages/daemon/src/restore.ts +80 -44
  103. package/packages/daemon/src/server/pane-stream-upgrade.ts +6 -0
  104. package/packages/daemon/src/server/websocket-heartbeat.ts +135 -0
  105. package/packages/daemon/src/terminal/attachments/native-runtime.ts +58 -14
  106. package/packages/daemon/src/terminal/mirror/events.ts +2 -0
  107. package/packages/daemon/src/terminal/mirror/layout-content-rows.ts +11 -0
  108. package/packages/daemon/src/terminal/mirror/mirror-service.ts +61 -2
  109. package/packages/daemon/src/terminal/mirror/session-channel.ts +15 -14
  110. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +140 -23
  111. package/packages/daemon/src/terminal/pane-stream/runtime.ts +4 -2
  112. package/packages/daemon/src/terminal/protocol/reader-option.ts +77 -0
  113. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +41 -1
  114. package/packages/daemon/src/terminal/protocol/stock-split-resize.ts +6 -1
  115. package/packages/daemon/src/terminal/session-runtime/registry.ts +23 -0
  116. package/packages/daemon/src/terminal/session-runtime/runtime-observability.ts +2 -0
  117. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +100 -3
  118. package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +60 -3
  119. package/packages/daemon/src/tmux-upgrade/cli.ts +118 -0
  120. package/packages/daemon/src/tmux-upgrade/io.ts +596 -0
  121. package/packages/daemon/src/tmux-upgrade/plan.ts +353 -0
  122. package/packages/daemon/src/tmux-upgrade/run.ts +325 -0
  123. package/packages/daemon/src/tui/chrome/snapshot.ts +3 -4
  124. package/packages/daemon/src/tui/mirror/runtime/application-home-agent-navigation.ts +110 -10
  125. package/packages/daemon/src/tui/mirror/runtime/application-home-agents-owner.ts +58 -6
  126. package/packages/daemon/src/tui/mirror/runtime/application-machine-agent-navigation.ts +20 -9
  127. package/packages/daemon/src/tui/mirror/runtime/application-root-v2.tsx +2 -2
  128. package/packages/daemon/src/tui/mirror/runtime/application-terminal-interaction-controller.ts +149 -128
  129. package/packages/daemon-client/src/direct-application-shell-transport.ts +21 -3
  130. package/packages/daemon-client/src/workspace-event-supervisor.ts +63 -2
  131. package/packages/tmux-bridge/src/runner.ts +3 -1
@@ -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.
@@ -114,7 +114,7 @@ export function validateBrowserOpen(url: string | undefined, options: OpenBrowse
114
114
  });
115
115
  }
116
116
 
117
- type Run = (args: readonly string[]) => string;
117
+ export type Run = (args: readonly string[]) => string;
118
118
 
119
119
  /** Printed when the opened browser never publishes tmux-ide's native controls. */
120
120
  export const NO_NATIVE_CONTROLS_NOTICE =
@@ -163,16 +163,16 @@ export async function nativeControlsNotice(
163
163
  await sleep(250);
164
164
  }
165
165
  }
166
- export function createBrowserPane(
166
+ type PaneKind = "BROWSER" | "READER";
167
+
168
+ /** Where a new browser or reader pane goes: resolved IDs, before any mutation. */
169
+ export function resolveOpenPaneTarget(
167
170
  run: Run,
168
- executable: string,
169
- url: string | undefined,
170
171
  options: OpenBrowserOptions,
171
172
  environment: NodeJS.ProcessEnv,
172
- cwd: string,
173
- namespace: Readonly<Record<string, string>>,
174
- ): { pane: string; session: string; window: string; status: "created" } {
175
- validateBrowserOpen(url, options);
173
+ kind: PaneKind = "BROWSER",
174
+ ): { session: string; window: string; sourcePane: string } {
175
+ const noun = kind.toLowerCase();
176
176
  const inheritedPane = /^%\d+$/u.test(environment.TMUX_PANE ?? "")
177
177
  ? environment.TMUX_PANE
178
178
  : undefined;
@@ -188,7 +188,7 @@ export function createBrowserPane(
188
188
  if (!target)
189
189
  throw new IdeError(
190
190
  "Run tmux-ide open inside a tmux pane, or select a session with --session NAME.",
191
- { code: "BROWSER_TARGET_REQUIRED", exitCode: 2 },
191
+ { code: `${kind}_TARGET_REQUIRED`, exitCode: 2 },
192
192
  );
193
193
  // Resolve IDs before mutation. No implicit last-used session or window target.
194
194
  const identity = run([
@@ -207,13 +207,13 @@ export function createBrowserPane(
207
207
  !/^@\d+$/u.test(window ?? "") ||
208
208
  !/^%\d+$/u.test(sourcePane ?? "")
209
209
  )
210
- throw new IdeError("The browser target is no longer available.", {
211
- code: "BROWSER_TARGET_UNAVAILABLE",
210
+ throw new IdeError(`The ${noun} target is no longer available.`, {
211
+ code: `${kind}_TARGET_UNAVAILABLE`,
212
212
  });
213
213
  if (implicit && serverPid !== inheritedServer?.[2])
214
214
  throw new IdeError(
215
215
  "The current pane belongs to a different tmux server. Select a session explicitly.",
216
- { code: "BROWSER_TARGET_MISMATCH", exitCode: 2 },
216
+ { code: `${kind}_TARGET_MISMATCH`, exitCode: 2 },
217
217
  );
218
218
  if (options.session && options.pane) {
219
219
  const selected = run([
@@ -225,21 +225,38 @@ export function createBrowserPane(
225
225
  ]).trim();
226
226
  if (selected !== session)
227
227
  throw new IdeError("The pane does not belong to the requested session.", {
228
- code: "BROWSER_TARGET_MISMATCH",
228
+ code: `${kind}_TARGET_MISMATCH`,
229
229
  exitCode: 2,
230
230
  });
231
231
  }
232
+ return { session: session!, window: window!, sourcePane: sourcePane! };
233
+ }
234
+
235
+ /**
236
+ * The tmux argv that creates the pane and runs `command` in it directly (no
237
+ * shell parsing). `format` is what tmux prints for the new pane.
238
+ */
239
+ export function openPaneArgs(
240
+ target: { session: string; window: string; sourcePane: string },
241
+ options: OpenBrowserOptions,
242
+ environment: NodeJS.ProcessEnv,
243
+ cwd: string,
244
+ namespace: Readonly<Record<string, string>>,
245
+ command: readonly string[],
246
+ format: string,
247
+ windowName: string,
248
+ ): string[] {
232
249
  const args = options.window
233
- ? ["new-window", "-t", `${session}:`, "-n", "Browser"]
250
+ ? ["new-window", "-t", `${target.session}:`, "-n", windowName]
234
251
  : [
235
252
  "split-window",
236
253
  options.split === "down" ? "-v" : "-h",
237
254
  "-t",
238
- `${session}:${window}.${sourcePane}`,
255
+ `${target.session}:${target.window}.${target.sourcePane}`,
239
256
  "-l",
240
257
  `${options.size ?? "50"}%`,
241
258
  ];
242
- args.push("-c", resolve(cwd), "-P", "-F", "#{session_id}\t#{window_id}\t#{pane_id}");
259
+ args.push("-c", resolve(cwd), "-P", "-F", format);
243
260
  // tmux supplies the new pane's TMUX and TMUX_PANE. Never copy the caller's
244
261
  // native-surface route, which belongs to a different pane.
245
262
  const childEnvironment: Record<string, string> = { ...namespace };
@@ -255,11 +272,35 @@ export function createBrowserPane(
255
272
  if (environment[key] !== undefined) childEnvironment[key] = environment[key];
256
273
  for (const [key, value] of Object.entries(childEnvironment)) args.push("-e", `${key}=${value}`);
257
274
  // Multiple command arguments use tmux's direct exec path, not shell parsing.
258
- args.push(executable, "open", ...(url === undefined ? [] : [url]), "--no-merge");
275
+ args.push(...command);
276
+ return args;
277
+ }
278
+
279
+ export function createBrowserPane(
280
+ run: Run,
281
+ executable: string,
282
+ url: string | undefined,
283
+ options: OpenBrowserOptions,
284
+ environment: NodeJS.ProcessEnv,
285
+ cwd: string,
286
+ namespace: Readonly<Record<string, string>>,
287
+ ): { pane: string; session: string; window: string; status: "created" } {
288
+ validateBrowserOpen(url, options);
289
+ const target = resolveOpenPaneTarget(run, options, environment);
290
+ const args = openPaneArgs(
291
+ target,
292
+ options,
293
+ environment,
294
+ cwd,
295
+ namespace,
296
+ [executable, "open", ...(url === undefined ? [] : [url]), "--no-merge"],
297
+ "#{session_id}\t#{window_id}\t#{pane_id}",
298
+ "Browser",
299
+ );
259
300
  const [createdSession, createdWindow, pane] = run(args).trim().split("\t");
260
301
  if (
261
302
  !/^%\d+$/u.test(pane ?? "") ||
262
- createdSession !== session ||
303
+ createdSession !== target.session ||
263
304
  !/^@\d+$/u.test(createdWindow ?? "")
264
305
  )
265
306
  throw new IdeError("tmux did not return the created browser pane ID.", {
@@ -0,0 +1,148 @@
1
+ import { realpathSync, statSync } from "node:fs";
2
+ import { relative, resolve } from "node:path";
3
+ import { resolveCliCommand } from "./lib/cli-command.ts";
4
+ import { IdeError } from "./lib/errors.ts";
5
+ import { resolveRuntimeNamespace, runtimeNamespaceEnvironment } from "./lib/runtime-namespace.ts";
6
+ import {
7
+ createPinnedWorkspaceTmuxRunner,
8
+ resolveWorkspacePaneTmuxAuthority,
9
+ } from "./lib/workspace-pane-creation.ts";
10
+ import {
11
+ openPaneArgs,
12
+ resolveOpenPaneTarget,
13
+ validateBrowserOpen,
14
+ type OpenBrowserOptions,
15
+ type Run,
16
+ } from "./open-browser.ts";
17
+ import { isMarkdownPath } from "./terminal/protocol/reader-option.ts";
18
+
19
+ export type OpenTarget =
20
+ | { kind: "browser" }
21
+ | {
22
+ kind: "reader";
23
+ /** Absolute real path. */
24
+ path: string;
25
+ /** The path as the user named it, relative to their cwd. */
26
+ display: string;
27
+ };
28
+
29
+ const SCHEME_URL = /^[a-z][a-z0-9+.-]*:\/\//iu;
30
+ const MARKDOWN_ARGUMENT = /\.(?:md|markdown)$/iu;
31
+
32
+ /**
33
+ * Decides what `tmux-ide open <arg>` opens. A Markdown file name with no
34
+ * `scheme://` is read in the native reader and must exist; everything else
35
+ * goes to the browser exactly as before.
36
+ */
37
+ export function classifyOpenTarget(
38
+ arg: string | undefined,
39
+ cwd: string,
40
+ fs: { realpath(path: string): string; isFile(path: string): boolean } = {
41
+ realpath: (path) => realpathSync(path),
42
+ isFile: (path) => statSync(path).isFile(),
43
+ },
44
+ ): OpenTarget {
45
+ if (arg === undefined || SCHEME_URL.test(arg) || !MARKDOWN_ARGUMENT.test(arg))
46
+ return { kind: "browser" };
47
+ const named = resolve(cwd, arg);
48
+ const display = relative(cwd, named) || named;
49
+ let path: string;
50
+ try {
51
+ path = fs.realpath(named);
52
+ if (!fs.isFile(path)) throw new Error("not a file");
53
+ } catch {
54
+ throw new IdeError(`No Markdown file at ${display}.`, {
55
+ code: "FILE_NOT_FOUND",
56
+ exitCode: 2,
57
+ });
58
+ }
59
+ if (!isMarkdownPath(path))
60
+ throw new IdeError(`${display} does not resolve to a Markdown file.`, {
61
+ code: "NOT_MARKDOWN",
62
+ exitCode: 2,
63
+ });
64
+ return { kind: "reader", path, display };
65
+ }
66
+
67
+ export interface ReaderPaneResult {
68
+ pane: string;
69
+ session: string;
70
+ window: string;
71
+ status: "created";
72
+ kind: "reader";
73
+ }
74
+
75
+ /**
76
+ * Splits a pane running `tmux-ide show <file>` (the TUI renderer, which also
77
+ * watches the file) and stamps `@tmux_ide_reader` with that process's pid,
78
+ * which is what lets the Mac app paint its native reader over the pane.
79
+ */
80
+ export function createReaderPane(
81
+ run: Run,
82
+ cli: readonly string[],
83
+ path: string,
84
+ options: OpenBrowserOptions,
85
+ environment: NodeJS.ProcessEnv,
86
+ cwd: string,
87
+ namespace: Readonly<Record<string, string>>,
88
+ ): ReaderPaneResult {
89
+ validateBrowserOpen(undefined, options);
90
+ const target = resolveOpenPaneTarget(run, options, environment, "READER");
91
+ const args = openPaneArgs(
92
+ target,
93
+ options,
94
+ environment,
95
+ cwd,
96
+ namespace,
97
+ [...cli, "show", path],
98
+ "#{session_id}\t#{window_id}\t#{pane_id}\t#{pane_pid}",
99
+ "Reader",
100
+ );
101
+ const [session, window, pane, pid] = run(args).trim().split("\t");
102
+ if (
103
+ !/^%\d+$/u.test(pane ?? "") ||
104
+ session !== target.session ||
105
+ !/^@\d+$/u.test(window ?? "") ||
106
+ !/^[1-9]\d{0,9}$/u.test(pid ?? "")
107
+ )
108
+ throw new IdeError("tmux did not return the created reader pane.", {
109
+ code: "READER_CREATE_FAILED",
110
+ });
111
+ run([
112
+ "set-option",
113
+ "-p",
114
+ "-t",
115
+ pane!,
116
+ "@tmux_ide_reader",
117
+ JSON.stringify({ version: 1, pid: Number(pid), path }),
118
+ ]);
119
+ return { pane: pane!, session: session!, window: window!, status: "created", kind: "reader" };
120
+ }
121
+
122
+ export async function openReader(
123
+ target: Extract<OpenTarget, { kind: "reader" }>,
124
+ options: OpenBrowserOptions = {},
125
+ ): Promise<ReaderPaneResult> {
126
+ validateBrowserOpen(undefined, options);
127
+ try {
128
+ const namespace = { ...runtimeNamespaceEnvironment(resolveRuntimeNamespace()) };
129
+ const run = createPinnedWorkspaceTmuxRunner(resolveWorkspacePaneTmuxAuthority(), {
130
+ timeoutMs: 10_000,
131
+ });
132
+ return createReaderPane(
133
+ run,
134
+ resolveCliCommand(),
135
+ target.path,
136
+ options,
137
+ process.env,
138
+ process.cwd(),
139
+ namespace,
140
+ );
141
+ } catch (error) {
142
+ if (error instanceof IdeError) throw error;
143
+ throw new IdeError(
144
+ "Could not create the reader pane. Check that the target tmux session is running.",
145
+ { code: "READER_CREATE_FAILED", cause: error instanceof Error ? error : undefined },
146
+ );
147
+ }
148
+ }
@@ -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");
@@ -15,6 +15,7 @@ import {
15
15
  type NotifyLevel,
16
16
  } from "./host-calls.ts";
17
17
  import { cliRunner } from "./worktree-calls.ts";
18
+ import { resolveCliCommand } from "../lib/cli-command.ts";
18
19
  import { defaultControlSocketPath } from "../control/server.ts";
19
20
  import { DEFAULT_PLUGIN_LIMITS } from "./protocol.ts";
20
21
  import { minimalHostEnv, PluginSupervisor, secretEnvValues } from "./supervisor.ts";
@@ -85,18 +86,7 @@ export async function tmuxSocketDirs(
85
86
  return [...dirs];
86
87
  }
87
88
 
88
- /**
89
- * The argv prefix that runs this tmux-ide's CLI: the bundled `bin/cli.js`,
90
- * or `bin/cli.ts` under the runtime's loader flags when run from source.
91
- */
92
- export function resolveCliCommand(
93
- here: string = fileURLToPath(import.meta.url),
94
- runtime: { execPath: string; execArgv: readonly string[] } = process,
95
- ): string[] {
96
- if (basename(here) === "cli.js") return [runtime.execPath, here];
97
- const cli = join(dirname(here), "..", "..", "..", "..", "bin", `cli${extname(here)}`);
98
- return [runtime.execPath, ...runtime.execArgv, cli];
99
- }
89
+ export { resolveCliCommand } from "../lib/cli-command.ts";
100
90
 
101
91
  /**
102
92
  * Files programs from plugins may not read: the daemon record (its port and