tmux-ide 2.9.21 → 2.9.22

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 (69) hide show
  1. package/bin/cli.js +5282 -3386
  2. package/package.json +1 -1
  3. package/packages/contracts/src/index.ts +1 -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/daemon/dist/command-center/tmux-server-reader.js +41 -0
  8. package/packages/daemon/dist/command-center/tmux-servers.js +6 -0
  9. package/packages/daemon/dist/doctor.js +106 -43
  10. package/packages/daemon/dist/lib/cli-command.js +13 -0
  11. package/packages/daemon/dist/lib/daemon-embed.js +15 -0
  12. package/packages/daemon/dist/lib/pane-reader-files.js +226 -0
  13. package/packages/daemon/dist/lib/remote-tmux-command.js +8 -5
  14. package/packages/daemon/dist/lib/tmux-client-execution.js +73 -7
  15. package/packages/daemon/dist/lib/tmux-pane-reader.js +105 -0
  16. package/packages/daemon/dist/lib/tmux-server-features.js +38 -0
  17. package/packages/daemon/dist/lib/tmux-server-owner.js +9 -0
  18. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  19. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  20. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  21. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  22. package/packages/daemon/dist/open-browser.js +26 -12
  23. package/packages/daemon/dist/open-reader.js +84 -0
  24. package/packages/daemon/dist/plugins/daemon-plugins.js +2 -10
  25. package/packages/daemon/dist/restore.js +57 -40
  26. package/packages/daemon/dist/terminal/mirror/session-channel.js +4 -1
  27. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +12 -3
  28. package/packages/daemon/dist/terminal/protocol/reader-option.js +66 -0
  29. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +7 -2
  30. package/packages/daemon/dist/tmux-upgrade/cli.js +106 -0
  31. package/packages/daemon/dist/tmux-upgrade/io.js +540 -0
  32. package/packages/daemon/dist/tmux-upgrade/plan.js +238 -0
  33. package/packages/daemon/dist/tmux-upgrade/run.js +199 -0
  34. package/packages/daemon/dist/tui/chrome/snapshot.js +3 -4
  35. package/packages/daemon/dist/tui/mirror/runtime/application-home-agent-navigation.js +64 -4
  36. package/packages/daemon/dist/tui/mirror/runtime/application-home-agents-owner.js +35 -5
  37. package/packages/daemon/dist/tui/mirror/runtime/application-machine-agent-navigation.js +12 -8
  38. package/packages/daemon/dist/tui/mirror/runtime/application-terminal-interaction-controller.js +125 -111
  39. package/packages/daemon/src/command-center/tmux-server-reader.ts +62 -0
  40. package/packages/daemon/src/command-center/tmux-servers.ts +6 -0
  41. package/packages/daemon/src/doctor.ts +118 -45
  42. package/packages/daemon/src/lib/cli-command.ts +16 -0
  43. package/packages/daemon/src/lib/daemon-embed.ts +17 -0
  44. package/packages/daemon/src/lib/pane-reader-files.ts +294 -0
  45. package/packages/daemon/src/lib/remote-tmux-command.ts +13 -6
  46. package/packages/daemon/src/lib/tmux-client-execution.ts +79 -7
  47. package/packages/daemon/src/lib/tmux-pane-reader.ts +144 -0
  48. package/packages/daemon/src/lib/tmux-server-features.ts +43 -0
  49. package/packages/daemon/src/lib/tmux-server-owner.ts +9 -0
  50. package/packages/daemon/src/open-browser.ts +59 -18
  51. package/packages/daemon/src/open-reader.ts +148 -0
  52. package/packages/daemon/src/plugins/daemon-plugins.ts +2 -12
  53. package/packages/daemon/src/restore.ts +80 -44
  54. package/packages/daemon/src/terminal/mirror/events.ts +2 -0
  55. package/packages/daemon/src/terminal/mirror/session-channel.ts +6 -1
  56. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +15 -2
  57. package/packages/daemon/src/terminal/protocol/reader-option.ts +77 -0
  58. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +10 -1
  59. package/packages/daemon/src/tmux-upgrade/cli.ts +118 -0
  60. package/packages/daemon/src/tmux-upgrade/io.ts +596 -0
  61. package/packages/daemon/src/tmux-upgrade/plan.ts +353 -0
  62. package/packages/daemon/src/tmux-upgrade/run.ts +325 -0
  63. package/packages/daemon/src/tui/chrome/snapshot.ts +3 -4
  64. package/packages/daemon/src/tui/mirror/runtime/application-home-agent-navigation.ts +110 -10
  65. package/packages/daemon/src/tui/mirror/runtime/application-home-agents-owner.ts +58 -6
  66. package/packages/daemon/src/tui/mirror/runtime/application-machine-agent-navigation.ts +20 -9
  67. package/packages/daemon/src/tui/mirror/runtime/application-root-v2.tsx +2 -2
  68. package/packages/daemon/src/tui/mirror/runtime/application-terminal-interaction-controller.ts +149 -128
  69. package/packages/tmux-bridge/src/runner.ts +3 -1
@@ -0,0 +1,294 @@
1
+ import { createHash } from "node:crypto";
2
+ import {
3
+ closeSync,
4
+ constants,
5
+ fstatSync,
6
+ lstatSync,
7
+ openSync,
8
+ readSync,
9
+ realpathSync,
10
+ statSync,
11
+ type BigIntStats,
12
+ } from "node:fs";
13
+ import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
14
+ import {
15
+ PANE_READER_ASSET_MAX_BYTES,
16
+ PANE_READER_MAX_BYTES,
17
+ PANE_READER_PAGE_BYTES,
18
+ hasControlCharacter,
19
+ type PaneReaderPage,
20
+ } from "@tmux-ide/contracts";
21
+ import { isMarkdownPath } from "../terminal/protocol/reader-option.ts";
22
+
23
+ /**
24
+ * File access for the native Markdown reader (card #756). Pure of tmux: the
25
+ * caller has already proven which pane and which file. Nothing here touches
26
+ * the network; a URL is always refused.
27
+ */
28
+ export type ReaderPageResult =
29
+ | { state: "unchanged"; revision: string }
30
+ | { state: "ok"; revision: string; size: number; offset: number; chunk: string }
31
+ | { state: "changed" }
32
+ | { state: "too_large"; revision: string; size: number }
33
+ | { state: "missing" };
34
+
35
+ export type ReaderAssetMime =
36
+ | "image/png"
37
+ | "image/jpeg"
38
+ | "image/gif"
39
+ | "image/webp"
40
+ | "image/svg+xml";
41
+ export type ReaderAssetResult =
42
+ | {
43
+ state: "ok";
44
+ mime: ReaderAssetMime;
45
+ revision: string;
46
+ size: number;
47
+ offset: number;
48
+ chunk: string;
49
+ }
50
+ | { state: "changed" | "refused" | "missing" | "too_large" };
51
+
52
+ const IMAGE_MIME: Readonly<Record<string, ReaderAssetMime>> = {
53
+ ".png": "image/png",
54
+ ".jpg": "image/jpeg",
55
+ ".jpeg": "image/jpeg",
56
+ ".gif": "image/gif",
57
+ ".webp": "image/webp",
58
+ ".svg": "image/svg+xml",
59
+ };
60
+
61
+ function revisionOf(stat: BigIntStats): string {
62
+ return createHash("sha256")
63
+ .update(`${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`)
64
+ .digest("hex")
65
+ .slice(0, 32);
66
+ }
67
+
68
+ function missingError(error: unknown): boolean {
69
+ const code = (error as NodeJS.ErrnoException | null)?.code;
70
+ return code === "ENOENT" || code === "ENOTDIR" || code === "ELOOP" || code === "EISDIR";
71
+ }
72
+
73
+ function realpathOrNull(path: string): string | null {
74
+ try {
75
+ return realpathSync(path);
76
+ } catch (error) {
77
+ if (missingError(error)) return null;
78
+ throw error;
79
+ }
80
+ }
81
+
82
+ /** Equal to or below `root`, compared by path segments rather than by string prefix. */
83
+ export function isInside(root: string, path: string): boolean {
84
+ const rel = relative(root, path);
85
+ return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`));
86
+ }
87
+
88
+ /** The nearest ancestor of `directory` holding a `.git` entry; no git process is run. */
89
+ export function gitRoot(directory: string): string | null {
90
+ for (let current = directory; ; ) {
91
+ try {
92
+ lstatSync(join(current, ".git"));
93
+ return current;
94
+ } catch {
95
+ /* keep walking up */
96
+ }
97
+ const parent = dirname(current);
98
+ if (parent === current) return null;
99
+ current = parent;
100
+ }
101
+ }
102
+
103
+ type Opened = { fd: number; stat: BigIntStats };
104
+
105
+ /**
106
+ * Steps a test can wrap, to change a file between the steps of one read.
107
+ * Production passes none.
108
+ */
109
+ export type ReaderFileSeams = {
110
+ readonly afterOpen?: () => void;
111
+ readonly read?: (fd: number, offset: number, size: number, real: typeof readChunk) => Buffer;
112
+ };
113
+
114
+ const NO_SEAMS: ReaderFileSeams = Object.freeze({});
115
+
116
+ /**
117
+ * Opens `real` (already resolved) without following a swapped-in final
118
+ * symlink, and only as a regular file. Then proves the descriptor is still the
119
+ * file at that real path: a fresh stat of the path, following every symlink on
120
+ * it, names the same device and inode as the open descriptor. A path or a
121
+ * folder on it swapped between resolving and opening is refused ("swapped").
122
+ * No separate realpath check is needed: whatever the path now resolves to,
123
+ * the stat proves the open file is the one it leads to.
124
+ */
125
+ function openRegular(real: string, seams: ReaderFileSeams): Opened | "swapped" | null {
126
+ let fd: number;
127
+ try {
128
+ fd = openSync(real, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
129
+ } catch (error) {
130
+ if (missingError(error)) return null;
131
+ throw error;
132
+ }
133
+ const stat = fstatSync(fd, { bigint: true });
134
+ if (!stat.isFile()) {
135
+ closeSync(fd);
136
+ return null;
137
+ }
138
+ seams.afterOpen?.();
139
+ let now: BigIntStats | null = null;
140
+ try {
141
+ now = statSync(real, { bigint: true });
142
+ } catch (error) {
143
+ if (!missingError(error)) {
144
+ closeSync(fd);
145
+ throw error;
146
+ }
147
+ }
148
+ if (!now || now.dev !== stat.dev || now.ino !== stat.ino) {
149
+ closeSync(fd);
150
+ return "swapped";
151
+ }
152
+ return { fd, stat };
153
+ }
154
+
155
+ function readChunk(fd: number, offset: number, size: number): Buffer {
156
+ const length = Math.max(0, Math.min(PANE_READER_PAGE_BYTES, size - offset));
157
+ const buffer = Buffer.alloc(length);
158
+ let done = 0;
159
+ while (done < length) {
160
+ const read = readSync(fd, buffer, done, length - done, offset + done);
161
+ if (read === 0) break;
162
+ done += read;
163
+ }
164
+ return buffer.subarray(0, done);
165
+ }
166
+
167
+ type Paged =
168
+ | { state: "ok"; revision: string; size: number; offset: number; chunk: string }
169
+ | { state: "changed" }
170
+ | { state: "too_large"; revision: string; size: number }
171
+ | { state: "unchanged"; revision: string };
172
+
173
+ /** One page of `opened`, re-checking after the read that the file did not change. */
174
+ function page(
175
+ opened: Opened,
176
+ limit: number,
177
+ have: string | null,
178
+ request: PaneReaderPage | null,
179
+ seams: ReaderFileSeams,
180
+ ): Paged {
181
+ const revision = revisionOf(opened.stat);
182
+ const size = Number(opened.stat.size);
183
+ if (size > limit) return { state: "too_large", revision, size };
184
+ if (request) {
185
+ if (request.revision !== revision || request.offset > size) return { state: "changed" };
186
+ } else if (have === revision) return { state: "unchanged", revision };
187
+ const offset = request?.offset ?? 0;
188
+ const bytes = seams.read
189
+ ? seams.read(opened.fd, offset, size, readChunk)
190
+ : readChunk(opened.fd, offset, size);
191
+ const after = fstatSync(opened.fd, { bigint: true });
192
+ if (
193
+ revisionOf(after) !== revision ||
194
+ bytes.length !== Math.min(PANE_READER_PAGE_BYTES, size - offset)
195
+ )
196
+ return { state: "changed" };
197
+ return { state: "ok", revision, size, offset, chunk: bytes.toString("base64") };
198
+ }
199
+
200
+ /** A page of the Markdown file at `path`; its real path must still be Markdown. */
201
+ export function readReaderPage(
202
+ path: string,
203
+ have: string | null,
204
+ request: PaneReaderPage | null,
205
+ seams: ReaderFileSeams = NO_SEAMS,
206
+ ): ReaderPageResult {
207
+ // A whole-file read retries once if the file changed underneath it.
208
+ for (let attempt = 0; ; attempt++) {
209
+ const real = realpathOrNull(path);
210
+ if (!real || !isMarkdownPath(real)) return { state: "missing" };
211
+ const opened = openRegular(real, seams);
212
+ if (!opened || opened === "swapped") {
213
+ // A document swapped mid-open reads again once, then reports changed.
214
+ if (opened === "swapped" && !request && attempt === 0) continue;
215
+ return opened === "swapped" ? { state: "changed" } : { state: "missing" };
216
+ }
217
+ try {
218
+ const result = page(opened, PANE_READER_MAX_BYTES, have, request, seams);
219
+ if (result.state !== "changed" || request || attempt > 0) return result;
220
+ } finally {
221
+ closeSync(opened.fd);
222
+ }
223
+ }
224
+ }
225
+
226
+ const SCHEME = /^[a-z][a-z0-9+.-]*:/iu;
227
+
228
+ /** The decoded relative path `src` names, or null when the reader must not follow it. */
229
+ export function localImageReference(src: string): string | null {
230
+ if (src.includes("\0") || SCHEME.test(src) || src.startsWith("//") || src.startsWith("\\"))
231
+ return null;
232
+ const bare = src.split(/[?#]/u, 1)[0] ?? "";
233
+ let decoded: string;
234
+ try {
235
+ decoded = decodeURIComponent(bare);
236
+ } catch {
237
+ return null;
238
+ }
239
+ if (
240
+ !decoded ||
241
+ hasControlCharacter(decoded) ||
242
+ decoded.startsWith("/") ||
243
+ decoded.startsWith("~") ||
244
+ decoded.startsWith("\\") ||
245
+ isAbsolute(decoded)
246
+ )
247
+ return null;
248
+ return decoded;
249
+ }
250
+
251
+ function imageMime(path: string): ReaderAssetMime | null {
252
+ return IMAGE_MIME[extname(path).toLowerCase()] ?? null;
253
+ }
254
+
255
+ /**
256
+ * A page of the image `src` names, relative to the Markdown file at `markdown`.
257
+ * Allowed only inside the file's git repository, or its folder when there is
258
+ * none, after every symlink is resolved.
259
+ */
260
+ export function readReaderAssetPage(
261
+ markdown: string,
262
+ src: string,
263
+ request: PaneReaderPage | null,
264
+ seams: ReaderFileSeams = NO_SEAMS,
265
+ ): ReaderAssetResult {
266
+ const reference = localImageReference(src);
267
+ if (reference === null) return { state: "refused" };
268
+ const document = realpathOrNull(markdown);
269
+ if (!document || !isMarkdownPath(document)) return { state: "missing" };
270
+ const base = dirname(document);
271
+ const root = gitRoot(base) ?? base;
272
+ const candidate = resolve(base, reference);
273
+ // Refuse outside paths before touching the file system, so the answer never
274
+ // says whether a file outside the root exists.
275
+ if (!isInside(root, candidate) || !imageMime(candidate)) return { state: "refused" };
276
+ const real = realpathOrNull(candidate);
277
+ if (!real) return { state: "missing" };
278
+ const mime = imageMime(real);
279
+ if (!isInside(root, real) || !mime) return { state: "refused" };
280
+ const opened = openRegular(real, seams);
281
+ if (opened === "swapped") return { state: "refused" };
282
+ if (!opened) return { state: "missing" };
283
+ try {
284
+ // The name as written must still lead to the file that was opened.
285
+ if (realpathOrNull(candidate) !== real) return { state: "refused" };
286
+ const result = page(opened, PANE_READER_ASSET_MAX_BYTES, null, request, seams);
287
+ if (result.state === "unchanged") return { state: "changed" };
288
+ if (result.state === "too_large") return { state: "too_large" };
289
+ if (result.state === "changed") return result;
290
+ return { ...result, mime };
291
+ } finally {
292
+ closeSync(opened.fd);
293
+ }
294
+ }
@@ -1,12 +1,19 @@
1
1
  import { shellEscape } from "./shell.ts";
2
2
 
3
+ // Respect the host's existing installation preference, then try the installer
4
+ // and common package-manager prefixes. Never source shell profiles.
5
+ const REMOTE_PATH =
6
+ 'export PATH="${PATH:-/usr/bin:/bin}:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/home/linuxbrew/.linuxbrew/bin:$HOME/.npm-global/bin"; ';
7
+
3
8
  /** Fixed commands only. SSH normally omits interactive shell PATH setup. */
4
9
  export function remoteTmuxIdeCommand(operation: "discover" | "start"): string {
5
- const args = operation === "discover" ? "remote-daemon-info --json" : "update --daemon --json";
6
- // Respect the host's existing installation preference, then try the installer
7
- // and common package-manager prefixes. Never source shell profiles.
8
- const script =
9
- 'export PATH="${PATH:-/usr/bin:/bin}:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/home/linuxbrew/.linuxbrew/bin:$HOME/.npm-global/bin"; ' +
10
- `exec tmux-ide ${args}`;
10
+ return remoteTmuxIdeArgsCommand(
11
+ operation === "discover" ? ["remote-daemon-info", "--json"] : ["update", "--daemon", "--json"],
12
+ );
13
+ }
14
+
15
+ /** `tmux-ide <args…>` on a remote host, each argument quoted for its shell. */
16
+ export function remoteTmuxIdeArgsCommand(args: readonly string[]): string {
17
+ const script = REMOTE_PATH + `exec tmux-ide ${args.map(shellEscape).join(" ")}`;
11
18
  return `/bin/sh -c ${shellEscape(script)}`;
12
19
  }
@@ -1,3 +1,4 @@
1
+ import { execFileSync } from "node:child_process";
1
2
  import { fileURLToPath } from "node:url";
2
3
  import { accessSync, constants, realpathSync, statSync } from "node:fs";
3
4
  import { delimiter, isAbsolute, join, resolve } from "node:path";
@@ -63,15 +64,91 @@ export function tmuxClientEnvironment(
63
64
  return { ...environment, ...bundledTmuxResourceEnvironment(executable) };
64
65
  }
65
66
 
66
- /** Ordinary CLI commands retain PATH selection; bundled tmux fills a missing system client. */
67
+ /**
68
+ * The socket an ordinary tmux client reaches, or null inside tmux (where the
69
+ * server exists by definition). Ordinary clients pass no -S or -L in
70
+ * production, so this is tmux's own rule: $TMUX, else the default socket.
71
+ */
72
+ export function ordinaryTargetSocket(environment: NodeJS.ProcessEnv): string | null {
73
+ if (environment.TMUX) return null;
74
+ const uid = process.getuid?.() ?? 0;
75
+ return join(environment.TMUX_TMPDIR || "/tmp", `tmux-${uid}`, "default");
76
+ }
77
+
78
+ const answering = new Set<string>();
79
+
80
+ /**
81
+ * Does a server answer on this socket? A socket file alone is not enough: a
82
+ * server that crashed leaves one behind. `probe` asks with `list-sessions`,
83
+ * which never starts a server. A running server is remembered for the process.
84
+ */
85
+ export function serverAnswers(socket: string, probe: string): boolean {
86
+ if (answering.has(socket)) return true;
87
+ try {
88
+ if (!statSync(socket).isSocket()) return false;
89
+ } catch {
90
+ return false;
91
+ }
92
+ try {
93
+ execFileSync(probe, ["-S", socket, "list-sessions", "-F", "#{pid}"], {
94
+ stdio: ["ignore", "ignore", "pipe"],
95
+ timeout: 3000,
96
+ env: withBundledTmuxResources(probe, process.env),
97
+ });
98
+ } catch (error) {
99
+ const stderr = String((error as { stderr?: unknown }).stderr ?? "");
100
+ // A refused connection is a stale socket. Anything else (a protocol
101
+ // mismatch, a timeout) means something is there: keep the PATH client.
102
+ if (/no server running|error connecting|connection refused|no such file/iu.test(stderr))
103
+ return false;
104
+ }
105
+ answering.add(socket);
106
+ return true;
107
+ }
108
+
109
+ export interface OrdinaryTmuxClientOptions {
110
+ /** Whether a server answers on this socket. Defaults to {@link serverAnswers}. */
111
+ readonly serverRunning?: (socket: string) => boolean;
112
+ /** The validated bundled executable, or null. */
113
+ readonly bundled?: () => string | null;
114
+ }
115
+
116
+ /**
117
+ * Ordinary CLI commands retain PATH selection for a running server. When no
118
+ * server runs, the next command starts one, so bundled tmux goes first: a
119
+ * Homebrew client must not start a reduced-feature server (#766).
120
+ * TMUX_IDE_TMUX_BIN always wins.
121
+ */
67
122
  export function resolveOrdinaryTmuxClient(
68
123
  environment: NodeJS.ProcessEnv,
69
124
  cwd?: string | URL,
125
+ options: OrdinaryTmuxClientOptions = {},
70
126
  ): {
71
127
  executable: string;
72
128
  environment: NodeJS.ProcessEnv;
73
129
  } {
130
+ const bundled =
131
+ options.bundled ??
132
+ (() =>
133
+ resolveBundledTmux([
134
+ ...(environment.TMUX_IDE_CLI ? [environment.TMUX_IDE_CLI] : []),
135
+ fileURLToPath(import.meta.url),
136
+ ]));
74
137
  const configured = environment.TMUX_IDE_TMUX_BIN;
138
+ if (!configured) {
139
+ const socket = ordinaryTargetSocket(environment);
140
+ if (socket !== null) {
141
+ let starter: string | null = null;
142
+ try {
143
+ starter = bundled();
144
+ } catch {
145
+ // An invalid bundle falls back to the PATH client below.
146
+ }
147
+ const running = options.serverRunning ?? ((at: string) => serverAnswers(at, starter!));
148
+ if (starter && !running(socket))
149
+ return { executable: starter, environment: withBundledTmuxResources(starter, environment) };
150
+ }
151
+ }
75
152
  const candidates = configured
76
153
  ? [configured]
77
154
  : (environment.PATH ?? "/usr/bin:/bin")
@@ -93,12 +170,7 @@ export function resolveOrdinaryTmuxClient(
93
170
  /* Try the next ordinary PATH candidate. */
94
171
  }
95
172
  }
96
- if (!executable && !configured)
97
- executable =
98
- resolveBundledTmux([
99
- ...(environment.TMUX_IDE_CLI ? [environment.TMUX_IDE_CLI] : []),
100
- fileURLToPath(import.meta.url),
101
- ]) ?? undefined;
173
+ if (!executable && !configured) executable = bundled() ?? undefined;
102
174
  if (!executable) throw new Error("tmux_executable_unavailable");
103
175
  return { executable, environment: withBundledTmuxResources(executable, environment) };
104
176
  }
@@ -0,0 +1,144 @@
1
+ import { basename, dirname } from "node:path";
2
+ import {
3
+ PaneReaderAssetRequestSchemaZ,
4
+ PaneReaderAssetResponseSchemaZ,
5
+ PaneReaderRequestSchemaZ,
6
+ PaneReaderResponseSchemaZ,
7
+ type PaneEditorContextTarget,
8
+ type PaneReaderAssetResponse,
9
+ type PaneReaderResponse,
10
+ } from "@tmux-ide/contracts";
11
+ import type { LiveSessionSummary } from "../command-center/discovery.ts";
12
+ import type { WorkspaceTerminalInventoryRuntime } from "../terminal/attachments/native-runtime.ts";
13
+ import type { WorkspaceRegistry } from "./workspace-registry.ts";
14
+ import { decodeTmuxArgument } from "../terminal/protocol/session-descriptor-discovery.ts";
15
+ import { readerOption, type ReaderOption } from "../terminal/protocol/reader-option.ts";
16
+ import { readReaderAssetPage, readReaderPage } from "./pane-reader-files.ts";
17
+
18
+ /** Any identity, liveness or option failure. Carries no path or detail. */
19
+ export class PaneReaderUnavailable extends Error {
20
+ constructor() {
21
+ super("The reader pane is unavailable");
22
+ }
23
+ }
24
+
25
+ export interface PaneReaderResolver {
26
+ read(input: unknown, cancellation: AbortSignal): Promise<PaneReaderResponse>;
27
+ asset(input: unknown, cancellation: AbortSignal): Promise<PaneReaderAssetResponse>;
28
+ }
29
+
30
+ /**
31
+ * Serves only the file named by the target pane's `@tmux_ide_reader` option,
32
+ * for a pane whose identity is proven again before and after the read, and
33
+ * whose reader process is alive.
34
+ */
35
+ export function createPaneReaderResolver(options: {
36
+ generation: string;
37
+ assertOpen(): void;
38
+ registry: Pick<WorkspaceRegistry, "get">;
39
+ catalog(): Promise<LiveSessionSummary[]>;
40
+ inventory: Pick<WorkspaceTerminalInventoryRuntime, "discoverTerminalInventory">;
41
+ run(args: readonly string[], signal: AbortSignal): Promise<string>;
42
+ alive?: (pid: number) => boolean;
43
+ }): PaneReaderResolver {
44
+ let readers = 0;
45
+ const withReader = async <T>(
46
+ target: PaneEditorContextTarget,
47
+ cancellation: AbortSignal,
48
+ work: (reader: ReaderOption) => T,
49
+ ): Promise<T> => {
50
+ const signal = AbortSignal.any([cancellation, AbortSignal.timeout(2500)]);
51
+ const workspace = options.registry.get(target.workspaceName);
52
+ const assertCurrent = () => {
53
+ options.assertOpen();
54
+ signal.throwIfAborted();
55
+ if (
56
+ target.generation !== options.generation ||
57
+ !workspace ||
58
+ options.registry.get(target.workspaceName) !== workspace
59
+ )
60
+ throw new PaneReaderUnavailable();
61
+ };
62
+ assertCurrent();
63
+ if (readers >= 8) throw new PaneReaderUnavailable();
64
+ readers++;
65
+ try {
66
+ const sessions = await options.catalog();
67
+ assertCurrent();
68
+ const matching = sessions.filter((s) => s.liveSessionId === target.liveSessionId);
69
+ if (matching.length !== 1 || matching[0]!.sessionName !== workspace!.sessionName)
70
+ throw new PaneReaderUnavailable();
71
+ const snapshot = await options.inventory.discoverTerminalInventory(signal);
72
+ assertCurrent();
73
+ if (
74
+ snapshot.catalog.invalidRuntimeProof ||
75
+ snapshot.catalog.duplicateSemanticStamp ||
76
+ snapshot.catalog.duplicateRuntimePaneBinding
77
+ )
78
+ throw new PaneReaderUnavailable();
79
+ const matches = snapshot.panes.filter(
80
+ (p) =>
81
+ p.workspaceName === target.workspaceName &&
82
+ p.semanticPaneId === target.semanticPaneId &&
83
+ p.sessionName === workspace!.sessionName,
84
+ );
85
+ if (matches.length !== 1) throw new PaneReaderUnavailable();
86
+ const pane = { ...matches[0]! };
87
+ if (!pane.nativePaneBirthId || !/^%[0-9]+$/u.test(pane.runtimePaneId))
88
+ throw new PaneReaderUnavailable();
89
+ const observe = async (): Promise<ReaderOption> => {
90
+ const raw = await options.run(
91
+ [
92
+ "display-message",
93
+ "-p",
94
+ "-t",
95
+ pane.runtimePaneId,
96
+ "#{qa:@tmux_ide_pane_id}\t#{qa:pane_birth_id}\t#{pane_pid}\t#{qa:@tmux_ide_reader}",
97
+ ],
98
+ signal,
99
+ );
100
+ assertCurrent();
101
+ if (raw.length > 16_384) throw new PaneReaderUnavailable();
102
+ const [semantic, birth, panePid, option] = raw
103
+ .trimEnd()
104
+ .split("\t")
105
+ .map(decodeTmuxArgument);
106
+ if (semantic !== target.semanticPaneId || birth !== pane.nativePaneBirthId)
107
+ throw new PaneReaderUnavailable();
108
+ const reader = readerOption(option ?? "", panePid ?? "", options.alive);
109
+ if (!reader) throw new PaneReaderUnavailable();
110
+ return reader;
111
+ };
112
+ const reader = await observe();
113
+ const result = work(reader);
114
+ const current = await observe();
115
+ if (current.path !== reader.path || current.pid !== reader.pid)
116
+ throw new PaneReaderUnavailable();
117
+ return result;
118
+ } finally {
119
+ readers--;
120
+ }
121
+ };
122
+ return {
123
+ read: async (input, cancellation) => {
124
+ const request = PaneReaderRequestSchemaZ.parse(input);
125
+ return withReader(request.target, cancellation, (reader) =>
126
+ PaneReaderResponseSchemaZ.parse({
127
+ version: 1,
128
+ name: reader.name,
129
+ folder: basename(dirname(reader.path)),
130
+ ...readReaderPage(reader.path, request.have, request.page),
131
+ }),
132
+ );
133
+ },
134
+ asset: async (input, cancellation) => {
135
+ const request = PaneReaderAssetRequestSchemaZ.parse(input);
136
+ return withReader(request.target, cancellation, (reader) =>
137
+ PaneReaderAssetResponseSchemaZ.parse({
138
+ version: 1,
139
+ ...readReaderAssetPage(reader.path, request.src, request.page),
140
+ }),
141
+ );
142
+ },
143
+ };
144
+ }
@@ -0,0 +1,43 @@
1
+ import { nativeSplitCapability } from "../terminal/protocol/native-split-resize.ts";
2
+
3
+ /** Runs one tmux command against a server and returns its stdout; throws with stderr. */
4
+ export type TmuxProbe = (args: readonly string[]) => string;
5
+ const UNKNOWN = (command: string) => new RegExp(`^unknown command: ${command}$`, "mu");
6
+
7
+ export type NativeAnswer = "full" | "stock" | "older" | "partial" | "no-server" | "unknown";
8
+ /** The same reading of the server as the mirror's: the stock resize when it refuses
9
+ * the split command by name, and full only with the split capability it requires. */
10
+ export function nativeCommands(probe: TmuxProbe): NativeAnswer {
11
+ const ask = (command: string) => {
12
+ try {
13
+ return { output: probe([command, "-V"]) };
14
+ } catch (error) {
15
+ const failure = error as { stderr?: unknown; message?: string };
16
+ return { failure: String(failure.stderr ?? failure.message ?? "") };
17
+ }
18
+ };
19
+ const split = ask("tmux-ide-resize-split");
20
+ const events = ask("tmux-ide-events");
21
+ const failures = [split.failure, events.failure].filter((text) => text !== undefined);
22
+ if (failures.some((text) => /no server running|error connecting/u.test(text!)))
23
+ return "no-server";
24
+ const refused = (answer: { failure?: string }, command: string) =>
25
+ answer.failure !== undefined && UNKNOWN(command).test(answer.failure);
26
+ if (refused(split, "tmux-ide-resize-split")) {
27
+ if (refused(events, "tmux-ide-events")) return "stock";
28
+ // The journal answers: a tmux-ide tmux built before the split command.
29
+ if (events.output !== undefined) return "older";
30
+ return "unknown";
31
+ }
32
+ if (split.output !== undefined && events.output !== undefined) {
33
+ try {
34
+ return nativeSplitCapability(split.output) ? "full" : "partial";
35
+ } catch {
36
+ return "partial";
37
+ }
38
+ }
39
+ return failures.length === 2 ? "unknown" : "partial";
40
+ }
41
+
42
+ /** The answers a live server can give (doctor also reports "no-server"). */
43
+ export type ServerFeatures = Exclude<NativeAnswer, "no-server">;
@@ -1,3 +1,4 @@
1
+ import { createPaneReaderResolver } from "./tmux-pane-reader.ts";
1
2
  import { createNativeBrowserResolver } from "./tmux-native-browser.ts";
2
3
  import { createNativeSurfaceContextResolver } from "./native-surface-context.ts";
3
4
  import type { LocalImageOwner } from "../terminal/graphics/local-image-owner.ts";
@@ -659,6 +660,14 @@ export async function createNativeTmuxServerOwner(options: NativeTmuxServerOwner
659
660
  inventory: terminalInventoryRuntime,
660
661
  run: generationRunAsync,
661
662
  }),
663
+ paneReader: createPaneReaderResolver({
664
+ generation,
665
+ assertOpen,
666
+ registry: workspaceRegistry,
667
+ catalog,
668
+ inventory: terminalInventoryRuntime,
669
+ run: generationRunAsync,
670
+ }),
662
671
  catalog,
663
672
  readWindowSplitLayout: async (workspaceName: string, input: WindowLinkTarget) => {
664
673
  assertOpen();